text
stringlengths
15
59.8k
meta
dict
Q: How to stop collection triggering code when scrolling back in to view swift I'm pretty new so apologies if my title doesn't phrase things correctly. I've been hacking away and haven't been able to find an answer to this problem. I have a horizontally scrolling collection. I'm trying to visually show poll results programatically adding CGRect to the relevant item in the collection based on voting data held in a Firestore array. This is working, but the problem is when you scroll away (so the item in the collection is off screen) and then back, the code to draw the CGRects gets triggered again and more graphics get added to the view. Is there a way to delete these CGRects when the user scrolls an item collection off screen so when the user scrolls the item back into view, code is triggered again it doesn't create duplicates? Here are a couple of screenshots showing first and second load Here is my code (cell b is where the CGrect gets triggered) //COLLECTION VIEW CODE func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if collectionView == self.sentCollectionView { let cellA = collectionView.dequeueReusableCell(withReuseIdentifier: "sCell", for: indexPath) as! SentCollectionViewCell cellA.sentQuestionLabel.text = sentMessages[indexPath.row].shoutText // Set up cell return cellA } else { let cellB = receivedCollectionView.dequeueReusableCell(withReuseIdentifier: "pCell", for: indexPath) as! ReceivedCollectionViewCell receivedMessages[indexPath.row].pollTotal = receivedMessages[indexPath.row].pollResults.reduce(0, +) print("Sum of Array is : ", receivedMessages[indexPath.row].pollTotal!) cellB.receivedShoutLabel.text = receivedMessages[indexPath.row].shoutText print(receivedMessages[indexPath.row].pollResults.count) if receivedMessages[indexPath.row].pollResults != [] { for i in 0...receivedMessages[indexPath.row].pollResults.count - 1 { cellB.resultsView.addSubview(sq(pollSum: receivedMessages[indexPath.row].pollTotal!, pollResult: receivedMessages[indexPath.row].pollResults[i])) } } return cellB } } //THIS DRAWS THE CGRECT func sq(pollSum: Int, pollResult: Int) -> UIView { // divide the width by total responses let screenDivisions = Int(view.frame.size.width) / pollSum // the rectangle top left point x axis position. let xPos = 0 // the rectangle width. let rectWidth = pollResult * screenDivisions // the rectangle height. let rectHeight = 10 // Create a CGRect object which is used to render a rectangle. let rectFrame: CGRect = CGRect(x:CGFloat(xPos), y:CGFloat(yPos), width:CGFloat(rectWidth), height:CGFloat(rectHeight)) // Create a UIView object which use above CGRect object. let greenView = UIView(frame: rectFrame) // Set UIView background color. greenView.backgroundColor = UIColor.green //increment y position yPos = yPos + 25 return greenView } A: Cells of collection are dequeued dequeueReusableCell , you need to override prepareForReuse Or set a tag greenView.tag = 333 And inside cellForItemAt do this cellB.resultsView.subviews.forEach { if $0.tag == 333 { $0.removeFromSuperview() } } if receivedMessages[indexPath.row].pollResults != [] { for i in 0...receivedMessages[indexPath.row].pollResults.count - 1 { cellB.resultsView.addSubview(sq(pollSum: receivedMessages[indexPath.row].pollTotal!, pollResult: receivedMessages[indexPath.row].pollResults[i])) } }
{ "language": "en", "url": "https://stackoverflow.com/questions/67759302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to access parent form properties from a child form in vb.net I have pretty much the same problem as described in this, but using VB.NET. There is a Form1 which is opened automatically as start window, so I cannot find the instance to use for accessing it. There is a Form2 opened from within Form1. I try to pass the instance of Form1 using keyword "Me": Private Sub Button1_click(...) Handles Button1.Click Dim childform as new Form2(Me) childform.show() End Sub In Form2 I have: Public Sub New(parentform As System.Windows.Forms.Form) InitializeComponents() MessageBox.Show(parentform.Button1.Text) End Sub Upon compiling I get the error: "Button1 is not a member of Form". So how to pass the Form1 instance correctly to Form2? Also I want to change some properties of the Button1 of Form1 from Form2. Button1 is declared in a Private Sub, will I nevertheless be able to access it from Form2 if I pass the instance correctly? If not, can I declaring a sub in Form1, e.g. Public Shared Sub ChangeText(newtext As Sting) Me.Button1.Text=newtext End Sub that will do the job? A: I'm not 100% sure about what you are trying to achieve, but, you can pass data between forms. So for example you can do something like: Public Class Form1 Private Sub Button1_click(...) Handles Button1.Click Dim newForm2 as New Form2() newForm2.stringText = "" If newForm2.ShowDialog() = DialogResult.OK Then Button1.Text = newForm2.stringText End If End Sub End Class And in Form2 you have Public Class Form2 Dim stringText as string Private Sub changeStringText() 'your method to change your data Me.DialogResult = DialogResult.OK 'this will close form2 End Sub End Class I hope this is what you need, if not let me know A: Thanks for your answer and comment. So I declared the wrong class for the parentform, means in Form2 it needs to be "parentform as Form1": Public Sub New(parentform As Form1) InitializeComponents() MessageBox.Show(parentform.Button1.Text) End Sub and yes, I need to skip the "shared" in the ChangeText: Public Sub ChangeText(newtext As Sting) Me.Button1.Text=newtext End Sub This way it worked for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/70332722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: the auto generated code for an Intent defined in a `intentdefinition` throws `No newline at end of file` I have added an Intents.intentdefinition to my project. In it I have added a new intent called OrderItem with a few parameters and parameter combination. When I try to import the autogenerated OrderItemIntent.h, the compiler throws a No newline at end of file compilation error. Not sure what is the correct way to resolve this issue. A: Let me explain please. The way to find an OrderItemIntent (XXXIntent) file * *Move to Intents(XXX).intentdefinition file. *Select a intent from any custom intents. *Move to Inspector panel from Xcode right side and go to third Identity Inspector section *You can find 'Custom class' blank and there are a right arrow button which connect to Class file. *Click that button Thanks A: It seems like Xcode has a bug in the generated Intent class for Objective-C. However you can go to your project settings, search for Intent Class Generation Language and chose Swift. That should fix the problem so far.
{ "language": "en", "url": "https://stackoverflow.com/questions/51054236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: @Valid does not work for nested object in bean class in spring I have a Bean class which has one nested object like below. import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.Valid; import javax.validation.constraints.NotNull; @Data @AllArgsConstructor @NoArgsConstructor public class UserRequestDTO { private String transactionId; private String email; @Valid @NotNull HistoryRequestDTO historyRequestDTO; } This is the nested object bean class. import javax.validation.constraints.*; @Data public class HistoryRequestDTO { @NotNull(message = Constants.INVALID_FIELD_DATA_EN_US) @Range(min = 0, max = 100, message = Constants.INVALID_FIELD_DATA_EN_US) @NumberFormat(style = NumberFormat.Style.NUMBER) Integer pageNumber; @NotNull(message = Constants.INVALID_FIELD_DATA_EN_US) @Range(min = 50, max = 500, message = Constants.INVALID_FIELD_DATA_EN_US) @NumberFormat(style = NumberFormat.Style.NUMBER) Integer pageSize; } I already have implemented validator for HistoryRequestDTO and working fine seperately. But when I use UserRequestDTO, HistoryRequestDTO validator does not work. I tried to implement seperate validator for UserRequestDTO, but still it is not calling HistoryRequestDTO validator. A: try this @Valid usage show here for nested object in bean class just check once.. hibernate validator
{ "language": "en", "url": "https://stackoverflow.com/questions/52889501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Finding the first day of specific months in R I currently have a column "Month" & a column "DayWeek" with the Month and Day of the week written out. Using the code below I can get a column with a 1 for each Wednesday in Feb, May, Aug & Nov. Im struggling to find a way to get a column with 1s just for the first Wednesday of each of the 4 months I just mentioned. Any ideas or do I have to create a loop for it? testPrices$Rebalance <- ifelse((testPrices$Month=="February" & testPrices$DayWeek == "Wednesday"),1,ifelse((testPrices$Month=="May" & testPrices$DayWeek == "Wednesday"),1,ifelse((testPrices$Month=="August" & testPrices$DayWeek == "Wednesday"),1,ifelse((testPrices$Month=="November" & testPrices$DayWeek == "Wednesday"),1,0)))) A: Well, without a reproducible example, I couldn't come up with a complete solution, but here is a way to generate the first Wednesday date of each month. In this example, I start at 1 JAN 2013 and go out 36 months, but you can figure out what's appropriate for you. Then, you can check against the first Wednesday vector produced here to see if your dates are members of the first Wednesday of the month group and assign a 1, if so. # I chose this as an origin orig <- "2013-01-01" # generate vector of 1st date of the month for 36 months d <- seq(as.Date(orig), length=36, by="1 month") # Use that to make a list of the first 7 dates of each month d <- lapply(d, function(x) as.Date(seq(1:7),origin=x)-1) # Look through the list for Wednesdays only, # and concatenate them into a vector do.call('c', lapply(d, function(x) x[strftime(x,"%A")=="Wednesday"])) Output: [1] "2013-01-02" "2013-02-06" "2013-03-06" "2013-04-03" "2013-05-01" "2013-06-05" "2013-07-03" [8] "2013-08-07" "2013-09-04" "2013-10-02" "2013-11-06" "2013-12-04" "2014-01-01" "2014-02-05" [15] "2014-03-05" "2014-04-02" "2014-05-07" "2014-06-04" "2014-07-02" "2014-08-06" "2014-09-03" [22] "2014-10-01" "2014-11-05" "2014-12-03" "2015-01-07" "2015-02-04" "2015-03-04" "2015-04-01" [29] "2015-05-06" "2015-06-03" "2015-07-01" "2015-08-05" "2015-09-02" "2015-10-07" "2015-11-04" [36] "2015-12-02" Note: I adapted this code from answers found here and here. A: I created a sample dataset to work with like this (Thanks @Frank!): orig <- "2013-01-01" d <- data.frame(date=seq(as.Date(orig), length=1000, by='1 day')) d$Month <- months(d$date) d$DayWeek <- weekdays(d$date) d$DayMonth <- as.numeric(format(d$date, '%d')) From a data frame like this, you can extract the first Wednesday of specific months using subset, like this: subset(d, Month %in% c('January', 'February') & DayWeek == 'Wednesday' & DayMonth < 8) This takes advantage of the fact that the day number (1..31) will always be between 1 to 7, and obviously there will be precisely one such day. You could do similarly for 2nd, 3rd, 4th Wednesday, changing the condition to accordingly, for example DayMonth > 7 & DayMonth < 15.
{ "language": "en", "url": "https://stackoverflow.com/questions/24714411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: SimpleXML & PHP: Extract part of XML document & convert as Array Consider the following XML: <?xml version="1.0" encoding="UTF-8"?> <OS> <data> <OSes> <centos> <v_5> <i386> <id>centos5-32</id> <name>CentOS 5 - 32 bit</name> <version>5</version> <architecture>32</architecture> <os>centos</os> </i386> <x86_64> <id>centos5-64</id> <name>CentOS 5 - 64 bit</name> <version>5</version> <architecture>64</architecture> <os>centos</os> </x86_64> </v_5> <v_6> <i386> <id>centos6-32</id> <name>CentOS 6 - 32 bit</name> <version>6</version> <architecture>32</architecture> <os>centos</os> </i386> <x86_64> <id>centos6-64</id> <name>CentOS 6 - 64 bit</name> <version>6</version> <architecture>64</architecture> <os>centos</os> </x86_64> </v_6> </centos> <ubuntu> <v_10> <i386> <id>ubuntu10-32</id> <name>Ubuntu 10 - 32 bit</name> <version>10</version> <architecture>32</architecture> <os>ubuntu</os> </i386> <amd64> <id>ubuntu10-64</id> <name>Ubuntu 10 - 64 bit</name> <version>10</version> <architecture>64</architecture> <os>ubuntu</os> </amd64> </v_10> </ubuntu> </OSes> </data> </OS> From the XML document above, I want to extract following 5 element node * *<id> *<name> *<version> *<architecture> *<os> And have them as a array. I tried doing the following: <?php require_once "xml.php"; try { $xml = new SimpleXMLElement($xmlstr); foreach($xml->xpath(' //id | //name | //version// | //architecture | //os ') as $record) { echo $record; } } catch(Exception $e){ echo $e->getMessage(); } the above code works but each record is an separate object. I want someone to consolidate all 5 elements nodes as one array element. something like this: $osList = Array( [0] => Array( ["id"] => "<id>", ["name"] => "<name>", ["version"] => "<version>", .... ) ..... ); syntax isn't correct but you get the idea. any idea how to do this? A: this might help $obj = new SimpleXMLElement($xml); $rtn = array(); $cnt = 0; foreach($obj->xpath('///OSes/*/*') as $rec) { foreach ($rec as $rec_obj) { if (!isset($rtn[$cnt])) { $rtn[$cnt] = array(); } foreach ($rec_obj as $name=>$val) { $rtn[$cnt][(string)$name] = (string)$val; } ++$cnt; } } A: By modifying the xpath as others suggested as well, I came to this conclusion. It works with one helper function to re-format each xpath result node and uses array_reduce to iterate over the result. It then returns the converted result (Demo): $xml = new SimpleXMLElement($xmlstr); $elements = array_reduce( $xml->xpath('//OSes/*/*'), function($v, $w) { $w = array_values((array) $w); // convert result to array foreach($w as &$d) $d = (array) $d; // convert inner elements to array return array_merge($v, $w); // merge with existing }, array() // empty elements at start ); Output: Array ( [0] => Array ( [id] => centos5-32 [name] => CentOS 5 - 32 bit [version] => 5 [architecture] => 32 [os] => centos ) [1] => Array ( [id] => centos5-64 [name] => CentOS 5 - 64 bit [version] => 5 [architecture] => 64 [os] => centos ) [2] => Array ( [id] => centos6-32 [name] => CentOS 6 - 32 bit [version] => 6 [architecture] => 32 [os] => centos ) [3] => Array ( [id] => centos6-64 [name] => CentOS 6 - 64 bit [version] => 6 [architecture] => 64 [os] => centos ) [4] => Array ( [id] => ubuntu10-32 [name] => Ubuntu 10 - 32 bit [version] => 10 [architecture] => 32 [os] => ubuntu ) [5] => Array ( [id] => ubuntu10-64 [name] => Ubuntu 10 - 64 bit [version] => 10 [architecture] => 64 [os] => ubuntu ) ) I also opted for converting the original xpath result into an array of two levels, each time within the current level a key already exists, move the current entry to a new entry (Demo): try { $xml = new SimpleXMLElement($xmlstr); $elements = array(); $curr = NULL; foreach($xml->xpath('//id | //name | //version | //architecture | //os') as $record) { $key = $record->getName(); $value = (string) $record; if (!$curr || array_key_exists($key, $curr)) { unset($curr); $curr = array(); $elements[] = &$curr; } $curr[$key] = $value; } unset($curr); } catch(Exception $e) { echo $e->getMessage(); } Result is like this then: Array ( [0] => Array ( [id] => centos5-32 [name] => CentOS 5 - 32 bit [version] => 5 [architecture] => 32 [os] => centos ) [1] => Array ( [id] => centos5-64 [name] => CentOS 5 - 64 bit [version] => 5 [architecture] => 64 [os] => centos ) [2] => Array ( [id] => centos6-32 [name] => CentOS 6 - 32 bit [version] => 6 [architecture] => 32 [os] => centos ) [3] => Array ( [id] => centos6-64 [name] => CentOS 6 - 64 bit [version] => 6 [architecture] => 64 [os] => centos ) [4] => Array ( [id] => ubuntu10-32 [name] => Ubuntu 10 - 32 bit [version] => 10 [architecture] => 32 [os] => ubuntu ) [5] => Array ( [id] => ubuntu10-64 [name] => Ubuntu 10 - 64 bit [version] => 10 [architecture] => 64 [os] => ubuntu ) ) A: Try this: // flatten: function arrayval1($any) { return array_values((array)$any); } function arrayval2($any) { return (array)$any; } // xml objects with xml objects: $oses = $xml->xpath('//OSes/*/*'); // an array of xml objects: $oses = array_map('arrayval1', $oses); // merge to a flat array: $oses = call_user_func_array('array_merge', $oses); // xml objects -> arrays $oses = array_map('arrayval2', $oses); print_r($oses); My result: Array ( [0] => Array ( [id] => centos5-32 [name] => CentOS 5 - 32 bit [version] => 5 [architecture] => 32 [os] => centos ) [1] => Array ( [id] => centos5-64 [name] => CentOS 5 - 64 bit [version] => 5 [architecture] => 64 [os] => centos ) [2] => Array ( [id] => centos6-32 [name] => CentOS 6 - 32 bit [version] => 6 [architecture] => 32 [os] => centos ) [3] => Array ( [id] => centos6-64 [name] => CentOS 6 - 64 bit [version] => 6 [architecture] => 64 [os] => centos ) [4] => Array ( [id] => ubuntu10-32 [name] => Ubuntu 10 - 32 bit [version] => 10 [architecture] => 32 [os] => ubuntu ) [5] => Array ( [id] => ubuntu10-64 [name] => Ubuntu 10 - 64 bit [version] => 10 [architecture] => 64 [os] => ubuntu ) ) If you're using PHP >= 5.3 (ofcourse you are, why whouldn't you) you can omit the nasty tmp function definitions and use cool anonymous functions for the mapping: // an array of xml objects: $oses = array_map(function($os) { return array_values((array)$os); }, $oses);
{ "language": "en", "url": "https://stackoverflow.com/questions/7015084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Difference between I am new to php and would like to know if there are any differences between these server tags : <?php ?> and <? ?> A: The first is a safe open and close tag variation, the second is the so called short-open tag. The second one is not always available, use the first option if it's possible. You could check the availability of short open tags in php.ini, at the short_open_tag. A: The problem with short open tags is that the following: <?xml version="1.0" ?> will cause problems if you're allowed to use short tags (i.e. <? and ?>). <?php is less open to misinterpretation. Whether or not you're allowed to use short tags is defined by the ini directive short_open_tag. A: Also I think shorttags are being removed in one of the upcomming releases. Edit: I was wrong. Farewell <% They will remove support for the ASP style tags, but the PHP short-code tag will remain - so to those on php general who reckon the short-tag is 'depreceated' - hah! ;) http://phpmysqldev.blogspot.com/2007/05/php-6.html A: There is no difference. The ability to use <? ?> is defined in your php.ini file - usually accessed only by the server host. You can find more information here A: Nothing AFAIK, however I have had servers (shared) where the settings do not support shorthand tags <? ?>, so I usually stick with the <?php ?> for good measure. A: Note short_open_tag = Off did not effect the <?= shorthand tag, which is equivalent to <?php echo A: As @erenon explained here: https://stackoverflow.com/a/1808372/1961535 The difference is that short_open_tag in some cases isnt available. You can check the status by accessing the php.ini file but in case of shared hosting server, the host does not always allow edits to php.ini file. You can easily print the phpinfo as explained here: https://www.php.net/manual/en/function.phpinfo.php phpinfo(); search for short_open_tag as shown below It is always better to use full tag because that will always be supported in every version of PHP weather old file or new.
{ "language": "en", "url": "https://stackoverflow.com/questions/1808365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "39" }
Q: Is this a form of a method's parameter accessing other method's parameter? I am an IT student and I'm completely new with Python. In a workshop I worked on there were a few lines in between that I don't really understand how they work and their purpose in the code. Those lines come from a fellow student who successfully ran it and I would like to fully understand. Thank you! Overall, this is my code: class AcademicPublication(): def __init__(self, title, year): self.__year = year self.__title = title self.__authors = [] def addAuthor(self, author_name): self.author_name = author_name self.__authors.append(author_name) def getReference(self): return f"{self.__authors}, {self.__authors}({self.__year}): {self.__title}." class Conference(): def __init__(self, acronym, name): self.acronym = acronym self.name = name self.paper = [] def addPaper(self, conference_paper): self.paper.append(conference_paper) conference_paper.Conference = self conference_paper.acronym = self.acronym conference_paper.name = self.name class ConferencePaper(AcademicPublication): def __init__(self, title, year): super().__init__(title, year) def getReference(self): return super().getReference() + '. In Proceedings of ' + str(self.name) + str(self.acronym) And I'm struggling with this part: self.paper.append(conference_paper) conference_paper.Conference = self conference_paper.acronym = self.acronym conference_paper.name = self.name At first I thought conference_paper is a class attribute, but there was no definition before in the code, and I did some research but I didn't find anything about a parameter from this method accessing another method's parameter.
{ "language": "en", "url": "https://stackoverflow.com/questions/71580403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to iterate through a list of objects with a specific variable? So I have a Deck class which holds a deck list which creates 52 Card objects and stores them in an array list. I can iterate through that deck list using the iterator I have shown but now I want to know how I can modify the iterator to iterate through the deck list for certain variables. For example, I just want to iterate through all the Spades or all the Kings. Thanks. fyi: The DeckIterator is within the Deck class I just didn't know how to format the code on stack. Apologies. public class Card implements Serializable, Comparable<Card> { static final long serialVersionUID = 100; Suit suit; Rank rank; public Card(Rank rank, Suit suit){ this.rank = rank; this.suit = suit; } } public enum Rank { TWO(2), THREE(3), FOUR(4), FIVE(5), SIX(6), SEVEN(7), EIGHT(8), NINE(9), TEN(10), JACK(10), QUEEN(10), KING(10), ACE(11); int value; public static Rank valuesList[] = Rank.values(); Rank(int value){ this.value = value; } public int getValue() { return this.value; } public Rank getNext() { if (this.value == 11) { return valuesList[0]; } else { return valuesList[ordinal() + 1]; } } public int getOrdinal() { return ordinal(); } } public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES; public static Suit suitsList[] = Suit.values(); public Suit randomSuit() { Random random = new Random(); return suitsList[random.nextInt(4)]; } } private class DeckIterator<Card> implements Iterator<Card> { private final Deck deck; private int pos = 0; public DeckIterator(Deck deck) { this.deck = deck; pos = 0; } @Override public boolean hasNext() { return pos < deck.size(); } @Override public Card next() { return (Card) deck.deck.get(pos++); } @Override public void remove() { deck.deck.remove(pos); } } A: You can't; not with this data structure. You have a few options: * *iterate through everything, but abort this iteration at the top if it doesn't match your required state. For example: for (Card card : deck) { if (card.getRank() != Rank.ACE) continue; /* code to deal with aces here */ } *You use stream API constructs to filter. You did not include your Deck class in your paste, but assuming deck.deck is some sort of java.util.List, you can for example do: deck.deck.stream().filter(x -> x.getRank() == Rank.ACE).iterator() which will give you an iterator that iterates through only the aces. A: I just want to iterate through all the Spades or all the Kings. Here we are. new DeckIterator(deck, card -> Rank.KING.equals(card.getRank())); new DeckIterator(deck, card -> Suit.SPADES.equals(card.getSuit())); I fully agree with @rzwitserloot's answer, and will extend his post with my iterator which takes a Predicate to form another iterator that runs over only selected elements. class DeckIterator implements Iterator<Card> { private final Iterator<? extends Card> iterator; public DeckIterator(Deck deck, Predicate<Card> predicate) { iterator = deck.deck.stream().filter(predicate).iterator(); } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Card next() { return iterator.next(); } @Override public void remove() { iterator.remove(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/54593223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: scala: Specifying method type for currying The following method type describes a function that passes configuration info and data to a method. Each method of this type can perform a different function. type FTDataReductionProcess =(PipelineConfiguration,RDDLabeledPoint) => RDDLabeledPoint The above works fin. But what I would like to do is different. I want to add the configuration to the method first, and then later add the data. So I need currying. I thought this would work: type FTDataReductionProcess =(PipelineConfiguration)(RDDLabeledPoint) => RDDLabeledPoint but this causes a compilation error Cannot resolve symbol RDDLabeledPoint Any suggestions would be appreciated A: You want a function that takes a PipelineConfiguration and returns another function that takes an RDDLabeledPoint and returns an RDDLabeledPoint. * *What is the domain? PipelineConfiguration. *What is the return type? A "function that takes RDDLP and returns RDDLP", that is: (RDDLabeledPoint => RDDLabeledPoint). All together: type FTDataReductionProcess = (PipelineConfiguration => (RDDLabeledPoint => RDDLabeledPoint)) Since => is right-associative, you can also write: type FTDataReductionProcess = PipelineConfiguration => RDDLabeledPoint => RDDLabeledPoint By the way: the same works for function literals too, which gives a nice concise syntax. Here is a shorter example to demonstrate the point: scala> type Foo = Int => Int => Double // curried function type defined type alias Foo scala> val f: Foo = x => y => x.toDouble / y // function literal f: Foo = $$Lambda$1065/1442768482@54089484 scala> f(5)(7) // applying curried function to two parameters res0: Double = 0.7142857142857143
{ "language": "en", "url": "https://stackoverflow.com/questions/48481614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to change column If another column has a special word on python? I have a long dataframe and I want to apply for every rows, I want to do this if 'word' in column 1 I want to change column2, but word will get dictionary.key, and column2 will get dictionary.value di = {'btw':'By The Way','afk':'Away From Keyboard'} A: Using apply: df['temp'] = df['sentences'].apply(lambda x:[j for j in di.keys() if j in x] df['shortly'] = df['temp'].apply(lambda a:','.join([di[key] for key in a])) df.drop(['temp'],axis = 1,inplace=True) Output: >>> df sentences shortly 0 btw I have to go By The Way 1 i am afk now Away From Keyboard The above would work even if there are multiple short forms in a single sentence, only the output will be separated with , in shortly column (you can change the separator in second apply statement). eg. sentences temp shortly 0 btw I have to go [btw] By The Way 1 i am afk btw [btw, afk] By The Way,Away From Keyboard If the short-forms can be a different case than in the dictionary, then just add .lower() in the first apply statement like so: df['temp'] = df['sentences'].apply(lambda x:[j for j in di.keys() if j in x.lower()] keep all the shortforms in dictionary as lower case though
{ "language": "en", "url": "https://stackoverflow.com/questions/66633231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Encoding issue with accented letter passenger RoR I have a bug when I run a RoR application on an Ubuntu server, my config is : ubuntu 14.04 - nginx - passenger 5.0.9 - rbenv - ruby 2.2.2 - rails 4.2.1. Everything works fine with a default config but when I try to change an environment variable and put an accented letter in it, I get an error when I read it from Ruby. My locales are correctly set to en_US.UTF-8. The error occurs in an HAML file. The backtrace is https://gist.github.com/Uelb/207cd29ffd91185529b6 . When I get the env variable from my console and send a to_json, I have no error and I see the accented letter correctly. A: I managed to solve the issue by explicitly setting the env variable LC_ALL to LC_ALL=en_US.UTF-8 in the rbenv-vars plugin file.
{ "language": "en", "url": "https://stackoverflow.com/questions/30710936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: rename regex not working in cygwin I am using cygwin under windows 7. In my directory there are files like fort.100 fort.101 ... fort.1xx I want to give them all an extension _v1. When I try to achieve it using rename by rename 's/$/_v1/' fort.* the prompt exit with no errors and nothing happens. I then tried rename -e 's/$/_v1/' fort.*, an error pops up, rename: unknown option -- e I also tried with a different delimiter @ instead of / with no luck. Now, I thought it was due to the character _ in the expression (I am a newbie to regex), I tried escaping it by \_ with no luck either. Again a try without _, for example, rename 's/$/v11/' fort.* - nothing happens again. Although I achieved my goal by for file in fort.*; do mv $file $file\_v1; done, I wonder why rename doesn't work. What am I doing wrong here? Is it because I am on cygwin? A: The manual of rename does not match your expectations. I see no regex capability. SYNOPSIS rename [options] expression replacement file... DESCRIPTION rename will rename the specified files by replacing the first occur‐ rence of expression in their name by replacement. OPTIONS -v, --verbose Give visual feedback which files where renamed, if any. -V, --version Display version information and exit. -s, --symlink Peform rename on symlink target -h, --help Display help text and exit. EXAMPLES Given the files foo1, ..., foo9, foo10, ..., foo278, the commands rename foo foo0 foo? rename foo foo0 foo?? will turn them into foo001, ..., foo009, foo010, ..., foo278. And rename .htm .html *.htm will fix the extension of your html files. for what you want to reach the easy way is: for i in fort*; do mv ${i} ${i}_v1 ; done A: I have found a workaround. I replaced the util-linux rename to perl rename a separate package. This was provided from @subogero from GitHub. All the usual rename expressions is working.
{ "language": "en", "url": "https://stackoverflow.com/questions/44279062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Send Azure Service Bus messages to Blob or Azure Data Factory Can someone let me know if its possible to send Azure Service Bus messages, (Service Bus Queues, in particular) to Azure Data Factory or Blob Storage. According to the following link, there isn’t a connector for Service Bus with ADF. However, it does state that its possible to send messages to Blob Store. But unfortunately, I can’t find any information on how to send messages to blob storage. Has anyone come across any links? https://learn.microsoft.com/en-us/answers/questions/424698/suggest-solution-for-reading-data-from-azure-servi.html A: If you're looking to turn Azure Service Bus into a Storage Blob, that's probably easy to achieve. You need a Service Bus trigger to retrieve the message payload and its ID to use as a blob name, storing the payload (message body) using whatever mechanism you want. Could be using Storage SDK to write the contents into a blob. Or a blob output binding with a random blob name. Or the message ID as the blob name. Below is an example of a function that will be triggered by a new message in Service bus queue called myqueue and will generate a blob named after message's ID in the messages container. In-process SDK public static class MessageTriggeredFunction { [FunctionName(nameof(MessageTriggeredFunction))] public static async Task Run( [ServiceBusTrigger("myqueue", Connection = "ServiceBusConnectionString")]string payload, string messageId, [Blob("messages/{messageId}.txt", FileAccess.Write, Connection = "StorageAccountConnectionString")] Stream output) { await output.WriteAsync(Encoding.UTF8.GetBytes(payload)); } } Isolated worker SDK public class MessageTriggeredFunctionIsolated { [Function(nameof(MessageTriggeredFunctionIsolated))] [BlobOutput("messages/{messageId}.txt", Connection = "StorageAccountConnectionString")] public string Run( [ServiceBusTrigger("myqueue", Connection = "ServiceBusConnectionString")] string payload, string messageId) { return payload; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/71244270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I need to implement a function that can be used multiple times I have one swift function and that I want to convert into objective C can any one help me to convert it? Any help will be appreciated func getdata(_ send: NSString) { let url=URL(string:send as String) do { let allContactsData = try Data(contentsOf: url!) let allContacts = try JSONSerialization.jsonObject(with: allContactsData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject] print(allContacts) if let musicJob = allContacts["Attendance"] as? [Any], !musicJob.isEmpty { print(musicJob) dataArray = allContacts["Attendance"] as! NSArray print(dataArray) } } { let send: String = String(format:"http://182.18.182.91/RaosMobileService/Service1.svc/GetStudentAttendance_ByMonth/%@/%@/1/%d/2017",loadedUserName,studentId,row+1) self.getdata(send as NSString) } How to convert this into objective C, Any help pls. I need to use this func getdata(_ send: NSString) multiple times A: NSJSONSerialization in Objective-c TRY 1: If Json return Array -(void)getdata:(NSString *)send { NSURL *url = [[NSURL alloc]initWithString:send]; NSData *data = [[NSData alloc] initWithContentsOfURL:url]; NSError *e = nil; NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e]; if (!jsonArray) { NSLog(@"Error parsing JSON: %@", e); } else { for(NSDictionary *item in jsonArray) { NSLog(@"Item: %@", item); } } } TRY 2: If Json return Dictinary -(void)getdata:(NSString *)send { NSURL *url = [[NSURL alloc]initWithString:send]; NSData *data = [[NSData alloc] initWithContentsOfURL:url]; NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves|| NSJSONReadingMutableContainers error:nil]; NSLog(@"%@",res); } To call Method: NSString *send = [NSString stringWithFormat:@"http://182.18.182.91/RaosMobileService/Service1.svc/GetStudentAttendance_ByMonth/%@/%@/1/%d/2017"]; [self getdata:send];
{ "language": "en", "url": "https://stackoverflow.com/questions/42572728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: NHAPI PID 13.1 Segment home phone is not able to get created Please Help me on this : I have stuct on this line.I'm not getting pid 13.1 Which is a Home Phone-Telephone number.Please tell me how to get this segment created. I'm using : NHAPI V231 adtA04.PID.GetPhoneNumberHome(0).PhoneNumber.Value = "(456)120-1478"; Note: Phone number is not the correct segment here. A: homePhone = a01.PID.GetPhoneNumberHome(0).TelecommunicationUseCode.Value; businessPhone = a01.PID.GetPhoneNumberBusiness(0).TelecommunicationUseCode.Value;
{ "language": "en", "url": "https://stackoverflow.com/questions/35172290", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I snap to grid a value between 0 and 1 let's say I have a value that is between 0 and 1. I have a grid size and would like the value to snap to grid. so if grid size is equal to two I would like to switch from 0 to 1 if grid size equal to three this would switch from 0, 0.5 to 1 if it's four 0, 0.33, 0.66, 1 and so on... A: Assuming the language you use has a round function that rounds to the nearest integer, and calling v the value and n the grid size: round(v * (n-1)) / (n-1)
{ "language": "en", "url": "https://stackoverflow.com/questions/69166380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Typescript - Access property of class using it's string name I'm having this class: import { SoapNotePage } from "../pages/forms/soap-note/soap-note"; export class FormMapper { public static SOAP_NOTE = SoapNotePage; } It is easy to access this property, see the following example: open(item){ if(item.id == 1){ this.navCtrl.push(FormMapper.SOAP_NOTE, { patientId: 509070, formId: 75598 }); } } But what I want is to access the "SOAP_NOTE" property by it's string name, kind of dynamically, for example like this: this.navCtrl.push(FormMapper['SOAP_NOTE'], { patientId: 509070, formId: 75598 }); The reason I'm asking this, is that the "item" paramater of the function "open(item)" may contain the property name of the FormMapper class. Is there any way of doing this? A: You can do this: function open(item: keyof typeof FormMapper) { console.log(FormMapper[item]); } That way you restrict item values to be keys of the FormMapper class, and the compiler won't complain.
{ "language": "en", "url": "https://stackoverflow.com/questions/45939326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: multiple url link variables index.php?dc=downloads&dl=all&sort=id shows all downloads, and sorts by id inside of downloads.php it GETs the variables dl and sort to query MySQL accordingly, to display the tables on downloads.php I have the links Show <a href="index.php?dc=downloads&dl=all">All</a>, tools, etc that set the dl variable to display certain tables but now, I want to be able to set another variable sort when the user clicks on one of the sort links from the list, without it resetting the dl variable Sort by <a href="index.php?dc=downloads&sort=id>id</a> wouldn't work because it would reset dl A: There are quite a few ways of doing this, but the easiest way, given the code you have supplied, is just to input the current $_GET['dl'] value. Like so: <a href="index.php?dc=downloads&sort=id&dl=<?=$_GET['dl']?>" >id</a> <?=$_GET['dl']?>: This will take the dl value that is currently in the get parameters and place it into your link. A better method would probably be to check if there is already a dl value in the GET parameters first: <? if(isset($_GET['dl']) && $_GET['dl'] != ''): ?> <a href="index.php?dc=downloads&sort=id&dl=<?=$_GET['dl']?>">id</a> <? else: ?> <a href="index.php?dc=downloads&sort=id">id</a> <? endif; ?> This way, you wont end up with a link like index.php?dc=download&sort=id&dl= if dl hasn't yet been set.
{ "language": "en", "url": "https://stackoverflow.com/questions/17417002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Issue on LEMP configuration and how can i redirect to NodeJS request to NGINX I configured a LEMP server on Ubuntu with NodeJS but I'm getting the following error on browser. "The page you are looking for is temporarily unavailable. Please try again later." how can i redirect to NodeJS request to NGINX .Can you please help me how can i sort out these issues. A: If NGINX work through PHP-FPM (FastCGI Process Manager) then you can uncomment the important part for PHP is the location ~ \.php$ {} stanza in the default vhost which is defined in the file vi /etc/nginx/sites-available/default like [...] location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; } [...] And for NodeJS you can also modify the same Vhost file vi /etc/nginx/sites-available/default and add lines below location ~ \.php$ {} stanza like [...] location /testapp/ { proxy_pass http://localhost:3000/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } [...] from this you can forwarding port to Node.js app with Nginx Now you can access the your page by this URL http://localhost/testapp/ instead of http://localhost:3000/ Hope It will work for you
{ "language": "en", "url": "https://stackoverflow.com/questions/22218665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cant remove commit from Master GIT I can't remove a commit from master. I tried lots of commands from stackOverflow, but nothing works. Last command git revert 655734672ea28811e0723981853f05cbcdda8ec8 just changed the commit. This how it looks now. .............................................(master) $ git log commit ddd171a390ce613a87e7f4e00135b48a1b03c2ad (HEAD -> master) Author: pet......... <[email protected]> Date: Sat Mar 7 15:08:57 2020 +0000 Revert "adding jacoco-maven-plugin" This reverts commit 655734672ea28811e0723981853f05cbcdda8ec8.` commit 655734672ea28811e0723981853f05cbcdda8ec8 (_D) Author: pet.... <[email protected]> Date: Sat Mar 7 13:42:48 2020 +0000 adding jacoco-maven-plugin A: git revert creates a new commit undoing the changes from a given commit. It seems that the operation you described produces the desired result. Read also: How to undo (almost) anything with Git . A: Git is: * *distributed, meaning, there is more than one repository; and *built specifically to make removing commits a little difficult: it "likes" to add commits, not remove them. Your original question left off the fact that, having added two commits, you published them to GitHub. (You did eventually note this in a comment.) If you really do want to remove some commits, you must now convince every Git that has them to give them up. Even if/when you manage this, they won't go away immediately: in general, you get at least 30 days to change your mind and bring them back again. But we won't get into that here. Let's just look at how you convince one Git to discard some commit(s), using git reset. We'll use git reset --hard here for reasons we won't get into properly. Be aware that git reset --hard destroys uncommitted work, so before you do that, make sure you do not have anything uncommitted that you do want to save. As Tarek Dakhran commented, you probably wanted git reset --hard HEAD^^. You'll need more than that, though—and before you blindly any of these commands, it is crucially important that you understand two things: * *what this kind of git reset is going to do; *what HEAD^^ means. To get there, and see how to reset your GitHub repository too, let's do a quick recap of some Git basics. Git stores commits Git is all about commits. Git is not really about branches, nor is it about files. It's about commits. The commit is your fundamental unit of storage in Git.1 What a commit contains comes in two parts. First, each commit holds a full snapshot of all of your files. This isn't a set of changes since a previous commit! It's just the entire set of files, as a snapshot. That's the main bulk of a typical commit, and because it is, the files that are stored in a commit like this are stored in a special, read-only, Git-only, frozen form. Only Git can actually use these files, but the up-side of this is that making hundreds or thousands of snapshots doesn't take lots of space. Meanwhile, the rest of the commit consists of metadata, or information about the commit: who made it, when, and so on. This metadata ties each new commit to some existing commit. Like the snapshot, this metadata is frozen forever once you make the commit. Nobody and nothing can change it: not you, and not even Git itself. The unchangeable-ness of every part of a commit is what makes commits great for archival ... and quite useless for getting any new work done. This is why Git normally extracts one commit for you to work on. The compressed, dehydrated, and frozen-for-all-time files come out and get defrosted and rehydrated and turned back into ordinary files. These files aren't in Git at all, but they let you get your work done. That's part of why a --hard reset is relatively dangerous (but not the whole story). We'll ignore these usable files here and just concentrate on the commits themselves. Every commit has a unique hash ID. The hash ID of a commit is the commit, in a sense. That hash ID is reserved for that commit, and only that commit can ever use it. In a way, that hash ID was reserved for that commit before you made the commit, and is still reserved for that commit even after you manage to remove it. Because the ID has to be unique—and reserved for all time for that commit—it has to be a truly enormous number. That's why commit hash IDs are so big and ugly, like 51ebf55b9309824346a6589c9f3b130c6f371b8f (and even these aren't big enough any more—they only count to about 1048—and Git is moving to bigger ones). The uniqueness of these hash IDs means that every Git that has a clone of some repository can talk to any other Git that has a clone of the same repository, and just exchange hash IDs with the other Git. If your Git has 51ebf55b9309824346a6589c9f3b130c6f371b8f and their Git doesn't, then you have a commit they don't, and they can get it from you. Now you both have 51ebf55b9309824346a6589c9f3b130c6f371b8f. That would be all there is to it, except for the part where we said that every commit can store the hash ID(s) of some earlier commit(s). Commit 51ebf55b9309824346a6589c9f3b130c6f371b8f stores commit hash ID f97741f6e9c46a75b4322760d77322e53c4322d7. That's its parent: the commit that comes just before it. 1A commit can be broken down into smaller units: commit objects, trees and sub-trees, and blob objects. But that's not the level on which you normally deal with Git. This is the key to Git and branches We now see that: * *Every commit has a big ugly hash ID, unique to that commit. *Every commit contains the hash ID of some earlier commit, which is the parent of that commit. (A commit can contain two parent hash IDs, making the commit a merge commit, but we won't get into these here.) When anything contains a commit hash ID, we say that thing points to the commit. So commits form backwards-pointing chains. If we use single uppercase letters to stand in for hash IDs, we can draw this kind of chain of commits like this. Imagine we have a nearly-new repository with just three commits in it. We'll call them A, B, and C, even though in reality they have some random-looking hash IDs. Commit C is the last commit, so it points back to B: B <-C But B has a backwards-pointing arrow (really, a stored hash ID) pointing to A: A <-B <-C Commit A is special. Being the very first commit ever made in this repository, it can't point back, so it doesn't. Adding new commits to a repository just consists of writing out the new commit such that it points back to the previous last commit. For instance, to add a new commit we'll call D, we just draw it in: A <-B <-C <-D No part of any existing commit can change, but none does: C doesn't point to D, D points to C. So we're good here, except for one thing. These hash IDs, in a real repository, don't just increment like this. We have big ugly things like 51ebf55b9309824346a6589c9f3b130c6f371b8f and f97741f6e9c46a75b4322760d77322e53c4322d7. There's no obvious way to put them in order. How do we know which one is last? Given any one hash ID, we can use that commit to find the previous commit. So one option would be: extract every commit in the repository, and see which one(s) don't have anything pointing back to them. We might extract C first, then A, then B, then D, or some other order, and then we look at all of them and realize that, hey, D points to C points to B points to A, but nobody points to D, so it must be the last one. This works, but it's really slow in a big repository. It can take multiple minutes to check all that stuff. We could write down the hash ID of the last commit (currently D), perhaps on a scrap of paper or whiteboard. But we have a computer! Why not write it down in the computer? And that's what a branch name does: it's just a file, or a line in a file, or something like that,2 where Git has scribbled down the hash ID of the last commit in the chain. Since this has the hash ID of a commit, it points to a commit: A--B--C--D <-- master We can get lazy now and stop drawing the arrows between commits, since they can never change, but let's keep drawing the ones from the branch names, because they do change. To add a new commit to master, we make a new commit. It gets some random-looking hash ID that we'll call E, and it points back to D. Then we'll have Git write the hash ID of new commit E into the name master, so that master points to E now: A--B--C--D--E <-- master Let's create a new branch name, feature, now. It too points to existing commit E: A--B--C--D--E <-- feature, master Now let's create a new commit F. Which branch name gets updated? To answer that last question, Git uses the special name HEAD. It stores the name of the branch into the HEAD file.3 We can draw this by attaching the special name HEAD to one of the two branches: A--B--C--D--E <-- feature, master (HEAD) Here, we're using commit E because we're on branch master, as git status would say. If we now git checkout feature, we continue using commit E, but we're now on branch feature, like this: A--B--C--D--E <-- feature (HEAD), master Now let's create new commit F. Git will make F point back to E, the current commit, and will then make the current branch name point to new commit F: A--B--C--D--E <-- master \ F <-- feature (HEAD) We've just seen how branches grow, within one repository. 2Git currently uses both methods to store branch-to-hash-ID information. The information may be in its own file, or may be a line in some shared file. 3This HEAD file is currently always a file. It's a very special file: if your computer crashes, and when it recovers, it removes the file HEAD, Git will stop believing that your repository is a repository. As the HEAD file tends to be pretty active, this is actually a bit common—not that the computer crashes often, but that when it does, you have to re-create the file to make the repository function. Git is distributed When we use Git, we hardly ever have just have one repository. In your case, for instance, you have at least two repositories: * *yours, on your laptop (or whatever computer); and *your GitHub repository, stored over in GitHub's computers (that part of "the cloud"). Each of these repositories has its own branch names. This is what is about to cause all our problems. To make your laptop repository, you probably ran: git clone <url> This creates a new, empty repository on your laptop. In this empty repository, it creates a remote, using the name origin. The remote stores the URL you put in on the command line (or entered into whatever GUI you used), so that from now on, instead of typing in https://github.com/... you can just type in origin, which is easier and shorter. Then your Git calls up that other Git, at the URL. The other Git, at this point, lists out its branch names and the hash IDs that these branch names select. If they have master and develop, for instance, your Git gets to see that. Whatever hash IDs those names select, your Git gets to see those, too. Your Git now checks: do I have this hash ID? Of course, your Git has nothing yet, so the answer this time is no. (In a future connection, maybe the answer will be yes.) Your Git now asks their Git to send that commit. Their Git is required to offer your Git the parent of that commit, by its hash ID. Your Git checks: do I have this commit? This goes on until they've sent the root commit—the commit A that has no parent—or they get to a commit you already have. In this way, your Git and their Git agree on what you have already and what you need from them. They then package up everything you need—commits and all their snapshotted files, minus any files you might already have in commits you already have—and send all that over. Since this is your very first fetch operation, you have nothing at all and they send everything over, but the next time you get stuff from them, they'll only send anything new. Let's suppose they have: A--B--C--D--E <-- master (HEAD) \ F <-- feature (your Git does get to see their HEAD). Your Git will ask for and receive every commit, and know their layout. But your Git renames their branches: their master becomes your origin/master, and their feature becomes your origin/feature. These are your remote-tracking names. We'll see why your Git does this in a moment. Your Git is now done talking with their Git, so your Git disconnects from them and creates or updates your remote-tracking names. In your repository, you end up with: A--B--C--D--E <-- origin/master \ F <-- origin/feature Note that you don't have a master yet! As the last step of git clone, your Git creates a branch name for you. You can choose which branch it should create—e.g., git clone -b feature means create feature—but by default, it looks at their HEAD and uses that name. Since their HEAD selected their master, your Git creates your master branch: A--B--C--D--E <-- master (HEAD), origin/master \ F <-- origin/feature Note that the only easy way you have of finding commit F is by your remote-tracking name origin/feature. You have two easy ways to find commit E: master and origin/master. Now, let's make a new commit on master in the usual way. This new commit will have, as its parent, commit E, and we'll call the new commit G: G <-- master (HEAD) / A--B--C--D--E <-- origin/master \ F <-- origin/feature Note that your master, in your laptop Git, has now diverged from their master, over on GitHub, that your laptop Git remembers as origin/master. Your master is your branch. You get to do whatever you want with it! Their master is in their repository, which they control. fetch vs push Let's make a couple more commits in our master now: G--H--I <-- master (HEAD) / A--B--C--D--E <-- origin/master \ F <-- origin/feature Note that, so far, we have not sent any of these commits to the other Git. We have commits G-H-I on our master, on the laptop, or wherever our Git is, but they don't have these at all. We can now run git push origin master. Our Git will call up their Git, like we did before, but this time, instead of getting stuff from them we will give stuff to them, starting with commit I—the commit to which our master points. We ask them: Do you have commit I? They don't, so we ask them if they have H, and G, and then E. They do have E so we'll give them the G-H-I chain of commits. Once we've given them these three commits (and the files that they need and don't have—obviously they have E so they have its snapshot, so our Git can figure out a minimal set of files to send), our Git asks them: Please, if it's OK, set your master to point to I. That is, we ask them to move their master branch, from the master name we used in our git push origin master. They don't have a mat1/master to keep track of your repository. They just have their branches. When we ask them to move their master like this, if they do, they'll end up with: A--B--C--D--E--G--H--I <-- master (HEAD) \ F <-- feature They won't lose any commits at all, so they'll accept our polite request. Their name master now points to commit I, just like our name master, so our Git adjusts our remote-tracking name: G--H--I <-- master (HEAD), origin/master / A--B--C--D--E \ F <-- origin/feature (Exercise: why is our G on a line above the line with E? Why didn't we draw it like this for their repository?) git reset makes removing commits locally easy Now, let's suppose commits H and I are bad and you'd like to get rid of them. What we can do is: git checkout master # if needed git reset --hard <hash-of-G> What this will do, in our repository, we can draw like this: H--I <-- origin/master / A--B--C--D--E--G <-- master (HEAD) \ F <-- origin/feature Note that commits H and I are not gone. They are still there, in our repository, findable by starting with the name origin/master, which points to commit I. From there, commit I points back to commit H, which points back to commit G. Our master, however, points to commit G. If we start from here, we'll see commit G, then commit E, then D, and so on. We won't see commits H-I at all. What git reset does is let us point the current branch name, the one to which HEAD is attached, to any commit anywhere in our entire repository. We can just select that commit by its hash ID, which we can see by running git log. Cut and paste the hash ID from git log output into a git reset --hard command and you can move the current branch name to any commit. If we do this, and then decide that, gosh, we want commits H-I after all, we can just git reset --hard again, with the hash ID of commit I this time, and make master point to I again. So aside from wrecking any uncommitted work, git reset --hard is sort of safe. (Of course, wrecking uncommitted work is a pretty big aside!) We still have to get their Git to change: we need more force Moving our master back to G only gets us updated. The other Git, over on GitHub ... they still have their master pointing to commit I. If we run git push origin master now, we'll offer then commit G. They already have it, so they'll say so. Then we'll ask them, politely: Please, if it's OK, make your master point to commit G. They will say no! The reason they'll say no is simple: if they did that, they'd have: H--I [abandoned] / A--B--C--D--E--G <-- master (HEAD) \ F <-- feature Their master can no longer find commit I. In fact, they have no way to find commit I. Commit I becomes lost, and so does commit H because commit I was how they found commit H. To convince them to do this anyway, we need a more forceful command, not just a polite request. To get that forceful command, we can use git push --force or git push --force-with-lease. This changes the last step of our git push. Instead of asking please, if it's OK, we send a command: Set your master! Or, with --force-with-lease, we send the most complicated one: I think your master points to commit I. If so, make it point to G instead! Then tell me whether I was right. The --force-with-lease acts as a sort of safety check. If the Git over on GitHub lists not just to you, but to other Gits as well, maybe some other Git had them set their master to a commit J that's based on I. If you're the only one who sends commits to your GitHub repository, that obviously hasn't happened, and you can just use the plain --force type of push. Again: --force allows you to tell another Git: move a name in some arbitrary way, that doesn't necessarily just add commits. A regular git push adds commits to the end of a branch, making the branch name point to a commit "further to the right" if you draw your graph-of-commits the way I have been above. A git push that removes commits makes the branch name point to an earlier commit, losing some later commit, or—in the most complicated cases—does both, removes some and adds other commits. (We haven't drawn this case and we'll leave that for other StackOverflow answers ... which already exist, actually, regarding rebasing.) Recap * *Branch names find the last commit in a branch (by definition). *Making new commits extends a branch, by having the new commit point back to the previous tip, and writing the new commit's big ugly random-looking hash ID into the branch name. *git reset allows you to move branch names around however you like. This can "remove" commits from the branch (they still exist in the repository, and maybe there's another way to find them). *git push asks some other Git to move its branch names. It defaults to only allowing branch-name-moves that *add8 commits. Hence, since you have pushed the commits you want to "remove", you'll need to git reset your own Git, but then git push --force or git push --force-with-lease to get the GitHub Git to do the same thing. What HEAD^ etc are about When we were looking for ways to "remove" commits with git reset, I suggested: * *Run git log (and here I'll suggest using git log --decorate --oneline --graph, which is so useful that you should probably make an alias, git dog, to do it: D.O.G. stands for Decorate Oneline Graph). *Cut-and-paste commit hash IDs. This works, and is a perfectly fine way to deal with things. It's a bit clumsy sometimes, though. What if there were a way to say: starting from the current commit, count back two commits (or any other number)? That is, we have some chain of commits: ...--G--H--I--... We can pick out one commit in the chain, such as H, by its hash ID, or any other way. Maybe it has a name pointing to it: ...--G--H <-- branchname \ I--J <-- master (HEAD) Using the name branchname will, in general, select commit H. If Git needs a commit hash ID, as in git reset, the name branchname will get the hash ID of commit H. Using the name HEAD tells Git: look at the branch to which HEAD is attached, and use that name. Since HEAD is attached to master, and master points to J, the name HEAD means "commit J*, in places where Git needs a commit hash ID. This means we could run: git reset --hard branchname right now and get: ...--G--H <-- branchname, master (HEAD) \ I--J [abandoned] The name branchname selects commit H, and git reset moves the branch name to which HEAD is attached—master—to the commit we select. Note, by the way, that: git reset --hard HEAD means: look at the name HEAD to figure out which commit we're using now, then do a hard reset that moves the current branch name to that commit. But since that's the commit we're using now, this "moves" the name to point to the same commit it already points to. In other words, move to where you're standing already ... ok, don't move after all. So this git reset --hard lets us throw out uncommitted work, if that's what we need to do. In any case, adding a single caret ^ character after any branch name or hash ID means select that commit's parent. So since branchname means commit H, branchname^ means commit G. If we have: ...--F--G--H--I <-- master (HEAD) then master^ and HEAD^ both mean commit H. Adding another ^ tells Git to do that again: master^^ or HEAD^^ means commit G. Adding a third ^ selects commit F, and so on. If you want to count five commits back, you can write master^^^^^ or HEAD^^^^^, but it's easier to use master~5 or HEAD~5. Once you get past "two steps back", the tilde ~ notation is shorter. Note that you can always use the tilde notation anyway: master~1 and master^ both count one commit back. You can omit the 1 here too, and write master~ or HEAD~. (There is a difference between ^2 and ~2. For more about this, see the gitrevisions documentation.)
{ "language": "en", "url": "https://stackoverflow.com/questions/60579091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Angularjs dynamic table I have following json string to generate report in angularjs: { "result": [{name:"AUS ba",date":"02-01-2014", "result": "pass","time" : "morning","reason":"ok"}], "result": [{name:"SA ba",date":"02-01-2014", "result": "pass","time" : "afternoon","reason":"ok"}], "result": [{name: "NZ ba",{"date":"02-01-2014", "result": "fail","time" : "morning","reason":"ok"}], "result": [{name:"AUS ba","date":"03-01-2014", "result": "pass","time" : "morning","reason":"ok"}], "result": [{name:"SA ba",date":"03-01-2014", "result": "fail","time" : "morning","reason":"batch failed"}], "result": [{name: "NZ ba",date": "03-01-2014", "result": "fail","time" : "morning","reason":"batch error"}] } Currently I am generating table in simple format using ng-repeat: Name Date Result Reason Time AU ba 02-01-2014 PASS Ok Morning AU ba 03-01-2014 ... AU ba 04-01-2014 ... ........... ........... Now I want to dynamically create table like this 02-01-2014 02-01-2014 02-01-2014 02-01-2014 03-01-2014 03-01-2014 Morning Morning Afternoon Afternoon Morning Morning AU ba Pass[Result] ok[Reason] Fail Ok Pass ok SA ba Fail batch failed Could somebody please help me with this? A: You could make a table with one row and then ng-repeat the columns in that row. In each column you can then make a table with 4 rows and one column: http://plnkr.co/edit/3xvdGC?p=preview (I reformatted your JSON data to be able to work with it) However, this will give problems if the text of some table cells require multiple lines. To solve that you could just use multiple ng-repeat statements: http://plnkr.co/edit/EUKNn5?p=preview A: Write your html like this: <body> <table ng-controller="MyCtrl"> <tr> <td ng-repeat="r in result"> <table border=1> <tr> <td> {{r.date}} </td> </tr> <tr> <td> {{r.result}} </td> </tr> <tr> <td> {{r.time}} </td> </tr> <tr> <td> {{r.reason}} </td> </tr> </table> </td> </tr> </table> </body> You will find a plunker here Note that i reformated your json, dropped some data and left all the fancy formating to you. A: You can just use ng-repeat multiple times for each label: http://jsfiddle.net/4HHc2/2/ After reformatting your json string as an array of results, you can just call each item as follows: <td ng-repeat="d in data">{{d.date}}</td>
{ "language": "en", "url": "https://stackoverflow.com/questions/21649441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to keep css style in a code/pre tag in markdown? I'm facing an issue while writing a markdown document. I'd like to insert a diff code output from the console, containing colors, transformed to HTML via a script, something like this: # Some title The following code as been updated: <pre> <code> <span style="color:green;">+</span><span style="color:green;"> if ($url !== $newUrl) {</span> <span style="color:green;">+</span><span style="color:green;"> $newDomain = parse_url($newUrl, PHP_URL_HOST);</span> </code> </pre> **Thank you** I've added some Markdown just to show some context. The problem is, using pre/code, the code structure is correct (correctly formated lines). If I change it (switching to code/pre), or changing code or pre to div, I loose either the line breaks, or the coloration. Here's the output of the above markdown: https://fiddle.md/tmvmwvztfd5d92xk65dwfx A: I know that Github have a diff expression who let you do something like this : https://gist.github.com/salmedina/ad8bea4f46de97ea132f71b0bca73663#file-markdowndiffexample-md But I thinks that there is no such way to do what your want in Markdown. Regards.
{ "language": "en", "url": "https://stackoverflow.com/questions/46221700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Entity Framework 4 + Oracle: Working in local pc but not on Windows Server 2008 R2 I'm trying to create a sample project with EF4 for an Oracle Database. In my PC I created a project. Some of the characteristics (if more info is needed please say so) * *Visual Studio 2010 *Entity Framework 4.1 with DB First + DbContext *Platform target "Any CPU" *Oracle BD 11g *My DB connection was created by using "Server Explorer" -> "Data Connections" -> "Oracle Data Provider for .NET" *I have one Oracle Home 11.2 with both client_32 and client_64 folders *I make no reference to Oracle.DataAccess.Client in my project *In my GAC I find Oracle.DataAccess vs 2.112.3.0 x86, 2.112.1.0 x86, 2.112.4.0 AMD64, 2.112.3.0 AMD64, 2.112.1.0 AMD 64 *listing my pc providers I get * *Odbc Data Provider Version=4.0.0.0 *OleDb Data Provider Version=4.0.0.0 *OracleClient Data Provider Version=4.0.0.0 *SqlClient Data Provider Version=4.0.0.0 *Oracle Data Provider for .NET Version=4.112.4.0 *Microsoft SQL Server Compact Data Provider Version=3.5.1.0 *Microsoft SQL Server Compact Data Provider 4.0 Version=4.0.0.0 Running the project (that makes a simple add using one of the entities generated by the EF) in my pc, works fine. The server: * *Windows Server 2008 R2 Standard *1 Oracle home in app64/32, vs 11.2 *All my IIS AppPools can run 32bit *In GAC I have Oracle.DataAccess 2.112.1.0 x86 and AMD64 *listing for providers I can see * *Odbc Data Provider Version=4.0.0.0 *OleDb Data Provider Version=4.0.0.0 *OracleClient Data Provider Version=4.0.0.0 *SqlClient Data Provider Version=4.0.0.0 When running the program on the server i get the following error: "[ArgumentException: Unable to find the requested .Net Framework Data Provider. It may not be installed.] System.Data.Common.DbProviderFactories.GetFactory(String providerInvariantName)" Looking at the providers I realized that the provider "Oracle Data Provider for .NET" was missing in the server, so i tried multiple oracle installations (ODAC, ODP, XCopy) but nothing seems to work, althouth several files were installed (I used the existing oracle home), the provider keeps not showing, in the registry, under SOFTWARE\ORACLE\ODP.NET I keep only seeing 2.112.1.0 version. After this i tried to deploy my exe with the oracle DLLs and even change the app.config to include <system.data> <DbProviderFactories> <remove invariant="Oracle.DataAccess.Client" /> <add name="Oracle Data Provider for .NET" invariant="Oracle.DataAccess.Client" description="Oracle Data Provider for .NET" type="Oracle.DataAccess.Client.OracleClientFactory, Oracle.DataAccess, Version=4.112.3.0, Culture=neutral, PublicKeyToken=89b483f429c47342"/> </DbProviderFactories> but i get the following error: System.Data.EntityException: The underlying provider failed on Open -> Oracle.DataAccess.Client.OracleException: ORA-12557: TNS:protocol adapter not loadable. Searched for the error and somewhere i found i should try the EZConnect form (user/pass@host:port/sid) but then i get a configuration exception... As of right now, other aplications that were running using oracle (I can't see how these are running) stopped working, so I'll have to go back befora all my installations... I've been in this for 3 days now and I really don't know what to do. After the server has been restores does anyone know what else can i try? ========================= UPDATE 1 ================================ After my server got restored to before all this i noticed something i forgot to check in regedit I have: * *HKEY_LOCAL_MACINE/SOFTWARE/ORACLE/KEY_OraClient11g_home1/ORACLE_HOME -> D:\app64\product\11.2.0 Obviously I have my oracle stuff with 64bit, so my next move was to change my program for 64bit. This resulted in the same error, after that i figured i needed to instal the 64bit ODAC. I downloaded ODAC112021Xcopy_x64 and installed it. With this the Oracle Data Provider for .NET Version appears (but version 4.112.2.0). Running my app now gives the following error : system.data. provider incompatible exception: the store provider factory type 'Oracle.DataAccess.Client.OracleClientFactory' does not implement the IServiceProvider interface After searching for the error I wen to check GAC64 bits. I can see oracle.dataaccess.dll in C:\Windows\Microsoft.NET\assembly\GAC_64\Oracle.DataAccess\v4.0_4.112.2.0__89b483f429c47342. What should be my next step? unistall this odac and try some newer version of 11? reading this (http://netdevelopmentmanfreddahmen.blogspot.pt/2013/07/c-error-store-provider-factory-type.html) it seems you need, for EF, version 112.3.0 or later and .Net 4 or later And guess what? tchanan!! it worked :) Good news is that, installing this ODAC did not affected (as far as i could see) the remaining and already running apps using oracle. NOTE: I installed ODAC using the command install.bat all D:\app64\produc t\11.2.0 Oracle - OraClient11g_home1 A: In resume: .NET + EF + ORACLE Prerequisites * *.Net 4 or above *At least one Oracle Home installed *ODAC 11.2.0.3.0 or above *Make sure the bit signature of oracle and of your software are the same *In case you are using 32bit, be sure that the appPools allow 32bit NOTE: EF version does not seem to matter
{ "language": "en", "url": "https://stackoverflow.com/questions/32860642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Access to a string in an ES6 Set object I am using this library to find the email address in a string. https://github.com/sindresorhus/get-emails I am struggling to access to the result. getEmails(text); //=> Set {'[email protected]', '[email protected]'} typeof getEmails(text); // 'object' How to get access to the first email address in this object? A: It looks like getEmails actually returns an ES6 Set object, not an array: Get first email: // Option 1 (ugly but efficient) let first = getEmails(text).values().next().value // Option 2 (pretty but inefficient) first = [...getEmails(text)][0] console.log(first) Iterate over all emails: for (let email of getEmails(text)) { console.log(email) } A: The README is misleading. The code returns an array of email addresses, so you can just access it by index: var firstAddress = getEmails(text)[0]; edit — I'm wrong; the comment really is accurate, because it returns a Set instance! I'll leave this here and accept my downvotes in penance. A: You can loop through all the values in the object via this: var emails = getEmails(); for (email in emails) { console.log(emails[email]) }
{ "language": "en", "url": "https://stackoverflow.com/questions/42587565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there an easy way to transform a tensor (3D array) to a 2D array of the tensor slices as the vectors in MATLAB? Consider a 3D matrix t of size d1 x d2 x d3. Is there a an easy way of making the matrix (2D array) of size d1d2 x d3? so the naive implementation/pseudo-code would be something like: T % d1 x d2 x d3 M % d1d2 x d3 for i=1:d3 t_slice = t(:,:,i); m = reshape(t_slice, [d1d2, 1]); %columns of t_slice are the vector M(:,i) = m; end but it seemed something that should already be implemented or some library in matlab that already does this. Doing this by hand seems a little inefficient and I was suspecting that there was some clever MATLAB trick to do this. Am I right? Ideally I thought something like: M = reshape(T,[d1d2, d3]) would exist, but wasn't sure or couldn't find it yet... I actually also mean to ask, is it possible to convert that matrix back to its tensor in a nice way in MATLAB? A: Your idea is fine. What's wrong with what you had in your question at the bottom? M = reshape(T, [d1*d2 d3]); This would unroll each 2D slice in your 3D tensor into a single column and stack all of the columns together into a 2D matrix. I don't see where your problem lies, other than the fact that you didn't multiply d1 and d2 together. In general, you would want to do this, given T: M = reshape(T, [size(T,1)*size(T,2) size(T,3)]); Or, you can let MATLAB infer the amount of columns by doing: M = reshape(T, size(T,1)*size(T,2), []); To address your other question, to go back from the converted 2D matrix into its original 3D tensor, just do: T2 = reshape(M, d1, d2, d3); In our case, this would be: T2 = reshape(M, size(T,1), size(T,2), size(T,3)); Bear in mind that you must be cognizant of the original dimensions of T before doing this. Remember, reshape works by going over column by column and reshaping the matrix to whatever dimensions you see fit. This will now take each column and convert it back into a 2D slice, then do this for all columns until you get your original 3D matrix back. To illustrate going back and forth, suppose we have this matrix T: >> T = randi(10,3,3,3) T(:,:,1) = 9 10 3 10 7 6 2 1 10 T(:,:,2) = 10 10 2 2 5 5 10 9 10 T(:,:,3) = 8 1 7 10 9 8 7 10 8 To get our unrolled slices so that they fit into columns, use the first line of code above and you you should get a 9 x 3 matrix: >> M = reshape(T, size(T,1)*size(T,2), []) M = 9 10 8 10 2 10 2 10 7 10 10 1 7 5 9 1 9 10 3 2 7 6 5 8 10 10 8 As you can see, each column is a slice from the 3D tensor unrolled into a single vector. Each column takes every column of a slice and stacks them on top of each other to get a single column. To go backwards: >> T2 = reshape(M, size(T,1), size(T,2), size(T,3)) T2(:,:,1) = 9 10 3 10 7 6 2 1 10 T2(:,:,2) = 10 10 2 2 5 5 10 9 10 T2(:,:,3) = 8 1 7 10 9 8 7 10 8 As you can see, both T and T2 are the same.
{ "language": "en", "url": "https://stackoverflow.com/questions/31815234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Uncaught Error: Class 'PhpAmqpLib\Connection\AMQPStreamConnection' not found I have installed RabbitMQ, Composer and its dependencies like vendor folder and phpamqplib successfully. But, still it is giving me an error that AMQPStreamConnection not found. Can anyone help me? Here, is my code- <?php require_once __DIR__ . '/vendor/autoload.php'; use PhpAmqpLib\Connection\AMQPStreamConnection; use PhpAmqpLib\Message\AMQPMessage; $connection = new AMQPStreamConnection('localhost', 15672, 'guest', 'guest'); $channel = $connection->channel(); $channel->queue_declare('task_queue', false, true, false, false); $data = implode(' ', array_slice($argv, 1)); if (empty($data)) { $data = "Hello World!"; } $msg = new AMQPMessage( $data, array('delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT) ); $channel->basic_publish($msg, '', 'task_queue'); echo ' [x] Sent ', $data, "\n"; $channel->close(); $connection->close(); ?> A: Most probbably this is because php-amqplib could not be installed properly. I had issues with composer install that I did not know because of which php-amqplib could not be installed. composer.json "php-amqplib/php-amqplib": ">=2.9.0" Issues with composer install: Then I ran composer update but that gave issues as well because of some libraries in composer.json Then I finally I had to run following command to see successful installation of php-amqplib which resolved the issue. This command could be different for you as there could be different issues with installation on your system. Just keep an eye on composer command outputs. Command: composer update --no-plugins --no-scripts magento-hackathon/magento-composer-installer Output: PHP File: <?php require_once('../../app/Mage.php'); Mage::app(); require_once '../../vendor/autoload.php'; use PhpAmqpLib\Connection\AMQPStreamConnection; use PhpAmqpLib\Message\AMQPMessage; $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->queue_declare('rabbitmq-dev', false, false, false, false); $msg = new AMQPMessage('Hello World!'); $channel->basic_publish($msg, '', 'hello'); echo " [x] Sent 'Hello World!'\n"; $channel->close(); $connection->close(); ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/52660406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Ajax only effects 1 button, instead of all buttons So I want to set up my index.php so that when the like button is clicked, ajax is used to go to liked_button.php and change the look of the button to 'Liked'. This works, for one button, the first button. It doesn't work for all the other buttons on the page. Liking another button other than the first button, makes it appear as if the first button was liked. So my question is, how do I apply this ajax code to 'ALL' of the like buttons on index.php? Here is the index.php : <!doctype html> <head> <?php include('header.php'); ?> <script> $(document).ready(function(){ $(".button").click(function(){ $.ajax({url:"liked_button.php",success:function(result){ $("#like_system").html(result); }}); }); }); </script> </head> <link type="text/css" rel="stylesheet" href="index.css"> <body> <?php $conn = mysqli_connect("localhost","root","") or die ("No SQLI"); mysqli_select_db($conn, "sample") or die ("No DB"); $sqli = "SELECT * FROM `photos` ORDER BY `id` DESC"; $result = mysqli_query($conn, $sqli) or die ("No query"); while($row = mysqli_fetch_assoc($result)) { $username = $row['username']; $title = $row['title']; $description = $row['description']; $image_name = $row['image_name']; $image_id = $row['image_id']; $random_directory = $row['random_direc']; $date = date('Y-m-d'); $image_info = "http://localhost/splindr_2.0/photos/$random_directory/$image_id"; echo "<div id=contentWrapper'> <div id='photo'> <div id='actual_image'> <img src='$image_info'> </div> <div id='like_system'><button type='button' class='button' name='button'>Like</button></div> <div id='info_wrapper'> <div id='info_header'>Title: $title &nbsp By: $username &nbsp Date: $date</div> <div id='description'>$description</div> </div> </div> </div>";//end contentWrapper } ?> </body> </html> Here is the liked_button.php : <!doctype html> <html> <head> <link type="text/css" rel="stylesheet" href="liked_button.css"> </head> <body> <button type="button" id="button_pressed">Liked</button> </body> </html> A: Here's the basic idea: $(document).ready(function(){ $(".button").click(function(){ var t=$(this); $.ajax({url:"liked_button.php",success:function(result){ t.replaceWith("<button type='button' id='button_pressed'>Liked</button>") }}); }); }); Your other issue is that you use id overly much. Replace all looped uses of id (including in the code I gave you) with class, or else your code won't work. A: HTML IDs (such as your like_system) must be unique. Your update selector is finding the first one every time. Try something like: $(".button").click(function(){ var clicked = $(this); $.ajax({url:"liked_button.php",success:function(result){ clicked.closest('div').html(result); }}); }); And either remove the like_system ID, or replace it with a class if you need to style it, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/23918452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pass an array type as generic type parameter to a VHDL package? I'm working on a generic package (list) in VHDL-2008. This package has a type generic for the element type. If I declare an array type of this element type within the package, it's a new type. So for e.g. integer, my new integer_array would be incompatible with integer_vector from library ieee. So I need also to pass in the array type (e.g. integer_vector). When an array instance of that array type is used with a 'range attribute, it gives me a warning in QuestaSim: Prefix of attribute "range" must be appropriate for an array object or must denote an array subtype. How do a denote that a generic type parameter is an array? Generic Package: package SortListGenericPkg is generic ( type ElementType; -- e.g. integer type ArrayofElementType; -- e.g. integer_vector function LessThan(L : ElementType; R : ElementType) return boolean; -- e.g. "<" function LessEqual(L : ElementType; R : ElementType) return boolean -- e.g. "<=" ); function inside (constant E : ElementType; constant A : in ArrayofElementType) return boolean; end package; package body SortListGenericPkg is function inside (constant E : ElementType; constant A : in ArrayofElementType) return boolean is begin for i in A'range loop -- this line causes the error if E = A(i) then return TRUE ; end if ; end loop ; return FALSE ; end function inside ; end package body; Instantiation: package SortListPkg is package SortListPkg_int is new work.SortListGenericPkg generic map ( ElementType => integer, ArrayofElementType => integer_vector, LessThan => "<", LessEqual => "<=" ); alias Integer_SortList is SortListPkg_int.SortListPType; end package SortListPkg ; A: ModelSim makes a similar error/warning, so it's maybe a VHDL standard issues. A workaround is to declare ArrayofElementType as part of the package, like: package SortListGenericPkg is generic ( type ElementType -- e.g. integer ); type ArrayofElementType is array (integer range <>) of ElementType; function inside(constant E : ElementType; constant A : in ArrayofElementType) return boolean; end package; and then convert the argument when inside is called, like: ... inside(int, ArrayofElementType(int_vec)); or simple use ArrayofElementType as type when declaring the argument if possible/feasible.
{ "language": "en", "url": "https://stackoverflow.com/questions/40595461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Repository pattern in entity framework model-first design I could not find any exact information which platforms are suitable for repository pattern implementation. I have a MySQL DB and console app that is written in VS 2010. I am using Entity Framework 4 and my database is imported to VS project by model-first approach. Is this configuration suitable for implementing a repository pattern or do i have to use min. EF 5, VS 2012, also code-first approach, MSSQL or etc.? If my configuration is suitable for implementing repository pattern, would you suggest me an article to implement repository pattern. A: Implementing a pattern is not related to a technical framework you might want to use. It's all about abstraction. So if you really do understand a pattern you can implement it. Well ok, you shouldn't try to implement e.g. the bridge pattern in assembler. ;o) But if you are going to use a programming language with object oriented concepts like C#, VB, C++ or Java (I know, that there are a lot of other possibilities) you will achieve your goal.
{ "language": "en", "url": "https://stackoverflow.com/questions/14340923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dividing numbers between rows in MySQL + PHP Hi I am working on a kind of raffle system which divides 1 million random numbers into an x amount of tickets, e.g. 1 million random numbers to 10,000 tickets. Each ticket is a row in a database, we then have another table ticket numbers in which i need to give 100 numbers to each ticket they are related by the ticket id. So at the moment this is my code: //Amount of the 1 million tickets divided to the tickets $numbersPerTickets = $_POST['numbersPerTicket']; //The total cost of the property $propertyPrice = $_POST['propertyPrice']; //The total amount of tickets $totalTickets = NUMBER_CIELING / $numbersPerTickets; //The ticket price $ticketPrice = $propertyPrice / $totalTickets; //Generate array with random numbers up to 999,999 $randomTicketNumbers = createTicketNumbers(); //Creation loop counter $ticketCreationCount = 1; //Loop and create each ticket while($ticketCreationCount <= $totalTickets) { //Create a padded ticket number $ticketNumber = str_pad($ticketCreationCount, 6, 0, STR_PAD_LEFT); $query = ' INSERT INTO tickets( propertyID, ticketNumber, price ) VALUES( "'.$propertyID.'", "'.$ticketNumber.'", "'.$ticketPrice.'" ) '; $db->query($query); //Get the ID of the inserted ticket to use to insert the ticket numbers $ticketID = $db->insert_id; $loopBreak = $numbersPerTickets; $addedNumberCount = 1; foreach($randomTicketNumbers as $key => $value) { $query = ' INSERT INTO ticketNumbers( ticketID, number ) VALUES( "'.$ticketID.'", "'.$value.'" ) '; $db->query($query); unset($randomTicketNumbers[$key]); if($addedNumberCount == $loopBreak){ break; }else{ $addedNumberCount++; } } $ticketCreationCount++; } But this isn't working it adds the right amount of tickets, which in the case for testing is 10,000 but then adds far too many ticket numbers, it ends up exceeding the million numbers in the random tickets array, The random tickets array is just a simple 1 tier array with 1 million numbers sorted randomly. A: Change the foreach loop to for: for ($i = 1; $i <= $numbersPerTickets; $i++) { $query = ' INSERT INTO ticketNumbers( ticketID, number ) VALUES( "'.$ticketID.'", "'.$randomTicketNumbers[$i].'" ) '; Guaranteed to only give you $numbersPerTickets iterations and removes the complexity of the iterator++/break logic. Sometimes simple is better. Please correct my php! TIA.
{ "language": "en", "url": "https://stackoverflow.com/questions/11376038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How convert 2 string columns (date and time) to one timestamp i have table with two columns (both string): | Dates | Times | | -------- | -------------- | |20210401 | 121012 | |20210401 | 121024 | And I would like to combine these columns into one in timestamp format: YYYY-MM-DD HH:MM:SS I tried this, but it is wrong: CONVERT(datetime, CONVERT(CHAR(8), DATES, 112) + ' ' + CONVERT(CHAR(6), TIMES, 108)) A: SQL Server allows you to add datetime values, so that is a convenient data type for this purpose. It is easy to convert the date to a datetime -- it is in a standard format. The time column is tricker, but you can add in ':' for the conversion: select v.*, convert(datetime, v.date) + convert(datetime, stuff(stuff(time, 5, 0, ':'), 3, 0, ':')) from (values ('20210401', '121012')) v(date, time); A: convert(datetime, DATES + ' ' + substring(TIMES, 1, 2) + ':' + substring(TIMES, 3, 2) + ':' + substring(TIMES, 5, 2) , 121)
{ "language": "en", "url": "https://stackoverflow.com/questions/67383925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I give my Flask Apache WSGI App permission to write/append to a file? I am writing a small Flask web-application hosted on an Apache Server running Ubuntu 14. There is a feedback section on the website where one can visit and submit a feedback message which will then be sent to the server, and appended to a text file. Here is the new_feedback method: def new_feedback(name, message): file = open('feedback.txt', "a") file.write(name + ' wrote: ' + message + '\n'+'***********************************'+'\n\n') file.close() However, when the method is called, the Apache server gives the following error in the error.log file. File "/var/www/FlaskApp/FlaskApp/feedback.py", line 2, in new_feedback [Sat Dec 05 13:15:02.825594 2015] [:error] file = open('feedback.txt', "a") [Sat Dec 05 13:15:02.825601 2015] [:error] IOError: [Errno 13] Permission denied: 'feedback.txt' One way I have attempted to debug this, is to run it locally, which has absolutely no issues on my Windows computer. In other words, the logic seems to be alright. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/34112974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Wordpress - create a page with custom URL I have a Wordpress page /users and it displays a list of all users created. Each user has a link to its profile page. What I need to do is create that page. I want it to go like this /users/{user_id}-{first_name}-{last_name}, for example - /users/1-john-doe. I have a template for /users and also for profile pages. Question - how do I properly make a page with that profile template so that it would have the url described above? The page does not need to select the user automatically, it needs to pass the user slug so I can read it in that page and query for that user (as a variable or something). Thanks. A: What you are looking for is the WordPress Rewrite API. This allows you to define a new "endpoint" for your URL's, and allows you to pick up the variable from the URL via built-in WordPress functionality. A great article on it can be found here: Custom Endpoints
{ "language": "en", "url": "https://stackoverflow.com/questions/19182842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Pass javascript variable to php with ajax , Nothing result? MY js page : $m = 77; var xhr = new XMLHttpRequest(); xhr.open("POST", "try.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send("m=" + escape(m)); php page : $var = $_POST['m']; echo $var; When I call php page nothing happens! can you help me? A: Just you need to change variable m to get expected output m = 77; // here what i have changed from $m to m var xhr = new XMLHttpRequest(); xhr.open("POST", "try.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send("m=" + escape(m)); A: You have two problems. Variable names At the top of your code you create a variable called $m but later you try to read m. This will throw a ReferenceError which you would have spotted if you had looked at the Console in your browser's Developer Tools You never look at the response Once you fix that error, your code will make the request … but you don't do anything with the response. You should add a load event listener for that. function alert_response() { alert(this.responseText); } xhr.addEventListener("load", alert_response); Asides * *escape is deprecated because it doesn't work properly. Use encodeURIComponent instead. *PHP sticks a text/html content-type on the response by default, by echoing out user input without modification or filtering, you are vulnerable to XSS attacks. Take steps to defend yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/48060311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Can't close frame in java? Hi guys I am writing a little program in java and it's my first try at anything with an interface/picture. It makes the frame for me but when I click the close button X, it doesn't close it just treats it like nothing happened...any ideas? class Graph extends Canvas{ public Graph(){ setSize(200, 200); setBackground(Color.white); } public static void main(String[] args){ Graph gr = new Graph(); Frame aFrame = new Frame(); aFrame.setSize(300, 300); aFrame.add(gr); aFrame.setVisible(true); } A: Is that java.awt.Frame? I think you need to explicitly add the handler for so: frame.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we){ System.exit(0); } } I used this source for so. If it were swing it would be something like jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) A: add aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); A: class Graph extends Canvas{ public Graph(){ setSize(200, 200); setBackground(Color.white); addWindowListener( new java.awt.event.WindowAdapter() { public void windowClosing( java.awt.event.WindowEvent e ) { System.out.println( "Closing window!" ); dispose() ; System.exit( 0 ); } } ); } public static void main(String[] args){ Graph gr = new Graph(); Frame aFrame = new Frame(); aFrame.setSize(300, 300); aFrame.add(gr); aFrame.setVisible(true); }
{ "language": "en", "url": "https://stackoverflow.com/questions/12707716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using Angular 1.2 and Animate.css for loading animation? I'm trying to get a page to animate in on load using Angular 1.2 and Animate.css. Here's the Plunker: http://plnkr.co/edit/oDiDfRCO2Msc0StNrtqH I'd like the background to crossfade in and the yellow menu on the right side to slide in from the right. In main.html: <div> <div class="background-container"> <my-Background></my-Background> </div> <div class="menu-container"> <my-Menu id="menu"></my-Menu> </div> </div> In main.css: .menu-container.ng-enter { animation:3s fadeInRightBig; } .background-container.ng-enter { animation:3s fadeInDown; } The animations defined in main.css don't seem to get fired. I'm pretty sure its due to the order and/or timing of css being loaded although I might be dealing with more than one issue. What's the "right" way to ensure everything, from an animation standpoint, is loaded and ready in order to make the animations work on load? A: Have you looked at something like an HTML5 loader to load your initial assets when the DOM is loaded. There is a jQuery plugin, I know it is not Angular and another library, but it may help your order of operation. http://gianlucaguarini.github.io/jquery.html5loader/ A: You can try nganimate , an easy documentation for you to refer https://docs.angularjs.org/api/ngAnimate
{ "language": "en", "url": "https://stackoverflow.com/questions/25292936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: setState doesnt render extra one time? Code A: componentDidMount(){ this.dateString = this.props.navigation.getParam('dateString', moment()); } Code B: state = { dateString: moment() } componentDidMount(){ const dateString = this.props.navigation.getParam('dateString', moment()); this.setState({ dateString }) } dateString is a parameter passed from previous screen. I've console.log in render() and found that they appeared to be exactly the same number of times? I was expecting Code B to render one extra time since it uses setState? Which way of above is a better approach? A: Not sure if this is the case in this your specific case, but: React may batch multiple setState calls together. So even if you have multiple async setState calls, there might only one (re-)render. So you shouldn’t rely on the number of calls to render A: Check the value of this.props.navigation.getParam('dateString', moment()) in render and componentDidmount(). If both values are same it wont trigger a re-render as react re-render the components only if state change there if you made it PureComponent. In this jsfiddle you can try running the code by changing Pure and normal component and can see the difference. A: Try to put in the Code B the state inside constructor() method like this: constructor(){ super(); this.state = { dateString: moment() } } I don't usually use to put state floating in the class, I always put him in the constructor.
{ "language": "en", "url": "https://stackoverflow.com/questions/54246824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scroll issue in mootools (In Firefox it's okay but Chrome giving some issue) I have set following code to create a floating navigation menu. It works fine in Firefox but Chrome has some issue. It keep resetting when I manually scroll the bar to it's threshold. var nav = $$('#navigationBar'); var navCord = nav.getCoordinates(); var navHomeY = navCord[0].top; var isFixed = false; var $w = $(window); $w.addEvent('scroll', function(){ var scrollTop = $w.getScroll().y; console.log(scrollTop + ' and ' + navHomeY); var shouldBeFixed = scrollTop > navHomeY; if (shouldBeFixed && !isFixed){ console.log("fix it now"); nav.setStyles({ position: 'fixed', top: 0, left: navCord[0].left, width: navCord[0].width }); isFixed = true; } else if (!shouldBeFixed && isFixed) { nav.setStyles({ position: null, top: null, left: null, width: null }); isFixed = false; } }); }); Here is the console.log output from Chrome. 0 and 25 index.php:532 10 and 25 index.php:532 20 and 25 index.php:532 41 and 25 index.php:532 fix it now index.php:537 0 and 25 index.php:532 (PROBLEM: scrollTop reset happen) Here is the console.log output from Firefox. 9 and 25 17 and 25 26 and 25 fix it now 33 and 25 In short, in Firefox scrollTop behave nicely and doesn't reset to 0 where as in Chrome it does.
{ "language": "en", "url": "https://stackoverflow.com/questions/25707024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: EJB - How to use CRUD code with multiple Persistence Units I would like to equip my EJBs with CRUD methods. I have many entities and multiple persistence units. I want to implement my CRUD methods once and invoke them on different persistence units. I tried to achieve this using inheritance, but it isn't working. The CRUD class is: public class FormEBean<T> { protected EntityManager em; public EntityManager getEm() { return em; } public void setEm(EntityManager em) { this.em = em; } public String create(T entity) { try { em.persist(entity); em.flush(); return null; } catch (Exception ex) { return ex.getLocalizedMessage(); } } public void create(List<T> entityList) { for (T entity : entityList) { em.persist(entity); } } public void edit(T entity) { em.merge(entity); } public void edit(Set<T> entitySet) { Iterator<T> it = entitySet.iterator(); while (it.hasNext()) { T entity = it.next(); em.merge(entity); } } public void remove(T entity) { em.remove(em.merge(entity)); } public void remove(T[] listaDaRimuovere) { for (T entity : listaDaRimuovere) { em.remove(em.merge(entity)); } } public void remove(List<T> listaDaRimuovere) { for (T entity : listaDaRimuovere) { em.remove(em.merge(entity)); } } } So I tryed in this way: @Stateless @Remote(MyEBeanRemote.class) public class MyEBean extends FormEBean<MyEntityClass> implements MyEBeanRemote { @PersistenceContext(unitName = "siat-ejbPU") private EntityManager em; // code here } Even if I haven't got any error, the CRUD functions have no effect on my DataBase. Instead if I insert them directly into MyEBean it behaves as expected. I don't want to use @PersistenceContext(unitName = "siat-ejbPU") in the FormEBean, because EJBs could use different persistence units. Is there a way to solve this problem? Is there a pattern I can use to reuse my code? Edit: The aim of this question is finding a solution that maximizes CRUD code reuse in EJBs belonging to different EJB modules and having different persistence units. Using generic methods in a stateless session bean seems like a good solution, but only for reusing CRUD code for EJBs in the same persistence unit. What solution could be persistence unit independent (if it exists)? A: Hi you can use setter method: @Stateless @Remote(MyEBean.class) public class MyEBean extends FormEBean implements MyEBeanRemote { final Logger logger = LoggerFactory.getLogger(MyEBean.class); @PersistenceContext(unitName = "siat-ejbPU") @Override public void setEmCrud(EntityManager em) { super.setEmCrud(em) } Worked for me. A: You need to make your CRUD methods generic (create/edit/remove). The class named FormEBean should NOT be generic. If you make the methods generic in stead of the class, you can implement them once and use them with any entity class. Generic crud methods might look something like this: public <T> T create(T someEntity) { em.persist(someEntity); return someEntity; } public <T> void create(Collection<T> entities) { for (T entity : entities) { em.persist(entity); } } public <T> void edit(T entity) { em.merge(entity); } public <T> void edit(Collection<T> entities) { for (T currentEntity : entities) { em.merge(currentEntity); } } Put those in your session bean and use them anywhere to operate on any entity. /** * Example managed bean that uses our * stateless session bean's generic CRUD * methods. * */ class ExampleManagedBean { @EJB MyCrudBeanLocal crudBean; public void createStuff() { // create two test objects Customer cust = createRandomCustomer(); FunkyItem item = createRandomItem(); // use generic method to persist them crudBean.create(cust); crudBean.create(item); } } This answer does exactly what I describe and provides example code: * *EJB 3 Session Bean Design for Simple CRUD Another example: * *EJB with Generic Methods A: I found a solution that solves the problem. It's based on jahroy's answer, but uses inheritance to deal with multiple persitence units. The common code is a base class (not generic but with generic methods): public class FormEBean { final Logger logger = LoggerFactory.getLogger(FormEBean.class); protected EntityManager emCrud; public EntityManager getEmCrud() { return emCrud; } public void setEmCrud(EntityManager em) { emCrud = em; } public <T> String create(T entity) { String exception = null; try { emCrud.persist(entity); emCrud.flush(); } catch (Exception ex) { //ex.printStackTrace(); exception = ex.getLocalizedMessage(); } return exception; } public <T> void create(List<T> entityList) { for (T entity : entityList) { emCrud.persist(entity); } } public <T> void edit(T entity) { emCrud.merge(entity); } public <T> void edit(Set<T> entitySet) { Iterator<T> it = entitySet.iterator(); while (it.hasNext()) { T entity = it.next(); emCrud.merge(entity); emCrud.flush(); } } public <T> void remove(T entity) { emCrud.remove(emCrud.merge(entity)); } public <T> void remove(T[] listaDaRimuovere) { for (T entity : listaDaRimuovere) { emCrud.remove(emCrud.merge(entity)); } } public <T> void remove(List<T> listaDaRimuovere) { for (T entity : listaDaRimuovere) { emCrud.remove(emCrud.merge(entity)); } } } ... and this is the interface: public interface FormEBeanRemote { public void setEmCrud(EntityManager em); public <T> String create(T entity); public <T> void create(List<T> entityList); public <T> void edit(T entity); public <T> void edit(Set<T> entitySet); public <T> void remove(T entity); public <T> void remove(T[] listaDaRimuovere); public <T> void remove(List<T> listaDaRimuovere); } The EJB (stateless session bean) looks like this: @Stateless @Remote(MyEBean.class) public class MyEBean extends FormEBean implements MyEBeanRemote { final Logger logger = LoggerFactory.getLogger(MyEBean.class); @PersistenceContext(unitName = "siat-ejbPU") private EntityManager em; public EntityManager getEm() { return em; } public void setEm(EntityManager em) { this.em = em; } @PostConstruct public void postConstruct() { this.setEmCrud(em); } ...where @Remote public interface MyEBeanRemote extends FormEBeanRemote { ...... } Note that the EJB uses the postConstruct method to set the entityManager, which is delegated to perform CRUD operations on a specific persistence unit. It's working like a charm so far. If someone finds any pitfalls please let me know.
{ "language": "en", "url": "https://stackoverflow.com/questions/12113213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is a safe way to use pointers as keys for an NSMutableDictionary? In a project, I have data objects XXData and objects which represent these objects visually XXDataVisual. There can be up to 10'0000 objects which need to be loosely coupled. Only the XXDataVisual knows the represented XXData. @interface XXDataVisual @property (strong) XXData *data; @end The XXData must not know it's visual representation: @interface XXData // Elements @end To manage the visual representations, I need an efficient lookup which visual representation exists for a given data element. Can I use the pointer of the XXData instances as a key to safely identify the the data elements? Which is the best approach using modern Objective-C and Cocoa? A: To have an NSDictionary-type collection where your keys are pointers, you might be needing an NSMapTable class. From this link: NSMapTable (as the name implies) is more suited to mapping in a general sense. Depending on how it is constructed, NSMapTable can handle the "key-to-object" style mapping of an NSDictionary but it can also handle "object-to-object" mappings — also known as an "associative array" or simply a "map". A: Using NSMutableDictionary is bad idea. It copies keys, so your memory usage will increase dramatically. Use NSMapTable. You can configure it to use non-copyable keys and storing weak references to values, for example: NSMapTable *mapTable = [NSMapTable mapTableWithKeyOptions:NSMapTableStrongMemory valueOptions:NSMapTableWeakMemory];
{ "language": "en", "url": "https://stackoverflow.com/questions/22182688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Labeling coordinates on an image using Python I have an input image and a dataframe with 1000 rows and 3 columns, an X coordinate, Y coordinate, and a Label (0-5). I want to read in my image, find each of the coordinates on the image from the dataframe and label them by to color depending on the label column and display the image. My DataFrame is something like this. data = {'X': [200, 246, 387, 86, 100], 'Y': [100, 200, 34, 98, 234], 'Texture': [0,1,2,3,4]} df = pd.DataFrame(data) I can plot a single point (200, 200) import matplotlib.pyplot as plt img = plt.imread('../data/textures/test/test_image.jpg') fig, ax = plt.subplots() ax.imshow(img, extent=[0, 400, 0, 300]) ax.plot(200, 200, 'x', color='firebrick') A: As far as I understood you want to mark certain pixels based on a label and you have the pixel/label as a data frame. You only need to define markers and colors and iterate over your data frame. The following will do this import pandas as pd import matplotlib.pyplot as plt data = {'X': [200, 246, 387, 86, 100], 'Y': [100, 200, 34, 98, 234], 'Texture': [0,1,2,3,4]} data = pd.DataFrame(data) img = plt.imread("img.jpg") # Define symbols and colors as you want. # Item at ith index corresponds to that label in 'Texture'. color = ['y', 'r', 'b', 'g', 'm'] marker = ['o', 'v', '1', 's', 'p'] # fig, ax = plt.subplots() ax.imshow(img, extent=[0, 400, 0, 300]) # for _, row in data.iterrows(): ax.plot(row['X'], row['Y'], marker[row['Texture']],color=color[row['Texture']]) plt.show() If you have your data as python dictionary, you can Zip the dictionary values and iterate over them. The following will do it, import matplotlib.pyplot as plt data = {'X': [200, 246, 387, 86, 100], 'Y': [100, 200, 34, 98, 234], 'Texture': [0,1,2,3,4]} img = plt.imread("img.jpg") # Define symbols and colors as you want. # Item at ith index corresponds to that label in 'Texture'. color = ['y', 'r', 'b', 'g', 'm'] marker = ['o', 'v', '1', 's', 'p'] # Zip the data, returns a generator of paired (x_i, y_i, texture_i) data_zipped = zip(*(data[col] for col in data)) # fig, ax = plt.subplots() ax.imshow(img, extent=[0, 400, 0, 300]) # for x,y, texture in data_zipped: ax.plot(x, y, marker[texture],color=color[texture]) plt.show()
{ "language": "en", "url": "https://stackoverflow.com/questions/73380512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create http query in Flask Python I am trying to work with querys in Flask. I have a page choose.html where you can click buttons. these should be sent in a query then to page 2. So page 2 should be rendered by Flask with the query e.g. 127.0.0.1/login?username=test&color=3 I have tried the following so far (hard coded): <a href="{{ url_for('login?username=test&color=3') }}"><button class="continue" id="submit" name="submit">Continue</button></a> @app.route('/login', methods=['post', 'get']) def login(): message = request.args.get('username') That was the response: werkzeug.routing.BuildError: Could not build url for endpoint 'login?username=test'. Did you mean 'login' instead? A: Found out the answer: {{ url_for('login', user='foo', name='test') }} This will create a query like this: http://127.0.0.1:10000/login?user=foo&name=test
{ "language": "en", "url": "https://stackoverflow.com/questions/74826679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Erlang install on Freebsd 10 on Amazon ec2 I'm trying to install erlang on amazon ec2 - on freebsd 10: fetch http://www.erlang.org/download/otp_src_17.0.tar.gz gunzip -c otp_src_17.0.tar.gz | tar xf - cd otp_src_17.0 ./configure --disable-hipe gmake gmake install and I get the following error: configure: error: Perl is required to generate v2 to v1 mib converter script configure: error: /bin/sh '/usr/home/ec2-user/otp_src_17.0/lib/snmp/./configure' failed for snmp/. configure: error: /bin/sh '/usr/home/ec2-user/otp_src_17.0/lib/configure' failed for lib How do I avoid this error and install erlang on freebsd 10? A: Use either packages ("pkg install erlang"), or ports (cd /usr/ports/lang/erlang && make install). Software often requires patches to make it run correctly, and ports/packages take care of that. They also automatically take care of dependencies, and that seems to be the root cause of your problem: you don't have perl installed. A: So, I think you can install package I have FreeBSD storage 10.1-RELEASE-p16 FreeBSD 10.1-RELEASE-p16 #0 And simple way is pkg install erlang A: There's kerl which is an excellent project for building and maintaining all Erlang/OTP versions
{ "language": "en", "url": "https://stackoverflow.com/questions/23476805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Checking if an input is formatted correctly in Python 3 so I've been assigned an assignment (obviously) to check if an input that a user has entered is formatted correctly, in the way AA99AAA (where A is a letter and 9 is a number from 0 to 9). So for the first character in the input, it would have to be a letter or python would return some sort of error and so on, you get the idea. I've got no clue where to start with this, I've tried looking around and haven't found anything - I guess I just don't know what it is I'm looking for. Any pointers would be greatly appreciated, thanks! A: To do this, you could split the string into 3 parts (the first group of letters, the numbers, and then the second group of letters). Then you can use s.isalpha() and s.isnumeric(). For example: while True: c=input('Password: ') if len(c)==7 and c[:2].isalpha() and c[2:4].isnumeric() and c[4:].isalpha(): break else: print('Invalid input') print('Valid input') A: Could you provide more information regarding the question, is the example you have provided the format you are attempting to match? AA99AAA, so 2-alpha, 2-numeric, 3-alpha? There are two approaches off the top of my head you could take here, one would be to utilize regular expressions to match on something like [\w]{2}[\d]{2}[\w]{3}, alternatively you could iterate through the string (recall that strings are character arrays). For this approach you would have to generate substrings to isolate parts you are interested in. So.. for c in user_input[0:2]: if c.isdigit: print('Invalid Input') for c in user_input[3:5]: ... ... There are definitely more pythonic ways to approach this but this should be enough information to help you formalize a solution. A: I finally did it! After about an hour... So I used [] formatting and .isdigit/.isalpha to check each part of the code, like recommended above, however I did it in a slightly different way: while True: regNo = input("Registration number:") if len(regNo) != 7: print("Invalid Registration Number! Please try again") elif regNo[:2].isdigit(): print("Invalid Registration Number! Please try again!") elif regNo[2:4].isalpha(): print("Invalid Registration Number! Please try again!") elif regNo[4:].isdigit(): print("Invalid Registration Number! Please try again!") else: break Hopefully this helps anyone else who stumbles across this problem!
{ "language": "en", "url": "https://stackoverflow.com/questions/40209158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to access ASP.NET Core web server from another device I created a project using C# and ASP.NET Core empty and it worked on localhost - how can I access it from another device using the IP of the computer running the project? A: You need to configure kestrel to bind requests from 0.0.0.0 instead of localhost to accept requests from everywhere. You can achieve this with different methods. 1- Run application with urls argument dotnet app.dll --urls "http://0.0.0.0:5000;https://0.0.0.0:5001" 2- Add kestrel config to appsettings.json (Or any other way that you can inject value to IConfiguration) { ... "Kestrel": { "Endpoints": { "Http": { "Url": "http://0.0.0.0:5000" }, "Https": { "Url": "https://0.0.0.0:5001" } } } ... } 3- Hard-code your binding in the program.cs file. and the result should look like this For complete details, please visit https://learn.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel/endpoints
{ "language": "en", "url": "https://stackoverflow.com/questions/71044525", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Syntax Error in Java print statement System.out.println("if(line.contains(\"<string key=\"concept:name\" value=\"LCSP\"/>\"\))"); I am getting an error. I want to print above statement as a string. Can someone help me. A: Remove the last backslash \ there is no need to escape ) System.out.println("if(line.contains(\"<string key=\"concept:name\" value=\"LCSP\"/>\"))"); DEMO1 Solution to the problem given in comment String v11 = "John"; System.out.println("if(line.contains(\"<string key=\\\"concept:name\\\" value=\\\""+v11+"\\\"/>\"))"); OUTPUT if(line.contains("<string key=\"concept:name\" value=\"John\"/>")) DEMO2 A: no need to escape ')' at end of the line. the changed statement is: System.out.println("if(line.contains(\"<string key=\"concept:name\" value=\"LCSP\"/>\"))"); A: Original System.out.println("if(line.contains(\"<string key=\"concept:name\" value=\"LCSP\"/>\"**\**))"); **** is not required I have removed from Original Changed: System.out.println("if(line.contains(\"<string key=\"concept:name\" value=\"LCSP\"/>\"))"); A: String v11 = "John1"; System.out.println("if(line.contains(\"<string key=\\\"concept:name\\\" value=\\\""+v11+"\\\"/>\"))"); remove the last backlash and update the "LCSP" to v11 variable. output: if(line.contains("<string key=\"concept:name\" value=\"John1\"/>"))
{ "language": "en", "url": "https://stackoverflow.com/questions/32789495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Getting data for a video fails Using the following call: https://www.googleapis.com/youtube/v3/videos?part=snippet&id=whatever&key=whatever We get the following response: { "error": { "errors": [ { "domain": "usageLimits", "reason": "accessNotConfigured", "message": "Access Not Configured. YouTube Data API has not been used in project 755558787820 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/youtube.googleapis.com/overview?project=755558787820 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.", "extendedHelp": "https://console.developers.google.com/apis/api/youtube.googleapis.com/overview?project=755558787820" } ], "code": 403, "message": "Access Not Configured. YouTube Data API has not been used in project 755558787820 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/youtube.googleapis.com/overview?project=755558787820 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry." } } We checked the project (truthorange), and the Youtube Data API has been enabled (since 2017 or so). Everything was actually fine until 5/11, but starting with 5/12, this started failing for some reason. Any ideas oh how to fix?
{ "language": "en", "url": "https://stackoverflow.com/questions/62218683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I perform a threaded sparse matrix - vector multiplication using MKL? I need to perform a matrix vector multiplication, where the matrix is complex, symmetric and has four off-diagonal non-zero bands. So far I am using the sparse BLAS routine mkl_zdiasymv to perform the multiplication and it works fine on one core. I would like to try if I can gain a performance boost by using multi-threading (e.g. openMP). As far as I have understood some (many?) of the MKL routines are threaded. However if I use mkl_set_num_threads(4) my program still runs on one single thread. To give a specific example here is a little test program which I compile (using icc 14.01) with: icc mkl_test_mp.cpp -mkl -std=c++0x -openmp mkl_test_mp.cpp: #include <complex> #include <vector> #include <iostream> #include <chrono> typedef std::complex<double> complex; using std::vector; using namespace std::chrono; #define MKL_Complex16 std::complex<double> #include "mkl.h" int vector_dimension = 10000000; int number_of_multiplications = 100; vector<complex> initialize_matrix() { complex value_main_diagonal = complex(1, 2); complex value_sub_and_super_diagonal = complex(3, 4); complex value_far_off_diagonal = complex(5, 6); std::vector<complex> matrix; matrix.resize(1 * vector_dimension, value_main_diagonal); matrix.resize(2 * vector_dimension, value_sub_and_super_diagonal); matrix.resize(3 * vector_dimension, value_far_off_diagonal); return matrix; } vector<complex> perform_matrix_vector_calculation(vector<complex>& matrix, const vector<complex>& x) { mkl_set_num_threads(4); vector<complex> result(vector_dimension); char uplo = 'L'; // since the matrix is symmetric we only need to declare one triangular part of the matrix (here the lower one) int number_of_nonzero_diagonals = 3; vector<int> matrix_diagonal_offsets = {0, -1, -int(sqrt(vector_dimension))}; complex *x_data = const_cast<complex* >(x.data()); // I do not like this, but mkl expects non const pointer (??) mkl_zdiasymv ( &uplo, &vector_dimension, matrix.data(), &vector_dimension, matrix_diagonal_offsets.data(), &number_of_nonzero_diagonals, x_data, result.data() ); return result; } void print(vector<complex>& x) { for(complex z : x) std::cerr << z; std::cerr << std::endl; } void run() { vector<complex> matrix = initialize_matrix(); vector<complex> current_vector(vector_dimension, 1); for(int i = 0; i < number_of_multiplications; ++i) { current_vector = perform_matrix_vector_calculation(matrix, current_vector); } std::cerr << current_vector[0] << std::endl; } int main() { auto start = steady_clock::now(); run(); auto end = steady_clock::now(); std::cerr << "runtime = " << duration<double, std::milli> (end - start).count() << " ms" << std::endl; std::cerr << "runtime per multiplication = " << duration<double, std::milli> (end - start).count()/number_of_multiplications << " ms" << std::endl; } Is it even possible to parallelize this way ? What am I doing wrong ? Are there other suggestions to speed up the multiplication ? A: Since you are not showing how you compile the code, could you check that you are linking against the multi threaded Intel MKL libs and e.g. pthreads? For example (this is for an older version of MKL): THREADING_LIB="$(MKL_PATH)/libmkl_$(IFACE_THREADING_PART)_thread.$(EXT)" OMP_LIB = -L"$(CMPLR_PATH)" -liomp5 There should be an examples directory in your MKL distribution e.g. intel/composer_xe_2011_sp1.10.319/mkl/examples. In there you can check the contents of spblasc/makefile to see how to correctly link against the multithreaded libs for you particular version of MKL. Another suggestion that should speed things up is adding compiler optimisation flags e.g. OPT_FLAGS = -xHost -O3 to allow icc to generate optimised code for your architecture so your line would end up as: icc mkl_test_mp.cpp -mkl -std=c++0x -openmp -xHost -O3
{ "language": "en", "url": "https://stackoverflow.com/questions/20613603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Get sequence of characters from words I wanted to generate a, unique code based on the input given. Input = "ABC DEF GHI" The code generated will be like, "ADG" (first letter of each word) and if this exists then "ABDG" (first two letters of first word and first letter of rest of the words) this exists too then "ABCDG" next is "ABCDEG" and like wise if goes on till a unique code is generated. The validation is made thorough an API. Types of input can be: "ABC" (or) "ABC DEF" (or) "ABC DEF GHI" (or) "ABC DEF GHI JKL" I have tried like, let count = 1; let val = this.userForm.get("name").value; let textArr = val.split(" "); let res; for(let i = 0; i< textArr.length; i++){ res += textArr[i].substring(0,count) } let char1 = "", char2 = "", char3 = ""; let ss:any = val.split(" ", 3); if(ss[0].length > 1) char1 = ss[0].substring(0,2) if(ss[1] && ss[1].length > 0) char2 = ss[1].substring(0,1) if(ss[2] && ss[2].length > 0) char3 = ss[2].substring(0,1) let result = char1 + char2 + char3; this.restApi.validateCode(result).subscribe((data: any) => { console.log(data) // returns boolean }); Couldn't get the logic what I want. Any help? A: You can use this code to generate your desire sequence in order. function generateCandidates(input) { let candidates = []; //associate pointers for each word let words = input.split(" ").map(str => {return {str, ptr:1}}); //First candidate let candidate = words.map(({str,ptr}) => str.substr(0,ptr)).join(""); candidates.push(candidate); //find the first pointer that is still less than the length of the word let word; while( word = words.find(({str,ptr}) => ptr < str.length ) ) { word.ptr++; //increment the pointer candidate = words.map(({str,ptr}) => str.substr(0,ptr)).join(""); candidates.push(candidate); } return candidates; } console.log(generateCandidates("ABC")); console.log(generateCandidates("ABC DEF")); console.log(generateCandidates("ABC DEF GHI")); console.log(generateCandidates("ABC DEF GHI JKL"));
{ "language": "en", "url": "https://stackoverflow.com/questions/70075975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pass String and File data with Volley POST method in Android? I am using Volley to make server requests but i came to know that volley is not passing params from getParams() method in POST request, so now i am passing these data by concatenating all param/values with the url like bellow. String url = "http://myweb/api/work?"+param1+"="+value; Now the problem is it works fine with text data only, i can make request successfully and all params are passing to server but now i have to upload some image file also using same api. How can i pass a file and string data using Volley POST method? Following are the solutions i tried but got no success. https://gist.github.com/anggadarkprince/a7c536da091f4b26bb4abf2f92926594#file-volleymultipartrequest-java https://www.simplifiedcoding.net/android-volley-tutorial-to-upload-image-to-server/ Edit Following is my current request code: StringRequest request = new StringRequest(Request.Method.POST, uri + param, new Response.Listener<String>() { @Override public void onResponse(String response) { dismissProgressDialog(); printResponse(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { dismissProgressDialog(); error.printStackTrace(); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<>(); headers.put("key", key); headers.put("tkey", tkey); headers.put("Content-Type", "application/multipart"); return headers; } }; A: Use Following code VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() { @Override public void onResponse(NetworkResponse response) { String resultResponse = new String(response.data); // parse success output } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("name", "Sam"); params.put("location", "India"); params.put("about", "UI/UX Designer"); params.put("contact", "[email protected]"); return params; } @Override protected Map<String, DataPart> getByteData() { Map<String, DataPart> params = new HashMap<>(); // file name could found file base or direct access from real path // for now just get bitmap data from ImageView params.put("avatar", new DataPart("file_avatar.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mAvatarImage.getDrawable()), "image/jpeg")); params.put("cover", new DataPart("file_cover.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mCoverImage.getDrawable()), "image/jpeg")); return params; } }; VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest); A: VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(com.android.volley.Request.Method.POST, url, new Response.Listener<NetworkResponse>() { @Override public void onResponse(NetworkResponse response) { } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }) { //pass String parameters here @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("category", "image"); params.put("p_name", "myImage"); return params; } //pass header @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<String, String>(); headers.put("key", key); headers.put("tkey", tkey); headers.put("Content-Type", "application/multipart"); return headers; } //pass file here (*/* - means you can pass any kind of file) @Override protected Map<String, VolleyMultipartRequest.DataPart> getByteData() { Map<String, DataPart> up_params = new HashMap<>(); up_params.put("params", new DataPart(file_path, file_name, "*/*")); return up_params; } }; VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
{ "language": "en", "url": "https://stackoverflow.com/questions/44512732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Problems with Programatically selecting checkbox nodes I have a checkbox group Listed in a tree structure.The tree is connected with a vector, which stores the state of checkboxes in the tree. I have buttons to select all checkboxes, and other buttons to select the corresponding checkbox. From the below diagram you can picturize UI. for (CheckBoxNode Node : CheckBoxNodeTree.checkBoxRows) { if(Node.isSelected()){ Node.setSelected(!Node.isSelected()); } For Select All the code used is : TreeModel model = TREE.getModel(); TreeNode rootofTree = (TreeNode) model.getRoot(); Enumeration<TreeNode> enumeratorForTree = ((DefaultMutableTreeNode)rootofTree).breadthFirstEnumeration(); while (enumeratorForTree.hasMoreElements()) { TreeNode child = enumeratorForTree.nextElement(); Object currentNode = ((DefaultMutableTreeNode) child).getUserObject(); if(currentNode instanceof CheckBoxNode) { ((CheckBoxNode) currentNode).setSelected(true); } } for (CheckBoxNode Node: CheckBoxNodeTree.checkBoxRows) { Node.setSelected(true); } The issue i am facing now is that on clicking the respective buttons the checkbox state changes, but after clicking "Select All" button i am able to see that the nodes get checked ,but after this , if i try to select the induvidual nodes using the corresponding button , i cannot see the result on the tree . Can anyone Help me with your suggestions. Thanks to the replier in advance. A: Looks like a notification issue - you are changing node state without the model knowing of it. Assuming your model is a DefaultTreeModel, invoke a model.nodeChanged after changing the selection: currentNode.setSelected(newState); model.nodeChanged(currentNode); A: Where is the code for your buttons used to select individual nodes? Are you trying to make a button that toggles but yours only checks the box right now? Maybe try this: buttonPushed() { //get your node for this button node.setSelected(!node.isSelected()); }
{ "language": "en", "url": "https://stackoverflow.com/questions/9123928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ChromeHeadless not starting: timing out when running ng test I am working on an Angular 7 (7.2.13) app and am having trouble running npm run test, which maps to ng test --watch=false --browsers=ChromeHeadless. I am running Ubuntu under Windows 10 and all of my app-relating command line stuff is done on Ubuntu. This is a requirement of the project, but I've only been here a few weeks and haven't yet found out why! I have installed ChromeHeadless by following these instructions. I set CHROME_BIN=/usr/bin/chromium-browser after doing this. However, it looks like ChromeHeadless is having trouble starting: 27 05 2019 11:26:40.497:INFO [karma-server]: Karma v4.0.1 server started at http://0.0.0.0:9876/ 27 05 2019 11:26:40.500:INFO [launcher]: Launching browsers ChromeHeadless with concurrency unlimited # 27 05 2019 11:26:40.506:INFO [launcher]: Starting browser ChromeHeadless 27 05 2019 11:27:40.507:WARN [launcher]: ChromeHeadless have not captured in 60000 ms, killing. 27 05 2019 11:27:40.724:INFO [launcher]: Trying to start ChromeHeadless again (1/2). It tries again a few times, but just times out. I have seen a few posts about turning on verbose logging, but modifying the captureTimeout has only the effect of making the process slower! Can anyone help? A: I solved an issue with this same message caused by a proxy-blocker of the client. I had to set --proxy-server flag in my customLauncher in karma.conf.js, so the karma server could get the ChromeHeadless and execute the tests perfectly. karma.conf.js browsers: ['MyChromeHeadless'], customLaunchers: { MyChromeHeadless: { base: 'ChromeHeadless', flags: [ '--no-sandbox', '--proxy-bypass-list=*', '--proxy-server=http://proxy.your.company' ] } }
{ "language": "en", "url": "https://stackoverflow.com/questions/56324624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Broadcast Receivers can not get new values from new intent and show the previous values I have alarm manager . when user click on add button , user select time , date and fill title and other ... and after this . I save this into database and show this values into recycle view . I get values and save them into database like this : saveAlarm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final String mTitle = title.getText().toString(); final String mDate = date; final String mTime = time; final String mRepeat = getrepeat.getText().toString(); final String mReport = single_choice_selected_report_as; if (isAnyStringNullOrEmpty(mTitle, mDate, mTime, mRepeat, mReport)) { Snackbar snackbar = Snackbar.make(mainLayout, "", Snackbar.LENGTH_LONG); Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) snackbar.getView(); TextView textView = (TextView) layout.findViewById(com.google.android.material.R.id.snackbar_text); textView.setVisibility(View.INVISIBLE); View snackView = LayoutInflater.from(SetAlarmActivity.this).inflate(R.layout.custom_toast, null, false); TextView txtNoticToExit = (TextView) snackView.findViewById(R.id.txtCustomToast); txtNoticToExit.setText(getResources().getString(R.string.fill_field)); txtNoticToExit.setTypeface(Apps.font); layout.setPadding(0, 0, 0, 0); layout.addView(snackView, 0); snackbar.show(); } else { if (editMode) { Alarm alarm = new Alarm(id, mTitle, mDate, mTime, mRepeat, mReport, active); mDatabase.updateAlarm(alarm); } else { Alarm alarm = new Alarm(mTitle, mDate, mTime, mRepeat, mReport, 0); mDatabase.addAlarm(alarm); } Intent intent = new Intent(SetAlarmActivity.this, AlarmActivity.class); startActivity(intent); SetAlarmActivity.this.finish(); } } In row of my recycle view I have a button to active this item to alarm base on the time . holder.toggleButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int test = alarm.getActive(); state = !state; if (test == 0) { holder.toggleButton.setBackgroundResource(R.drawable.on); holder.row.setBackgroundResource(R.drawable.purple_row); holder.reminderCalenderRow.setTextColor(context.getResources().getColor(R.color.white)); holder.reminderTitleRow.setTextColor(context.getResources().getColor(R.color.white)); holder.showCalenderRow.setTextColor(context.getResources().getColor(R.color.white)); holder.showTimeRow.setTextColor(context.getResources().getColor(R.color.white)); holder.reminderCalenderRow.setTextColor(context.getResources().getColor(R.color.white)); holder.reminderTimeRow.setTextColor(context.getResources().getColor(R.color.white)); Drawable myDrawable = context.getResources().getDrawable(R.drawable.menu_icon); holder.popUp_menu.setBackground(myDrawable); alarm.setActive(1); String strTime = alarm.getTime(); String[] timeRemoveSpace = strTime.split(" "); String[] splitTime = timeRemoveSpace[0].split(":"); hour = getHour(strTime); mintue = Integer.parseInt(splitTime[1]); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, mintue); calendar.set(Calendar.SECOND, 00); Long date = calendar.getTimeInMillis(); StartAlarm(alarm.getId(), alarm, date); } else { holder.row.setBackgroundResource(R.drawable.white_row); holder.reminderTitleRow.setTextColor(context.getResources().getColor(R.color.colorBlack)); holder.showCalenderRow.setTextColor(context.getResources().getColor(R.color.colorBlack)); holder.showTimeRow.setTextColor(context.getResources().getColor(R.color.colorBlack)); holder.reminderCalenderRow.setTextColor(context.getResources().getColor(R.color.colorBlack)); holder.reminderTimeRow.setTextColor(context.getResources().getColor(R.color.colorBlack)); Drawable myDrawable = context.getResources().getDrawable(R.drawable.menu_icon_black); holder.popUp_menu.setBackground(myDrawable); alarm.setActive(0); } mDatabase.updateActive(state, alarm.getId()); notifyDataSetChanged(); } }); and send intent into broatcast : public void StartAlarm(int id, Alarm alarm, Long time) { Intent intent = new Intent(context, MyReceiver.class); intent.setAction("com.nooshindroid.yastashir"); Bundle bundle = new Bundle(); bundle.putString(EXTRA_TITLE, alarm.getTitle()); bundle.putString(EXTRA_ALARM_DATE, alarm.getDate()); bundle.putString(EXTRA_REPORT, alarm.getReport()); bundle.putString(EXTRA_REPEAT, alarm.getRepeat()); intent.putExtras(bundle); pendingIntent = PendingIntent.getBroadcast(context, id, intent, 0); AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE); if ("بدون تکرار".equals(alarm.getRepeat())) { Log.i("ShowMeTime", "111111"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { alarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent); Toast.makeText(context, "Alarm>kitkat", Toast.LENGTH_SHORT).show(); } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent); Toast.makeText(context, "Alarm<kitkat", Toast.LENGTH_SHORT).show(); } } else { Log.i("ShowMeTime", "222222"); switch (alarm.getRepeat()) { case "هر ساعت": alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_HOUR, pendingIntent); break; case "هر روز": alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_DAY, pendingIntent); break; case "هر هفته": alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_DAY * 7, pendingIntent); break; case "هر ماه": alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_DAY * 30, pendingIntent); break; } } } all thins is ok until I want to edit , Once I edit my values and all these repeat , broad cast show the old values . this my Receiver : public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //and doing something if (intent.getAction().equals("com.nooshindroid.yastashir")) { String title = intent.getExtras().getString(EXTRA_TITLE); Toast.makeText(context, "Its time!!!", Toast.LENGTH_SHORT).show(); Log.i("khhhhhhhhhhhhhhh", "Started >>>>>>>"+title); } } } Why this happen ? any help?
{ "language": "en", "url": "https://stackoverflow.com/questions/59692745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to pass data from useSelector (redux) to useSate hook in react? Hi i am trying to work on a app, which has some predefined code of redux, and react. I am trying to get the players data which is formated json file and pass it to useSate hook. The data which I get using const players = useSelector(getPlayers); // redux looks perfect when I do console log, however when I pass this to useState const [playerData, setPlayerData] = useState(players); //react there is no data on the console. I do not know if this is the right way to do, if not what would be the best solution to this? as I am more into react hooks and not redux. any help is appreciated . Thanks A: you can set it in useEffect like that but my suggestion is to use the directly redux players variable. useEffect(() => { setPlayerData(players); }, [players])
{ "language": "en", "url": "https://stackoverflow.com/questions/72965495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NSData dataWithContentsOfURL: returning nil NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"CRN_JSON" ofType:@"json"]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ data = [NSData dataWithContentsOfURL: [NSURL URLWithString:@"http://properfrattire.com/Classifi/CRN_JSON.json"]]; [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES]; }); My data variable is nil after running this code. If you follow the link you'll see that it is a JSON file. I've run the function with this exact same file locally but it is not able to obtain the data at the given URL without error. A: Not sure why you're nesting calls to URLWithString: [NSURL URLWithString:[NSURL URLWithString:@"http://properfrattire.com/Classifi/CRN_JSON.json"]]]; Once will do: [NSURL URLWithString:@"http://properfrattire.com/Classifi/CRN_JSON.json"]; Also, you should use dataWithContentsOfURL:options:error: so you can see any error.
{ "language": "en", "url": "https://stackoverflow.com/questions/16883818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: How to call Rust async method from Python? I want to use a Rust async method in Python. I'm trying to use PyO3 or rust-cpython. For example, for sync Rust functions, I can use, #[pyfunction] fn myfunc(a: String) -> PyResult<String> { let mut contents = String::new(); contents = a.to_string() + " appended"; Ok((contents)) } #[pymodule] fn MyModule(py: Python, m: &PyModule) -> PyResult<()> { m.add_wrapped(wrap_pyfunction!(urlshot))?; Ok(()) } For async methods, how can I do it? For example, I want to call the following method in Python, async fn hello_world() { println!("hello, world!"); } A: Since there was no easy way of solving this issue (at least, I hadn't found), I converted my async method to sync one. And called it on Python side as, async fn my_method(s: &str) -> Result<String, Error> { // do something } #[pyfunction] fn my_sync_method(s: String) -> PyResult<String> { let mut rt = tokio::runtime::Runtime::new().unwrap(); let mut contents = String::new(); rt.block_on(async { result = format!("{}", my_sync_method(&s).await.unwrap()).to_string(); }); Ok((result)) } #[pymodule] fn MyModule(py: Python, m: &PyModule) -> PyResult<()> { m.add_wrapped(wrap_pyfunction!(my_sync_method))?; Ok(()) } Edited In the Cargo.toml file, I added the following dependencies, [dependencies.pyo3] git = "https://github.com/PyO3/pyo3" features = ["extension-module"] After running cargo build --release, target/release/libMyModule.so binary file is generated. Rename it as MyModule.so and it now can be imported from Python. import MyModule result = MyModule.my_sync_method("hello") Using setuptools-rust, I could bundle it as an ordinary Python package. All of the above code and commands are tested on newly-released Linux Mint 20. On MacOS, the binary file will be libMyModule.dylib. A: If you want to use Python to control Rust's async function, I don't think it will work (Or at least it is very complicated, as you need to connect two different future mechanism). For async functions, Rust compiler will maintain a state machine to manage the coroutines run correctly under await's control. This is an internal state of Rust applications and Python cannot touch it. Similarly Python interpreter also has a state machine that cannot be touched by Rust. I do found this topic about how to export an async function using FFI. The main idea is to wrap the async in a BoxFuture and let C control the timing of returning it to Rust. However, you cannot use BoxFuture in PyO3 since its pyfunction macro cannot convert a function returns BoxFuture to a Python callback. You may try to create a library using FFI and use python's cffi module to load it.
{ "language": "en", "url": "https://stackoverflow.com/questions/62619870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to keep decimal places with two zeros? Using the lib Decimal i can set the quantize to get the 2 decimal places with zero: from decimal import Decimal value = Decimal('1000.0').quantize(Decimal('1.00')) print(value) # Decimal('1000.00') But if i need to change it to float the last zero disappear: value = float(value) print(value) # 1000.0 How can i set two zeros at decimal place and still use as float? the print method was an e example to show the final result, i need to use the value as float and not string. the value will be used in a json request: { "value": 1000.00 }
{ "language": "en", "url": "https://stackoverflow.com/questions/56026703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Retrofit2 How to get redirect url @HEAD("/") I have a minified URL and I want to have the final URL With Retrofit 1.9 I used to do this : @HEAD("/XXXXXXXXX") void fetchFinalUrl(Callback<String> cb); public void getUrl() { mMinifyService.fetchFinalUrl(new Callback<String>() { @Override public void success(String s, Response response) { response.getUrl(); } [...] } But now with Retrofit 2 .getUrl() not exist any ideas how to do this? Thanks in advance. EDIT Finally got it! public class ApiProvider<T> { private Retrofit retrofit; private static final String END_POINT_MINIFY = "XXXXXXX"; public ApiProvider() { initAdapter(); } public T getService(Class<T> service) { return retrofit.create(service); } private void initAdapter() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(interceptor) .followRedirects(false) .build(); retrofit = new Retrofit.Builder() .baseUrl(END_POINT_MINIFY) .addConverterFactory(new ToStringConverterFactory()) .client(client) .build(); } } public interface IMinifyService { @HEAD("/XXXXXXXXX") Call<Void> fetchFinalUrl(Callback<String> cb); } public class MinifyServiceImpl { private ApiProvider<IMinifyService> mApiProvider = new ApiProvider<>(); private IMinifyService mMinifyService = mApiProvider.getService(IMinifyService.class); public Promiser<String, Integer> fetchMinifyUrl() { return new Promiser<>((resolve, reject) -> mMinifyService.fetchMinifyUrl().enqueue(new Callback<Void>() { @Override public void onResponse(Call<Void> call, Response<Void> response) { if (response.code() >= 300 && response.code() < 400){ resole.run(response.headers().get("Location")); } else { reject.run(response.code()); } } @Override public void onFailure(Call<Void> call, Throwable t) { reject.run(t.hashCode()); } })); } } if you want to use Promizer --> Click here A: response.raw().request().url()
{ "language": "en", "url": "https://stackoverflow.com/questions/37548238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how fix cors error on react app and coinbase connect api I can't get authorization URL to coinbase connect OAuth2 api. fetch("https://www.coinbase.com/oauth/authorize?response_type=code&client_id=cc460ce71913c49e4face4ac0e072c38564fabea867ebcd7ab9905970d8f3021&redirect_uri=http://localhost:3000/callback&state=SECURE_RANDOM&scope=wallet:accounts:read") .then(res => res.json()) .then( (result) => { console.log(result) }, (error) => { console.log(error) } ) give me this error enter image description here A: You can disable cors like that : fetch('https://www.coinbase.com/oauth/authorize?response_type=code&client_id=cc460ce71913c49e4face4ac0e072c38564fabea867ebcd7ab9905970d8f3021&redirect_uri=http://localhost:3000/callback&state=SECURE_RANDOM&scope=wallet:accounts:read', { mode: 'no-cors', method:'GET' }).then(res => res.json()) .then( (result) => { console.log(result) }, (error) => { console.log(error) } )
{ "language": "en", "url": "https://stackoverflow.com/questions/70394816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Visualforce - Clickable DataTable Cells - How to get Column and Row information I'd like to create a datatable where each cell is clickable. I'm assuming that I can probably fill each cell with apex:outputlink and that takes care of the clickable part as well as calling my controller for each click. The big question I need an answer for is how do I pass information to my apex controller about which cell (i.e.: which row and which column) was actually clicked. Any help for this is highly appreciated. A: Its easy. Just define an action function to catch the values from the dataTable: 1) First defining three vars tht we will pass to controller: raw-id, cell-value, cell-type public String clickedRowId { get; set; } public String clickedCellValue { get; set; } public String clickedCellType { get; set; } public PageReference readCellMethod(){ System.debug('#### clickedRowId: ' + clickedRowId); System.debug('#### clickedCellValue: ' + clickedCellValue); System.debug('#### clickedCellType: ' + clickedCellType); return null; } 2) Second we create an action function, that calls our apex method an pass three vars to it: <apex:actionFunction name="readCell" action="{!readCellMethod}"> <apex:param name="P1" value="" assignTo="{!clickedRowId}"/> <apex:param name="P2" value="" assignTo="{!clickedCellValue}"/> <apex:param name="P3" value="" assignTo="{!clickedCellType}"/> </apex:actionFunction> 3) And third we create our dataTable, where each cell has onClick listener: <apex:pageBlockTable value="{!someArray}" var="item"> <apex:column value="{!item.name}" onclick="readCell('{!item.id}','{!item.name}','name')" /> <apex:column value="{!item.CustomField1__c}" onclick="readCell('{!item.id}','{!item.CustomField1__c}','custom1')" /> <apex:column value="{!item.CustomField2__c}" onclick="readCell('{!item.id}','{!item.CustomField2__c}','custom2')" /> </apex:pageBlockTable> We can access our actionFunction like any other JavaScript function. If user clicks on the cell - three vars will be send to the actionFunction and then to controller.
{ "language": "en", "url": "https://stackoverflow.com/questions/11939740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: webm to mp4 without loosing audio video sync Iam trying to covert webm to mp4 using ffmpeg so that the output file is playable in all browsers. Iam using this ffmpeg command in ubuntu ffmpeg -i inpput.webm -f mp4 -copyts -vcodec libx264 -strict -2 -vf scale="380:-2" -pix_fmt yuv420p -profile:v baseline -level 3 output.mp4 It is converting the file to mp4 but that file is out of sync in Mac safari browser and chrome browser. Means the audio and video is not syncing and sometimes the video gets stopped in between and audio goes on. If I play the input.web media file directly in chrome it is playing perfectly fine, the same input.webm is also playing good with firefox. But the converted mp4 is out of sync in safari on mac and all chrome browsers. However if the output.mp4 is played on ipad safari it is playing fine. The Mac safari version I tried is 11.03 iPad safari version is 11.3 Firefox and chrome are all latest. firefox : 59.0.2(64 bit), chrome : 65.0.3325.181 (Official Build) (64-bit) Please help me out with what Iam doing wrong. Thanks in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/49729020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to check if string is a proper subset of another string I want to check if a string is a strictly a subset of another string. For this end I used boost::contains and I compare the size of strings as follows: #include <boost/algorithm/string.hpp> #include <iostream> using namespace std; using namespace boost::algorithm; int main() { string str1 = "abc news"; string str2 = "abc"; //strim strings using boost trim(str1); trim(str2); //if str2 is a subset of str1 and its size is less than the size of str1 then it is strictly contained in str1 if(contains(str1,str2) && (str2.size() < str1.size())) { cout <<"contains" << end; } return 0; } Is there a better way to solve this problem? Instead of also comparing the size of strings? Example * *ABC is a proper subset of ABC NEWS *ABC is not a proper subset of ABC A: I would use the following: bool is_substr_of(const std::string& sub, const std::string& s) { return sub.size() < s.size() && s.find(sub) != s.npos; } This uses the standard library only, and does the size check first which is cheaper than s.find(sub) != s.npos. A: You can just use == or != to compare the strings: if(contains(str1, str2) && (str1 != str2)) ... If string contains a string and both are not equal, you have a real subset. If this is better than your method is for you to decide. It is less typing and very clear (IMO), but probably a little bit slower if both strings are long and equal or both start with the same, long sequence. Note: If you really care about performance, you might want to try the Boyer-Moore search and the Boyer-Moore-Horspool search. They are way faster than any trivial string search (as apparently used in the string search in stdlibc++, see here), I do not know if boost::contains uses them. A: About Comparaison operations TL;DR : Be sure about the format of what you're comparing. Be wary of how you define strictly. For example, you did not pointed out thoses issue is your question, but if i submit let's say : "ABC " //IE whitespaces "ABC\n" What is your take on it ? Do you accept it or not ? If you don't, you'll have to either trim or to clean your output before comparing - just a general note on comparaison operations - Anyway, as Baum pointed out, you can either check equality of your strings using == or you can compare length (which is more efficient given that you first checked for substring) with either size() or length(); A: another approach, using only the standard library: #include <algorithm> #include <string> #include <iostream> using namespace std; int main() { string str1 = "abc news"; string str2 = "abc"; if (str2 != str1 && search(begin(str1), end(str1), begin(str2), end(str2)) != end(str1)) { cout <<"contains" << endl; } return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/30029869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What happens to the Apache process when a PHP session expires? My understanding is that when a request is received, the Apache server will fork a new process and invoke the appropriate php script/file. What happens when the session started by the php script, in this new process forked by Apache, has expired or the user has ended it by closing their browser ? There is an exit(); call after errors or logout redirects that I use but I am unsure of what it does at the Server/OS level. Does Apache kill the process ? How does the communication between apache and php work ? A: My understanding is that when a request is received, the Apache server will fork a new process and invoke the appropriate php script/file. This is only the case for PHP-CGI configurations, which are not typical. Most deployments use the mod_php SAPI, which runs PHP scripts within the Apache process. What happens when the session started by the php script, in this new process forked by Apache, has expired or the user has ended it by closing their browser ? Nothing. In PHP-CGI configurations, the process exits as soon as your script finishes generating a response. In mod_php configurations, the Apache process returns to listening for new requests when your script finishes. The lifetime of sessions is not tied to any specific process. Keep in mind that sessions are stored as files in your system's temporary directory -- PHP periodically checks this directory for sessions which have expired and removes them as appropriate. Closing your browser does not remove the session from the server's temporary directory. It may cause your browser to discard the cookies related to the session, causing the session to stop being used, but the server is not notified of this.
{ "language": "en", "url": "https://stackoverflow.com/questions/38426698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: load an OCX dynamically and get the handle of loaded module in C# I am going to load an OCX in runtime and pass the handle of loaded ocx to another function which is a patch , I have the delphi code and it works fine , I want to convert it to c# but I don't know how Type TDLLFunc = procedure(param1: dword); VAR DLLFunc : TDLLFunc; OcxDllHndle : LongInt; DllHandle : LongInt; begin OcxDllHndle := LoadLibrary('SampleOcx.Dll'); DllHandle := LoadLibrary('Patch.dll'); @DLLFunc := GetProcAddress(DllHandle, 'DoPatch'); DLLFunc(OcxDllHndle); end; here is the c# code but it doesnt work (I made AxInterop version of OCX ) : AppDomain Domain = AppDomain.CreateDomain("TestApp", null, null); var assemblyName = AssemblyName.GetAssemblyName(@".\AxInterop.SampleOcx.dll"); Assembly Ocx = Assembly.Load(assemblyName); IntPtr DLLHandle = LoadLibrary(Application.StartupPath + @"\Patch.dll"); IntPtr funcaddr = GetProcAddress(DLLHandle, "DoPatch"); [UnmanagedFunctionPointer(CallingConvention.StdCall)] delegate void MyFunc(int Handle); MyFunc DLLFunc = Marshal.GetDelegateForFunctionPointer(funcaddr, typeof(MyFunc)) as MyFunc; IntPtr OCXHandle = Marshal.GetHINSTANCE(Ocx.GetType().Module); DLLFunc(OCXHandle.ToInt32()); Please help A: The function that is exported from that Delphi DLL cannot be called from C#. The Delphi DLL exports the function using the register calling convention which is a non-standard Delphi only calling convention. You will need to modify the DLL to export using, for instance, stdcall. Assuming you made the change the C# code would look like this: [DllImport("patch.dll")] static extern void DoPatch(IntPtr moduleHandle); .... IntPtr OcxHandle = LoadLibrary("SampleOcx.dll"); if (OcxHandle == IntPtr.Zero) .... handle error DoPatch(OcxHandle); Note that the parameter is not really a DWORD. It is an HMODULE. That's a 64 bit type under 64 bit process. Which leads me to point out that your program must target x86 to work with your 32 bit Delphi DLL. And the OCX is presumably 32 bits too.
{ "language": "en", "url": "https://stackoverflow.com/questions/23845451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error in config.preparations.append(modelName.self) Use of unresolved identifier 'modelName' I have already gone through the proper way of the fluent provider to build a relation for my model (Swift) using vapor (server side) and PostgreSQL provider (database), I follow the general method of fluent, but I don't know where I am doing mistake, in extension for modelName preparation, below the code of my modelName.swift and main.swift. import Foundation import Vapor import FluentProvider import PostgreSQLProvider final class modelName: Model { let storage = Storage() var id: Node? var name:String var displayName:String public var content: String init(content: String, displayName:String, name:String) { self.content = content self.displayName = displayName self.name = name } func forDataBase() { let array:[berichtDataPoint] = [intDataPoint(), boolDataPoint(), doubleDataPoint()] let _ = array[0] as! intDataPoint let _ = array[1] as! doubleDataPoint for point in array { switch point { case is intDataPoint: print("int") case is doubleDataPoint: print("double") case is boolDataPoint: print("bool") default: print("error") } } } func makeRow() throws -> Row { var row = Row() try row.set("id", idKey) try row.set("displayName", displayName) try row.set("name", name) return row } init(row: Row) throws { content = try row.get("content") displayName = try row.get("displayName") name = try row.get("name") } func makeNode(context: Context) throws -> Node { return try Node(node: [ "id": id, "content": content, "displayName": displayName, "name": name ]) } } extension modelName: Preparation { static func prepare(_ database: Database) throws { try database.create(self) { modelName in modelName.id() modelName.string("displayName") modelName.string("name") } } static func revert(_ database: Database) throws { try database.delete(self) } } main.swift import App import Vapor import FluentProvider import PostgreSQLProvider /// We have isolated all of our App's logic into /// the App module because it makes our app /// more testable. /// /// In general, the executable portion of our App /// shouldn't include much more code than is presented /// here. /// /// We simply initialize our Droplet, optionally /// passing in values if necessary /// Then, we pass it to our App's setup function /// this should setup all the routes and special /// features of our app /// /// .run() runs the Droplet's commands, /// if no command is given, it will default to "serve" let config = try Config() config.preparations.append(modelName.self) \\error is here '(Use of unresolved identifier 'modelName') let drop = try Droplet(config) try drop.setup() try drop.run() A: I think the root cause is that modules are separated. If you created vapor project as vapor new, main.swift is in Run module, modelName.swift is in App module. // Package.swift let package = Package( name: "hello", targets: [ Target(name: "App"), Target(name: "Run", dependencies: ["App"]), ], When access to other module class, target class's access level is must use open or public. // modelName.swift public class moduleName: Model { ... Please note that you must also modify other method declarations according to this change. Thanks. A: move modelName.swift to run folder
{ "language": "en", "url": "https://stackoverflow.com/questions/46429079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to run android instrumental test using `androidx` and `navgation architecture`? I'm trying to write tests for an android app. Which has one Activity and two fragments (i.e FragmentOne and FragmentTwo) by clicking a button on FragmentOne it goes to the FragmentTwo. And I wrote the test for the same and I'm using androidx and navigation architecture. I have read this link and this link but didn't succeed. Here is my current code- ExampleInstrumentedTest @RunWith(JUnit4::class) class ExampleInstrumentedTest { @Test fun checkSecondFrag() { // Create a mock NavController val mockNavController = mock(NavController::class.java) // Create a graphical FragmentScenario for the OneFragment val oneFragmentScenario = launchFragmentInContainer<OneFragment>() // Set the NavController property on the fragment oneFragmentScenario.onFragment { fragment -> Navigation.setViewNavController(fragment.requireView(), mockNavController) } // Verify that performing a click prompts the correct Navigation action onView(ViewMatchers.withId(R.id.nextFragment)).perform(ViewActions.click()) verify(mockNavController).navigate(R.id.action_oneFragment_to_twoFragment) } } Gradle(App) apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android { compileSdkVersion 28 defaultConfig { applicationId "com.varun.navtesting" minSdkVersion 16 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation 'androidx.appcompat:appcompat:1.0.2' implementation 'androidx.core:core-ktx:1.0.2' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' implementation 'androidx.legacy:legacy-support-v4:1.0.0' // Core library androidTestImplementation 'androidx.test:core:1.2.0' // AndroidJUnitRunner and JUnit Rules androidTestImplementation 'androidx.test:runner:1.2.0' androidTestImplementation 'androidx.test:rules:1.2.0' // Assertions androidTestImplementation 'androidx.test.ext:junit:1.1.1' androidTestImplementation 'androidx.test.ext:truth:1.2.0' androidTestImplementation 'com.google.truth:truth:0.42' // Espresso dependencies androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.2.0' androidTestImplementation 'androidx.test.espresso:espresso-intents:3.2.0' androidTestImplementation 'androidx.test.espresso:espresso-accessibility:3.2.0' androidTestImplementation 'androidx.test.espresso:espresso-web:3.2.0' androidTestImplementation 'androidx.test.espresso.idling:idling-concurrent:3.2.0' testImplementation 'junit:junit:4.12' implementation 'androidx.navigation:navigation-fragment-ktx:2.0.0' implementation 'androidx.navigation:navigation-ui-ktx:2.0.0' // required if you want to use Mockito for unit tests testImplementation 'org.mockito:mockito-core:2.25.0' // required if you want to use Mockito for Android tests androidTestImplementation 'org.mockito:mockito-android:2.19.0' // Fragment test implementation 'androidx.fragment:fragment:1.2.0-alpha01' androidTestImplementation 'androidx.fragment:fragment-testing:1.2.0-alpha01' implementation 'com.android.support:support-annotations:28.0.0' } Mainfiest <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.varun.navtesting"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme" tools:ignore="GoogleAppIndexingWarning"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <uses-library android:name="android.test.runner" android:required="false"/> <uses-library android:name="android.test.base" android:required="false"/> <uses-library android:name="android.test.mock" android:required="false"/> </application> <instrumentation android:targetPackage="com.varun.navtesting" android:name="android.test.ExampleInstrumentedTest"/> </manifest> This line <instrumentation android:targetPackage="com.varun.navtesting" android:name="android.test.ExampleInstrumentedTest"/> is showing in red color in android studio. Here is the Logcat 2019-07-30 22:00:16.967 6821-6837/com.varun.navtesting E/TestRunner: failed: checkSecondFrag(com.varun.navtesting.ExampleInstrumentedTest) 2019-07-30 22:00:16.967 6821-6837/com.varun.navtesting E/TestRunner: ----- begin exception ----- 2019-07-30 22:00:16.968 6821-6837/com.varun.navtesting E/TestRunner: java.lang.RuntimeException: Unable to resolve activity for: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.varun.navtesting/androidx.fragment.app.testing.FragmentScenario$EmptyFragmentActivity (has extras) } at androidx.test.core.app.InstrumentationActivityInvoker.startActivity(InstrumentationActivityInvoker.java:344) at androidx.test.core.app.ActivityScenario.launchInternal(ActivityScenario.java:231) at androidx.test.core.app.ActivityScenario.launch(ActivityScenario.java:209) at androidx.fragment.app.testing.FragmentScenario.internalLaunch(FragmentScenario.java:299) at androidx.fragment.app.testing.FragmentScenario.launchInContainer(FragmentScenario.java:282) at com.varun.navtesting.ExampleInstrumentedTest.checkSecondFrag(ExampleInstrumentedTest.kt:39) at java.lang.reflect.Method.invoke(Native Method) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.junit.runners.Suite.runChild(Suite.java:128) at org.junit.runners.Suite.runChild(Suite.java:27) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at org.junit.runner.JUnitCore.run(JUnitCore.java:115) at androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56) at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:392) at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2145) 2019-07-30 22:00:16.968 6821-6837/com.varun.navtesting E/TestRunner: ----- end exception ----- Any help will be appriciated. A: As per the Fragment testing page, you must use debugImplementation for the fragment-testing artifact: debugImplementation 'androidx.fragment:fragment-testing:1.2.0-alpha01'
{ "language": "en", "url": "https://stackoverflow.com/questions/57279944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Day of week last year Im trying to calculate the date of the equivalent current day last year same week in standard SQL BigQuery. For instance if the current date 2019-07-01 is a monday of week 27. I want to know the date of monday of week 27 last year (2018). Current week would be select extract(isoweek from current_date()) but I don't know how to use this to calculate a date. Expected output is 2018-07-02 if current date is 2019-07-01 The reason for this is that I want to compare current sales with same week and day of week as last year. Any suggestions are appreciated. A: Something like this should get you going... with dates as (select * from unnest(generate_date_array('2018-01-01','2019-12-31', interval 1 day)) as cal_date), cal as (select cal_date, cast(format_date('%Y', cal_date) as int64) as year, cast(format_date('%V', cal_date) as int64) as week_num, format_date('%A', cal_date) as weekday_name from dates) select c1.cal_date, c1.week_num, c1.weekday_name, c2.cal_date as previous_year_same_weekday from cal c1 inner join cal c2 on c1.year = c2.year+1 and c1.week_num = c2.week_num and c1.weekday_name = c2.weekday_name The above query uses a week starting on a Monday, you may need to play around with the format_date() arguments as seen here to modify it for your needs. A: This query returns no results, implying that SHIFT works. The function returns NULL if a year does not have the same number of weeks as its predecessor. CREATE TEMP FUNCTION P_YEAR(y INT64) AS ( MOD(CAST(y + FLOOR(y / 4.0) - FLOOR(y / 100.0) + FLOOR(y / 400.0) AS INT64), 7) ); CREATE TEMP FUNCTION WEEKS_YEAR(y INT64) AS ( 52 + IF(P_YEAR(y) = 4 OR P_YEAR(y - 1) = 3, 1, 0) ); CREATE TEMP FUNCTION SHIFT(d DATE) RETURNS DATE AS ( CASE WHEN WEEKS_YEAR(EXTRACT(ISOYEAR FROM d)) != WEEKS_YEAR(EXTRACT(ISOYEAR FROM d) - 1) THEN null WHEN WEEKS_YEAR(EXTRACT(ISOYEAR FROM d)) = 52 THEN DATE_SUB(d, INTERVAL 52 WEEK) ELSE d END ); WITH dates AS ( SELECT d FROM UNNEST(GENERATE_DATE_ARRAY('2000-12-31', '2020-12-31', INTERVAL 1 DAY)) AS d ) SELECT d, EXTRACT(ISOWEEK FROM d) AS orig_iso_week, EXTRACT(ISOWEEK FROM SHIFT(d)) AS new_iso_week, SHIFT(d) AS new_d FROM dates WHERE EXTRACT(ISOWEEK FROM d) != EXTRACT(ISOWEEK FROM SHIFT(d)) AND SHIFT(d) IS NOT NULL
{ "language": "en", "url": "https://stackoverflow.com/questions/56855846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NSTextView Chinese/Unicode Characters I have a piece of text drawn in my cocoa app but I also need to draw it in a NSTextField and a NSTextView and look exactly the same, they all usually draw fine but if there are unicode or Chinese characters in the text then the NSTextView has large line spaces between the lines, it works perfectly in the nstextfield and when drawing normally. I have tried every setting that I can find but none affect this issue, has anyone run into this issue before and know of a fix? You can see the issue in a screenshot at http://cl.ly/3e0U1T2U2G2z341j3O3T Here is my test code to show the issue NSTextField *textField = [[NSTextField alloc] initWithFrame:NSMakeRect(5, 50, 100, 100)]; [textField setStringValue:@"え?移転!? TESTTestTer 友達の旦那の店 THIS IS A TEST THIS IS A TEST"]; [textField setBordered:NO]; [textField setBezeled:NO]; [textField setAllowsEditingTextAttributes:YES]; [textField setDelegate:self]; [textField setFont:[NSFont fontWithName:@"LucidaGrande" size:12.0]]; [textField setTextColor:[NSColor colorWithDeviceRed:(74.0/255.0) green:(74.0/255.0) blue:(74.0/255.0) alpha:1.0]]; [[window contentView] addSubview: textField]; NSTextView *textView = [[NSTextView alloc] initWithFrame:NSMakeRect(200, 50, 100, 100)]; [textView setString:@"え?移転!? TEST TestTer 友達の旦那の店 THIS IS A TEST THIS IS A TEST"]; [textView setDelegate:self]; [textView setFont:[NSFont fontWithName:@"LucidaGrande" size:12.0]]; [textView setTextColor:[NSColor colorWithDeviceRed:(74.0/255.0) green:(74.0/255.0) blue:(74.0/255.0) alpha:1.0]]; [[textView layoutManager] setTypesetterBehavior:NSTypesetterBehavior_10_2_WithCompatibility]; [[textView textContainer] setLineFragmentPadding:0.0]; [[window contentView] addSubview: textView];
{ "language": "en", "url": "https://stackoverflow.com/questions/4278856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Reset my app on Fortrabbit I created app on Fortrabbit and purchased a service for my app. I pushed some my app (Laravel) and created my database. Now I want to reset my app. How can I do that? Could somebody help? A: This is the script I use myself using laravel 4 to flush a complete DB in Fortrabbit DB::statement('SET FOREIGN_KEY_CHECKS=0'); $tables= DB::select('SHOW TABLES;'); foreach ($tables as $table) { foreach ($table as $key=>$tableName) { $tables= DB::statement("DROP TABLE $tableName;"); } } DB::statement('SET FOREIGN_KEY_CHECKS=1'); A: This answer is from Fortrabbit Support: sorry, it's not possible to reset the git repo (for now). But you can push new code any time. You can also delete files when you ssh into you App. If you want to start form the scratch, I suggest to spin up a new App.
{ "language": "en", "url": "https://stackoverflow.com/questions/32047462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: STL and UTF-8 file input/output. How to do it? I use wchar_t for internal strings and UTF-8 for storage in files. I need to use STL to input/output text to screen and also do it by using full Lithuanian charset. It's all fine because I'm not forced to do the same for files, so the following example does the job just fine:#include <io.h> #include <fcntl.h> #include <iostream> _setmode (_fileno(stdout), _O_U16TEXT); wcout << L"AaĄąfl" << endl; But I became curious and attempted to do the same with files with no success. Of course I could use formatted input/output, but that is... discouraged. FILE* fp; _wfopen_s (&fp, L"utf-8_out_test.txt", L"w"); _setmode (_fileno (fp), _O_U8TEXT); _fwprintf_p (fp, L"AaĄą\nfl"); fclose (fp); _wfopen_s (&fp, L"utf-8_in_test.txt", L"r"); _setmode (_fileno (fp), _O_U8TEXT); wchar_t text[256]; fseek (fp, NULL, SEEK_SET); fwscanf (fp, L"%s", text); wcout << text << endl; fwscanf (fp, L"%s", text); wcout << text << endl; fclose (fp);This snippet works perfectly (although I am not sure how it handles malformed chars). So, is there any way to: * *get FILE* or integer file handle form a std::basic_*fstream? *simulate _setmode () on it? *extend std::basic_*fstream so it handles UTF-8 I/O? Yes, I am studying at an university and this is somewhat related to my assignments, but I am trying to figure this out for myself. It won't influence my grade or anything like that. A: Use std::codecvt_facet template to perform the conversion. You may use standard std::codecvt_byname, or a non-standard codecvt_facet implementation. #include <locale> using namespace std; typedef codecvt_facet<wchar_t, char, mbstate_t> Cvt; locale utf8locale(locale(), new codecvt_byname<wchar_t, char, mbstate_t> ("en_US.UTF-8")); wcout.pubimbue(utf8locale); wcout << L"Hello, wide to multybyte world!" << endl; Beware that on some platforms codecvt_byname can only emit conversion only for locales that are installed in the system. A: Well, after some testing I figured out that FILE is accepted for _iobuf (in the w*fstream constructor). So, the following code does what I need.#include <iostream> #include <fstream> #include <io.h> #include <fcntl.h> //For writing FILE* fp; _wfopen_s (&fp, L"utf-8_out_test.txt", L"w"); _setmode (_fileno (fp), _O_U8TEXT); wofstream fs (fp); fs << L"ąfl"; fclose (fp); //And reading FILE* fp; _wfopen_s (&fp, L"utf-8_in_test.txt", L"r"); _setmode (_fileno (fp), _O_U8TEXT); wifstream fs (fp); wchar_t array[6]; fs.getline (array, 5); wcout << array << endl;//For debug fclose (fp);This sample reads and writes legit UTF-8 files (without BOM) in Windows compiled with Visual Studio 2k8. Can someone give any comments about portability? Improvements? A: The easiest way would be to do the conversion to UTF-8 yourself before trying to output. You might get some inspiration from this question: UTF8 to/from wide char conversion in STL A: get FILE* or integer file handle form a std::basic_*fstream? Answered elsewhere. A: You can't make STL to directly work with UTF-8. The basic reason is that STL indirectly forbids multi-char characters. Each character has to be one char/wchar_t. Microsoft actually breaks the standard with their UTF-16 encoding, so maybe you can get some inspiration there.
{ "language": "en", "url": "https://stackoverflow.com/questions/4018384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Accessing a javascript variable outside its assigned method I want to access the javascript variable called locations outside of its assigned method. Javascript code: $(document).ready(function() { var locations; console.log('document ready'); function initializeMap() { $.ajax({url: "getlocation.php", success: function(result){ locations = $.parseJSON(result); alert(locations); } }); var map = new google.maps.Map(document.getElementById('map_canvas'), { zoom: 10, center: new google.maps.LatLng(-33.92, 151.25), mapTypeId: google.maps.MapTypeId.ROADMAP }); var infowindow = new google.maps.InfoWindow(); var marker, i; for (i = 0; i < locations.length; i++) { marker = new google.maps.Marker({ position: new google.maps.LatLng(locations[i][1], locations[i][2]), map: map }); google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infowindow.setContent(locations[i][0]); infowindow.open(map, marker); } })(marker, i)); } } initializeMap(); }); How can I get the json parsed data passed to the locations variable so I can get data outside of its assigned method and into the loop? Here is the finished code that solves my problem: $(document).ready(function() { console.log('document ready'); function initializeMap() { var locations; $.ajax({url: "getlocation.php", success: function(result){ alert(result); locations = $.parseJSON(result); alert(locations); } }); var map = new google.maps.Map(document.getElementById('map_canvas'), { zoom: 10, center: new google.maps.LatLng(-33.92, 151.25), mapTypeId: google.maps.MapTypeId.ROADMAP }); var infowindow = new google.maps.InfoWindow(); var marker, i; for (i = 0; i < locations.length; i++) { marker = new google.maps.Marker({ position: new google.maps.LatLng(locations[i][1], locations[i][2]), map: map }); google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infowindow.setContent(locations[i][0]); infowindow.open(map, marker); } })(marker, i)); } } initializeMap(); }); "Pass by Reference" and "Pass by Value" are two programming terms that describe how a method behaves when passing a variable into a method. A: The function is called after excecuting the block of code, so the var location was assigned a value after it was adressed, this is why you saw undefined. There are two ways to fix this, 1) put the block of code inside the function or 2) call the function directly after initializing it ! General tip: do not use the ready function instead put the script just before body tag ends and avoid many problems !
{ "language": "en", "url": "https://stackoverflow.com/questions/33251451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to execute python script from another python script and send it's output in text file I have a script test.py which is used for server automation task and have other script server.py which list out all server name. server.py list all sevrer name in text.log file and this log file is used by test.py as a input. I want one single script test.py to execute server.py from inside it and also redirect server.py script output to text.log file as well. So far i have tried with execfile("server.py") >text.log in test.py which didn't worked. A: Use subprocess.call with stdout argument: import subprocess import sys with open('text.log', 'w') as f: subprocess.call([sys.executable, 'server.py'], stdout=f) # ADD stderr=subprocess.STDOUT if you want also catch standard error output
{ "language": "en", "url": "https://stackoverflow.com/questions/43984237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Angular universal-starter prerender with 4 levels nesting parameters For some reasons I want to create prerender build of my angular 5 project using https://github.com/angular/universal-starter instead of server-side rendering. There are 4 levels in my routes like this: example.com/category/:id/subcategory/:id/event/:id/ticket/:id Also, There is a rest api backend which I'm using for fetching data for each section. For example, /category/1 is sport, /category/1/subcategory/1 is football and so on. First question: How can I create a html file for each of these levels by using prerender.js and How should my static.paths.ts look like? Second question: How can I set meta tags for each of these pages? Third question: How should my app-routing.module look like? Should I use children approach? I'm using Angular 5.0.0 and ngx-restangular 2.0.2 Thank you. A: The setup for prerender and runtime server-side render is mostly similar, the only difference is one is static, the other dynamic. You will still configure everything Universal requires you to set up for it to work. Before I go into your questions, I highly recommend you to follow this (step-by-step configurations) and this (useful sections about Angular Universal pitfalls) guides to configure Angular Universal as it is one of the more comprehensive and up-to-date write ups that I've read. First question: How can I create a html file for each of these levels by using prerender.js and How should my static.paths.ts look like? Your static.path.ts should contain all routes that you want to prerender: export const ROUTES = [ '/', '/category/1/subcategory/1/event/1/ticket/1', '/category/1/subcategory/1/event/1/ticket/2', ... ]; Look tedious right? This is the trade off for having a static generated HTML as opposed to flexible run-time server-side rendering. You could and probably should write your own scripts to generate all routes available to your app (querying the database, generating all possible values, etc) to prerender all the pages that you want. Second question: How can I set meta tags for each of these pages? No different to how you set metatags or any Angular app, you can use the Title and Meta services that Angular provides. Example: constructor( @Inject(PLATFORM_ID) private platformId: Object, private meta: Meta, private title: Title, private pageMetaService: PageMetaService ) { } ngOnInit() { if (isPlatformBrowser(this.platformId)) { this.title.setTitle((`${this.article.title} - Tilt Report`)); let metadata = [ { name: 'title', content: 'Title' }, { name: 'description', content: 'This is my description' }, { property: 'og:title', content: 'og:Title' }, { property: 'og:description', content: 'og:Description' }, { property: 'og:url', content: 'http://www.example.com' }, ]; metadata.forEach((tag) => { this.meta.updateTag(tag) }); }; } Third question: How should my app-routing.module look like? Should I use children approach You can choose to or not to use the 'children' approach, which I assume is lazy loading modules. As you configure Angular Universal, you should do certain setups to enable lazy loaded module to work server-side.
{ "language": "en", "url": "https://stackoverflow.com/questions/50201410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Auth fail : Running maven plugin with JGit I am facing this issue while building a maven project [INFO] Cloning [email protected]:bookkeeper/bookkeeper-openapi3-hosted-ui-configuration.git:refs/tags/v5.0.0 into /Users/shubhamjain/bookkeeper/de/bookkeeper-ui-service/service/bookkeeper-api/bookkeeper-platform-hosted-ui-configuration-5.0.0 [ERROR] Failed to fetch bookkeeper-platform-hosted-ui-configuration API (5.0.0): org.eclipse.jgit.api.errors.TransportException: [email protected]:bookkeeper/bookkeeper-openapi3-hosted-ui-configuration.git: Auth fail at org.eclipse.jgit.api.FetchCommand.call (FetchCommand.java:222) ---- ---- Caused by: org.eclipse.jgit.errors.TransportException: [email protected]:bookkeeper/bookkeeper-openapi3-hosted-ui-configuration.git: Auth fail at org.eclipse.jgit.transport.JschConfigSessionFactory.getSession (JschConfigSessionFactory.java:162) at org.eclipse.jgit.transport.SshTransport.getSession (SshTransport.java:107) Initially I had issues in access to the mentioned repository but then I got required permissions. In the pom.xml ----- ----- <plugin> <groupId>com.bookkeeper</groupId> <artifactId>bookkeeper-api-maven-plugin</artifactId> <executions> <execution> <id>generate-hosted-ui-configuration-openapi-hook</id> <goals> <goal>generate-client</goal> </goals> <configuration> <apiName>bookkeeper-platform-hosted-ui-configuration</apiName> <apiVersion>5.0.0</apiVersion> <repositorySpecPath>bookkeeper-platform-hosted-ui-configuration/application-hosted-ui-configuration.yaml</repositorySpecPath> <gitUrlTemplate>[email protected]:bookkeeper/bookkeeper-openapi3-hosted-ui-configuration.git</gitUrlTemplate> <openapiConfigurationOverrides> <isExperimental>false</isExperimental> <apiName>hosted-ui-configuration</apiName> </openapiConfigurationOverrides> </configuration> </execution> </executions> </plugin> ----- ----- What could be missing ? Thanks in advance. A: Issue was Maven couldn't find ssh binary path on the environment Setting GIT_SSH environment variable worked. export GIT_SSH=${SSH_BINARY_PATH} In my case export GIT_SSH=/usr/bin/ssh
{ "language": "en", "url": "https://stackoverflow.com/questions/75005817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Forgot Password showing 401 (Unauthorized) error I am trying to use forgot password function from strapi's Authentication documentation. When trying to send forgot password request to the api returning an 401 error. I am using vue js as frontend framework. <template> <form @submit.prevent="onForgetPassword"> <label for="name">your email</label> <input type="email" class="from-input" placeholder="Enter Your Email..." v-model="email"/> <button type="submit" class="form-btn">reset password</button> </form> </template> data() { return { email: "" }; }, methods: { onForgetPassword() { axios .post("http://localhost:1337/auth/forgot-password", { email: this.email }) .then(response => { // Handle success. console.log("Your user received an email"); }) .catch(error => { // Handle error. console.log("An error occurred:", error); }); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/59222882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create several variables in a for loop increasing each one by 3 months in R? I need to create 12 variables starting from a certain date t1, increasing each one by 3 months. Here's an example: t1 t2 t3 01-01-2000 01-04-2000 01-07-2000 I've tried something like this (with package lubridate): for (i in 1:12) { month(AAA$t(i+1)) <- month(AAA$t(i)) + 3 } But I'm obtaining: Error in as.POSIXlt(x) : attempt to apply non-function A: If you want to create a dataframe with t1 through t12 containing a range of dates: t = seq(mdy("01/01/2000"), by = "3 months", length.out = 12) #this replaces the loop names(t) <- paste0("t", c(1:12)) #this names your vector data.frame(as.list(t)) #this creates the df
{ "language": "en", "url": "https://stackoverflow.com/questions/56809254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: HealthKit permissions not opening My app is not opening the HealthKit permissions screen where the user can allow access to Healthkit. I receive the screen on my watch that my app "would like to access your health data". But the phone simply moves to the app launch screen then first page instead of bringing up the settings. There is no error. The app is coded below to request authorisations. Any ideas? In the phone AppDelegate: import UIKit import WatchConnectivity import HealthKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, WCSessionDelegate { var window: UIWindow? let healthStore = HKHealthStore() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { WatchSessionManager.sharedManager.startSession() return true } // authorization from watch func applicationShouldRequestHealthAuthorization(application: UIApplication) { let healthStore = HKHealthStore() let quantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) let calorieQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned) let dataTypesToRead = NSSet(objects: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!, HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)!) healthStore.requestAuthorizationToShareTypes(nil, readTypes: dataTypesToRead as! Set<HKObjectType>, completion: { (success, error) in if success { } else { print(error!.description) } }) healthStore.handleAuthorizationForExtensionWithCompletion { success, error in } } A: let healthKitStore:HKHealthStore = HKHealthStore() func authorizeHealthKit(completion: ((_ success:Bool, _ error:NSError?) -> Void)!) { //check app is running on iPhone not other devices(iPad does not have health app) if !HKHealthStore.isHealthDataAvailable() { let error = NSError(domain: "DomainName.HealthKitTest", code: 2, userInfo: [NSLocalizedDescriptionKey:"HealthKit is not available in this Device"]) if completion != nil { completion(false, error) } return; } healthKitStore.requestAuthorization(toShare: healthKitTypeToWrite() as? Set<HKSampleType>, read: nil) { (success, error) -> Void in if completion != nil { print("Success: \(success)") print("Error: \(error)") completion?(success, error as NSError?) } } } func healthKitTypeToWrite() -> NSSet { let typesToWrite = NSSet(objects: HKQuantityType.quantityType(forIdentifier: .dietaryFatTotal), HKQuantityType.quantityType(forIdentifier: .dietaryFatSaturated), HKQuantityType.quantityType(forIdentifier: .dietaryCarbohydrates), HKQuantityType.quantityType(forIdentifier: .dietarySugar), HKQuantityType.quantityType(forIdentifier: .dietaryProtein), HKQuantityType.quantityType(forIdentifier: .dietarySodium)) return typesToWrite } And make sure you add 'NSHealthUpdateUsageDescription' to your info.plist and description saying why you need access to your app. Hope this will help you. A: Adding NSHealthUpdateUsageDescription in my info.plist fixed the issue for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/39927755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: LLVM traverse the IR and look for all calls to @llvm.dbg.declare I am writing an LLVM pass that bookeeps the number of declared variables in an openCL Kernel. To do so, I need to enable debugging information and access the @llvm.dbg.declare info. I iterate through all the instructions of a function and I use the isa<CallInst> template to identify the calling instructions. Now there are two cases here, I can have either call void @llvm.dbg.declare(metadata float addrspace(1)** %4, metadata !20, metadata !DIExpression()), !dbg !21 or %6 = call i32 @get_global_id(i32 0), !dbg !25 How can I check that a CallInst has metadata associated with it, that is, it has @llvm.dbg.declare inside and then how do I extract the name of the variable declaration (I suspect via a getOperand() method ?
{ "language": "en", "url": "https://stackoverflow.com/questions/50764298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: proxy pattern no suitable methods found to override? Help i'm not sure what just went wrong This is all in the form... namespace Proxy_Pattern { public partial class Form1 : Form { public Form1() { InitializeComponent(); } double bankAmount = 1000.00; private void btnCheck_Click(object sender, EventArgs e) { double amount; amount = double.Parse(txtAmount.Text); CheckProxy cp =new CheckProxy(); cp.CheckTransactionRequest(amount); lbltotal.Text = bankAmount.ToString(); } private void btnCreditCard_Click(object sender, EventArgs e) { } } abstract class BankSubject { public abstract void CreditTransactionRequest(double amount); public abstract void CheckTransactionRequest(double amount); } class RealBankSubject : BankSubject { double bank; public RealBankSubject(double m_bacc) { bank = m_bacc; } public override void CreditTransactionRequest(double num) { bank -= num; } public override void CheckTransactionRequest(double num) { bank += num; } } Does not implement inherited abstract members.... but why? class CreditCardProxy : BankSubject { RealBankSubject realSubject; double amount; public CreditCardProxy (double m_bacc) { amount = m_bacc ; } no suitable method to override?... how is this an error? I have a method right here? public override void CreditTransactionRequest() { if (realSubject == null) { realSubject = new RealBankSubject(amount); } realSubject.CreditTransactionRequest(amount); } public override void CheckTransactionRequest() { } } class CheckProxy : BankSubject { RealBankSubject realSubject; double amount; public override void CreditTransactionRequest() { } public override void CheckTransactionRequest() { if (realSubject == null) { realSubject = new RealBankSubject(amount); } realSubject.CheckTransactionRequest(amount); } } } A: CreditTransactionRequest in CreditCardProxy does not take any arguments but CreditTransactionRequest in BankSubject does. This is why you can not override the method the signatures do not match. A: In your proxy, you are not specifying the amount as a parameter to the method: public override void CreditTransactionRequest(); So it cannot override public abstract void CreditTransactionRequest(double amount); as the method signature doesn't not match
{ "language": "en", "url": "https://stackoverflow.com/questions/13036528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I calculate the number of occurrences that is followed by a specific value? (add if statement) How can I calculate the number of occurrences that are ONLY followed by a specific value that is after E*? e.g:'EXXXX' ? file.txt: E2dd,Rv0761,Rv1408 2s32,Rv0761,Rv1862,Rv3086 6r87,Rv0761 Rv2fd90c,Rv1408 Esf62,Rv0761 Evsf62,Rv3086 i tried input: awk -F, '{map[$2]++} END { for (key in map) { print key, map[key] } }' file.txt and add: if [[ $line2 == `E*` ]];then but not working, have syntax error Expected Output: total no of occurrences: Rv0761: 2 Rv3086:1 Now i can only count all number of occurrences of the second value A: if [[ $line2 == `E*` ]];then This definitely is not legal GNU AWK if statement, consult If Statement to find what is allowed, though it is not required in this case as you might as follows, let file.txt content be E2dd,Rv0761,Rv1408 2s32,Rv0761,Rv1862,Rv3086 6r87,Rv0761 Rv2fd90c,Rv1408 Esf62,Rv0761 Evsf62,Rv3086 then awk 'BEGIN{FS=","}($1~/^E/){map[$2]++} END { for (key in map) { print key, map[key] } }' file.txt gives output Rv3086 1 Rv0761 2 Explanation: actions (enclosed in {...}) could be preceeded by pattern, which does restrict their execution to lines which does match pattern (in other words: condition does hold) in above example pattern is $1~/^E/ which means 1st column does starts with E. (tested in gawk 4.2.1) A: You are so close. You are only missing the REGEX to identify records beginning with 'E' and then a ":" concatenated on output to produce your desired results (not in sort-order). For example you can do: awk -F, '/^E/{map[$2]++} END { for (key in map) { print key ":", map[key] } }' file.txt Example Output With your data in file.txt you would get: Rv3086: 1 Rv0761: 2 If you need the output sorted in some way, just pipe the output of the awk command to sort with whatever option you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/74140406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Store pandastable dataframe into variable I currently have the below script that reads an imported csv file and displays as pandastable in the tkinter GUI. As the file is imported its adds x2 additional columns self.table.addColumn("Current Status") and self.table.addColumn("Assign Technician"). How can I store the updated pandastable dataframe into a variable outside of class TestApp(tk.Frame): so that I can call other functions on the dataframe later in my code? I have used the global variable before so that I can call a variable created from within a function outside of it later but not sure if thats what I need for this purpose. import csv import tkinter as tk import tkinter.ttk as tkrttk from tkinter import * from tkinter import filedialog import pandas as pd from pandastable import Table, TableModel root = tk.Tk() root.geometry("2000x1000") root.title('Workshop Manager') def select_input_file(): global input_file_path input_file_path = filedialog.askopenfilename( filetypes=(("CSV files", "*.csv"),)) app = TestApp(root, input_file_path) app.place(bordermode = INSIDE,height = 500, width = 2000, x =0, y=50) class TestApp(tk.Frame): def __init__(self, parent, input_file_path, editable = True, enable_menus = True): super().__init__(parent) self.table = Table(self, showtoolbar=False, showstatusbar=False) self.table.importCSV(input_file_path) self.table.show(input_file_path) self.table.addColumn('Current Status') self.table.addColumn('Assign Technician') self.table.autoResizeColumns() root.mainloop() A: You don't necessarily need a global variable here. You can directly access the member attributes of a class by using the object itself. So in this case, you can access the table attr of the class TestApp using app.table, which would look something like this, def select_input_file(): #... app = TestApp(root, input_file_path) app.place(bordermode = INSIDE,height = 500, width = 2000, x =0, y=50) df = app.table # contains the updated table which can be passed to other functions newFunc( df ) # sample call A: Avoid global to achieve this. Currently, all your stateful variables exist in the module (file). You can do the same for your table, outside of TestApp, and then pass it though __init__: import csv import tkinter as tk import tkinter.ttk as tkrttk from tkinter import * from tkinter import filedialog import pandas as pd from pandastable import Table, TableModel table = Table(showtoolbar=False, showstatusbar=False) root = tk.Tk() root.geometry("2000x1000") root.title('Workshop Manager') def select_input_file(): global input_file_path input_file_path = filedialog.askopenfilename( filetypes=(("CSV files", "*.csv"),)) app = TestApp(root, input_file_path) app.place(bordermode = INSIDE,height = 500, width = 2000, x =0, y=50) class TestApp(tk.Frame): def __init__(self, parent, input_file_path, editable = True, enable_menus = True, table=table): super().__init__(parent) self.table = table self.table.importCSV(input_file_path) self.table.show(input_file_path) self.table.addColumn('Current Status') self.table.addColumn('Assign Technician') self.table.autoResizeColumns() root.mainloop() Your table object is now accessible to anything that can see the module namespace. Here table is a mutable object, and all changes will be reflected to any function that accesses that object. One suggestion: it is preferable to separate out your definitions (classes, functions) from your stateful bits that are created at run time. This will greatly help clarify dependencies. It is typical to use the line if __name__ == "__main__": at the bottom of the file to start the "script" part of your app, keeping all definitions above. I've seen some packages (looking at you, Flask!) break this convention a bit, and it can cause headaches. On that note, your select_input_file function has a few issues. There's no good reason to create an app instance there. A better option would be to make this a method in the App class for example.
{ "language": "en", "url": "https://stackoverflow.com/questions/63555587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Created shell script for mac but I am getting an error when I run it run_QA.sh: #!/bin/bash set v # ------------------------------------------------------- # 0 : Do NOT execute tests for the platform # Anything else(e.g. 1) Execute tests for the platform # ------------------------------------------------------- export PROJECT_DIR=$CD # TEST SUITE CAPBILITIES # include or exclude test scenarios and/or story files (e.g. "- skip,+checkout") # -: means exclude # +: means include export PARAM="-skip,+Delta" # MAVEN EXECUTION PROFILE export SINGLETHREAD=singlethread export PARALLEL=parallel export MULTITHREAD=multithread # set profile for building export PROFILE=$SINGLETHREAD # TEST RESULTS LOCATION export TEST_RESULTS=TestResults # =================================== DESKTOP ======================================== # ---------- Delta (English) ---------- #:DESKTOP_DT_EN # chrome, iexplorer, firefox export BROWSER=firefox export BRAND=TIMBERLAND export TEST_ENV=NA export LAN=EN export PLATFORM=DESKTOP export SOURCE=${PROJECT_DIR}/src/test/resources/test_data/$BRAND/$TEST_ENV export DESTINATION=${PROJECT_DIR}/src/test/resources echo --- Creating Test Results folder... #MD $PROJECT_DIR/$TEST_RESULTS/$BRAND_$TEST_ENV_$PLATFORM_$LAN_$TEST_RESULTS$/site/serenity #echo --- Testing DESKTOP_DT_EN export BASE_URL=http://qa.timberland.com/ export META_FILTER=$PARAM echo --- calling run.sh file... #$PROJECT_DIR #echo "test" #source=/Users/oletis/git/automation/TimberlandSuite call %PROJECT_DIR%\run.sh run.sh: #!/bin/bash #set v echo -------------------------------------------------------------------------------------- echo Test Environment: $BRAND:$TEST_ENV_$PLATFORM_$LAN echo $BRAND echo $TEST_ENV echo $PLATFORM echo $LAN echo $BASE_URL echo -------------------------------------------------------------------------------------- #::echo Removing previous test results... #::IF exist $PROJECT_DIR/$TEST_RESULTS/$BRAND_$TEST_ENV_$PLATFORM_$LAN_$TEST_RESULTS DEL /S /Q /F $PROJECT_DIR/$TEST_RESULTS/$BRAND_$TEST_ENV_$PLATFORM_$LAN_$TEST_RESULTS | echo > /dev/null #::echo Done #::echo echo cd to project directory… cd "${PROJECT_DIR}" echo Done echo . set DEFAULTPROFILE=$SINGLETHREAD echo thread if [ $PROFILE=$MULTITHREAD ] then export DEFAULTPROFILE=$MULTITHREAD echo here elif [ $PROFILE=$SINGLETHREAD ] then export DEFAULTPROFILE=$SINGLETHREAD echo hereo elif [ $PROFILE=$PARALLEL ] then export DEFAULTPROFILE=$PARALLEL echo sdsf else echo ****************** Invalid profile configuration... echo ****************** Using default profile: "$DEFAULTPROFILE" fi echo bush echo --- Running in $DEFAULTPROFILE mode --- echo --- Deleting table files from $DESTINATION... if [ -e $destionation/*.table ] DEL /Q /F $DESTINATION/*.table echo Done else echo ****** No files deleted echo. fi echo Preparing test-data files... # copy test_data to appropriate files cp -f "$SOURCE/$LAN_General.table" "$DESTINATION/General.table" echo Done echo # ) echo Cleaning... .mvn clean echo Done echo. echo Compiling... .mvn compile echo Done echo. echo Executing... # the metafilter=-skip is configured in Serenity.properties file, so no need to pass it as a parameter # . mvn verify -Dmetafilter="-skip" | echo >> log.txt # to run with checkstyle and OMD use -DskipTests. To disable code compliance use -DskipCodeCompliance=true # . mvn verify -DskipTests -Dwebdriver.driver=$BROWSER -Dwebdriver.base.url="$BASE_URL" # . mvn verify -Dmetafilter=$META_FILTER -Dwebdriver.driver=$BROWSER -Dwebdriver.base.url="$BASE_URL" -Dbrand="$BRAND" if [ $PROFILE==$MULTITHREAD ]; then{ #echo Starting in myversion .mvn integration-test -P $DEFAULTPROFILE -Dlan=$LAN -Dbrand=$BRAND -Dtestenv=$TEST_ENV -Dmetafilter=$META_FILTER -Dwebdriver.driver=$BROWSER -Dwebdriver.base.url="$BASE_URL" -Dplatform=$PLATFORM .mvn serenity:aggregate -P $DEFAULTPROFILE } elif [ $PROFILE==$SINGLETHREAD ]; then { echo SINGLETHREAD # .mvn verify -Dmetafilter=$META_FILTER -Dwebdriver.driver=$BROWSER -Dwebdriver.base.url="$BASE_URL" -Dbrand.name="$BRAND" if [ $PLATFORM=="BROWSERSTACK" ]; then { .mvn verify -P $DEFAULTPROFILE -DproxySet=true -DproxyHost=proxy4.wipro.com -DproxyPort=8080 -DproxyUser=PA257736 -DproxyPass=Fossil#in -Dlan=$LAN -Dbrand=$BRAND -Dmetafilter=$META_FILTER -Dplatform=$PLATFORM -Dbrowserstack.os=$BROWSERSTACK_OS -Dbrowserstack.os.version=$BROWSERSTACK_OS_VERSION -Dbrowserstack.browser=$BROWSER -Dbrowserstack.browser.version=$BROWSER_VERSION -Dbrowserstack.build=BROWSERSTACK_BUILD -Dbrowserstack.url=$BROWSERSTACK_URL -Dwebdriver.base.url="$BASE_URL" } else .mvn verify -P $DEFAULTPROFILE -Dlan=$LAN -Dbrand=$BRAND -Dtestenv=$TEST_ENV -Dmetafilter=$META_FILTER -Dwebdriver.driver=$BROWSER -Dwebdriver.base.url="$BASE_URL" -Dplatform=$PLATFORM fi } fi echo Execution Done echo echo a date=$(date +"%d%m%y") echo $date timestamp=$(date +"%H%M") echo $timestamp echo s echo --- Copying test result to $TEST_RESULTS folder... if ![ -e $PROJECT_DIR/$TEST_RESULTS MD $PROJECT_DIR/$TEST_RESULTS ] #XCP /E "$PROJECT_DIR/target/*.*" "$PROJECT_DIR/"$TEST_RESULTS"/"$BRAND"_"$TEST_ENV"_"$PLATFORM"_"$LAN"_"$TEST_RESULTS"/*.*" | echo > /dev/null XCP /E "$PROJECT_DIR/target/*.*" "$PROJECT_DIR/$TEST_RESULTS/$BRAND_$TEST_ENV_$PLATFORM_$BROWSER_$LAN_$date_$timestamp/*.*" | echo > /dev/null fi echo Done echo When I run it, command not found error is coming. l-185002536:timberlandsuite imguser$ sh run_QA.sh : command not found : command not found : command not found : command not found : command not found : command not found : command not found : command not found : command not found : command not found : command not found : command not found : command not found : command not found : command not found : command not found : command not found : command not found --- Creating Test Results folder... : command not found : command not found : command not found --- calling run.sh file... : command not found run_QA.sh: line 63: call: command not found
{ "language": "en", "url": "https://stackoverflow.com/questions/42801638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PostScript Path Combine I have just begun learning PostScript in order to produce graphics for LaTeX and I have no idea how to combine a path with itself so the stroke only affect the outer border of the drawn shape. My code is as follows: /black { 0 0 0 1 setcmykcolor } def /gold { 0.02 0.17 0.72 0.05 setcmykcolor } def newpath % the center is 1/2w and 1/2h /cx { 1200 2.0 div } def % center-x /cy { 600 2.0 div } def % center-y /r { 600 9.0 div 4 mul 2.0 div } def % star's radius cx r 0 cos mul add cy r 0 sin mul add moveto cx r 144 cos mul add cy r 144 sin mul add lineto cx r 288 cos mul add cy r 288 sin mul add lineto cx r 72 cos mul add cy r 72 sin mul add lineto cx r 216 cos mul add cy r 216 sin mul add lineto closepath gsave gold fill grestore 1 setlinewidth black stroke When the stroke is drawn, the lines crossing the shape are drawn. I would like to know if there is a way to only have the outer border of the shape stricken and not the inner lines. i would rather not have to calculate where the lines forming the star intersect, i.e. keep 5 lines instead of getting 10 smaller ones. Note also, that I am learning PS as-is and am not wanting to use external programs (read Illustrator and the like). The purpose of this question is to built up my knowledge of PostScript. A: Simplest would be to do the stroke first and then the fill. You may want to double your linewidth as doing this effectively cuts the lines in half. %... closepath gsave 2 setlinewidth black stroke grestore gold fill A: PostScript is missing an anticlip operator, which should restrict painting to outside the current path. There is clip, which restricts painting to inside, but that doesn’t help with this problem. As previously suggested, you could stroke at double linewidth, and then fill white, but if you want to paint this on top of something else, that strategy obscures whatever is below. Or you could make the star a little bigger (I suspect, but haven’t checked, by currentlinewidth 2 5 sqrt 2 mul 5 div add sqrt mul 2 div), but that would only look right if 1 setlinejoin.
{ "language": "en", "url": "https://stackoverflow.com/questions/11302089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Power BI dashboard with reports based on a push dataset do not alwasy update regularly I have written a little C# program which pushes data to a a streaming push dataset on Power BI Service. I have a report with a couple of simple visuals (nothing fancy) which are in turn pinned to a dashboard. About half the time I open the dashboard the Dashboard updates every few seconds. But half the time it does not update at all and is laggy even if I push the refresh button. Why is it inconsistent? I know the data pusher is running as I can refresh the base report and see the new data points come in. What is it that I am missing? Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/72809530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't insert a function to a element on onclick event (JS) I have problem with this code: var xButton = document.createElement("a"); xButton.className = "cXButton"; xButton.href = "#"; xButton.onclick = "closePanel()"; xButton.innerHTML = "X"; While "closePanel()" is a function I already wrote. I used Firebug and found out that "onclick" attribute doesn't appear in a tag. I saw some threads where instead of the name of the function there is it's implementation (function closePanel(){...}). This is not what I'm looking for. Any suggestions how to solve it? A: Your have two problems in your original code: * *"closePanel()" is a string. *closePanel() attempts to (or would if it wasn't a string) call the function and assign it's output to xButton.onclick It should be this instead: xButton.onClick = closePanel; This will assign a reference to the function closePanel() to xButton.onClick, calling closePanel() when the xButton.onClick event is triggered. Remember you can use this inside the declaration of closePanel() to reference the clicked element.
{ "language": "en", "url": "https://stackoverflow.com/questions/16151107", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What's the difference between @observable and @published in polymer.dart? In polymer.dart, if you want to expose a variable defined in controller to the view side, you define the variable with @observable and use double mustache to embed the variable. However, some docs and tutorials use @published to meet the same purpose. The official docs also uses both, so I don't think @published is legacy and deprecated way of defining variables. So is there any difference between the two? And which one should I use in my code? A: @published - is two way binding ( model to view and view to model) Use case for @published is ,if your model property is also attribute in a tag. Example : For a table-element you want to provide data from external source ,so you'll define attribute data,in this case data property should be @published . <polymer-element name = "table-element" attributes ="structure data"> <template> <table class="ui table segment" id="table_element"> <tr> <th template repeat="{{col in cols}}"> {{col}} </th> </tr> <tr template repeat="{{row in data}}"> etc...... </template> <script type="application/dart" src="table_element.dart"></script> </polymer-element> @CustomTag("table-element") class Table extends PolymerElement { @published List<Map<String,String>> structure; // table struture column name and value factory @published List<dynamic> data; // table data @observable - is one way binding - ( model to view) If you just want to pass data from model to view use @observable Example : To use above table element i have to provide data ,in this case data and structure will be observable in my table-test dart code. <polymer-element name = "table-test"> <template> <search-box data ="{{data}}" ></search-box> <table-element structure ="{{structure}}" data = "{{data}}" ></table-element> </template> <script type="application/dart" src="table_test.dart"></script> </polymer-element> dart code CustomTag("table-test") class Test extends PolymerElement { @observable List<People> data = toObservable([new People("chandra","<a href=\"http://google.com\" target=\"_blank\"> kode</a>"), new People("ravi","kiran"),new People("justin","mat")]); @observable List<Map<String,String>> structure = [{ "columnName" : "First Name", "fieldName" : "fname"}, {"columnName" : "Last Name", "fieldName" : "lname","cellFactory" :"html"}]; Test.created():super.created(); Examples are taken from My Repo
{ "language": "en", "url": "https://stackoverflow.com/questions/23599378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Can Kafka replication deploy on different machine? I'm running a project. My goal is to design a Kafka cluster. Preventing the condition that when one machine die, the data on that Kafka all disappear. I wonder if Kafka replication can be set on different machine in order to back-up? A: In addition to setting a replication factor of 2 or 3 on your topics to ensure backup replica copies are eventually created, you should also publish messages with acks=all to ensure that acknowledgements indicate a guarantee that the data has been written to all the replicas. Otherwise with acks=1 you get an ack after only 1 copy is committed, and with acks=0 you get no acks at all so you would never know if your published messages ever made it into the Kafka commit log or not. Also set unclean leader election parameter to false to ensure that only insync replicas can ever become the leader. A: In Kafka you can define the replication factor for a topic and in this way each partition is replicated on more broker. One of them is a leader where producer and consumer connect for exchanging messages. The other will be followers which get copies of messages from the leader to be in sync. If the leader goes down, a new leader election starts between all in sync replicas. Kafka will support N-1 failed brokers where N is the replication factor. A: yes , the replication factor defines this.
{ "language": "en", "url": "https://stackoverflow.com/questions/44594188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flutter Webrtc Build error on M1 android and ios I am trying to build a webrtc flutter app on my m1 macbook air. But I got different issues both on android and ios. Latest one ^0.8.2 has error on both then ^0.7.0+hotfix.1 demo demo only works for android. On iOS part 'Libyuv''s deployment target is set to 8.0 but min deployment target is 9.0 occurs. I set the deployment target above 10 then it still happens. /Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterWebRTCPlugin.h:8:9: fatal error: 'WebRTC/WebRTC.h' file not found #import <WebRTC/WebRTC.h> ^~~~~~~~~~~~~~~~~ 1 error generated. /Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterRTCMediaStream.m:3:9: fatal error: 'WebRTC/WebRTC.h' file not found #import <WebRTC/WebRTC.h> ^~~~~~~~~~~~~~~~~ 1 error generated. In file included from /Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterRTCFrameCapturer.m:8: /Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterRTCFrameCapturer.h:6:9: fatal error: 'WebRTC/WebRTC.h' file not found #import <WebRTC/WebRTC.h> ^~~~~~~~~~~~~~~~~ 1 error generated. In file included from /Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterRTCDataChannel.m:2: In file included from /Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterRTCDataChannel.h:1: /Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterWebRTCPlugin.h:8:9: fatal error: 'WebRTC/WebRTC.h' file not found #import <WebRTC/WebRTC.h> ^~~~~~~~~~~~~~~~~ 1 error generated. note: Using new build system note: Building targets in parallel note: Planning build note: Analyzing workspace note: Constructing build description note: Build preparation complete /Users/alperenbaskaya/AndroidStudioProjects/flutter-webrtc-demo/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 4.3, but the range of supported deployment target versions is 9.0 to 14.5.99. (in target 'Libyuv' from project 'Pods') Could not build the application for the simulator. Error launching application on iPhone 8 Plus. After a workaround I updated libyuv deployment target but now I got following ios Error; objc[66512]: Class AMSupportURLConnectionDelegate is implemented in both /usr/lib/libauthinstall.dylib (0x20d426c10) and /System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice (0x113d3c2b8). One of the two will be used. Which one is undefined. objc[66512]: Class AMSupportURLSession is implemented in both /usr/lib/libauthinstall.dylib (0x20d426c60) and /System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice (0x113d3c308). One of the two will be used. Which one is undefined. ** BUILD FAILED ** Xcode's output: ↳ warning: [CP] Unable to find matching .xcframework slice in 'ios-arm64_x86_64-simulator ios-arm64_armv7' for the current build architectures (arm64 x86_64 i386). In file included from /Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.8.2/ios/Classes/FlutterRTCPeerConnection.m:2: /Users/alperenbaskaya/Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.8.2/ios/Classes/FlutterWebRTCPlugin.h:8:9: fatal error: 'WebRTC/WebRTC.h' file not found #import <WebRTC/WebRTC.h> ^~~~~~~~~~~~~~~~~ 1 error generated. note: Using new build system note: Building targets in parallel note: Planning build note: Analyzing workspace note: Constructing build description note: Build preparation complete Could not build the application for the simulator. Error launching application on iPhone 8 Plus. On android side I got following; Execution failed for task ':flutter_webrtc:compileDebugJavaWithJavac'. A: For version ^0.8.2 following solutions work for me. iOS in ios/Podfile add following to end of file. post_install do |installer| installer.pods_project.targets.each do |target| flutter_additional_ios_build_settings(target) target.build_configurations.each do |build_configuration| build_configuration.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = 'arm64 i386' end end end Then clean your project and follow these steps as santoshakil mentioned santoshakilsanswer; (Those steps work for me if not follow all steps mentioned in link) flutter clean && flutter pub get cd ios arch -x86_64 pod update arch -x86_64 pod install then at the top of your Pod file, paste this line platform :ios, '10.0' right click on ios folder and open in xcode and then set all deployment target to 10 Android Your android/app/build.gradle look like below as webrtcflutterdemo def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) } } def flutterRoot = localProperties.getProperty('flutter.sdk') if (flutterRoot == null) { throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } apply plugin: 'com.android.application' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" android { compileSdkVersion 28 lintOptions { disable 'InvalidPackage' } defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "com.cloudwebrtc.flutterwebrtcdemo" minSdkVersion 21 targetSdkVersion 28 versionCode flutterVersionCode.toInteger() versionName flutterVersionName testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.debug useProguard true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } packagingOptions { exclude 'META-INF/proguard/androidx-annotations.pro' } } flutter { source '../..' } dependencies { testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' } android/app/AndroidManifest.xml <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.cloudwebrtc.flutterwebrtcdemo"> <!-- The INTERNET permission is required for development. Specifically, flutter needs it to communicate with the running application to allow setting breakpoints, to provide hot reload, etc. --> <uses-permission android:name="android.permission.INTERNET"/> <uses-feature android:name="android.hardware.camera" /> <uses-feature android:name="android.hardware.camera.autofocus" /> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> <!-- io.flutter.app.FlutterApplication is an android.app.Application that calls FlutterMain.startInitialization(this); in its onCreate method. In most cases you can leave this as-is, but you if you want to provide additional functionality it is fine to subclass or reimplement FlutterApplication and put your custom class here. --> <application android:label="flutter_webrtc_demo" android:icon="@mipmap/ic_launcher"> <meta-data EDIT For Android side, i can not build for compilesdk and targetsdk 31. Temporary solution is downgrading compilesdk to 30. It is about jdk version on your mac device.
{ "language": "en", "url": "https://stackoverflow.com/questions/71024372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Not able to click on the button using Selenium <button class="css-obkt16-button" type="button"><span class="css-1mhnkuh">Download CSV</span></button> I am trying to click on the highlighted button 'Download CSV' having the above HTML code and save the csv file at some particular location, but I am not able to do so. The file is getting downloaded in Downloads folder. My python code: def scrape_data(): DRIVER_PATH = r"C:\chrome\chromedriver.exe" driver = webdriver.Chrome(DRIVER_PATH) driver.get('Link to the dashboard') time.sleep(20) buttons = driver.find_element(By.XPATH,"//button/span[text()='Download CSV']") time.sleep(5) driver.execute_script("arguments[0].click();", buttons) driver.quit() So please suggest a way to search via the button text) and save the file to a particular location?? A: To download the file on specific location you can try like blow. from selenium.webdriver.chrome.options import Options options = Options() options.add_experimental_option("prefs", { "download.default_directory": r"C:\Data_Files\output_files" }) s = Service('C:\\BrowserDrivers\\chromedriver.exe') driver = webdriver.Chrome(service=s, options=options) A: * *You should not use hardcoded sleeps like time.sleep(20). WebDriverWait expected_conditions should be used instead. *Adding a sleep between getting element and clicking it doesn't help in most cases. *Clicking element with JavaScript should be never used until you really have no alternative. *This should work in case the button you trying to click is inside the visible screen area and the locator is unique. def scrape_data(): DRIVER_PATH = r"C:\chrome\chromedriver.exe" driver = webdriver.Chrome(DRIVER_PATH) wait = WebDriverWait(driver, 30) driver.get('Link to the dashboard') wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(.,'Download CSV')]"))).click()
{ "language": "en", "url": "https://stackoverflow.com/questions/74768873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to instrumentation test activity going into background (STOPPED) then foreground (RESUMED)? I'm trying to do an instrumentation test to test behaviour when the app has been backgrounded then brought back to the foreground. I thought it would be easy to use ActivityScenario.moveToState(), then it doesn't have an enum for the stopped state. I was then thinking to use UiAutomator to press the home button, then somehow find the app icon and click on it again to launch it. It might be possible...but also very fragile. Is there any easy and solid way to just bring the activity to stopped state, then bring it back to resumed?
{ "language": "en", "url": "https://stackoverflow.com/questions/72400671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Voximplant – the callSIP method to call a phone number I want to use the Voximplant's callSIP method to call a phone number. Is it possible? How do I specify a number to call in the VoxEngine.callSIP() method? A: When you call via callSIP, you make a call to a 3rd-party PBX. If the PBX allows calling to phone numbers, yes, you can do it, but you need to find out what format the PBX accepts. In most cases, you can specify the number in the To field in the username part of the SIP address, for example: number_to_call@domain. Alternatively, you can call a phone number directly through Voximplant via the callPSTN() method.
{ "language": "en", "url": "https://stackoverflow.com/questions/75408226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is a graph library (eg NetworkX) the right solution for my Python problem? I'm rewriting a data-driven legacy application in Python. One of the primary tables is referred to as a "graph table", and does appear to be a directed graph, so I was exploring the NetworkX package to see whether it would make sense to use it for the graph table manipulations, and really implement it as a graph rather than a complicated set of arrays. However I'm starting to wonder whether the way we use this table is poorly suited for an actual graph manipulation library. Most of the NetworkX functionality seems to be oriented towards characterizing the graph itself in some way, determining shortest distance between two nodes, and things like that. None of that is relevant to my application. I'm hoping if I can describe the actual usage here, someone can advise me whether I'm just missing something -- I've never really worked with graphs before so this is quite possible -- or if I should be exploring some other data structure. (And if so, what would you suggest?) We use the table primarily to transform a user-supplied string of keywords into an ordered list of components. This constitutes 95% of the use cases; the other 5% are "given a partial keyword string, supply all possible completions" and "generate all possible legal keyword strings". Oh, and validate the graph against malformation. Here's an edited excerpt of the table. Columns are: keyword innode outnode component acs 1 20 clear default 1 100 clear noota 20 30 clear default 20 30 hst_ota ota 20 30 hst_ota acs 30 10000 clear cos 30 11000 clear sbc 10000 10199 clear hrc 10000 10150 clear wfc1 10000 10100 clear default 10100 10101 clear default 10101 10130 acs_wfc_im123 f606w 10130 10140 acs_f606w f550m 10130 10140 acs_f550m f555w 10130 10140 acs_f555w default 10140 10300 clear wfc1 10300 10310 acs_wfc_ebe_win12f default 10310 10320 acs_wfc_ccd1 Given the keyword string "acs,wfc1,f555w" and this table, the traversal logic is: * *Start at node 1; "acs" is in the string, so go to node 20. *None of the presented keywords for node 20 are in the string, so choose the default, pick up hst_ota, and go to node 30. *"acs" is in the string, so go to node 10000. *"wfc1" is in the string, so go to node 10100. *Only one choice; go to node 10101. *Only one choice, so pick up acs_wfc_im123 and go to node 10130. *"f555w" is in the string, so pick up acs_f555w and go to node 10140. *Only one choice, so go to node 10300. *"wfc1" is in the string, so pick up acs_wfc_ebe_win12f and go to node 10310. *Only one choice, so pick up acs_wfc_ccd1 and go to node 10320 -- which doesn't exist, so we're done. Thus the final list of components is hst_ota acs_wfc_im123 acs_f555w acs_wfc_ebe_win12f acs_wfc_ccd1 I can make a graph from just the innodes and outnodes of this table, but I couldn't for the life of me figure out how to build in the keyword information that determines which choice to make when faced with multiple possibilities. Updated to add examples of the other use cases: * *Given a string "acs", return ("hrc","wfc1") as possible legal next choices *Given a string "acs, wfc1, foo", raise an exception due to an unused keyword *Return all possible legal strings: * *cos *acs, hrc *acs, wfc1, f606w *acs, wfc1, f550m *acs, wfc1, f555w *Validate that all nodes can be reached and that there are no loops. I can tweak Alex's solution for the first two of these, but I don't see how to do it for the last two. A: Definitely not suitable for general purpose graph libraries (whatever you're supposed to do if more than one of the words meaningful in a node is in the input string -- is that an error? -- or if none does and there is no default for the node, as for node 30 in the example you supply). Just write the table as a dict from node to tuple (default stuff, dict from word to specific stuff) where each stuff is a tuple (destination, word-to-add) (and use None for the special "word-to-add" clear). So e.g.: tab = {1: (100, None), {'acs': (20, None)}), 20: ((30, 'hst_ota'), {'ota': (30, 'hst_ota'), 'noota': (30, None)}), 30: ((None, None), {'acs': (10000,None), 'cos':(11000,None)}), etc etc Now handling this table and an input comma-separated string is easy, thanks to set operations -- e.g.: def f(icss): kws = set(icss.split(',')) N = 1 while N in tab: stuff, others = tab[N] found = kws & set(others) if found: # maybe error if len(found) > 1 ? stuff = others[found.pop()] N, word_to_add = stuff if word_to_add is not None: print word_to_add A: Adding an answer to respond to the further requirements newly edited in...: I still wouldn't go for a general-purpose library. For "all nodes can be reached and there are no loops", simply reasoning in terms of sets (ignoring the triggering keywords) should do: (again untested code, but the general outline should help even if there's some typo &c): def add_descendants(someset, node): "auxiliary function: add all descendants of node to someset" stuff, others = tab[node] othernode, _ = stuff if othernode is not None: someset.add(othernode) for othernode, _ in others.values(): if othernode is not None: someset.add(othernode) def islegal(): "Return bool, message (bool is True for OK tab, False if not OK)" # make set of all nodes ever mentioned in the table all_nodes = set() for node in tab: all_nodes.add(node) add_desendants(all_nodes, node) # check for loops and connectivity previously_seen = set() currently_seen = set([1]) while currently_seen: node = currently_seen.pop() if node in previously_seen: return False, "loop involving node %s" % node previously_seen.add(node) add_descendants(currently_seen, node) unreachable = all_nodes - currently_seen if unreachable: return False, "%d unreachable nodes: %s" % (len(unreachable), unreachable) else: terminal = currently_seen - set(tab) if terminal: return True, "%d terminal nodes: %s" % (len(terminal), terminal) return True, "Everything hunky-dory" For the "legal strings" you'll need some other code, but I can't write it for you because I have not yet understood what makes a string legal or otherwise...!
{ "language": "en", "url": "https://stackoverflow.com/questions/844505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: toXmlString analog in XmlService? currently I am trying to rewrite my old script which uses Xml, the only trouble I have is that I cannot find in XmlService documentation any method similar to .toXmlString() from Xml. This issue isn't critical since I was using it for debug purposes only, but if possible I'd like to keep this functionality. tl;dr; The question is - how can I get raw xml string representation of element in new google's XmlService? I tried almost all methods of Element class and none of them produce this Not sure if this specific info would be helpful or not - I am using google script to populate google sheet from rss feed. Below is a simple code snippet I used for testing various XmlService methods. I left items[0].getValue() which I used to confirm that I have correct items array with real data (in log I see all values of subelements, concatenated into single string) var stream = UrlFetchApp.fetch(url).getContentText() var xmldata = XmlService.parse(stream); Logger.log("XMLDATA fetch from " + url) var channel = xmldata.getRootElement().getChild('channel') var items = channel.getChildren("item") Logger.log("Items count: " + items.length) Logger.log(items[0].getValue()) return To be precise, instead of getValue() I need some method that would convert inner xml object into it's string representation A: Found an answer - Element class doesn't have this functionality anymore, it's been moved to global XmlService, like this: XmlService.getCompactFormat().format(items[0]) produces what I need - one text line containing xml-formatted items[0] element
{ "language": "en", "url": "https://stackoverflow.com/questions/29842636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Messenger on different windows issue I have a messenger on PHP/js, imported to all pages of the website. The messenger works through ajax, checking for new messages each 5 seconds. Also I have desktop and sound notifications. The problem is, if I opened multiple pages, and I'm currently on one of them, the reminder may come from another page, which is currently not active. However, inactive pages should notify only if the active page is not the same website. Ideas? A: Check for window focus: var window_focus; $(window).focus(function() { window_focus = true; }).blur(function() { window_focus = false; }); Check if location.host matches specified domain and window is focused: if((location.host == "example.com")&&(window_focus == true)) { //window is focused and on specified domain for that website. //sounds, notifications, etc. here } Not completely sure if this is what you mean, but I hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/46582682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Uploading images for inline content without an html editor I've got a client with a D7 site in which all content is created by a single employee who knows html and css, but never accesses the back end. Is there a way to let them upload images to embed in content (not a field) without installing an html editor? No styles are used or needed. The images are created just as they need to use them. A: Have you already looked at the IMCE module? IMCE is an image/file uploader and browser that supports personal directories and quota. https://drupal.org/project/imce
{ "language": "en", "url": "https://stackoverflow.com/questions/21053389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Xcode 11 Beta 3 animation no longer works I have just changed from Xcode 11 Beta 2, to Beta 3, and although I had to also change the navigationButton to navigationLink, all is ok, expect for the .animation() Has anyone else seen this issue? Have they changed something? I was working just fine in Beta 2. Thanks !! import SwiftUI struct BackGround : View { var body: some View { ZStack{ Rectangle() .fill(Color.gray) .opacity(0.9) .cornerRadius(15.0) .shadow(radius: /*@START_MENU_TOKEN@*/10/*@END_MENU_TOKEN@*/) .blur(radius: 5) .padding(20) .animation(.basic()) } } } A: I found that if I wrapped the content of a view in a VStack, perhaps other Stacks would also work, the view will animate in the previewer Heres a quick example of a view that if wrapped in a VStack in the PreviewProvider previews the button will animate. But if the VStack is removed it will no longer animate. Try it out! struct AnimatedButton : View { @State var isAnimating: Bool = false var body: some View { Button(action: { self.isAnimating.toggle() }) { Text("asdf") }.foregroundColor(Color.yellow) .padding() .background(Color(.Green)) .cornerRadius(20) .animation(.spring()) .scaleEffect(isAnimating ? 2.0 : 1.0) } } #if DEBUG struct FunButton_Previews : PreviewProvider { static var previews: some View { VStack { AnimatedButton() } } } #endif
{ "language": "en", "url": "https://stackoverflow.com/questions/56896491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bag of Words encoding for Python with vocabulary I am trying to implement new columns into my ML model. A numeric column should be created if a specific word is found in the text of the scraped data. For this I created a dummy script for testing. import pandas as pd bagOfWords = ["cool", "place"] wordsFound = "" mystring = "This is a cool new place" mystring = mystring.lower() for word in bagOfWords: if word in mystring: wordsFound = wordsFound + word + " " print(wordsFound) pd.get_dummies(wordsFound) The output is cool place 0 1 This means there is one sentence "0" and one entry of "cool place". This is not correct. Expectations would be like this: cool place 0 1 1 A: Found a different solution, as I cound not find any way forward. Its a simple direct hot encoding. For this I enter for every word I need a new column into the dataframe and create the encoding directly. vocabulary = ["achtung", "suchen"] for word in vocabulary: df2[word] = 0 for index, row in df2.iterrows(): if word in row["title"].lower(): df2.set_value(index, word, 1)
{ "language": "en", "url": "https://stackoverflow.com/questions/59443912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Selecting Individual rows using LIMIT I'm trying to figure out if there's anyway to use GROUP_CONCAT to select rows based on these parameters. What I'm trying to to get the lowest time for every single style/zonegroup. AKA: Lowest Time for Style 0 ZoneGroup 0 Lowest Time for Style 0 ZoneGroup 1 Lowest Time for Style 0 ZoneGroup 2 Lowest Time for Style 1 ZoneGroup 0 Lowest Time for Style 2 ZoneGroup 0 ... I could have multiple queries sent through my plugin, but I would like to know if this could be firstly eliminated with a GROUP_CONCAT function, and if so -how. Here's what I could do, but I'ld like to know if this could be converted into one line. for (int i = 0; i < MAX_STYLES; i++) { for (int x = 0; x < MAX_ZONEGROUPS; x++) { Transaction.AddQuery("SELECT * FROM `t_records` WHERE mapname = 'de_dust2' AND style = i AND zonegroup = x ORDER BY time ASC LIMIT 1;"); } } Thanks. A: You don't need group_concat(). You want to filter records, so use WHERE . . . in this case with a correlated subquery: select r.* from t_records r where r.mapname = 'de_dust2' and r.timestamp = (select min(r2.timestamp) from t_records r2 where r2.mapname = r.mapname and r2.style = r.style and r2.zonegroup = r.zonegroup );
{ "language": "en", "url": "https://stackoverflow.com/questions/40948605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generic Try[T] function I want to refactor some common error handling logic in a generic Try[T] handler, similar to this: def handler[T](t: Try[T], successFunc: T => Unit) = { t.map { case Success(res) => { // type mismatch required T, found Any (in successFunc line) //case Success(res: T) => { // Type abstract type pattern T is unchecked since it is eliminated by erasure successFunc(res) } case Failure(e: CustomException) => { // custom actions } case Failure(e) => { // custom actions } } } Seems I can't match against the type T because of type erasure. But I can't pass an Any to successFunc. How can I implement this function? A: Mapping on a try applies a function to the value held by a success of that try, what you have there is not a Success or a Failure, it's a T, what you want is a match: def handler[T](t: Try[T], successFunc: T => Unit) = { t match { case Success(res) => successFunc(res) case Failure(e: FileNotFoundException) => case Failure(e) => } } The usage in your case of map would be: t.map(someT => successFunc(someT))
{ "language": "en", "url": "https://stackoverflow.com/questions/34075324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }