text
stringlengths
64
89.7k
meta
dict
Q: JRE Redistributable License Is JRE (standard edition) freely redistributable with our commercial application? Is yes, what license text / note should I look into. Any pointers will greatly appreciated. A: If you download the JRE from Oracle, you should receive a license, where this all is explained in great detail.
{ "pile_set_name": "StackExchange" }
Q: Elasticsearch order responses and then facet Is it possible to order responses by a certain field and then apply faceting? My app contains workorder documents and activity log entries. Employees log time spent working on a workorder by creating activity log entries in separate documents that are then associated with the workorder document. I'd like to be able to query ES and have it return activity log entries ordered by workorderID and then compute a stats facet against the activity log entries for each workorder. A: From what I gather (glanced at the gist) you don't need info from Workorder-docs to fullfill this query right? i.e: all data you need exists in Activity-docs. If I understand your question correctly you can use Terms-Stats-field http://www.elasticsearch.org/guide/reference/api/search/facets/terms-stats-facet/ Whereby you specify: key_field = workorderId value_field = numHours From that url: { "query" : { "match_all" : { } }, "facets" : { "tag_price_stats" : { "terms_stats" : { "key_field" : "tag", "value_field" : "price" } } } } hth
{ "pile_set_name": "StackExchange" }
Q: how to remember scroll position of page I am submitting some data to my database then reloading the same page as the user was just on, I was wondering if there is a way to remember the scroll position the user was just on? A: I realized that I had missed the important part of submitting, so, I decided to tweak the code to store the cookie on click event instead of the original way of storing it while scrolling. Here's a jquery way of doing it: jsfiddle ( Just add /show at the end of the url if you want to view it outside the frames ) Very importantly, you'll need the jquery cookie plugin. jQuery: // When document is ready... $(document).ready(function() { // If cookie is set, scroll to the position saved in the cookie. if ( $.cookie("scroll") !== null ) { $(document).scrollTop( $.cookie("scroll") ); } // When a button is clicked... $('#submit').on("click", function() { // Set a cookie that holds the scroll position. $.cookie("scroll", $(document).scrollTop() ); }); }); Here's still the code from the original answer: jsfiddle jQuery: // When document is ready... $(document).ready(function() { // If cookie is set, scroll to the position saved in the cookie. if ( $.cookie("scroll") !== null ) { $(document).scrollTop( $.cookie("scroll") ); } // When scrolling happens.... $(window).on("scroll", function() { // Set a cookie that holds the scroll position. $.cookie("scroll", $(document).scrollTop() ); }); }); @Cody's answer reminded me of something important. I only made it to check and scroll to the position vertically. A: (1) Solution 1: First, get the scroll position by JavaScript when clicking the submit button. Second, include this scroll position value in the data submitted to PHP page. Third, PHP code should write back this value into generated HTML as a JS variable: <script> var Scroll_Pos = <?php echo $Scroll_Pos; ?>; </script> Fourth, use JS to scroll to position specified by the JS variable 'Scroll_Pos' (2) Solution 2: Save the position in cookie, then use JS to scroll to the saved position when page reloaded. A: Store the position in an hidden field. <form id="myform"> <!--Bunch of inputs--> </form> than with jQuery store the scrollTop and scrollLeft $("form#myform").submit(function(){ $(this).append("<input type='hidden' name='scrollTop' value='"+$(document).scrollTop()+"'>"); $(this).append("<input type='hidden' name='scrollLeft' value='"+$(document).scrollLeft()+"'>"); }); Than on next reload do a redirect or print them with PHP $(document).ready(function(){ <?php if(isset($_REQUEST["scrollTop"]) && isset($_REQUEST["scrollLeft"])) echo "window.scrollTo(".$_REQUEST["scrollTop"].",".$_REQUEST["scrollLeft"].")"; ?> });
{ "pile_set_name": "StackExchange" }
Q: How can I make my iPhone 3GS icons in my app iPhone-4 savvy I have a quite simple question concerning the difference in screen size between the iPhone 3/3GS and the iPhone 4. I've googled around, but was unable to come up with a good explanation. Here's the thing: tabbar icons. All my icons are 30x30 and 60x60. I named the high resolution ones like [icon]@2x.png. When I load my app on my own iPhone 3GS, all goes fine. But when I load the app in Simulator, simulating a 4 with retina-display, the icon looks pixelated and is clearly the wrong resolution. What am I doing wrong? These were the exact steps I followed, but I'm probably missing something. Is there something like an option I need to set in the plist? Any help is greatly appreciated! Kind regards, Reinder A: It seems that you're doing it the right way. Did you try to remove the app from the simulator? Clean up the project? Re-import the icon image files?
{ "pile_set_name": "StackExchange" }
Q: Indexing the datetime column in the csv file using pandas I would like to slice the column which contains datetime type in the csv file using pandas. thanks in advance. for ex: data.csv Country,Player,Runs,ScoreRate,MatchDate,Weekday Afghanistan,Mohammad Shahzad,118,97.52,16-02-2010,Tue india,schin,112,98.02,16-03-2010,wed I want to slice the column containing datetime format. A: If i understand your question correctly, thats how you can do it: from pandas import * Read in the data, index by MatchDate: frame=read_csv("dates.csv", parse_dates = True, index_col = 4) print frame Country Player Runs ScoreRate Weekday MatchDate 2010-02-16 Afghanistan Mohammad Shahzad 118 97.52 Tue 2010-03-16 india schin 112 98.02 wed Define two datetime object's that define the range that you want slice: x=datetime(2010, 1, 5) y=datetime(2010, 2, 25) And slice it (get all rows, that have a MatchDate between x and y): print frame.ix[x:y] Country Player Runs ScoreRate Weekday MatchDate 2010-02-16 Afghanistan Mohammad Shahzad 118 97.52 Tue If you just want to get a certain month or year, you can just do this: frame.ix['2010-2'] Country Player Runs ScoreRate Weekday MatchDate 2010-02-16 Afghanistan Mohammad Shahzad 118 97.52 Tue A: I'm planning to add a usecols option to the file readers for reading out individual columns. Probably for pandas 0.10 (later this month)
{ "pile_set_name": "StackExchange" }
Q: Forces at angles being resolved into perpendicular components Why is that when a force acts at 30° from the horizontal, for example, that its horizontal and vertical components can be treated as being separate? A: Experiment shows that forces act that way. Forces add the same way that vectors add, so vectors make an excellent mathematical representation of a force. There is a rule for the addition of vectors; two vectors can add to produce a third. In math, the addition rule is just a definition. The fact that forces behave the same way is a question of physics, not math. The connection between the physics and the math is called, in physics, the superposition principle.
{ "pile_set_name": "StackExchange" }
Q: EF code-first optional 1-to-1 relationship I have an EF data model that represents a report with a hierarchical tree of report sections. Each ReportSection entity contains a collection of zero or more child ReportSections. Each Report entity contains a single ReportSection entity that serves as the root of tree of ReportSections. My data model that has the following navigation properties: public class Report { // Primary key public int Id { get; set; } // A Report has one root ReportSection [ForeignKey("RootReportSection")] public int ReportSectionId { get; set; } public virtual ReportSection RootReportSection { get; set; } } public class ReportSection { // Primary key public int Id { get; set; } // Optional self-reference to the parent ReportSection [ForeignKey("ParentReportSection")] public int? ParentReportSectionId { get; set; } public virtual ReportSection ParentReportSection { get; set; } // Optional foreign key to the parent Report [ForeignKey("ParentReport")] public int? ReportId { get; set; } public virtual Report ParentReport { get; set; } // Child ReportSections contained in this ReportSection public virtual ICollection<ReportSection> ReportSections { get; set; } } Everything works fine if I omit the ReportSectionId and RootReportSection navigation claptrap from the Report entity. But, as coded above, attempting to add a migration gets an error: Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'. After a bit of digging, I now understand that EF apparently wants me to use the primary key of my ReportSections entity as the foreign key to my Report entity. But, in my scenario, only the top-level ReportSection in a hierarchical tree of ReportSection entities participates in a relationship with a Report entity. The rest of the ReportSection entities are related to each other, and their primary keys are independent of any Report primary keys. Is there a way to get this to work? Specifically, is there a way for a Report entity to "contain" a top-level ReportSection entity, which ReportSection entity has its own collection of self-referenced ReportSection entities? A: Apparently ReportSection is the principal in the relationship und Report the dependent (because Report must refer to an existing RootReportSection since Report.ReportSectionId is not nullable). In this case it is well possible that a ReportSection exists without a related Report. All your child ReportSection would have no Report. But this can only work if the key in Report is not autogenerated because the key would have to be the same as the key of the related (and already existing) RootReportSection. So, you could try to model it like this: public class Report { [DatabaseGenerated(DatabaseGeneratedOption.None)] [ForeignKey("RootReportSection")] public int Id { get; set; } public virtual ReportSection RootReportSection { get; set; } } public class ReportSection { public int Id { get; set; } // Optional self-reference to the parent ReportSection [ForeignKey("ParentReportSection")] public int? ParentReportSectionId { get; set; } public virtual ReportSection ParentReportSection { get; set; } // Optional foreign key to the parent Report public virtual Report ParentReport { get; set; } // Child ReportSections contained in this ReportSection public virtual ICollection<ReportSection> ReportSections { get; set; } } (It's possible that [DatabaseGenerated(DatabaseGeneratedOption.None)] is redundant because EF understands that the key cannot be database generated in this one-to-one relationship. I'm not 100% sure though.) Downside of such a one-to-one relationship with shared primary key is that you could not change the relationship between Report and RootReportSection, i.e. you cannot have the Report refer to any other section than the one that has the same primary key. If that doesn't work for you, you have to model the relationship as one-to-many because EF does not support one-to-one relationships with separate foreign key. Either remove that part altogether... [ForeignKey("ParentReport")] public int? ReportId { get; set; } public virtual Report ParentReport { get; set; } ...if you don't need to navigate from the section to the report or replace it by a collection: public virtual ICollection<Report> ParentReports { get; set; } You would have to ensure in business logic that never more than one report is added to this collection to have kind of a simulation of a one-to-one relationship. In the database you could add a unique constraint on Report.ReportSectionId to have data integrity on database level. But EF won't understand this constraint and still allow to add more than one item to the collection. However, if you try to save it you'd get a unique key violation exception from the database.
{ "pile_set_name": "StackExchange" }
Q: Continuity from below for regular outer measures. We define an outer measure in a set $X$ as a function $\mu: \mathcal{P}(X) \to [0,\infty] $ that satisfies: $\mu(\emptyset) = 0$; $A \subset B \Rightarrow \mu(A) \leq \mu(B)$; $\mu(\bigcup A_n) \leq \sum \mu(A_n)$ for $(A_n) \subset \mathcal{P}(X)$. We say that a subset $A \subset X$ is $\mu$-measurable if $$ \mu(B) = \mu(B\cap A) + \mu(B \setminus A), \, \forall B \subset X, $$ and we denote the collection of all $\mu$-measurable sets by $\sigma(\mu)$. Besides, if an outer measure satisfies $$ \forall A \subset X, \, \exists E \in \sigma(\mu), \, A \subset E, \, \mu(A) = \mu(E), $$ we say that $\mu$ is regular. I'm trying to proof the following problem If $\mu$ is a regular outer measure and $(E_n)$ is an increasing sequence of subsets of $X$, then $\mu(\bigcup E_n) = \lim \mu (E_n)$. The above problem is true if each $E_n$ is a $\mu$-measurable set. I'm trying to use this fact and the regularity of $\mu$ to proof that it holds. Well, the result is true if $\mu(E_n) = \infty$ of some $n$. Then, take (E_n) an increasing sequence of subsets of $X$ with $\mu(E_n) < \infty.$ I've tried taking measurable sets $F_n$ such that $E_n \subset F_n$ and then take the unions of such $F_n$ to be an increasing sequence of measurable sets. However, I couldn't get anywhere. Help? A: You have taken the $F_n$ as measurable sets with $E_n\subseteq F_n$ such that $\mu(E_n)=\mu(F_n)$ through regularity. Moreover without loss of generality you can assume that the $F_n$ are an increasing sequence. Indeed, you can increase $F_n$ by redefining it as its union with $F_{n-1}$. The regularity property holds for this union still since $$ \mu(F_n\cup F_{n-1}\setminus E_n)\leq \mu(F_n\setminus E_n)+ \mu(F_{n-1}\setminus E_n)\leq \mu(F_n\setminus E_n)+\mu(F_{n-1}\setminus E_{n-1})=0.$$ Then you have $$ \bigcup_{n=1}^\infty E_n \subseteq \bigcup_{n=1}^\infty F_n,$$ so you can use property 2 of your outer measure to get $$ \mu\left(\bigcup_{n=1}^\infty E_n\right) \leq \mu\left(\bigcup_{n=1}^\infty F_n\right)=\lim_{n\to\infty}\mu(F_n)=\lim_{n\to\infty}\mu(E_n),$$ with the equalities following from your observation that the claim holds for measurable sets and the regularity condition. To get the lower inequality, note that for each $n$ you trivially have $E_n\subseteq \bigcup_{j=1}^\infty E_j$ and so by property 2 of your outer measure $$\mu(E_n)\leq \mu\left(\bigcup_{j=1}^\infty E_j\right),$$ taking the limit $n\to\infty$ then gives the result.
{ "pile_set_name": "StackExchange" }
Q: ASP.NET AJAX $find method failes when used in jQuery's $(document).ready() method I'm trying to find a tree using ASP.NET AJAX's client-side framework. I also use jQuery for doing any JavaScript operation after the DOM is ready. my code is like: $(function(){ var tree = $find('treeId'); }); Here, tree simply is null. But when I try to find the tree on click of one of elements, it's not null: $(function(){ $('saveButton').click(function(){ var tree = $find('treeId'); }): }); A: this worked for me with Telerik controls: $telerik.$(document).ready(function () { var tree = $telerik.$find("<%=RadTreeView1.ClientID%>"); }); see this http://www.telerik.com/help/aspnet-ajax/introduction-using-jquery.html
{ "pile_set_name": "StackExchange" }
Q: How to set position of bootstrap slider images to center? I want in my bootstrap slider the images placed in center of page such as this image: In this slider two section must be empty : right and left section <!--Slider--> <div class="row"> <div id="myCarousel" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <div class="carousel-inner"> <div class="item"> <img src="images/4172_780x354_hp_mysterious_v1.jpg" /> <div class="container"> </div> </div> <div class="item"> <img src="images/4181_780x354_hp_kitchen_v1.jpg" /> <div class="container"> </div> </div> <div class="item active"> <img src="images/4182_780x354_hp_sport-wear_v1.jpg" /> <div class="container"> </div> </div> </div> </div> </div> I use this codes but images placed in right of page. My website direction is right to left A: You can try this .carousel-inner img { margin: auto; }
{ "pile_set_name": "StackExchange" }
Q: Sanitize filter_var PHP string but keep " ' I am sanitizing a contact form string : $note = filter_var($_POST["note"], FILTER_SANITIZE_STRING); Which works great except when people write in inches (") and feet ('). So I'm interested in 5" 8" 10" & 1' comes up as I&#39;m interested in 5&#34; 8&#34; 10&#34; & 1&#39; Which is a bit of a garbled mess. Can I sanitize yet keep my I'm 5'9"? A: Computer data itself is neither harmful nor innocuous. It's just a piece of information that can be later be used for a given purpose. Sometimes, data is used as computer source code and such code eventually leads to physical actions (a disk spins, a led blinks, a picture is uploaded to remote computer, a thermostat turns off the boiler...). And it's then (and only then) when data can become harmful; we even lose expensive space ships now and then because of software bugs. Code you write yourself can be as harmful or innocuous as your abilities or good faith dictate. The big problem comes when your application has a vulnerability that allows execution of untrusted third-party code. This is particularly serious in web applications, which are connected to the open internet and are expected to receive data from anywhere in the world. But, how's that physically possible? There're several ways but the most typical case is due to dynamically generated code and this happens all the time in modern www. You use PHP to generate SQL, HTML, JavaScript... If you pick untrusted arbitrary data (e.g. an URL parameter or a form field) and use it to compose code that will later be executed (either by your server or by the visitor's browser) someone can be hacked (either you or your users). You'll see that everyday here at Stack Overflow: $username = $_POST["username"]; $row = mysql_fetch_array(mysql_query("select * from users where username='$username'")); <td><?php echo $row["title"]; ?></td> var id = "<?php echo $_GET["id"]; ?>"; Faced to this problem, some claim: let's sanitize! It's obvious that some characters are evil so we'll remove them all and we're done, right? And then we see stuff like this: $username = $_POST["username"]; $username = strip_tags($username); $username = htmlentities($username); $username = stripslashes($username); $row = mysql_fetch_array(mysql_query("select * from users where username='$username'")); This is a surprisingly widespread misconception adopted even by some professionals. You see the symptoms everywhere: your comment is mutilated at first < symbol, you get "your password cannot contain spaces" on sign-up and you read Why can’t I use certain words like "drop" as part of my Security Question answers? in the FAQ. It's even inside computer languages: whenever you read "sanitize", "escape"... in a function name (without further context), you have a good hint that it might be a misguided effort. It's all about establishing a clear separation about data and code: user provides data but only you provide code. And there isn't a universal one-size-fits-all solution because each computer language has its own syntax and rules. DROP TABLE users; can be terribly dangerous in SQL: mysql> DROP TABLE users; Query OK, 56020 rows affected (0.52 sec) (oops!)... but it's not as bad in e.g. JavaScript. Look, it doesn't even run: C:\>node > DROP TABLE users; SyntaxError: Unexpected identifier at Object.exports.createScript (vm.js:24:10) at REPLServer.defaultEval (repl.js:235:25) at bound (domain.js:287:14) at REPLServer.runBound [as eval] (domain.js:300:12) at REPLServer.<anonymous> (repl.js:427:12) at emitOne (events.js:95:20) at REPLServer.emit (events.js:182:7) at REPLServer.Interface._onLine (readline.js:211:10) at REPLServer.Interface._line (readline.js:550:8) at REPLServer.Interface._ttyWrite (readline.js:827:14) > This last example also illustrates that it's not only a security concern. Even if you're not being hacked, generating code from random input can simply make your app crash: SELECT * FROM customers WHERE last_name='O'Brian'; You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Brian'' So, what shall be done then if there isn't a universal solution? Understand the problem: If you inject raw literal data improperly it can become code (and sometimes invalid code). Use the specific mechanism for each technology: If target language requires escaping: <p><3 to code</p> → <p>&lt;3 to code</p> ... find a specific tool to escape in source language: echo '<p>' . htmlspecialchars($motto) . '</p>'; If language/framework/technology allows to send data in a separate channel, do it: $sql = 'SELECT password_hash FROM user WHERE username=:username'; $params = array( 'username' => $username, );
{ "pile_set_name": "StackExchange" }
Q: MSBuild - how to copy files that may or may not exist? I have a situation where I need to copy a few specific files in a MSBuild script, but they may or may not exist. If they don't exist it's fine, I don't need them then. But the standard <copy> task throws an error if it cannot find each and every item in the list... A: Use the Exists condition on Copy task. <CreateItem Include="*.xml"> <Output ItemName="ItemsThatNeedToBeCopied" TaskParameter="Include"/> </CreateItem> <Copy SourceFiles="@(ItemsThatNeedToBeCopied)" DestinationFolder="$(OutputDir)" Condition="Exists('%(RootDir)%(Directory)%(Filename)%(Extension)')"/> A: The easiest would be to use the ContinueOnError flag http://msdn.microsoft.com/en-us/library/7z253716.aspx <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup> <MySourceFiles Include="a.cs;b.cs;c.cs"/> </ItemGroup> <Target Name="CopyFiles"> <Copy SourceFiles="@(MySourceFiles)" DestinationFolder="c:\MyProject\Destination" ContinueOnError="true" /> </Target> </Project> But if something else is wrong you will not notice it. So the condition exist from madgnome's answer would be better.
{ "pile_set_name": "StackExchange" }
Q: how can act fractional operator on kets? Knowing $\hat{A}\left|ψ\right\rangle$ and $\hat{B}\left|ψ\right\rangle$ , how to find answer of ($\hat{A}+\hat{B} )^ {1/2} \left|ψ\right\rangle $ Note : may $\hat{A}$ and $\hat{B}$ are not in the form of tensors. A: You have to expand $(\hat A+\hat B)^{1/2}$ in terms of a Taylor series. This holds in general. Let us say you wanted to find: $$f(\hat A)| \psi \rangle$$ then you have to expand $f(\hat A)$ in terms of a Taylor series, so in your specific case we can write it as $(\hat A+\hat B-\hat I+\hat I)^{1/2}$ where $\hat I$ is the identity operator. Expanding this we get: $$(\hat A+\hat B-\hat I+\hat I)^{1/2}=\hat I+\frac{1}{2}(\hat A+\hat B-\hat I)-\frac{1}{8}(\hat A+\hat B-\hat I)^2+...$$ And thus: $$(\hat A+\hat B)^{1/2}|\psi \rangle=\left(\hat I+\frac{1}{2}(\hat A+\hat B-\hat I)-\frac{1}{8}(\hat A+\hat B-\hat I)^2+...\right)|\psi \rangle$$ Which depending on your values of $\hat A$ and $\hat B$ may be easy or hard to do.
{ "pile_set_name": "StackExchange" }
Q: Which relationship is more natural? Have a quick question on how to best structure something for my Java project: I'm a user. I can work at one or more places. At those workplaces, I have one or more roles. For each of these roles, I work a shift. I either came up with: My workplaces have shifts, my shifts have exactly 1 position (what position did I work when I worked my shift? It varies day to day..) or Workplaces have positions, each position has shifts I think the 2nd is more natural but keep going back and forth / unsure of what has more of an advantage both now and for the future. It's hard for me as I can argue both I guess? Thanks! A: It might make the most sense to look at how you'll use those structures in your code. If you're writing a scheduling app, then putting shifts higher might make more sense because they're a scheduling artifact. If you're doing a HR app, then putting positions higher might make sense because you're worried about managing people and their roles. An entity-relationship diagram would help, although you've pretty much got it laid out already. But it's actually both. A workplace "has a" list of positions, but also "has a" list of shifts. Shifts will have additional information, like start and end time. And a shift "has a" position that describes what to do during that shift. Another way to think of it is, a shift "realizes" a position. That is, it makes it real by adding scheduling information. Here's another alternative: Positions and shifts are top-level entities, and they "have a" reference to a workplace. You might bust out a simple Entity-Relationship diagram, and then decide which of the relationships (and in what direction) you want to model in your code. Some of the relationships you can rely on queries and joins to pull from your database.
{ "pile_set_name": "StackExchange" }
Q: css3 animation on element focus I am building a single page website and in a section of that site I have a CSS animation .animation { background-color: #54a3f7; -webkit-animation: html 2s ease-in-out; } set with @-webkit-keyframes html { 0% { width: 0%;} 100% { width: 100%; } } I have a working example here: http://jsfiddle.net/RqH5H/ My problem is that this animation will (of course) start at window load, but I want it to start when the user clicks on the top menu and wants to see <section id="animations"> So when the user clicks on "Animation" it will scroll down to that section at start the animation A: You will need Javascript to make this happen. You can add the class the points to CSS animation on click (or whatever interaction event you wish). I have put together a basic JSFiddle to demonstrate: Note: jQuery is used. http://jsfiddle.net/zensign/sg9ty/1/ $('#start-btn').click(function () { $('#animate-me').addClass('animation'); });
{ "pile_set_name": "StackExchange" }
Q: How to break struct members into bytes of a single word Say I have a C structure like: typedef struct { UINT8 nRow; UINT8 nCol; UINT16 nData; } tempStruct; Is there a way to put all of those 3 members of the struct into a single 32-bit word, yet still be able to access them individually? A: Something with the help of unions? typedef struct { UINT8 nRow; UINT8 nCol; UINT16 nData; } tempStruct; typedef union { tempStruct myStruct; UINT32 myWord; } stuff; Or even better (with no "intermediate" struct): #include <stdlib.h> #include <stdio.h> typedef union { struct { int nRow:8; int nCol:8; int nData:16; }; int myWord; } stuff; int main(int args, char** argv){ stuff a; a.myWord=0; a.nCol=2; printf("%d\n", a.myWord); return 0; } A: What about just referring to it as a UINT32? It's not like C is type-safe. tempStruct t; t.nRow = 0x01; t.nCol = 0x02; t.nData = 0x04; //put a reference to the struct as a pointer to a UINT32 UINT32* word = (UINT32 *) &t; printf("%x", *word); You can then get the value of the struct as a 32-bit word by dereferencing the pointer. The specifics of your system may matter, though...if I run this on my machine, the value of word is 0x00040201---that is, the fields are in reverse order. I don't think that's necessarily going to be the case if you're trying to serialize this to another system, so it's not portable. If you want to actually store it as a 32-bit integer and then refer to the fields individually, why not UINT32 word = 0x01020004; and then somewhere else... UINT8* row(UINT32 word) { return (UINT8 *) &word + 3; } UINT8* col(UINT32 word) { return ((UINT8 *) &word) + 2; } UINT16* data(UINT32 word) { return ((UINT16 *) &word); } Macros will facilitate portable endianness.
{ "pile_set_name": "StackExchange" }
Q: Why is the program looping instead of it asking for input? I'm currently writing a program that needs to except an option then followed by a piece of text if the piece of text. if the text is true then a piece of code executes? At least I think that's how it works, however, the program goes straight to the else and keeps looping because of the initial condition it doesn't ask the another input from the user which is getline() ? #include <iostream> #include <fstream> #include <string> #include <iomanip> using namespace std; int main() { fstream gFile; int choice; string gb; do { cout << "Student Grade Book Info Program....\n"; cout << "\tPlease Select an Option: (1 or 2) \n" << endl << "\t1. Review Grades" << "\n\t2. Quit" << "\n\tChoose: "; cin >> choice; switch (choice) { case 1: cout << "\n\tPlease Enter the Name of the File you wish to View the Grades for: " << endl; cout << "\n\tAvailable Grade Books: gradeBook\n" << "\tType in the Grade Book you would like to view. "; getline(cin, gb); if (gb == "gradeBook") { cout << "execute code..."; } else { cout << "\nError there is no such entry in the system." << endl; } case 2: break; } } while (choice != 2); return 0; } A: cin >> choice; This will read the number that's entered. However, the number that gets typed in here will be followed by a newline, which operator>> will not read. cout << "\n\tAvailable Grade Books: gradeBook\n" << "\tType in the Grade Book you would like to view. "; getline(cin, gb); And this getline() will now read the newline that was left over from the prior operator>>, instead of waiting for the next line of input to be entered. This is a common mistake: mixing operator>> and std::getline(). Although it is possible to use both together, additional steps must be taken to do that correctly. The simplest and the easiest way to read newline-terminated lines of text is to use std::getline(). That's what it's for. Simply use std::getline() to always read text input. If you want to parse it as an integer, or something else, construct a std::istringstream, and parse it.
{ "pile_set_name": "StackExchange" }
Q: Return all group values divided by first value in group I have a query SELECT GROUP, VALUE, UNIXTIME FROM TABLE1 that returns a table that looks like this: GROUP VALUE UNIXTIME A 866 1522540800 A 123 1525132800 A 100 1527811200 A 85 1530403200 A 77 1533081600 A 65 1535760000 B 376 1522540800 B 66 1525132800 B 45 1527811200 B 58 1530403200 B 42 1533081600 C 481 1522540800 C 68 1525132800 C 77 1527811200 C 50 1530403200 D 792 1522540800 D 126 1525132800 D 84 1527811200 E 1297 1522540800 E 203 1525132800 F 882 1522540800 How can I get a result that returns the same result, but where each row is divided by the first value in its own group. So for example VALUE on row1 should be 866/866 = 1 row2 should be 123/866 = 0.142 row3 = 100/866 = 0.115 Value on row7 (first row of group B) should be 376/376=1 row8 should be 66/376 = 0.176 etc A: Consider the following... DROP TABLE IF EXISTS my_table; CREATE TABLE my_table (group_id INT NOT NULL ,unixtime INT NOT NULL ,value INT NOT NULL ,PRIMARY KEY(group_id,unixtime) ); INSERT INTO my_table VALUES (1 , 1522540800 , 866), (1 , 1525132800 , 123), (1 , 1527811200 , 100), (1 , 1530403200 , 85), (1 , 1533081600 , 77), (1 , 1535760000 , 65), (2 , 1522540800 , 376), (2 , 1525132800 , 66), (2 , 1527811200 , 45), (2 , 1530403200 , 58), (2 , 1533081600 , 42), (3 , 1522540800 , 481), (3 , 1525132800 , 68), (3 , 1527811200 , 77), (3 , 1530403200 , 50), (4 , 1522540800 , 792), (4 , 1525132800 , 126), (4 , 1527811200 , 84), (5 , 1522540800 , 1297), (5 , 1525132800 , 203), (6 , 1522540800 , 882); SELECT x.* , value/CASE WHEN @prev = group_id THEN @val:=@val ELSE @val:=value END val , @prev:=group_id FROM my_table x ,(SELECT @prev:=null,@val:=0) vars ORDER BY group_id , unixtime; +----------+------------+-------+--------+-----------------+ | group_id | unixtime | value | val | @prev:=group_id | +----------+------------+-------+--------+-----------------+ | 1 | 1522540800 | 866 | 1.0000 | 1 | | 1 | 1525132800 | 123 | 0.1420 | 1 | | 1 | 1527811200 | 100 | 0.1155 | 1 | | 1 | 1530403200 | 85 | 0.0982 | 1 | | 1 | 1533081600 | 77 | 0.0889 | 1 | | 1 | 1535760000 | 65 | 0.0751 | 1 | | 2 | 1522540800 | 376 | 1.0000 | 2 | | 2 | 1525132800 | 66 | 0.1755 | 2 | | 2 | 1527811200 | 45 | 0.1197 | 2 | | 2 | 1530403200 | 58 | 0.1543 | 2 | | 2 | 1533081600 | 42 | 0.1117 | 2 | | 3 | 1522540800 | 481 | 1.0000 | 3 | | 3 | 1525132800 | 68 | 0.1414 | 3 | | 3 | 1527811200 | 77 | 0.1601 | 3 | | 3 | 1530403200 | 50 | 0.1040 | 3 | | 4 | 1522540800 | 792 | 1.0000 | 4 | | 4 | 1525132800 | 126 | 0.1591 | 4 | | 4 | 1527811200 | 84 | 0.1061 | 4 | | 5 | 1522540800 | 1297 | 1.0000 | 5 | | 5 | 1525132800 | 203 | 0.1565 | 5 | | 6 | 1522540800 | 882 | 1.0000 | 6 | +----------+------------+-------+--------+-----------------+ 21 rows in set (0.00 sec)
{ "pile_set_name": "StackExchange" }
Q: How do you specify a custom location for crossdomain.xml in actionscript? We are hosting the swf assets on a media hosting server and can't get a file to the root, anyone know what the code looks like to specify a custom location for crossdomain.xml? Sample code if you have it. A: I hate to answer my own question but I found the code so I thought I'd post here to add to the reference value of this question: pulled from: http://www.voiceoftech.com/swhitley/?p=117 The problem with setting up a crossdomain.xml file on the SSL server is that I don’t have access to the server. It’s just pointing to a virtual root on my server and I don’t have access to the SSL server’s web root. flash.system.Security.loadPolicyFile("{Url to my crossdomain.xml file on the SSL virtual root}"); With these changes in place, I’m able to easily integrate Google Accounts with my Flash app.
{ "pile_set_name": "StackExchange" }
Q: The composition of functions and inverse of a set? I'm a bit confused on how to do some of my discrete math work. I tried doing all of the problems, but I feel like I'm doing something wrong. If anyone could correct me, it would be greatly appreciated. Suppose $g: A\rightarrow B$ and $f: B\rightarrow C$ where $A = \{1, 2, 3, 4\}$, $B = \{a,b,c\}$, $C = \{2,8,10\}$, and $g$ and $f$ are defined by $g = \{(1, b), (2, a), (3, b), (4, a)\}$ and $f = \{(a,8),(b,10),(c,2)\}$ Find the following. 1) $f\circ g$ 2) $f^{-1}$ 3) $f\circ f^{-1}$ For one, I remember $f\circ g$ being the same as $f(g)$, so I substituted g in for every letter value in f. $\{(\{(1,b),(2,a),(3,b),(4,a)\},8),({(1,b),(2,a),(3,b),(4,a)},10),(\{(1,b),(2,a),(3,b),(4,a)\},2)\}$ However, I'm certain I'm doing something wrong, as that's a massive jumble of values, but I'm not sure what exactly I've done wrong, or how to fix it. As for the inverse of f, I believe it would be $\{(8,a),(10,b),(2,c)\}$ Once I learn how to properly do part one, I should be able to find $f\circ g^{-1}$ without any problem. A: A function $g:A\rightarrow B$ is (quite often, but not always) interpreted as a subset of the cartesian product $A\times B$ having the special property that for every $u\in A$ there is exacly one element $v\in B$ with $(u,v)\in g$. Another notation for $(u,v)\in g$ is the wellknown expression $v=g(u)$. Note that from this point of view we have: $g=\{(u,g(u)\mid u\in A\}$. Also it is said that in this context '$g$ sends element $u\in A$ to element $g(u)\in B$'. The composition $f\circ g$ sends element $u\in A$ to element $f(g(a))\in C$, so that $f\circ g=\{(u,f(g(u))\mid u\in A\}$. To write $f\circ g$ as subset of $A\times C$ take element $1\in U$, note that $g$ sends it to $g(1)=b$ and then note that $f$ sends $g(1)=b$ to $f(g(1))=f(b)=10$. Do the same with the other elements to come to: $$f\circ g=\{(1,10),(2,8),(3,10),(4,8)\}$$ You are correct where it concerns $f^{-1}$. Not every function has an inverse as function. If you do for $g$ what you did for $f$ then you would come to $g^{-1}=\{(b,1),(a,2),(b,3),(a,4)\}$. This however is not a function (it misses the special property mentioned above). You can still refer to it as the inverse of the relation $g$.
{ "pile_set_name": "StackExchange" }
Q: Determine optimal strategy in board game We have a $25 \times 25$ board and two players. The fields of the board are numbered like this: From $0$ to $24$ from west to the east, and from $24$ to $0$ from north to the south. The first player places the pawn in one of the fields in the top line, for example, in the column number $1$. Then the second player moves the pawn in one of three direction by any number of fields: To the south, to the west, or to the south-west, and so does the first player, and so on. One of the players wins when he places the pawn in the most south-west corner (that is, column $0$, line $0$). Determine the optimal first move for the second player, that is, the move such that after making it the second player will win for sure. It's a hard problem for me, as I'm not used to dealing with combinatorial game problems. Any hints appreciated. A: This game does have a number of theorems known about it, but re-deriving tough theory is not necessary for the problem as stated. The key idea for solving a question like this with a program is the concept of winning positions and losing positions (sometimes called $N$-positions and $P$-positions). For example, $(7,7)$ is a winning position since if the pawn is at $(7,7)$ the next player to move can win by moving the pawn south-west by $7$ units (the OP said "by any number of fields"). More interestingly, $(1,2)$ is a losing position since the next player can only move to $(0,2)$, $(1,1)$, $(1,0)$, or $(0,1)$, all of which are definitely winning positions since the next player from any of them can end the game immediately. Therefore, $(1,3)$ is a winning position since moving to $(1,2)$ would be a good move. The general definition is that a position is losing if all available moves are to winning positions ($(0,0)$ counts as losing since there are no available moves), and a position is winning if there is at least one move to a losing position. With this recursive definition, you can use a computer program (or pen and paper) to find all of the winning and losing positions among $(a,b)$ for $0\le a,b\le24$. It might be useful to arrange your results in a table or matrix. It will turn out that the losing positions have a vague pattern, and that all positions of the form $(24,b)$ for $0\le b\le24$ are winning positions, so the "second player" can win no matter which of those positions the "first player" places the pawn. The winning first moves from each position like $(24,b)$ will then be clear from a table of the winning positions and losing positions: just make a move south, west, or south-west that leads to a losing position. This problem can be done without a computer if you understand how to mark positions in your table by looking at it (it was first solved over 100 years ago), but to do so for larger numbers without the theorems that have been proven would require basically making a big table of winning and losing positions by hand and then seeing a pattern, making a very nonobvious guess at that pattern, then doing a lot of work to prove that pattern. This is why I asked about the context of the problem, because if you had just covered (in the book or class) a theorem which tells you a formula for the winning and losing positions already, then this becomes much easier.
{ "pile_set_name": "StackExchange" }
Q: using task queue to send email I wrote my first code with Google Task Queue Python API. It is supposed to send out an email every time URL is entered into the address bar. Although it shows a task in default task queue in my dashboard, I don't know why is it not executed even after an hour of initiating it. queue-mail.py:- class sendMail(webapp.RequestHandler): def post(self): mail.send_mail( '[email protected]', self.request.get('to'), self.request.get('subject'), self.request.get('body')) taskqueue.add(url='/sendMail',params=dict( to='[email protected]', subject = 'Testing task queues', body = 'this is a message!')) app.yaml:- handlers: - url: /mail script: queue-mail.py I invoked the code as: appid.appspot.com/mail A: Please read the section of the docs regarding how to use the webapp framework. You've defined a handler class, but you haven't defined a WSGI app for it, or invoked it in your script. As a result, your handler code will never get run. Since you've put the code to enqueue the task at the module level, and haven't defined a main() function, every time a request is sent to the module, it will execute that code - so all your code does is enqueue the same task, over and over again, without actually doing anything. You need to separate the code to enqueue the task from the code that executes it, and put the enqueueing code in another handler that you invoke from a different URL. A: Seeing as your problem is solved, I figured I'd post an official answer. post worked while get didn't because that is the default method for task queue. If you look at the function documentation, one of the kwargs is method, in which you can specify get/post/etc, but as you didn't in your code, it defaulted to post. As a side note, you probably didn't see a 404 for a missing handler, but a 405 for "method not allowed" (since the task queue was trying to send a post request to a handler that didn't have a post function defined)
{ "pile_set_name": "StackExchange" }
Q: Unable to resolve .foo.local domain names My workplace has an intranet with domain names like server01.foo.local, server02.foo.local, etc. I recently booted the Fedora 16 live environment to test it out and discovered that these domain names do not resolve. For example: $ ping server01.foo.local ping: unknown host server01.foo.local $ ping server01 PING server01.foo.local (X.X.X.X) ... Why will server01 resolve (and print the name as server01.foo.local), but server01.foo.local will not? A: While I'm not 100% up on the reasoning behind why it doesn't work as expected, there seems to be a very large conflict with the mDNS service (Avahi in Linux, Bonjour/Zeroconf in Mac/Windows) and Windows networks that use .local as the internal routing name for domains. What seems to happen is that when pinging server01, it's skipping over using mDNS for resolution and then appending the search domain (foo.local) to the request, successfully querying the DNS server for server01.foo.local. However, when using mDNS (which uses .local as the default machine name extension), when you try to ping server01.foo.local, it's actually broadcasting over mDNS looking for a machine with the name of "server01.foo"; when it fails, it doesn't move on to straight-up DNS for whatever reason. A large workaround to this is not naming your domain .local, which probably goes against most Windows admins' training for domain structuring. That being said: If mDNS is of no consequence in your network (as is common in the enterprise, which tends to run dedicated DNS servers versus the home network, where mDNS is sometimes used), then changing the search order is the easiest workaround. This can be found in /etc/nsswitch.conf. The section for hosts will list the order, which for Fedora 16 default is: hosts: files mdns4_minimal [NOTFOUND=return] dns myhostname If you change that to: hosts: files dns mdns4_minimal [NOTFOUND=return] myhostname where you're moving dns ahead in the search order, that should fix things for now. Alternatively, if you know you're not going to need mDNS at all, just remove the "mdns4_minimal [NOTFOUND=return]" portion. Looking at this bug on Red Hat's tracker, it seems that this is a long-standing problem with no apparent fix at the moment. Though, if someone can provide more insight as to why this happens this way, it'd be appreciated.
{ "pile_set_name": "StackExchange" }
Q: Prevent duplicate COUNT in SELECT query I have the following query which as you can see does multiple Count(CompetitorID) calls. Is this a performance issue, or does SQL Server 2008 'cache' the Count? If this is a performance issue, is it possible to store the Count to prevent the multiple lookups? SELECT EventID,Count(CompetitorID) AS NumberRunners, CASE WHEN Count(CompetitorID)<5 THEN 1 WHEN Count(CompetitorID)>=5 AND Count(CompetitorID)<=7 THEN 2 ELSE 3 END AS NumberPlacings FROM Comps GROUP BY EventID Order By EventID; A: Its always a better practice to get the value once and use it subsequently whenever possible. In your case, you can always use Inner query to get the count only once and compute other (derived) columns off its value as shown below: SELECT EventID, NumberRunners, CASE WHEN NumberRunners <5 THEN 1 WHEN NumberRunners >=5 AND NumberRunners <=7 THEN 2 ELSE 3 END AS NumberPlacings FROM ( SELECT EventID, NumberRunners = Count(CompetitorID) FROM Comps GROUP BY EventID ) t Order By EventID;
{ "pile_set_name": "StackExchange" }
Q: liferay portlet to redirect request to webapplication hosted on another server Im new to liferay. My requirement is to display web application hosted on weblogic server(10.3.5) in liferay portal. This application is using JDK 1.6 To achieve this I wrote a sample portlet public class TestPortlet extends GenericPortlet { public static final String VIEW_PAGE = "/View.jsp"; public static final String VERSION = "version"; private String webVersion; @Override public void init(PortletConfig config) throws PortletException { super.init(config); webVersion = config.getInitParameter("webVersion"); } @Override protected void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException { response.setContentType("text/html"); request.setAttribute(VERSION, webVersion); PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(VIEW_PAGE); dispatcher.include(request, response); } } JSP Code: <%@page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" session="false" isELIgnored="false"%> <%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %> <portlet:defineObjects /> <jsp:useBean id="version" class="java.lang.String" scope="request" /> <div id="remote-container" style="width:100%;"></div> <div> <footer id="footer" class="foot-Note" role="contentinfo"><small>Version: <%=version%> &#47; </small><small id="applicationVersion" ></small></footer> </div> <script> jQuery.support.cors = true; $("#remote-container").load('/contextRoot/test', function(response, status, xhr) { if (status == "error") { var msg = "If this problem persists please contact the Support "; $("#remote-container").html(msg + xhr.statusText); } }); </script> Im using liferay 6.1.2 with weblogic 10.3.6 and JDK 1.7. Its working correctly if I deploy the web app in same liferay server. I want to know how to redirect the context to the application hosted in other server. Please help me. A: Liferay IFrame module is final solution. A few customizations are required to use the portal cookie.Its working now.
{ "pile_set_name": "StackExchange" }
Q: Applying a transformation to a set in Raphael.js Using Raphael 2.0, I am trying to apply a transform to a set of objects in a way that is relative to all of the objects in the set. However, the effect I am getting is that the transform is applied to each item individually, irrespective of the other objects in the set. For example: http://jsfiddle.net/tim_iles/VCca9/8/ - if you now uncomment the last line and run the code, each circle is scaled to 0.5x. The actual effect I am trying to achieve would be to scale the whole set of circles, so their relative distances are also scaled, which should put all four of them inside the bounding box of the white square. Is there a way to achieve this using Raphael's built in tools? A: When you scale, the first parameter is the X-scale. If you provide no other parameters, it will use that as the Y-scale, and scale around the center of the object. When you scaled the rectangle, it scaled around the center of the rectangle. If you want the circles to scale around that point as well, rather than their centers, you should provide that point. So the last line could be set.transform("s0.5,0.5,100,100"); (100,100 being the center of the rectangle you scaled) At least, I think this is what you're asking for.
{ "pile_set_name": "StackExchange" }
Q: ARC: how to inject custom dealloc IMP in object which in turn calls original dealloc without causing malloc error I'm trying to do the following: get a hold to a class'dealloc IMP inject into said class a custom IMP which essentially calls the original dealloc IMP When an instance of said class gets deallocated, both IMPs should run. This is my attempt: @implementation ClassB - (void)dealloc { NSLog(@"\n%@ | %@", self, NSStringFromSelector(_cmd)); } @end @implementation ClassC - (void)swizzleMe:(id)target { SEL originalDeallocSelector = NSSelectorFromString(@"dealloc"); __block IMP callerDealloc = [target methodForSelector:originalDeallocSelector]; const char *deallocMethodTypeEncoding = method_getTypeEncoding(class_getInstanceMethod([target class], originalDeallocSelector)); IMP newCallerDealloc = imp_implementationWithBlock(^(id _caller) { NSLog(@"\n new dealloc | calling block %p for %@", callerDealloc, _caller); callerDealloc(_caller, originalDeallocSelector); }); NSLog(@"\nswapping %p for %p", newCallerDealloc, callerDealloc); class_replaceMethod([target class], originalDeallocSelector, newCallerDealloc, deallocMethodTypeEncoding); } @end To be used like so: ClassB *b = [[ClassB alloc] init]; ClassC *c = [[ClassC alloc] init]; [c swizzleMe:b]; But the results are: zombie objects disabled: 2013-07-03 13:24:58.368 runtimeTest[38626:11303] swapping 0x96df020 for 0x2840 2013-07-03 13:24:58.369 runtimeTest[38626:11303] new dealloc | calling block 0x2840 for <ClassB: 0x93282f0> 2013-07-03 13:24:58.370 runtimeTest[38626:11303] <ClassB: 0x93282f0> | dealloc 2013-07-03 13:24:58.370 runtimeTest[38626:11303] new dealloc | calling block 0x2840 for <ClassB: 0x93282f0> 2013-07-03 13:24:58.371 runtimeTest[38626:11303] <ClassB: 0x93282f0> | dealloc runtimeTest(38626,0xac55f2c0) malloc: *** error for object 0x93282f0: pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug 2013-07-03 13:24:58.371 runtimeTest[38626:11303] new dealloc | calling block 0x2840 for <ClassB: 0x93282f0> 2013-07-03 13:24:58.372 runtimeTest[38626:11303] <ClassB: 0x93282f0> | dealloc zombie objects enabled (Line 11 is a EXC_BAD_ACCESS in the picture) 2013-07-03 13:34:37.466 runtimeTest[38723:11303] swapping 0x97df020 for 0x2840 2013-07-03 13:34:37.467 runtimeTest[38723:11303] new dealloc | calling block 0x2840 for <ClassB: 0x715a920> 2013-07-03 13:34:37.468 runtimeTest[38723:11303] <ClassB: 0x715a920> | dealloc Any thoughts on what am I doing wrong? A: If you really want to know when an object is deallocated, then use associated objects. Specifically, associate an object with the object you want to observe such that the object being observed has the only strong reference -- the only retain'd reference -- to the object. Then, you can override dealloc and know that when it is called the object being observed has been (or is just about to be) deallocated. Do not mess with the object being deallocated, though!! It will already have had all of its dealloc methods invoked (by inheritance) and, thus, the internal state will be completely undefined. Note that if your goal is to try and clean up something in the system frameworks, then... don't. Down that path is nothing instability and pain. like I mentioned in the comments to nielsbot, I am NOT trying to know when an object is deallocated. It would be helpful to know exactly what is in your injected dealloc implementation. On the face of it, the only reason I can think of that couldn't be solved through the use of associated objects to detect deallocation is exactly because you are trying to change the behavior of a class's dealloc, which is a really bad thing to do. A: After some time I finally found the real cause of the problem: I was overlooking the signature of the IMP type. From Apple's Objective-C Runtime Reference: IMP A pointer to the start of a method implementation. id (*IMP)(id, SEL, ...) Particularly, IMP has a return type of id and so in ARCLandia ARC tries to manage this id, causing the objc_retain crash. So, assuming you have an IMP to -dealloc, explicitly casting it to a C function pointer with return type void makes it where ARC won't try to manage the return value anymore: void (*deallocImp)(id, SEL) = (void(*)(id, SEL))_originalDeallocIMP; deallocImp(self,NSSelectorFromString(@"dealloc"));
{ "pile_set_name": "StackExchange" }
Q: python iterator skip_func def yield_and_skip(iterable,skip): for i in iterable: print(skip(i)) for x in range(skip(i)): pass yield i I'm defning a function called skip_yield, which produces a value from the iterable but then it then skips the number of values specified when the function argument is called on the just-produced value. It takes 2 parameters: skip is a small function. However, if I try to do this: print(''.join([v for v in yield_and_skip('abbabxcabbcaccabb',lambda x : {'a':1,'b':2,'c':3}.get(x,0))])) it gives me: abbabcabbcaccabb but it should give me: abxccab Any idea? A: First of all, pass doesn't do anything to iterable. If you need to advance the iterator, call the next function on iterator object skip(i) number of times (either directly or indirectly). Also, next call may raise StopIteration, thus terminating the loop. yield i before advancing the iterator or provide the second argument, to make next swallow the exception. Your code would look like def yield_and_skip(iterable, skip): it = iter(iterable) for i in it: for _ in range(skip(i)): next(it, None) yield i
{ "pile_set_name": "StackExchange" }
Q: Add conditional group identifier using rollup functions I have a data frame that has sub sequences (groups of rows) and the condition to identify these sub sequences is to watch for a surge in the column diff. This is what the data looks like : > dput(test) structure(list(vid = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "2a38ebc2-dd97-43c8-9726-59c247854df5", class = "factor"), events = structure(c(3L, 2L, 4L, 1L, 3L, 2L, 4L, 1L, 3L, 2L, 4L, 1L, 3L, 2L, 4L, 1L, 3L, 2L, 4L, 1L), .Label = c("click", "mousedown", "mousemove", "mouseup"), class = "factor"), deltas = structure(6:25, .Label = c("154875", "154878", "154880", "155866", "155870", "38479", "38488", "38492", "38775", "45595", "45602", "45606", "45987", "50280", "50285", "50288", "50646", "54995", "55001", "55005", "55317", "59528", "59533", "59537", "59921", "63392", "63403", "63408", "63822", "66706", "66710", "66716", "67002", "73750", "73755", "73759", "74158", "77999", "78003", "78006", "78076", "81360", "81367", "81371", "82381", "93365", "93370", "93374", "93872"), class = "factor"), serial = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20), diff = c(0, 9, 4, 283, 6820, 7, 4, 381, 4293, 5, 3, 358, 4349, 6, 4, 312, 4211, 5, 4, 384)), .Names = c("vid", "events", "deltas", "serial", "diff"), row.names = c(NA, 20L), class = "data.frame") I am trying to add a column that will indicate when a new sub sequence is identified and assign the entire sub sequence a unique id. I'll demonstrate the criterion for the grouping with the following example: The diff value of row 5 is 6829 which is 10 times higher than the max value until that row (283). The result should be something like this df: structure(list(vid = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "2a38ebc2-dd97-43c8-9726-59c247854df5", class = "factor"), events = structure(c(3L, 2L, 4L, 1L, 3L, 2L, 4L, 1L, 3L, 2L, 4L, 1L, 3L, 2L, 4L, 1L, 3L, 2L, 4L, 1L), .Label = c("click", "mousedown", "mousemove", "mouseup"), class = "factor"), deltas = structure(6:25, .Label = c("154875", "154878", "154880", "155866", "155870", "38479", "38488", "38492", "38775", "45595", "45602", "45606", "45987", "50280", "50285", "50288", "50646", "54995", "55001", "55005", "55317", "59528", "59533", "59537", "59921", "63392", "63403", "63408", "63822", "66706", "66710", "66716", "67002", "73750", "73755", "73759", "74158", "77999", "78003", "78006", "78076", "81360", "81367", "81371", "82381", "93365", "93370", "93374", "93872"), class = "factor"), serial = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20), diff = c(0, 9, 4, 283, 6820, 7, 4, 381, 4293, 5, 3, 358, 4349, 6, 4, 312, 4211, 5, 4, 384), group = c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5)), .Names = c("vid", "events", "deltas", "serial", "diff", "group"), row.names = c(NA, 20L), class = "data.frame") Any help greatly appreciated A: Let me give you a bit more detail on why it works and how it works. First, let us just add a column without the cumsum part: df$tag <- df$diff > 500 head(df) vid events deltas serial diff tag 1 2a38ebc2-dd97-43c8-9726-59c247854df5 mousemove 38479 1 0 FALSE 2 2a38ebc2-dd97-43c8-9726-59c247854df5 mousedown 38488 2 9 FALSE 3 2a38ebc2-dd97-43c8-9726-59c247854df5 mouseup 38492 3 4 FALSE 4 2a38ebc2-dd97-43c8-9726-59c247854df5 click 38775 4 283 FALSE 5 2a38ebc2-dd97-43c8-9726-59c247854df5 mousemove 45595 5 6820 TRUE 6 2a38ebc2-dd97-43c8-9726-59c247854df5 mousedown 45602 6 7 FALSE As you can see, it simply creates a logical of TRUE/FALSE values in the tag column that says whether or not the difference is 'big enough' (based on selected threshold). Now, when you do cumsum on that column and store it in group column, it will keep cumulatively adding. Every TRUE value will increment the cumulative sum by 1 and every FALSE value will keep the cumulative sum the same as it was before that row was hit. So, this will give you the desired incrementing group values: df$group <- cumsum(df$tag) head(df) vid events deltas serial diff tag group 1 2a38ebc2-dd97-43c8-9726-59c247854df5 mousemove 38479 1 0 FALSE 0 2 2a38ebc2-dd97-43c8-9726-59c247854df5 mousedown 38488 2 9 FALSE 0 3 2a38ebc2-dd97-43c8-9726-59c247854df5 mouseup 38492 3 4 FALSE 0 4 2a38ebc2-dd97-43c8-9726-59c247854df5 click 38775 4 283 FALSE 0 5 2a38ebc2-dd97-43c8-9726-59c247854df5 mousemove 45595 5 6820 TRUE 1 6 2a38ebc2-dd97-43c8-9726-59c247854df5 mousedown 45602 6 7 FALSE 1 Notice that the group value starts at zero. Since cumulative sum of the first few FALSE values is zero. But, you may want your group identifiers to start with 1 instead. So, I added a 1 to the cumsum, but you can also do it as follows as an extra step. df$group <- df$group + 1 head(df) vid events deltas serial diff tag group 1 2a38ebc2-dd97-43c8-9726-59c247854df5 mousemove 38479 1 0 FALSE 1 2 2a38ebc2-dd97-43c8-9726-59c247854df5 mousedown 38488 2 9 FALSE 1 3 2a38ebc2-dd97-43c8-9726-59c247854df5 mouseup 38492 3 4 FALSE 1 4 2a38ebc2-dd97-43c8-9726-59c247854df5 click 38775 4 283 FALSE 1 5 2a38ebc2-dd97-43c8-9726-59c247854df5 mousemove 45595 5 6820 TRUE 2 6 2a38ebc2-dd97-43c8-9726-59c247854df5 mousedown 45602 6 7 FALSE 2 Hope this helps.
{ "pile_set_name": "StackExchange" }
Q: ScrollTop goes to the wrong top I have a list of items. When I click on one item (project) it opens (this is ok) and it scrolls to the top of the page (the wrong top!). The problem occurs when I have an opened item and I decide to open the one below: the top position is increased by the opened project height and the second project I click goes too far over the top. Following the FIDDLE below: if I open project1 and then I click on project2, this goes on the wrong top. Same if I try to open any project below another opened one. JS $('.accordion-section-title').on('click', function () { var idName = $(this).attr('id'); $('html, body').animate({ scrollTop: $("#" + idName).offset().top }, 500); }); Here's the FIDDLE A: The problem seems to be the .slideUp() and .slideDown() methods are animated at the same time the window is scrolling. By the time the window has scrolled to the right Y coordinate, the accordion sections' heights have been altered, thus causing the window to end up in the wrong position. I'm sure there are other ways to accomplish correct scroll positions, but my first thought was to store the initial Y positions once the page is loaded. This can be done this way: $('.accordion-section-title').each(function() { $(this).data('ypos', $(this).offset().top) }) Each .accordion-section-title element will have its Y position stored in a data attribute called ypos. Later when you scroll the window, don't scroll to the elements position, but rather to its stored initial position. In other words, change scrollTop: $("#" + idName).offset().top to scrollTop: $("#" + idName).data('ypos'). Put together with your code it will look like the following: $('.accordion-section-title').on('click', function(e) { var idName = $(this).attr('id'); $('html, body').animate({ scrollTop: $("#" + idName).data('ypos') - 10 }, 500); }); You can see how it plays out in this fiddle
{ "pile_set_name": "StackExchange" }
Q: Harmonic Functions and Partial Derivatives with Chain Rule (Complex Variables) Suppose that an analytic function $w= f(z) = u(x,y) + iv(x,y)$ maps a domain $D_z$ in the $z$ plane onto a domain $D_w$ in the $w$ plane. Let a function $h(u,v)$ with continuous first and second partial derivatives be defined on $D_w$. Show using chain rule that if $H(x,y) = h\left( u(x,y) , v(x,y) \right)$ then $$H_{xx} (x,y) + H_{yy} (x,y) = \left( h_{uu}(u,v) + h_{vv}(u,v) \right) |f’(z)|^2.$$ How does it follow from this that $H(x,y)$ is harmonic in $D_z$ when $h(u,v)$ is harmonic in $D_w?$ I feel that this is just a huge messy chain rule using partial derivatives problem, is there another approach to this or at least a way to do this elegantly without creating a big mess of terms? We know that since $f$ is analytic, the Cauchy-Riemann equations hold: $u_x = v_y \text{ and } u_y = -v_x$. Also, the functions $u$ and $v$ satisfy Laplace’s Equation. The continuity conditions on the partial derivatives yield $h_{vu} = h_{uv}$. (I am having trouble putting these together as well.) A: For example: $\begin{align} H_x&=h_uu_x+h_vv_x\\ \Rightarrow H_{xx}&=(h_uu_x)_x+(h_vv_x)_x\\ &=(h_{uu}u_x+h_{uv}v_x)u_x+h_uu_{xx}+(h_{vv}v_x+h_{uv}u_x)v_x+h_vv_{xx}\\ &=h_{uu}u_x^2+h_{uv}v_xu_x+h_uu_{xx}+h_{vv}v_x^2+h_{uv}u_xv_x+h_vv_{xx} \end{align}$ By symmetry: $$H_{yy}=h_{uu}u_y^2+h_{uv}v_yu_y+h_uu_{yy}+h_{vv}v_y^2+h_{uv}u_yv_y+h_vv_{yy}$$ change some of the $y$'s to $x$'s with CR: $$H_{yy}=h_{uu}u_y^2-h_{uv}v_xu_x+h_uu_{yy}+h_{vv}v_y^2-h_{uv}u_xv_x+h_vv_{yy}$$ Combine: $$H_{xx}+H_{yy}= h_{uu}(u_x^2+u_y^2)+h_u(u_{xx}+u_{yy})+h_v(v_{xx}+v_{yy})+h_{vv}(v_x^2+v_y^2)$$ But $u$ and $v$ are harmonic, so this simplifies further:$$H_{xx}+H_{yy}= h_{uu}(u_x^2+u_y^2)+h_{vv}(v_x^2+v_y^2)$$ Use CR again: $$H_{xx}+H_{yy}= (h_{uu}+h_{vv})(u_x^2+u_y^2)$$ To see that $(u_x^2+u_y^2)=|f'(z)|^2$, (Complex chain rule for complex valued functions) $$f'(z)=u_x-iu_y\Rightarrow |f'(z)|^2=u_x^2+u_y^2$$ as desired.
{ "pile_set_name": "StackExchange" }
Q: Unable to play RTSP video in Qt media player demo I was trying to develop a video management software for which I was evaluating Qt Phonon. The software would be built on windows platform and I understand that Phonon uses Directshow as windows backend and if it runs on Linux it uses GStreamer. Using Qt 4.7.4 on Linux which has a demo example of a video player using phonon I was successfully able to see video stream from panasonic IP camera (RTSP stream), however when I tried the same example on windows platform it does not work (returns error 0x800c0000d). What could be the problem? Regards, Saurabh Gandhi A: 0x800c000d is INET_E_UNKNOWN_PROTOCOL, which in turn is "The specified protocol is unknown". DirectShow and Windows don't offer anything standard to support RTSP feeds, so the two together suggest that the IP camera feeds are not supported (at least without third party components).
{ "pile_set_name": "StackExchange" }
Q: Is there any option to do Column split? Need to see maker names against car models something like this: trying to use below function, but it is creating as list strsplit(carz$maker,split = " ") A: Here is an approach that uses lapply() with the Motor Trend Cars data frame. data(mtcars) mtcars$type <- rownames(mtcars) mtcars$make <-unlist(lapply(strsplit(mtcars$type," "),function(x){x[[1]]})) head(mtcars) and the result: > head(mtcars) mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 type make Mazda RX4 Mazda RX4 Mazda Mazda RX4 Wag Mazda RX4 Wag Mazda Datsun 710 Datsun 710 Datsun Hornet 4 Drive Hornet 4 Drive Hornet Hornet Sportabout Hornet Sportabout Hornet Valiant Valiant Valiant > Note, that some additional data cleaning is necessary, because the Valiant and Duster were made by Plymouth, the Camaro Z28 was made by Chevrolet, and the Hornet 4 Drive was made by American Motor Cars, also known as AMC. Regarding the question in the comments about the syntax used within lapply(), I used lapply() to process the results of strsplit(), including an anonymous function that extracts the first word from each element of the list. Since the output of an R function can be used as the argument to another function, this solution nests functions to produce the desired result. The sapply() answer provided by akrun does the same thing, using output from strsplit() as its input, and using [, one of the four forms of the extract operator to extract the data. sapply() also produces a vector rather than a list as its output.
{ "pile_set_name": "StackExchange" }
Q: Usage of _path gives a "No route matches.." error I am following a tutorial of Rails and I have a few pages that I am adding some tests for. I am trying to use help_path instead of :help in my pages_controller_test : test "should get help" do get help_path assert_response :success assert_select "title", "Help | #{@base_title}" end I added this line in my routes.rb file : get '/help', to: 'pages#help' But I get this error : 1) Error: PagesControllerTest#test_should_get_help: ActionController::UrlGenerationError: No route matches {:action=>"/help", :controller=>"pages"} test/controllers/pages_controller_test.rb:62:in `block in ' I have tried a few solutions but none of them solved my issue. I've also tried using this line instead : match '/home' => 'main_pages#home', :as => :home But it didn't work either. My rails version is : 4.2.4 My Ruby version is : ruby 2.1.9p490 (2016-03-30 revision 54437) [x86_64-linux-gnu] Output of $rake routes : Prefix Verb URI Pattern Controller#Action root GET / pages#home help GET /help(.:format) pages#help courses GET /courses(.:format) pages#courses programs GET /programs(.:format) pages#programs schools GET /schools(.:format) pages#schools dashboard GET /dashboard(.:format) pages#dashboard profile GET /profile(.:format) pages#profile account GET /account(.:format) pages#account signout GET /signout(.:format) pages#signout EDIT : I can use help_path .. etc in my html code without any issue, but in the test it gives that error. Thank you :) A: I've ran your tests using the repo, Rails 4.2.4, Minitest 5.10.2 and the only one test that doesn't pass is the one using get help_path. I put only the 3 tests in order to shorten the post: PagesControllerTest#test_should_get_help_using_"get_:help" = 0.39 s = . PagesControllerTest#test_should_get_help_using_"get_help_path" = 0.00 s = E PagesControllerTest#test_should_get_help_using_"get_'help'" = 0.01 s = . Finished in 0.405330s, 7.4014 runs/s, 9.8685 assertions/s. 1) Error: PagesControllerTest#test_should_get_help_using_"get_help_path": ActionController::UrlGenerationError: No route matches {:action=>"/help", :controller=>"pages"} test/controllers/pages_controller_test.rb:70:in `block in <class:PagesControllerTest>' 3 runs, 4 assertions, 0 failures, 1 errors, 0 skips What I did: $ rm -rf Gemfile.lock (because of a json -v 1.8.1 gem error) $ bundle $ rake db:migrate $ rake db:migrate RAILS_ENV=test $ rake test test/controllers/pages_controller_test.rb -v What you can use to make the test work with help_path as the route to test specifying the controller and action is to use: assert_routing asserts that the routing of the given path was handled correctly and that the parsed options (given in the expected_options hash) match path. Basically, it asserts that Rails recognizes the route given by expected_options. Or: assert_recognizes asserts that path and options match both ways; in other words, it verifies that path generates options and then that options generates path. This essentially combines assert_recognizes and assert_generates into one step. Like: test "should get help using assert_recognizes and help_path" do assert_recognizes({controller: 'pages', action: 'help'}, help_path) assert_response :success end test "should get help using assert_routing and help_path" do assert_routing help_path, controller: 'pages', action: 'help' assert_response :success end
{ "pile_set_name": "StackExchange" }
Q: Main idea of Bagging I just read this post and several other websites, but I still don't understand what bagging is. I understand it is an algorithm for machine learning, that it improves stability and accuracy of the algorithm and decreased the variance of my prediction, but what is the main idea behind this algorithm? Is it to put a dataset into a bag? For example, to me the main idea behind boosting is to boost records that are weighted incorrectly. A: Bootstrapping is a concept in statistics of approximating the sampling distribution of a statistic by repeatedly sampling from a given sample of size $n$. We construct $B$ samples, each of size $n$, by sampling with replacement from the original sample. The statistic of interest is calculated for each of the $B$ samples. For sufficiently large $B$, we have a good idea of how the statistic is distributed. Roughly speaking, this distribution indicates the range of values of a statistic and how dense these values are. Bagging, or Bootstrap AGGregatING, is an extension of bootstrapping to classification and regression problems. The main idea is to sample with replacement from the training data so that we now have $B$ training data sets, each having $n' \le n$ observations. The machine-learning algorithm is trained on each of the $B$ data sets to form a committee. When predicting (or classifying) future test observations, we ask each trained algorithm in the committee for its prediction. We then compute a (weighted) average of the $B$ predictions to obtain a single prediction. The simplest approach is to weight each of the $B$ committee members equally. However, several variants are available that reduce the weight of less reliable committee members (e.g., poor classification accuracy, multiple outliers are present, etc).
{ "pile_set_name": "StackExchange" }
Q: createBottomTabNavigator white space (icon is auto hide) when keyboard show React-native application with version: [email protected] [email protected] react-navigation@^4.0.10 react-navigation-stack@^1.10.3 react-navigation-tabs@^2.5.6 I'm trying to make an application with createBottomTabs, when i try to type in TextInput, when the keyboard show, there are bottomtabs with icon, the icon will auto hide, leaving the white space / gap behind on top of the keyboard my code example : <SafeAreaView style={ flex: 1, alignItems: 'center' }> <View> <TextInput /> </View> </SafeAreaView> already tried to change SafeAreaView with KeyboardAvoidingView, but the white space/gap is still there. const MainTabs = createBottomTabNavigator({ Screen1: { screen: Screen1Stack, navigationOptions: { tabBarIcon: Icon } }, Screen2: { screen: Screen2Screen, navigationOptions: { tabBarIcon: Icon } }, Screen3: { screen: Screen3Screen, navigationOptions: { tabBarIcon: Icon } }, Screen4: { screen: Screen4Screen, navigationOptions: { tabBarIcon: Icon } }, }, { tabBarOptions: { ... showLabel: false } } ) A: i get the answer from the comment at react navigation tabs github (with title "Bottom tab bars and keyboard on Android #16"), and i will share it here, incase someone experiencing a same issue as me, its answered by @export-mike and detailed by @hegelstad import React from 'react'; import { Platform, Keyboard } from 'react-native'; import { BottomTabBar } from 'react-navigation-tabs'; // need version 2.0 react-navigation of course... it comes preinstalled as a dependency of react-navigation. export default class TabBarComponent extends React.Component { state = { visible: true } componentDidMount() { if (Platform.OS === 'android') { this.keyboardEventListeners = [ Keyboard.addListener('keyboardDidShow', this.visible(false)), Keyboard.addListener('keyboardDidHide', this.visible(true)) ]; } } componentWillUnmount() { this.keyboardEventListeners && this.keyboardEventListeners.forEach((eventListener) => eventListener.remove()); } visible = visible => () => this.setState({visible}); render() { if (!this.state.visible) { return null; } else { return ( <BottomTabBar {...this.props} /> ); } } } Usage : const Tabs = createBottomTabNavigator({ TabA: { screen: TabA, path: 'tab-a', navigationOptions: ({ navigation }) => ({ tabBarLabel: 'Tab A', }) }, TabB: { screen: TabB, path: 'tab-b', navigationOptions: ({ navigation }) => ({ tabBarLabel: 'Tab B', }) } }, (Platform.OS === 'android') ? { tabBarComponent: props => <TabBarComponent {...props} />, tabBarPosition: 'bottom' } : { // don't change tabBarComponent here - it works on iOS after all. } );
{ "pile_set_name": "StackExchange" }
Q: What does Gulzar actually mean by saying that Earth can hide a river inside? The poem "The Magical Earth" by Gulzar (from Green Poems, 2014) contains these lines (in the English translation by Pavan K. Varma): There is something indeed in the earth of my garden Is this earth magical? The earth knows how to do magic! […] A sherbet, or milk, or water Anything may fall, it absorbs them all How much water does it drink?! It gulps down whatever you give Be it from a jug or a bucket Amazingly, its stomach never fills I have heard that it can even hide a river inside! The earth knows how to do magic! What does it poetically mean that earth can hide a river inside? Better give a summary of the poetic non literal lines in the poem "The Magical Earth". A: The soil in the poet’s garden is permeable, so that water quickly disappears into the spaces between the grains. Moreover, the poet has heard that in karst landscapes where soluble rock like limestone lies on top of insoluble rock like sandstone, subterranean rivers may flow. The poem takes these geological commonplaces and defamiliarizes them using a childlike sense of wonder.
{ "pile_set_name": "StackExchange" }
Q: Using the map() function within a class I've been trying to get the map() function to work within a class but have had trouble because I'm not sure if I should be passing self into it. If so, I'm unsure how to make self into a list to go with my other iterables. Here is my code so far: from itertools import repeat class test: def __init__(self): self.nums = [1, 4, 8] self.empty_list = [] map(self.fxn, repeat(self, len(self.nums)), self.nums) print(self.empty_list) def fxn(self, num): self.empty_list.append(num ** num) instance = test() Even after trying to append to the empty list, the list still seems to be blank, what am I doing wrong in that example? A: map doesn't mutate its argument. It returns a new iterable. self.nums = list(map(...)) test.fxn is a function of two arguments: self and num. self.fxn is a bound method of one argument: num. Since you're just repeatedly applying it on self, you can bind it and save yourself the extra argument. self.nums = list(map(self.fxn, self.nums))
{ "pile_set_name": "StackExchange" }
Q: How to get distinct count in aggregate I simply want to get distinct_count aggregation. I have this code: data_frame = data_frame.group_by(:job_id) .aggregate(job_id: :max, bid_id: :count) I want something like this: data_frame = data_frame.group_by(:job_id) .aggregate(job_id: :max, bid_id: :distinct_count) I know there is no statistical method like that implemented yet, is there any other way? A: I found one way to do this: data_frame = data_frame.group_by(:job_id) .aggregate(job_id: :max, bid_id: lambda{ |x| x.uniq.size }) or maybe better yet: data_frame = data_frame.group_by(:job_id) .aggregate(job_id: :max, bid_id: ->(x) { x.uniq.size }) I am not sure if it is the right way, but it seems to work. This pandas solution helped me.
{ "pile_set_name": "StackExchange" }
Q: how to implement TCP server and TCP client in java to transfer files I have implement the simple TCP server and TCP client classes which can send the message from client to server and the message will be converted to upper case on the server side, but how can I achieve transfer files from server to client and upload files from client to server. the following codes are what I have got. TCPClient.java: import java.io.*; import java.net.*; class TCPClient { public static void main(String args[]) throws Exception { String sentence; String modifiedSentence; BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); Socket clientSocket = new Socket("127.0.0.1", 6789); DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); sentence = inFromUser.readLine(); outToServer.writeBytes(sentence + "\n"); modifiedSentence = inFromServer.readLine(); System.out.println("FROM SERVER:" + modifiedSentence); clientSocket.close(); } } TCPServer.java: import java.io.*; import java.net.*; class TCPServer { public static void main(String args[]) throws Exception { int firsttime = 1; while (true) { String clientSentence; String capitalizedSentence=""; ServerSocket welcomeSocket = new ServerSocket(3248); Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); clientSentence = inFromClient.readLine(); //System.out.println(clientSentence); if (clientSentence.equals("set")) { outToClient.writeBytes("connection is "); System.out.println("running here"); //welcomeSocket.close(); //outToClient.writeBytes(capitalizedSentence); } capitalizedSentence = clientSentence.toUpperCase() + "\n"; //if(!clientSentence.equals("quit")) outToClient.writeBytes(capitalizedSentence+"enter the message or command: "); System.out.println("passed"); //outToClient.writeBytes("enter the message or command: "); welcomeSocket.close(); System.out.println("connection terminated"); } } } So, the TCPServer.java will be executed first, and then execute the TCPClient.java, and I try to use the if clause in the TCPServer.java to test what is user's input,now I really want to implement how to transfer files from both side(download and upload).Thanks. A: So lets assume on server side you have received the file name and file path. This code should give you some idea. SERVER PrintStream out = new PrintStream(socket.getOutputStream(), true); FileInputStream requestedfile = new FileInputStream(completeFilePath); byte[] buffer = new byte[1]; out.println("Content-Length: "+new File(completeFilePath).length()); // for the client to receive file while((requestedfile.read(buffer)!=-1)){ out.write(buffer); out.flush(); out.close(); } requestedfile.close(); CLIENT DataInputStream in = new DataInputStream(socket.getInputStream()); int size = Integer.parseInt(in.readLine().split(": ")[1]); byte[] item = new byte[size]; for(int i = 0; i < size; i++) item[i] = in.readByte(); FileOutputStream requestedfile = new FileOutputStream(new File(fileName)); BufferedOutputStream bos = new BufferedOutputStream(requestedfile); bos.write(item); bos.close(); fos.close();
{ "pile_set_name": "StackExchange" }
Q: How to create an Angular 2+ component and put it on npm I am stuck on how to create an AngularX (2+) component and publish it on npm. My goal is to publish a modal component I created in my current Angular App, but for now I just want to create a <hello-world> component. I want my component to be written in TypeScript too. What steps should I follow to achieve this ? I think I have to start with a npm init, maybe npm install --save @angular/core ? And which files should I create, how should I write them ? (i.e. : I should add a tsconfig.json ?) A: I finally found a way to do this, here is my way to create a npm module : Step 1 : create a folder "helloworld" First, create an empty folder (you can name it like you want, here I'll name it "helloworld"). It will contain all your files for the module Step 2 : npm init Then, you have to open a command window in the folder you just created and type npm init, like any npm package. You'll define your package name, description, main file, and some other datas. If you want to create a module with Typescript, type main.ts when it will ask you for the main file. Once finished, this command will generate a package.json file in your folder. Step 3 : npm install --save @angular/core rxjs zone.js Now you have to install Angular and rxjs + zone.js (depedencies needed by Angular). So now, type the command npm install --save @angular/core rxjs zone.js. You should have a file who looks like mine, Here is my package.json : { "name": "helloworld", "version": "1.0.0", "description": "my first npm package", "main": "index.ts", "scripts": { "prepublish" : "tsc", "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "@angular/core": "^4.2.5", "rxjs": "^5.4.1", "zone.js": "^0.8.12" } } Step 3.1 : add an extra script "prepublish" Maybe you noticed that I have an extra line on my script value : "prepublish". This line will be usefull later; when we will publish our package (before sending your files on the npm server) npm will call the prepublish command. Here, this command will call tsc to compile your .ts file(s) in a .js file. To do that, you'll also need a file named tsconfig.json. Step 4 : create a file "tsconfig.json This file will be used when you will compile your .ts file(s) in a .js file. Here is my tsconfig.json file : { "compilerOptions": { "removeComments": true, "target": "es5", "module": "commonjs", "moduleResolution": "node", "declaration": true, "emitDecoratorMetadata": true, // Needed by Angular "experimentalDecorators": true, // Needed by Angular "sourceMap": false, "outDir": "./dist", // Output directory "lib": ["es6", "dom"], "typeRoots": [ "./node_modules/@types" ] }, "files": [ "./index.ts" // File to compile ], "include": [ "lib" // Where you files are stored ], "exclude": [ "node_modules" ] } Step 5 : Create folders "dist" and "lib", create a "index.ts" file Now you have to create two directories : dist and lib. dist will contain the compiled files and lib will contain your files. Create a index.ts file too which will include all your component(s) which need to be exported in the lib folder. Here is my index.ts file : export * from "./lib/helloworld.component"; Step 6 : Create helloworld.component.ts inside the lib folder Then, go to your lib folder and create your component file : helloworld.component.ts. Here is mine : import { Component } from "@angular/core"; @Component({ selector: "helloworld", template: "Hello cool world, I'm your npm component !" }) export class HelloWorldComponent { } Step 7 : Create a ".gitignore" and ".npmignore" file Now your component is ready, before publishing it, you have to write a .gitignore file (if you want to publish your code on Git) and a .npmignore file. You don't need to store the folder node_module nor the generated files on Git. So here is my .gitignore : (I added .idea and *.iml because I'm using IntelliJ Idea which creates a folder and a file.iml) .idea node_modules dist *.iml Then, do almost the same for the .npmignore which just doesn't need your ts files : .idea *.iml *.ts Step 8 : run the publish command or link to test your module If you want to test your module before sending it to npm servers, go to your root package folder (at the same level than the package.json) and run npm link. Once done, go to an Angular project and run npm link helloworld : It will get your package like if it was on npm server and you can use it in your project to check if everything is good. If you want to publish it on npm servers, run npm publish. Just remember, if you want to update your package, you just have to re-run npm publish after you updated your package version. To do that, just run npm version [patch | minor | major] to upgrade your patch or minor/major version !
{ "pile_set_name": "StackExchange" }
Q: Some problems about functions. 1- Let $X = \{1,2,3,7,12\} $ and $Y = \{1,15,7,4,20\} $. We use notation $(x,y)$ to denote that the element $x \in X$ is assigned to (or paired with) the element $y \in Y$. For the relations defined below answer the following questions: Does the relation define a function from $X$ to $Y$? If it does not define a function, explain why not. If the relation defines a function, decide whether the function is injective or not and explain why. Also decide whether the function surjective or not and explain why. $$\begin{align} (a)&\Big\{ (1,15),(7,7),(3,7),(12,4) \Big\}\\ (b)&\Big\{ (1,1),(3,4),(7,7) \Big\}\\ (c)&\Big\{ (1,15),(3,7),(7,4),(12,20) \Big\}\\ (d)&\Big\{ (1,4),(3,7),(7,1),(1,15) \Big\} \end{align}$$ 2- Let $g \, : X \to Y$ be a function. Suppose $A \subseteq X$, that is $A$ is a subset of or equal to $X$. Suppose $B=g(A) \subseteq Y$. Answer the following questions: $\begin{align} (a)&\text{If}\, x \in A, \text{what can you say about}\, g(x)?\\ (b)&\text{If}\, y \in g(A), \,\text{what does this mean?}\\ (c)&\text{If}\, x \in X \, \text{and}\, g(x) \in g(a), \,\text{is it necessarily true that}\, x \in A? \end{align}$ I just have a few issues. For 2. I said all of those except (d)[as it is not a function ] are not surjective since there is always one element in Y that is not paired. Is that right? For 3. a) g(x)=B? b) A=x. c) Is not always true. It is not the case for functions that are not injective. I am really having doubts about question 3 ( all of it ). Are my answers correct? Many thx in advance. A: (b) is not a function $X\to Y$ either as $12$ is not mapped anywhere. (c) is injective and surjectivity is indeed already not possible because $Y$ has more elements than $X$. 3.(a). No. $g(x)\in B$. (b) No. $y\in B$ or more interestingly, there exists $x\in A$ with $y=g(x)$. (c) You are right
{ "pile_set_name": "StackExchange" }
Q: Converting a company from SVN to Hg? We're a heavy user of SVN here. While the advantages of GIT over SVN made us want to change, the advantages of Hg over SVN mean it's now time to change and we need to start doing so very soon. I'm not so worried on the client side, but here are my questions. There are some excellent books on setting file metaproperties, properly organizing projects, etc on SVN. What is that book(s) for Hg? Is there a way to convert an SVN repository (that you've used) and can report how well it went? We don't want to lose years of commit logs if possible. When you DO convert, how did you split up the old code? Did you commit trunk as one project, and tags/forks as another? If you used SVN for legacy work, did you check in updates to SVN or something else? A: There's a free book available at http://hgbook.red-bean.com/ and published by O'Reilly in 2009. As of release 0.9.5, Mercurial comes with a conversion tool. I must admit I switched to Git instead of Mercurial. That said, with Git you can import branches, tags and trunk at the same time in the same repository. Git takes care of everyone and gracefully stores tags as tags, branches as branches and the trunk as the master branch. I'm confident it's almost the same with Mercurial. I recommend you to switch to Mercurial (or Git or any other DVCS) as soon as you can. Do not continue to work on two different repositories. When I switched, I kept svn as long as I was confident enough with Git (git-svn enables yout to interact from git to svn and viceversa). Then I made the switch and I locked the SVN repos. A: Please start by going to the Mercurial wiki. There you'll find a prominent link called Mercurial: The Definitive Guide which links to the hg book as it's called. You probably know the svn book for Subversion -- this is the equivalent for Mercurial (they're even hosted on the same server, but written by different authors). Further down on the wiki front page, you'll find a section for refugees from other version control systems. There is a link with information for SVN users and repository conversion. The former explains that you can try HgSubversion if you want to do a bi-directional conversion between Subversion and Mercurial and the latter explains how to use the convert extension to do a (possible incremental) Subversion -> Mercurial conversion. Did you find any of these pages already? If not, please tell us how we can improve these pages in order to make these things easier to find. A: I've started the conversion from Subversion to something else a couple of times, once to Darcs, and now I'm playing with Git. I also did a fairly major move from CVS to Subversion quite some time ago. My biggest piece of advice is, don't do it all at once. Pick one non-trivial but not huge project, and convert that first. Allocate a reasonable time budget (an hour per day per developer for the first couple of weeks is not unreasonable) for learning the system and adapting your workflow. A month or so later, once you have a reasonable amount of experience with the system amongst several developers, then you can look at converting everything else, if you still feel you even want to go that way. When you do that, make sure that your developers who are experienced with the new VCS are available to the others, ideally one should be working in the same room with anybody who is being converted. Oh, yes, and this does presume that you've already done a reasonable amount of playing with the system, and built a "toy" project using it. Not too toy, though: it should involve at least three developers, a few dozen files, hundreds of commits, and should use a workflow similar to one of your real projects.
{ "pile_set_name": "StackExchange" }
Q: Using font-awesome icons in angular 6 inside index.html I have successfully added a loader to my andular 6 project that will show the loader upon initial load until the app fully loads. I however cant seem to get a font awesome icon to load inside the spinner. app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FontAwesomeModule } from '@fortawesome/angular-fontawesome'; import { library } from '@fortawesome/fontawesome-svg-core'; import { fab } from '@fortawesome/free-brands-svg-icons'; import { AppComponent } from './app.component'; library.add(fab); @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, FontAwesomeModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } src/index.html <body> <abe-root> <div class="app-loading"> <div class="logo"><fa-icon [icon]="['fab', 'angular']"></fa-icon></div> <svg class="spinner" viewBox="25 25 50 50"> <circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="2" stroke-miterlimit="10"/> </svg> </div> </abe-root> </body> It doesn't error or anything it just doesn't show the icon? I'm fairly new to angular so i may be doing something completely wrong. A: This wont work <div class="logo"><fa-icon [icon]="['fab', 'angular']"></fa-icon></div> as there is no app context yet. You can display FA fonts like this, without angular components (yet) <i class="fa fa-angular"></i> I also assume that you have incuded FA CSS in index.html head section.
{ "pile_set_name": "StackExchange" }
Q: Get the full graph of a query in Neo4j Suppose tha I have the default database Movies and I want to find the total number of people that have participated in each movie, no matter their role (i.e. including the actors, the producers, the directors e.t.c.) I have already done that using the query: MATCH (m:Movie)<-[r]-(n:Person) WITH m, COUNT(n) as count_people RETURN m, count_people ORDER BY count_people DESC LIMIT 3 Ok, I have included some extra options but that doesn't really matter in my actual question. From the above query, I will get 3 movies. Q. How can I enrich the above query, so I can get a graph including all the relationships regarding these 3 movies (i.e.DIRECTED, ACTED_IN,PRODUCED e.t.c)? I know that I can deploy all the relationships regarding each movie through the buttons on each movie node, but I would like to know whether I can do so through cypher. A: Use additional optional match: MATCH (m:Movie)<--(n:Person) WITH m, COUNT(n) as count_people ORDER BY count_people DESC LIMIT 3 OPTIONAL MATCH p = (m)-[r]-(RN) WHERE type(r) IN ['DIRECTED', 'ACTED_IN', 'PRODUCED'] RETURN m, collect(p) as graphPaths, count_people ORDER BY count_people DESC
{ "pile_set_name": "StackExchange" }
Q: Unable to loop/delete with QgsVectorLayer and dataProvider I have a csv file with the following columns: table geometry field type typeName len precision and my goal is to create a number of shp files programatically with PyQGIS. My script stops after creating the first shp file. Here's my code. import sys import re import csv from PyQt4.QtCore import * from PyQt4.QtGui import * reload(sys) sys.setdefaultencoding('utf8') final_list = [] with open(r"D:\Users\Ravi_narayanan\Documents\shpgen.csv", "rU") as s: reader_tables = csv.DictReader(s,delimiter=';') liste_tables = list(reader_tables) l_tables = [i['table'] for i in liste_tables] l_tables = set(l_tables) for table in l_tables: l1 = [line for line in liste_tables if line['table'] == table] geometry = l1[1]['geometry'] layer_mem = QgsVectorLayer(geometry+"?crs=epsg:2154",table,"memory") QgsVectorFileWriter.writeAsVectorFormat(layer_mem,r"D:\setupCAPFT2.00\{}.shp".format(table),"utf-8",None,"ESRI Shapefile",False) layer_path = "D:\{}.shp".format(table) shp = QgsVectorLayer(layer_path,table,'ogr') pr = shp.dataProvider() shp.startEditing() for field in l1: if field['type'] != 'Double': pr.addAttributes([QgsField(field['field'],getattr(QVariant,field['type']),field['typeName'],int(field['len']))]) else: pr.addAttributes([QgsField(field['field'],getattr(QVariant,field['type']),field['typeName'],int(field['len']),int(field['precision']))]) shp.updateFields() shp.commitChanges() shp.stopEditing() del layer_mem,shp,pr A: I think you shouldn't use both dataProvider and an editing session at the same. It's either one or the other one. The same script without the dataprovider, working only in an editing session: shp = QgsVectorLayer(layer_path,table,'ogr') shp.startEditing() for field in l1: if field['type'] != 'Double': shp.addAttributes([QgsField(field['field'],getattr(QVariant,field['type']),field['typeName'],int(field['len']))]) else: shp.addAttributes([QgsField(field['field'],getattr(QVariant,field['type']),field['typeName'],int(field['len']),int(field['precision']))]) shp.commitChanges() or with the dataProvider without an editing session shp = QgsVectorLayer(layer_path,table,'ogr') pr = shp.dataProvider() for field in l1: if field['type'] != 'Double': pr.addAttributes([QgsField(field['field'],getattr(QVariant,field['type']),field['typeName'],int(field['len']))]) else: pr.addAttributes([QgsField(field['field'],getattr(QVariant,field['type']),field['typeName'],int(field['len']),int(field['precision']))]) shp.updateFields() I would personally go for the first one.
{ "pile_set_name": "StackExchange" }
Q: Should I upgrade to be able to use the new async methods for SqlDataReader? I'm working on a large project that runs on .NET 4.0. This framework uses ADO.NET for database calls and we're currently adding asynchronous API methods. The SqlCommand class has the APM methods SqlCommand.BeginExecuteReader() and SqlCommand.EndExecuteReader(), but SqlDataReader does not have asynchronous implementations. When the SqlCommand.ExecuteReader() is finished I want to iterate through the results using SqlDataReader. Microsoft introduces asynchronous methods for SqlDataReader in .NET 4.5, so I can't use those in 4.0. Question: Should we upgrade to be able to use the asynchronous (TAP) methods of SqlDataReader? If we do, why? I searched the web and stackoverflow alot for answers, but I only seem to find implementations for this. It doesn't tell me what benefit those new implementations give. .NET 4.0 implementation Here we use the asynchronous methods of SqlCommand, but we can't use the new asynchronous methods for SqlDataReader, like SqlDataReader.ReadAsync(). private Task<IDataReader> ExecuteReaderAsync(IDbCommand dbCommand) { var sqlCommand = CheckIfSqlCommand(dbCommand); PrepareExecuteReader(dbCommand); return Task<IDataReader> .Factory .FromAsync(sqlCommand.BeginExecuteReader, sqlCommand.EndExecuteReader, null); } private void ReadAll(Task<IDataReader> readerTask) { var reader = readerTask.Result; while (reader.Read()) // Should this be asynchronously? { // Do something } } public Task<IDataReader> Foo(IDbCommand dbCommand) { return ExecuteReaderAsync(dbCommand) .ContinueWith(readerTask => ReadAll(readerTask)); } .NET 4.5 implementation In .NET 4.5 we can use the async/await keywords, and we can use the new asynchronous methods for SqlDataReader, like SqlDataReader.ReadAsync(). private async Task<SqlDataReader> ExecuteReaderAsync(SqlCommand dbCommand) { PrepareExecuteReader(dbCommand); return await dbCommand.ExecuteReaderAsync(); } private async Task ReadAll(SqlDataReader reader) { while (await reader.ReadAsync()) // Should this be asynchronously? { // Do something } } public async Task<IDataReader> Foo(SqlCommand dbCommand) { var reader = await ExecuteReaderAsync(dbCommand); await ReadAll(reader); return reader; } A: The theoretical benefit is that your application will use fewer threads, therefore consuming less memory and CPU resources on thread overhead. That, in turn, leaves more resources available for your application or other system activities, improving the performance and scalability of the application. For applications that receive a lot of simultaneous requests the benefit can be significant. You can only find the actual difference that you would see by testing your specific application, though. This is a nice article that digs in to details. My opinion is that if you don't find the async DataReader code to be harder to understand, read, and debug then go ahead and use it. It will be consistent with how you handle Command code and async is generally considered a modern best practice. What do you have to lose? I do want to mention, however, that you should really consider using a higher-level API, i.e., an ORM. I think that Entity Framework and nHibernate are the most popular for .NET currently. EF6 has built-in async support and for a typical query to be async you can simply use something like ToListAsync(). See this for a start.
{ "pile_set_name": "StackExchange" }
Q: how to unlock a vagrant machine while it is being provisioned Our vagrant box takes ~1h to provision thus when vagrant up is run for the first time, at the very end of provisioning process I would like to package the box to an image in a local folder so it can be used as a base box next time it needs to be rebuilt. I'm using vagrant-triggers plugin to place the code right at the end of :up process. Relevant (shortened) Vagrantfile: pre_built_box_file_name = 'image.vagrant' pre_built_box_path = 'file://' + File.join(Dir.pwd, pre_built_box_file_name) pre_built_box_exists = File.file?(pre_built_box_path) Vagrant.configure(2) do |config| config.vm.box = 'ubuntu/trusty64' config.vm.box_url = pre_built_box_path if pre_built_box_exists config.trigger.after :up do if not pre_built_box_exists system("echo 'Building gett vagrant image for re-use...'; vagrant halt; vagrant package --output #{pre_built_box_file_name}; vagrant up;") end end end The problem is that vagrant locks the machine while the current (vagrant up) process is running: An action 'halt' was attempted on the machine 'gett', but another process is already executing an action on the machine. Vagrant locks each machine for access by only one process at a time. Please wait until the other Vagrant process finishes modifying this machine, then try again. I understand the dangers of two processes provisioning or modifying the machine at one given time, but this is a special case where I'm certain the provisioning has completed. How can I manually "unlock" vagrant machine during provisioning so I can run vagrant halt; vagrant package; vagrant up; from within config.trigger.after :up? Or is there at least a way to start vagrant up without locking the machine? A: vagrant This issue has been fixed in GH #3664 (2015). If this still happening, probably it's related to plugins (such as AWS). So try without plugins. vagrant-aws If you're using AWS, then follow this bug/feature report: #428 - Unable to ssh into instance during provisioning, which is currently pending. However there is a pull request which fixes the issue: Allow status and ssh to run without a lock #457 So apply the fix manually, or waits until it's fixed in the next release. In case you've got this error related to machines which aren't valid, then try running the vagrant global-status --prune command.
{ "pile_set_name": "StackExchange" }
Q: Copy and rename the new file using BAT command I have a file in C:\ folder which is the following: My_File_mmddyyyy_hhmmss.txt The file's mmddyy_hhmmss will change based on the date and time the file is generated. How can I create a batch file which will copy that file to C:\TEST\ and rename the copied file to My_File_mmddyy.txt (drop the _hhmmss from the file name)? since the date and time changes in the filename, can I do something like this: @ECHO OFF xcopy /s c:\My_File_*.txt c:\TEST\My_File_mmddyyyy.txt But then the original mmddyyyy will disappear. How can I achieve what I am looking to do? A: The command COPY (among others) has this bit of little-known functionality: COPY My_File_*.txt My_File_????????.txt The eight question marks in the new name will result in the mmddyyyy part of the source being exactly preserved.
{ "pile_set_name": "StackExchange" }
Q: MAAS Apache2 Webserver configuration TL;DR Please paste content of /usr/share/maas/maas-http.conf I screwed up configuring my maas-http.conf and now I don't reach the webserver. I tried to install letsencrypt certificates for https but that is not a good idea for the internal network, since the local hostsname of the machine differs and it is not included in the LE Certificate. To restore my original configuration it would be nice, if anyone could just paste the raw content of the /usr/share/maas/maas-http.conf, so I can use it on my server. Thanks for your help! A: Here is my maas http configuration file. http://paste.ubuntu.com/24380295/ MAAS version: 2.1.5
{ "pile_set_name": "StackExchange" }
Q: PHP Array Undefined Index Issue I am creating a sitemap using XML. When I try to put multiple values to array, I am getting undefined index for the second variable. Sample code below. How I gather the results: $tempArray = array(); switch ($type) { case "v": $dbResult = $db->get_dbResult("Select title,id,vdate from " . DB_PREFIX . "tpV order by id desc " . this_offset($getFirstK)); if ($dbResult) { foreach($dbResult as $pResult) { $tempArray[]['loc'] = convert_to_URL($pResult->id, $pResult->title); $tempArray[]['vdate'] = $pResult->vdate; } } break; How I print the result. array_filter($tempArray = array_map("unserialize", array_unique(array_map("serialize", $tempArray)))); echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'; foreach($tempArray as $tVars) { echo '<url> <loc> '.$tVars["loc"].' </loc> <lastmod>'.$tVars["vdate"].'</lastmod> <changefreq>weekly</changefreq> </url>'; } echo '</urlset>'; I am getting undefined index error for $tempArray[]['vdate']. Is there anything am I missing? A: $tempArray[]['loc'] = convert_to_URL($pResult->id, $pResult->title); $tempArray[]['vdate'] = $pResult->vdate; here you create two arrays, one with loc key, another with vdate, so one of the two keys must be undefined in the two arrys. to fix this error, just change the two lines to $tempArray[] = array('loc' => convert_to_URL($pResult->id, $pResult->title), 'vdate' => $pResult->vdate); here is a demo <?php $array=array(); $array[]['a'] = 'a'; $array[]['b'] = 'b'; echo json_encode($array); result:[{"a":"a"},{"b":"b"}]
{ "pile_set_name": "StackExchange" }
Q: Matching part of a multivalued field to my setString function I am trying to select payment plans for a specific term from my database. The problem is that my pay_plan field is multivalued, and is set up like this: UTAD*00000*2010SP. I want to match up the specific terms like so: stmt = conn.prepareStatement("SELECT person FROM schema.payments WHERE pay_plan = ?"); stmt.setString(1, term); Is there anyway to only match the characters after the final *, or is there any other way to go about this? A: WHERE pay_plan LIKE '%*%*' + @MySearchValue; This means you'll match only the last bit and assume you always have abc*123*wanted Note: an index will be ignored because of the leading % so you'll have to accept poor performance as a consequence of un-normalised data
{ "pile_set_name": "StackExchange" }
Q: no appropriate default constructor available . (when creating a child class) I am creating some custom exception classes doing the following class GXException { public: GXException(LPCWSTR pTxt):pReason(pTxt){}; LPCWSTR pReason; }; class GXVideoException : GXException { public: GXVideoException(LPCWSTR pTxt):pReason(pTxt){}; LPCWSTR pReason; }; When I created GXVideoException to extend GXException, I get the following error 1>c:\users\numerical25\desktop\intro todirectx\godfiles\gxrendermanager\gxrendermanager\gxrendermanager\gxexceptions.h(14) : error C2512: 'GXException' : no appropriate default constructor available A: You need to call your base class constructor inside your derived constructor's initializer list. Also since you are deriving from the base class you should not redeclare a second variable by the same name (pReason). class GXException { public: GXException(LPCWSTR pTxt):pReason(pTxt){}; LPCWSTR pReason; }; class GXVideoException : GXException { public: GXVideoException(LPCWSTR pTxt) : GXException(pTxt) {} };
{ "pile_set_name": "StackExchange" }
Q: Traversing a DOM tree to get (name,value) pairs of attributes and leaf nodes I want to traverse through an XML file in DOM for the purpose of retrieving as (name,value) pairs all: Attribute names and values; All leaf node names and their text content; So given the following XML file as an example: <?xml version="1.0" encoding="UTF-8"?> <title text="title1"> <comment id="comment1"> <data> abcd </data> <data> efgh </data> </comment> <comment id="comment2"> <data> ijkl </data> <data> mnop </data> <data> qrst </data> </comment> </title> What I want as name value pairs are: text=title1 id=comment1 data=abcd data=efgh id=commment2 data=ijkl data=mnop data=qrst A: An easier solution might be to use XPath to extract all name value pairs as in the following example. You could also skip the DOM construction and call evaluate directly on the InputSource. The XPath expression //@* | //*[not(*)] matches the union of all attributes and all nodes that don't have any child nodes. import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; public class Test { private static final String xml = "<title text='title1'>\n" + " <comment id='comment1'>\n" + " <data> abcd </data>\n" + " <data> efgh </data>\n" + " </comment>\n" + " <comment id='comment2'>\n" + " <data> ijkl </data>\n" + " <data> mnop </data>\n" + " <data> qrst </data>\n" + " </comment>\n" + "</title>\n"; public static void main(String[] args) throws Exception { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(xml))); XPathFactory xpf = XPathFactory.newInstance(); XPath xp = xpf.newXPath(); NodeList nodes = (NodeList)xp.evaluate("//@* | //*[not(*)]", doc, XPathConstants.NODESET); System.out.println(nodes.getLength()); for (int i=0, len=nodes.getLength(); i<len; i++) { Node item = nodes.item(i); System.out.println(item.getNodeName() + " : " + item.getTextContent()); } } }
{ "pile_set_name": "StackExchange" }
Q: SQL Server 2008 - Use IDENTITY field when inserting a row My table has 3 columns ID, ISOCode and CountryName. Column ID is an IDENTITY column. When I insert new records into this table, I want to populate the ISOCode field - on occasion - with the same value as the ID field. I've tried SCOPE_IDENTITY(), @@IDENTITY and IDENT_CURRENT but none of these seems to work. Is there a way I can do this? A: you could write a trigger to update the ISOCode column In Trigger use the code below update T set T.ISOCode=I.ID from your_table T join INSERTED I on T.ID=I.ID
{ "pile_set_name": "StackExchange" }
Q: Inserting to a number of containers in azure cosmos db as one atomic operation I'm a little new to Azure Cosmos DB. I wanted to know if it has an option to make a number of operations on multiple containers as one atomic operation. E.g., all succeed or or fail from a .NET backend. A: Operations are atomic to a single operation in a single container. If you use a Stored Procedure, you may perform an atomic set of multiple operations within a single partition within a single container. You cannot perform any atomic operations across multiple containers, or across multiple partitions of a single container. This has nothing to do with which language environment (e.g. .NET as you mentioned) you're using. This is just how the Cosmos DB service works.
{ "pile_set_name": "StackExchange" }
Q: How to make a simple update with Firebase and Angular Why is Firebase not being updated when the button is pressed in this plunk? http://plnkr.co/6FmAOarpdEg3ylKAkArg Notice the item is added, but not persisted because a refresh makes it go away again. I'm able to successfully read and display Firebase data. In looking at the TodoSample controller I don't see they are doing anything special other than updating the model. The Firebase settings have read/write enabled. A: To use FireBase implicitly, change this explicit binding: $scope.items = angularFireCollection(url); to use the implicit binding: angularFire(url, $scope, 'items', []); If you want to keep the explicit binding, don't add items like this: $scope.items.add({name: "Firebase", desc: "is awesome!"}); Instead add items like this: $scope.items.push({name: "Firebase", desc: "is awesome!"});
{ "pile_set_name": "StackExchange" }
Q: Jquery fill text area with linebreak and nothin if no data I am trying to show JSON data in a textbox. Data is in this format: address{ "street":"1st main Road" "building_name":"Florence" "Floor":"" "city":"New York" } I have tried this: $('#id_address').val(address.street+'\n'+address.building_name+'\n'+address.Floor+'\n'+address.city); But issue is that if there is no data in Floor then there will a linebreak between floor and city. How to avoid line breaks if there is no data in address line? A: You can use Object.keys(address) to get the keys of the address property and loop over that and check if the value is empty or not. Then prepare the value for the textarea accordingly based on the condition address[key] !== ''. For more perfection use a condition index+1 !== allKeys.length to prevent \n for the last item. var address = { "street":"1st main Road", "building_name":"Florence", "Floor":"", "city":"New York" }; var textValue = ''; var allKeys = Object.keys(address); allKeys.forEach(function(key, index){ if(address[key] !== ''){ textValue += address[key]; if(index+1 !== allKeys.length){ textValue += '\n'; } } }); console.log(textValue); $('#id_address').val(textValue); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea id='id_address' rows='5'></textarea> A: I know you already accepted an answer, but here is my solution anyway. I propose you a all-in-one-line solution, not using any loop or something complicated. Only existing functions/methods, I think that's the easiest solution!… And it's vanilla Javascript! See comments in my code below: var address = { "street":"1st main Road", "building_name":"Florence", "Floor":"", "city":"New York" }; // Get values from the object, join them with new lines, and replace the multiple new lines var textValue = Object.values(address).join('\n').replace(/[\n]+/g, '\n'); // Display in console console.log(textValue); I hope it helps.
{ "pile_set_name": "StackExchange" }
Q: How to take picture with ip camera using android Hi i have created and android application using an ipcamera,for that i have used mjpeg class Main class package com.example.mjpeg; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import android.view.WindowManager; import com.example.mjpeg.MjpegInputStream; import com.example.mjpeg.MjpegView; public class MainActivity extends Activity { private MjpegView mv; private static final int MENU_QUIT = 1; /* Creates the menu items */ public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, MENU_QUIT, 0, "Quit"); return true; } /* Handles item selections */ public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_QUIT: finish(); return true; } return false; } public void onCreate(Bundle icicle) { super.onCreate(icicle); //sample public cam String URL = "http://192.168.2.1/?action=appletvstream"; requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); mv = new MjpegView(this); setContentView(mv); mv.setSource(MjpegInputStream.read(URL)); mv.setDisplayMode(MjpegView.SIZE_BEST_FIT); mv.showFps(false); } public void onPause() { super.onPause(); mv.stopPlayback(); } } MjpegInputstream class package com.example.mjpeg; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Properties; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.graphics.Bitmap; import android.graphics.BitmapFactory; public class MjpegInputStream extends DataInputStream { private final byte[] SOI_MARKER = { (byte) 0xFF, (byte) 0xD8 }; private final byte[] EOF_MARKER = { (byte) 0xFF, (byte) 0xD9 }; private final String CONTENT_LENGTH = "Content-Length"; private final static int HEADER_MAX_LENGTH = 100; private final static int FRAME_MAX_LENGTH = 40000 + HEADER_MAX_LENGTH; private int mContentLength = -1; public static MjpegInputStream read(String url) { HttpResponse res; DefaultHttpClient httpclient = new DefaultHttpClient(); try { res = httpclient.execute(new HttpGet(URI.create(url))); return new MjpegInputStream(res.getEntity().getContent()); } catch (ClientProtocolException e) { } catch (IOException e) {} return null; } public MjpegInputStream(InputStream in) { super(new BufferedInputStream(in, FRAME_MAX_LENGTH)); } private int getEndOfSeqeunce(DataInputStream in, byte[] sequence) throws IOException { int seqIndex = 0; byte c; for(int i=0; i < FRAME_MAX_LENGTH; i++) { c = (byte) in.readUnsignedByte(); if(c == sequence[seqIndex]) { seqIndex++; if(seqIndex == sequence.length) return i + 1; } else seqIndex = 0; } return -1; } private int getStartOfSequence(DataInputStream in, byte[] sequence) throws IOException { int end = getEndOfSeqeunce(in, sequence); return (end < 0) ? (-1) : (end - sequence.length); } private int parseContentLength(byte[] headerBytes) throws IOException, NumberFormatException { ByteArrayInputStream headerIn = new ByteArrayInputStream(headerBytes); Properties props = new Properties(); props.load(headerIn); return Integer.parseInt(props.getProperty(CONTENT_LENGTH)); } public Bitmap readMjpegFrame() throws IOException { mark(FRAME_MAX_LENGTH); int headerLen = getStartOfSequence(this, SOI_MARKER); reset(); byte[] header = new byte[headerLen]; readFully(header); try { mContentLength = parseContentLength(header); } catch (NumberFormatException nfe) { mContentLength = getEndOfSeqeunce(this, EOF_MARKER); } reset(); byte[] frameData = new byte[mContentLength]; skipBytes(headerLen); readFully(frameData); return BitmapFactory.decodeStream(new ByteArrayInputStream(frameData)); } } Mjpeg View package com.example.mjpeg; import java.io.IOException; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.Typeface; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; public class MjpegView extends SurfaceView implements SurfaceHolder.Callback { public final static int POSITION_UPPER_LEFT = 9; public final static int POSITION_UPPER_RIGHT = 3; public final static int POSITION_LOWER_LEFT = 12; public final static int POSITION_LOWER_RIGHT = 6; public final static int SIZE_STANDARD = 1; public final static int SIZE_BEST_FIT = 4; public final static int SIZE_FULLSCREEN = 8; private MjpegViewThread thread; private MjpegInputStream mIn = null; private boolean showFps = false; private boolean mRun = false; private boolean surfaceDone = false; private Paint overlayPaint; private int overlayTextColor; private int overlayBackgroundColor; private int ovlPos; private int dispWidth; private int dispHeight; private int displayMode; public class MjpegViewThread extends Thread { private SurfaceHolder mSurfaceHolder; private int frameCounter = 0; private long start; private Bitmap ovl; public MjpegViewThread(SurfaceHolder surfaceHolder, Context context) { mSurfaceHolder = surfaceHolder; } private Rect destRect(int bmw, int bmh) { int tempx; int tempy; if (displayMode == MjpegView.SIZE_STANDARD) { tempx = (dispWidth / 2) - (bmw / 2); tempy = (dispHeight / 2) - (bmh / 2); return new Rect(tempx, tempy, bmw + tempx, bmh + tempy); } if (displayMode == MjpegView.SIZE_BEST_FIT) { float bmasp = (float) bmw / (float) bmh; bmw = dispWidth; bmh = (int) (dispWidth / bmasp); if (bmh > dispHeight) { bmh = dispHeight; bmw = (int) (dispHeight * bmasp); } tempx = (dispWidth / 2) - (bmw / 2); tempy = (dispHeight / 2) - (bmh / 2); return new Rect(tempx, tempy, bmw + tempx, bmh + tempy); } if (displayMode == MjpegView.SIZE_FULLSCREEN) return new Rect(0, 0, dispWidth, dispHeight); return null; } public void setSurfaceSize(int width, int height) { synchronized(mSurfaceHolder) { dispWidth = width; dispHeight = height; } } private Bitmap makeFpsOverlay(Paint p, String text) { Rect b = new Rect(); p.getTextBounds(text, 0, text.length(), b); int bwidth = b.width()+2; int bheight = b.height()+2; Bitmap bm = Bitmap.createBitmap(bwidth, bheight, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(bm); p.setColor(overlayBackgroundColor); c.drawRect(0, 0, bwidth, bheight, p); p.setColor(overlayTextColor); c.drawText(text, -b.left+1, (bheight/2)-((p.ascent()+p.descent())/2)+1, p); return bm; } public void run() { start = System.currentTimeMillis(); PorterDuffXfermode mode = new PorterDuffXfermode(PorterDuff.Mode.DST_OVER); Bitmap bm; int width; int height; Rect destRect; Canvas c = null; Paint p = new Paint(); String fps = ""; while (mRun) { if(surfaceDone) { try { c = mSurfaceHolder.lockCanvas(); synchronized (mSurfaceHolder) { try { bm = mIn.readMjpegFrame(); destRect = destRect(bm.getWidth(),bm.getHeight()); c.drawColor(Color.BLACK); c.drawBitmap(bm, null, destRect, p); if(showFps) { p.setXfermode(mode); if(ovl != null) { height = ((ovlPos & 1) == 1) ? destRect.top : destRect.bottom-ovl.getHeight(); width = ((ovlPos & 8) == 8) ? destRect.left : destRect.right -ovl.getWidth(); c.drawBitmap(ovl, width, height, null); } p.setXfermode(null); frameCounter++; if((System.currentTimeMillis() - start) >= 1000) { fps = String.valueOf(frameCounter)+"fps"; frameCounter = 0; start = System.currentTimeMillis(); ovl = makeFpsOverlay(overlayPaint, fps); } } } catch (IOException e) {} } } finally { if (c != null) mSurfaceHolder.unlockCanvasAndPost(c); } } } } } private void init(Context context) { SurfaceHolder holder = getHolder(); holder.addCallback(this); thread = new MjpegViewThread(holder, context); setFocusable(true); overlayPaint = new Paint(); overlayPaint.setTextAlign(Paint.Align.LEFT); overlayPaint.setTextSize(12); overlayPaint.setTypeface(Typeface.DEFAULT); overlayTextColor = Color.WHITE; overlayBackgroundColor = Color.BLACK; ovlPos = MjpegView.POSITION_LOWER_RIGHT; displayMode = MjpegView.SIZE_STANDARD; dispWidth = getWidth(); dispHeight = getHeight(); } public void startPlayback() { if(mIn != null) { mRun = true; thread.start(); } } public void stopPlayback() { mRun = false; boolean retry = true; while(retry) { try { thread.join(); retry = false; } catch (InterruptedException e) {} } } public MjpegView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public void surfaceChanged(SurfaceHolder holder, int f, int w, int h) { thread.setSurfaceSize(w, h); } public void surfaceDestroyed(SurfaceHolder holder) { surfaceDone = false; stopPlayback(); } public MjpegView(Context context) { super(context); init(context); } public void surfaceCreated(SurfaceHolder holder) { surfaceDone = true; } public void showFps(boolean b) { showFps = b; } public void setSource(MjpegInputStream source) { mIn = source; startPlayback(); } public void setOverlayPaint(Paint p) { overlayPaint = p; } public void setOverlayTextColor(int c) { overlayTextColor = c; } public void setOverlayBackgroundColor(int c) { overlayBackgroundColor = c; } public void setOverlayPosition(int p) { ovlPos = p; } public void setDisplayMode(int s) { displayMode = s; } } i got this code from a blog,now i want to take a picture when i click on a button and save it in sd card,can anyone help me please currently i can only view the video from the ipcam,i need to add a button in this class and when i click on the button it should capture a image and save it in sdcard. A: You have a public Bitmap readMjpegFrame() method right there in MjpegInputStream. Take the bitmap from that method and save it on SD card after you click on the button.
{ "pile_set_name": "StackExchange" }
Q: Twitter API PHP Get latest tweets not authenticating I'm using this peice of code to try and get all my latest tweets for printing on my site but it's returning an error about being not authenticated. I've created an app in the Dev section and get my consumer and OAuth keys, and added them in the right place in the code. <?php function buildBaseString($baseURI, $method, $params) { $r = array(); ksort($params); foreach($params as $key=>$value){ $r[] = "$key=" . rawurlencode($value); } return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r)); } function buildAuthorizationHeader($oauth) { $r = 'Authorization: OAuth '; $values = array(); foreach($oauth as $key=>$value) $values[] = "$key=\"" . rawurlencode($value) . "\""; $r .= implode(', ', $values); return $r; } $url = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=jameskrawczyk"; $oauth_access_token = "SECURITY"; $oauth_access_token_secret = "SECURITY"; $consumer_key = "SECURITY"; $consumer_secret = "SECURITY"; $oauth = array( 'oauth_consumer_key' => $consumer_key, 'oauth_nonce' => time(), 'oauth_signature_method' => 'HMAC-SHA1', 'oauth_token' => $oauth_access_token, 'oauth_timestamp' => time(), 'oauth_version' => '1.0'); $base_info = buildBaseString($url, 'GET', $oauth); $composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret); $oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true)); $oauth['oauth_signature'] = $oauth_signature; $header = array(buildAuthorizationHeader($oauth), 'Expect:'); $options = array( CURLOPT_HTTPHEADER => $header, //CURLOPT_POSTFIELDS => $postfields, CURLOPT_HEADER => false, CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false); $feed = curl_init(); curl_setopt_array($feed, $options); $json = curl_exec($feed); curl_close($feed); $twitter_data = json_decode($json, true); foreach ($twitter_data as $elem) { print_r($elem); echo '<br>'; } Error returned on page Array ( [0] => Array ( [message] => Could not authenticate you [code] => 32 ) ) A: Answer seemed to be that the line $url = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=jameskrawczyk"; should not have the ?screen_name=jameskrawczyk at the end.
{ "pile_set_name": "StackExchange" }
Q: Android Camera Crashes every time in onResume or onRestart I built a camera application from android camera example. it's working but every time my application resume or restart from onPause and onStop, my application crashes. I already tried this two link1, link2 but nothing changed. How should I fix it? The logcat shows this message: 2169-2169/com.exshinigami.theremembrance E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.exshinigami.theremembrance, PID: 2169 java.lang.NullPointerException at com.exshinigami.theremembrance.CameraPreview.surfaceCreated(CameraPreview.java:35) at android.view.SurfaceView.updateWindow(SurfaceView.java:572) at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:232) at android.view.View.dispatchWindowVisibilityChanged(View.java:8004) at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1077) at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1077) at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1077) at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1077) at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1077) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1237) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761) at android.view.Choreographer.doCallbacks(Choreographer.java:574) at android.view.Choreographer.doFrame(Choreographer.java:544) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5017) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) at dalvik.system.NativeStart.main(Native Method) A: I did what @Kevin Crain said, I added this line of code to my surefaceCreated and it's working now. if ( mCamera == null ) return; My CameraPreview Class : import java.io.IOException; import android.content.Context; import android.hardware.Camera; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; /** A basic Camera preview class */ public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback { private SurfaceHolder mHolder; private Camera mCamera; private static final String TAG = "------MyCamera------"; public CameraPreview(Context context, Camera camera) { super(context); mCamera = camera; // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = getHolder(); mHolder.addCallback(this); // deprecated setting, but required on Android versions prior to 3.0 mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public void surfaceCreated(SurfaceHolder holder) { // The Surface has been created, now tell the camera where to draw the preview. if(mCamera == null) return; try { mCamera.setPreviewDisplay(holder); mCamera.startPreview(); } catch (IOException e) { Log.d(TAG, "Error setting camera preview: " + e.getMessage()); } } public void surfaceDestroyed(SurfaceHolder holder) { // empty. Take care of releasing the Camera preview in your activity. if (mCamera != null) { mCamera.stopPreview(); mCamera.setPreviewCallback(null); mCamera.release(); mCamera = null; } } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // If your preview can change or rotate, take care of those events here. // Make sure to stop the preview before resizing or reformatting it. if (mHolder.getSurface() == null) { // preview surface does not exist return; } // stop preview before making changes try { mCamera.stopPreview(); } catch (Exception e) { // ignore: tried to stop a non-existent preview } // set preview size and make any resize, rotate or // reformatting changes here // start preview with new settings try { mCamera.setPreviewDisplay(mHolder); //mCamera.setDisplayOrientation(180); mCamera.startPreview(); } catch (Exception e) { Log.d(TAG, "Error starting camera preview: " + e.getMessage()); } } } In my MainActivity : @Override protected void onStop() { super.onStop(); if (mPreview != null) { FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview); preview.removeView(mPreview); mPreview = null; } } @Override protected void onRestart() { super.onRestart(); mCamera = getCameraInstance(); //Open rear camer mPreview = new CameraPreview(this, mCamera); preview = (FrameLayout) findViewById(R.id.camera_preview); preview.addView(mPreview); }
{ "pile_set_name": "StackExchange" }
Q: Wrapper for getter and setter methods in c++ I have few classes with pair of methods which stands for "setter" and "getter" methods, like: class ClassA { void SetSomeProperty(const int& value) { ... } int GetSomeProperty() { ... } void SetAnotherProperty(const Vec3& value) { ... } Vec3 GetAnotherProperty() { ... } }; class ClassB { void SetColor(const Vec4& value) { ... } Vec4 GetColor() { ... } } I want to create a class called PropertyAccess that can wrap each pair of setter and getter of any class. This will allow me to past this PropertyAccess to other object which will be able to call those setters and getters wihout any knowledgne about ClassA or ClassB. this is my iplementation: class PropertyAccess { public: template <typename TClass, typename TType> using SetterPointer = void (TClass::*)(const TType&); template <typename TClass, typename TType> using GetterPointer = TType(TClass::*)(); template <typename TClass, typename TType> PropertyAccess( TClass* object, SetterPointer<TClass, TType> setter, GetterPointer<TClass, TType> getter) { using std::placeholders::_1; m_setter = new Setter<TType>(std::bind(setter, object, _1)); m_getter = new Getter<TType>(std::bind(getter, object)); } ~PropertyAccess() { delete m_setter; delete m_getter; } template <typename T> void Set(const T& value) { ((Setter<T>*)m_setter)->m_setter(value); } template <typename T> T Get() { return ((Getter<T>*)m_getter)->m_getter(); } private: struct Base { virtual ~Base() {} }; template <typename TType> struct Setter : public Base { Setter(std::function < void(const TType&) > setter) { m_setter = setter; } std::function < void(const TType&) > m_setter; }; template <typename TType> struct Getter : public Base { Getter(std::function < TType() > getter) { m_getter = getter; } std::function < TType() > m_getter; }; Base* m_setter; Base* m_getter; }; I use it like that: ClassA a; PropertyAccess p(&a, &ClassA::SetSomeProperty, &ClassA::GetSomeProperty); p.Set<int>(10); int v = p.Get<int>(); Everything works fine, but this is exteremly slow approach. Calling setters through PropertAccess is approx 18 times slower than call them directly. Speed is important here, because I need to use that mechanism in animation library (Animator will set properties without knowledge about source objects). So my question is: how to speed up this mechanism? Is there any "industry standard" approach for that? Maybe I should use classic method pointers instead of std::function? A: You can take Anton Slavin's solution and introduce an interface to erase object type. It will make lifetime management of accessors more complicated (you'll have to use references/pointers/smart pointers and manage lifetime because you won't be able to copy accessors) and will cost at runtime as virtual method calls will not inline so I would measure if it is quicker than your original solution. template<typename TType> struct PropertyAccess { virtual void Set(const TType& value) = 0; virtual TType Get() = 0; }; template <typename TClass, typename TType> class PropertyAccessT : public PropertyAccess<TType> { public: using SetterPointer = void (TClass::*)(const TType&); using GetterPointer = TType(TClass::*)(); PropertyAccessT(TClass* object, SetterPointer setter, GetterPointer getter) : m_object(object), m_setter(setter), m_getter(getter) { } void Set(const TType& value) { (m_object->*m_setter)(value); } TType Get() { return (m_object->*m_getter)(); } private: TClass* m_object; SetterPointer m_setter; GetterPointer m_getter; };
{ "pile_set_name": "StackExchange" }
Q: Redirect / to /index.jsp when deployed to root I am struggling with a webapp deployment in Jetty 6. Previously the the webapp was deployed in /mywebapp and everytime I accessed http://localhost/mywebapp/ Jetty directed me to http://localhost/mywebapp/index.jsp. When I change the contextPath to /, suddenly the redirect behaviour is broken. Instead, Jetty makes an internal forward request. Does anyone have any input why this is happening? The DefaultServlet has the following settings: <init-param> <param-name>dirAllowed</param-name> <param-value>false</param-value> </init-param> <init-param> <param-name>welcomeServlets</param-name> <param-value>false</param-value> </init-param> <init-param> <param-name>redirectWelcome</param-name> <param-value>true</param-value> </init-param> A: Turns out it was not exactly the change of contextPath that made the redirects fail. Instead, I realized that simply the action of adding mywebapp.xml into $JETTY_HOME/contexts/ made Jetty not execute the redirects. I overcame this issue by deleting my context XML file, instead renaming $JETTY_HOME/webapps/mywebapp.war to $JETTY_HOME/webapps/root.war solved the issue. Unclear why this happened in the first place, but I'm happy things are back on track.
{ "pile_set_name": "StackExchange" }
Q: How to post multiple data to web server I have below code for posting data to the web server but it gives me null response, I have multiple data and they are:- date, rig, driller, offsider-1, offsider-2, shift , project, supervisoremail, geologistemail, comments, plants[0][name-id], plants[0][start-usage], plants[0][end-usage], consumables[0][category], consumables[0][name-id], consumables[0][used], consumables[0][code], consumables[0][description], I have to post this data and I used this code for posting but it didn't work for me. Please help me out. NSURL *url=[NSURL URLWithString:@"http://www.mydor.com.au/staff/dor/idorInsert"]; NSString *post =[[NSString alloc]initWithFormat:@"date=15/08/2012&rig=53&driller=207&offsider-1=131&offsider- 2=236&shift=day&project=24&supervisoremail=24&geologistemail=24&comments=&plants[0][name- id]=286&plants[0][start-usage]=1.0&plants[0][end-usage]=0.0"]; NSLog(post); NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; [request setURL:url]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]]; NSError *error; NSURLResponse *response; NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSLog(@"here u re"); NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding]; NSLog(@"here also called"); NSLog(@"%@",data) Thanks in advance. A: Here is an article which demonstrates how to consume .NET Web service using iOS application. You can use the techniques discussed in the article: http://www.highoncoding.com/Articles/809_Consuming__NET_Web_Services_in_an_iOS_Application.aspx
{ "pile_set_name": "StackExchange" }
Q: How to pass is operator parameter through function in Kotlin val k = " asdfasdf " fun test() { if(k is String) { // Do something } } So, how do I pass that String through the function calls eg: fun test(xxxx) { if(k is xxxx) { // do something } } A: Like this: inline fun <reified T> testType(k: Any) { if(k is T) { println("is a ${T::class.simpleName}") } else { println("is not a ${T::class.simpleName}") } } Call it like this: test<String>("Hello") // is a String test<String>(1) // is no String Here some further reading.
{ "pile_set_name": "StackExchange" }
Q: What is the better way to escape from too many if/else-if from the following code snippet? I am trying to write a servlet which does task based on the "action" value passed it to as input. Here is the sample of which public class SampleClass extends HttpServlet { public static void action1() throws Exception{ //Do some actions } public static void action2() throws Exception{ //Do some actions } //And goes on till action9 public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException { String action = req.getParameter("action"); /** * I find it difficult in the following ways * 1. Too lengthy - was not comfortable to read * 2. Makes me fear that action1 would run quicker as it was in the top * and action9 would run with a bit delay - as it would cross check with all the above if & else if conditions */ if("action1".equals(action)) { //do some 10 lines of action } else if("action2".equals(action)) { //do some action } else if("action3".equals(action)) { //do some action } else if("action4".equals(action)) { //do some action } else if("action5".equals(action)) { //do some action } else if("action6".equals(action)) { //do some action } else if("action7".equals(action)) { //do some action } else if("action8".equals(action)) { //do some action } else if("action9".equals(action)) { //do some action } /** * So, the next approach i tried it with switch * 1. Added each action as method and called those methods from the swith case statements */ switch(action) { case "action1": action1(); break; case "action2": action2(); break; case "action3": action3(); break; case "action4": action4(); break; case "action5": action5(); break; case "action6": action6(); break; case "action7": action7(); break; case "action8": action8(); break; case "action9": action9(); break; default: break; } /** * Still was not comfortable since i am doing un-necessary checks in one way or the other * So tried with [reflection][1] by invoking the action methods */ Map<String, Method> methodMap = new HashMap<String, Method>(); methodMap.put("action1", SampleClass.class.getMethod("action1")); methodMap.put("action2", SampleClass.class.getMethod("action2")); methodMap.get(action).invoke(null); /** * But i am afraid of the following things while using reflection * 1. One is Security (Could any variable or methods despite its access specifier) - is reflection advised to use here? * 2. Reflection takes too much time than simple if else */ } } All i need is to escape from too many if/else-if checks in my code for better readability and better code maintanance. So tried for other alternatives like 1.switch case - still it does too many checks before doing my action 2.reflection i]one main thing is security - which allows me to access even the variables and methods within the class despite of its access specifier - i am not sure weather i could use it in my code ii] and the other is it takes time more than the simple if/else-if checks Is there any better approach or better design some one could suggest to organise the above code in a better way? EDITED I have added the answer for the above snippet considering the below answer. But still, the following classes "ExecutorA" and "ExecutorB" does only a few lines of code. Is it a good practice to add them as a class than adding it as a method? Please advise in this regard. A: Based on the previous answer, Java allows enums to have properties so you could define a strategy pattern, something like public enum Action { A ( () -> { //Lambda Sintax // Do A } ), B ( () -> executeB() ), // Lambda with static method C (new ExecutorC()) //External Class public Action(Executor e) this.executor = e; } //OPTIONAL DELEGATED METHOD public foo execute() { return executor.execute(); } // Action Static Method private static foo executeB(){ // Do B } } Then your Executor (Strategy) would be public interface Executor { foo execute(); } public class ExecutorC implements Executor { public foo execute(){ // Do C } } And all your if/else in your doPost method become something like public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String action = req.getParameter("action"); Action.valueOf(action).execute(); } This way you could even use lambdas for the executors in the enums. A: Instead of using reflection, use a dedicated interface. ie instead of : /** * Still was not comfortable since i am doing un-necessary checks in one way or the other * So tried with [reflection][1] by invoking the action methods */ Map<String, Method> methodMap = new HashMap<String, Method>(); methodMap.put("action1", SampleClass.class.getMethod("action1")); methodMap.put("action2", SampleClass.class.getMethod("action2")); methodMap.get(action).invoke(null); Use public interface ProcessAction{ public void process(...); } Implements each of them for each actions and then : // as attribute Map<String, ProcessAction> methodMap = new HashMap<String, ProcessAction>(); // now you can add to the map you can either hardcode them in an init function methodMap.put("action1",action1Process); // but if you want some more flexibility you should isolate the map in a class dedicated : // let's say ActionMapper and add them on init : public class Action1Manager{ private static class ProcessAction1 implements ProcessAction{...} public Action1Manager(ActionMapper mapper){ mapper.addNewAction("action1", new ProcessAction1()); } } Of course this solution isn't the lighest, so you may not need to go up to that length.
{ "pile_set_name": "StackExchange" }
Q: Install WebExtensions on Firefox from the command line I found the question How to install Firefox addon from command line in scripts? that seems to work for Firefox extensions (i.e. ones with an install.rdf file) but what about WebExtensions (extension with a manifest.json file instead)? A: Please see: Installing extensions Customizing Firefox: Including extensions with your distribution of Firefox The question you link on askubuntu: How to install Firefox addon from command line in scripts? is several years out of date, but does have some good information. At this point, most Mozilla add-ons, including all Firefox WebExtension add-ons, are installed manually by placing the add-on's .xpi file in the appropriate directory with the correct name for the extension without unpacking (unzipping) the contents. [You can also install them by downloading them in Firefox, drag-and-drop the .xpi onto Firefox/Thunderbird, etc.] You can determine those add-ons that must be unpacked by unpacking the add-on's .xpi file and looking at the install.rdf file to see if it has <em:unpack>true</em:unpack>. All WebExtensions don't have this file and are installed without unpacking. The .xpi file must be called [extensionID].xpi. You can find the extension ID from either the install.rdf file (non-WebExtension add-ons). In that file, you are looking for <em:id>ThisEntireStringIsTheAddOnsID</em:id> For a WebExtension, the ID is in the manifest.json file under the applications property: "applications": { "gecko": { "id": "ThisEntireStringIsTheAddOnsID" } }, For both of the above examples the .xpi file must be renamed to ThisEntireStringIsTheAddOnsID.xpi If the install.rdf file includes <em:unpack>true</em:unpack>, then the files in the .xpi must be unpacked (unzipped) and placed in a subdirectory under the extensions directory. In the above install.rdf example (again WebExtensions are not unpacked), the directory would be named: ThisEntireStringIsTheAddOnsID Extension directories: The extension directories where you put the .xpi file or unpacked directory are (information partially copied from MDN): For all users running a particular version of Firefox: [Firefox install directory]/browser/extensions/ Firefox will ask the user to confirm installation of the add-on when that version of Firefox is run. The user will not have the ability to remove the extension, only disable it. The extension will not be automatically updated. For all users running a particular version of Firefox: [Firefox install directory]/distribution/extensions The extension will be installed for all users/profiles the first time the profile is run with that version of Firefox. The extension will be copied into the profile's extensions directory and the user will be able to remove it in addition to disabling it. The user will not be asked to confirm installation. The extension copied to each profile will be automatically updated along with all other extensions installed for that profile. You should not unpack any .xpi files in this directory. If the file needs to be unpacked, it will be done automatically by Firefox when the extension is installed in each profile. For a particular User's specific profile: [profile directory]/extensions/ On Windows: All profiles for a specific user: <I>%appdata%\\Mozilla\\Extensions\\{ec8030f7-c20a-464f-9b0e-13a3a9e97384}\</I> Profile directories are located at: <i>\\Mozilla\\Firefox\\Profiles\\*</i> OSX: For all users: /Library/Application Support/Mozilla/Extensions/{ec8030f7-c20a-464f-9b0e-13a3a9e97384}/ Just for a specific user, place it in that user's library folder hierarchy: ~/Library/Application Support/Mozilla/Extensions/{ec8030f7-c20a-464f-9b0e-13a3a9e97384}/ Linux: For all users: /usr/lib/Mozilla/extensions/{ec8030f7-c20a-464f-9b0e-13a3a9e97384}/ or /usr/lib64/Mozilla/extensions/{ec8030f7-c20a-464f-9b0e-13a3a9e97384}/ or /usr/share/Mozilla/extensions/{ec8030f7-c20a-464f-9b0e-13a3a9e97384}/ Just for a specific user: ~/.Mozilla/extensions/{ec8030f7-c20a-464f-9b0e-13a3a9e97384}/ NOTE: The -install-global-extension option mentioned in the question/answer you linked was removed from Firefox as of Gecko 1.9.2 ( a long time ago).
{ "pile_set_name": "StackExchange" }
Q: odd program behavior after adding one instruction in C Actually, I have asked another question with the same code, but this is very different. I have this code below that displays a very annoying behavior. I've included as much comment in the code as I can so that you can have an idea of what's going on. #include <stdio.h> #include <stdlib.h> /* This is a struct describing properties of an element */ struct element{ int age; char* name; }; /* This struct contains a pointer to a pointer on a element "struct element" */ struct person{ struct element** p; size_t size; unsigned int id; }; /* This function initializes a struct person by allocating memory for it */ struct person* init(int _size) { if(_size == 0) { printf("You gonna have to make some choices \n"); exit(1); } struct person* sample = (struct person* )malloc(_size*sizeof(struct person)); sample->p = (struct element** ) malloc(_size*sizeof(struct element*)); sample->id = 0; sample->size = _size; return sample; } /* use this function to insert a new element in the struct */ void insert(struct person* sample, char* _name, int _age) { if (sample->id >= sample->size) { sample->p = (struct element** ) realloc(sample->p, (sample->size*2) * sizeof(struct element*)); if(sample->p == NULL){ printf("Get a new RAM buddy \n"); exit(1); } } sample->p[sample->id]->name = _name; sample->p[sample->id]->age = _age; /* of course, this will cause trouble too because it has the same construct as the previous one */ sample->id++; } /* main entry */ int main(int argc, char** argv) { int i = 0; struct person* student = init(10); /* Allocating space for 10 students */ insert(student, "baby", 2); insert(student, "dady", 33); /* if you remove this line, the program runs, but GDB will signal a segmentation fault. If you keep it, the program will freeze and GDB will behave as expected */ /* I don't understand why this is happening!!!??? */ insert(student, "grandma", 63); printf("Your name is %s and your age is %d \n", student->p[1]->name, student->p[1]->age); /* When you only insert two elements, use the results here to match with GDB's results*/ printf("student->p: %p \n", &student->p); printf("student->p[0]: %p \n", &student->p[0]); printf("student->p[1]: %p \n", &student->p[1]); printf("student->p[0]->age: %p \n", &student->p[0]->age); printf("student->p[0]->name: %p \n", &student->p[0]->name); /* Won't work for more than two elements inserted */ for(i = 0; i < 2; i++){ printf("Your name is %s and your age is %d \n", student->p[i]->name, student->p[i]->age); } return 0; } I hope you can figured out what's going on. Here is a part of a debugging session. (gdb) run The program being debugged has been started already. Start it from the beginning? (y or n) y Starting program: C:\Users\NTWALI\Desktop\tests\help\bin\Debug/help.exe [New thread 11408.0x1228] Error: dll starting at 0x770a0000 not found. Error: dll starting at 0x76ab0000 not found. Error: dll starting at 0x770a0000 not found. Error: dll starting at 0x76d40000 not found. Program received signal SIGSEGV, Segmentation fault. 0x0040146f in insert (sample=0x6816c0, _name=0x409031 "ntwali", _age=22) at C:\Users\NTWALI\Desktop\tests\help\main.c:44 44 sample->p[sample->id]->name = _name; (gdb) p sample $4 = (struct person *) 0x6816c0 (gdb) p sample->p $5 = (struct element **) 0x681750 (gdb) p sample->p[0] $6 = (struct element *) 0xbaadf00d (gdb) p sample->p[1] $7 = (struct element *) 0xbaadf00d (gdb) As you see in the code comment's, the data the program gives when it works, don't match with what one gets with GDB. Thanks for helping. A: You haven't allocated any memory for an element as far as I can see. Here you allocate memory for a pointer to an element: sample->p = (struct element** ) malloc(_size*sizeof(struct element*)); A: If the presence of a debugger alters the way your program behaves, you are very likely misusing memory or threads. Just like daven11 points out, you are not allocating the elements itself. A: The root cause of your problem is that you are allocating pointers to struct element, but those pointers are uninitialised - you're not allocating any actual struct element objects. When you dereference those invalid pointers, you get undefined behaviour. There is also no need to allocate _size of the struct person structs - you only ever use one. Your struct person should look like (note type of p is different): struct person{ struct element *p; size_t size; unsigned int id; }; and your init() function should then look like: struct person* init(int _size) { if(_size < 1) { printf("You gonna have to make some choices \n"); exit(1); } struct person* sample = malloc(sizeof *sample); sample->p = malloc(_size * sizeof sample->p[0]); sample->id = 0; sample->size = _size; return sample; } The insert() function should look like: void insert(struct person* sample, char* _name, int _age) { if (sample->id >= sample->size) { sample->size *= 2; sample->p = realloc(sample->p, sample->size * sizeof sample->p[0]); if(sample->p == NULL){ printf("Get a new RAM buddy \n"); exit(1); } } sample->p[sample->id].name = _name; sample->p[sample->id].age = _age; /* of course, this will cause trouble too because it has the same construct as the previous one */ sample->id++; } The main function should then use student->p[i].name and student->p[i].age to access the data.
{ "pile_set_name": "StackExchange" }
Q: Randomly Selecting Rows with MySQL To randomly select records from one table; do I have to always set a temporary variable in PHP? I need some help with selecting random rows within a CodeIgniter model, and then display three different ones in a view every time my homepage is viewed. Does anyone have any thoughts on how to solve this issue? Thanks in advance! A: If you don't have a ton of rows, you can simply: SELECT * FROM myTable ORDER BY RAND() LIMIT 3; If you have many rows, this will get slow, but for smaller data sets it will work fine. As Steve Michel mentions in his answer, this method can get very ugly for large tables. His suggestion is a good place to jump off from. If you know the approximate maximum integer PK on the table, you can do something like generating a random number between one and your max PK value, then grab random rows one at a time like: $q="SELECT * FROM table WHERE id >= {$myRandomValue}"; $row = $db->fetchOne($q); //or whatever CI's interface to grab a single is like Of course, if you need 3 random rows, you'll have three queries here, but as they're entirely on the PK, they'll be fast(er than randomizing the whole table). A: I would do something like: SELECT * FROM table ORDER BY RAND() LIMIT 1; This will put the data in a random order and then return only the first row from that random order. A: I have this piece of code in production to get a random quote. Using MySQL's RAND function was super slow. Even with 100 quotes in the database, I was noticing a lag time on the website. With this, there was no lag at all. $result = mysql_query('SELECT COUNT(*) FROM quotes'); $count = mysql_fetch_row($result); $id = rand(1, $count[0]); $result = mysql_query("SELECT author, quote FROM quotes WHERE id=$id");
{ "pile_set_name": "StackExchange" }
Q: Is it possible to vectorize this calculation in numpy? Can the following expression of numpy arrays be vectorized for speed-up? k_lin1x = [2*k_lin[i]*k_lin[i+1]/(k_lin[i]+k_lin[i+1]) for i in range(len(k_lin)-1)] Is it possible to vectorize this calculation in numpy? A: x1 = k_lin x2 = k_lin s = len(k_lin)-1 np.roll(x2, -1) #do this do bring the column one position right result1 = x2[:s]+x1[:s] #your divider. You add everything but the last element result2 = x2[:s]*x1[:s] #your upper part # in one line result = 2*x2[:s]*x1[:s] / (x2[:s]+x1[:s]) You last column wont be added or taken into the calculations and you can do this by simply using np.roll to shift the columns. x2[0] = x1[1], x2[1] = x1[2]. This is barely a demo of how you should approach google numpy roll. Also instead of using s on x2 you can simply drop the last column since it's useless for the calculations.
{ "pile_set_name": "StackExchange" }
Q: Firebug not working in Mozilla Firefox version 56 I am using Firefox 56. After auto update of Firefox to version 56, Firebug has stopped working Is there any patch to use Firebug on Firefox 56 version? A: Firebug is no longer supported by Firefox browser 56.0.You might need to look out for alternatives like Firefox Developer Tools/use older versions of Firefox with its compatible firebug version :-(
{ "pile_set_name": "StackExchange" }
Q: Custom git merge union strategy for a Changelog We have an ONGOING.md file where each developer adds item when pushing code. It looks like : ### Added - item 1 ### Changed - item 2 It happened all the time that lines got overwritten when pulling/pushing code so I added a .gitattributes file at the repo root : ONGOING.md -text merge=union I expected that every written line got kept after that, but that's not the case, overwrites still happen. What is the proper way to deal with this? Edit: OK, it just happened so I copy/paste content of my terminal : $ more fab/hotfix/ONGOING.md ### Added $ nano fab/hotfix/ONGOING.md; git commit fab/hotfix/ONGOING.md -m "update ongoing" $ more fab/hotfix/ONGOING.md ### Added - add slug column to BO fack topic admin page $ git pull remote: Enumerating objects: 14, done. remote: Counting objects: 100% (14/14), done. remote: Compressing objects: 100% (13/13), done. remote: Total 14 (delta 1), reused 0 (delta 0) Unpacking objects: 100% (14/14), done. From gitlab.com:kraymer/website a740fe8a0..12d531e8d hotfix -> origin/hotfix First, rewinding head to replay your work on top of it... Applying: add slug column to BO fack topic admin page Using index info to reconstruct a base tree... M fab/hotfix/ONGOING.md Falling back to patching base and 3-way merge... $ more fab/hotfix/ONGOING.md ### Added - shared task for old notifications to be deleted I thought the sentence "Falling back to patching base and 3-way merge..." meant git resolved a conflict, so the merge driver should come into play, no? Edit2: So quoting @VonC : But if the 3-way merge completes without conflicts... no merge driver called. So I guess my problem can be rephrased like : how can I configure git so a 3-way merge on ONGOING.md ends up with a conflict when 2 developers edit the same section (like ### Added in my previous example), such that the merge driver comes into play ? If we reconsider my example in Edit1, I don't get how git ends up picking up the other dev line rather than mine or both. A: Merge drivers are called in case on merge conflicts. If overwrite are still happening, check if the developers are not doing at some point a push --force, overriding the remote history with their own. Or if they somehow ignore the changes pulled (by saving their local copy from their IDE, overriding what was just pulled) Make sure they have: git config --global pull.rebase=true git config --global rebase.autostash=true That will force them to do a local resolution of ONGOING.md, replaying their own commit on top of the ones pulled from the remote. I thought the sentence "Falling back to patching base and 3-way merge..." meant git resolved a conflict, so the merge driver should come into play, no? No: it just means it needs the common ancestor to make the merge. If that common ancestor shows common lines being modified/merged, then yes, a conflict would occur, and the merge driver would be called. But if the 3-way merge completes without conflicts... no merge driver called.
{ "pile_set_name": "StackExchange" }
Q: SMS Performance view dont showing the proper data I have a journey with different versions from which I send an SMS using the SMS activity. Checking the SMS Performance tab to see the tracking it seems there is some discrepancy between the count I have in the Journey and the one is displayed in SMS Analytics. I tried to change the dates but the number doesn't change. Is there any other way to check the SMS tracking sent from a Journey? A: There isn't an out of the box solution to get SMS tracking of a specific journey. However, there are other ways to get what you want: Option 1: Query SMSMessageTracking data view and tie the data back to your customers who received that specific SMS. This data view allows customers to view their send and receive history. Information from this query relates to the owner of a private short code or long code or a client using a shared short code to which the subscriber has opted in. Option 2: Another way to go would be the SMS Message Detail Report. This report includes detailed tracking information about messages sent from an account, including descriptive information about the message and send status at an individual level. These are the fields you'll get on your report's file. The only limitation is you can only create a Date based report and not Journey based. -Date -EID -ClientID -MessageName -MessageType -CampaignName -MessageOrigin -MessageText -MobileNumber -IsoCountryCode -ShortCode -Status -MobileMessageTrackingID -SubscriberKey Option 3: Or, you can check the SMS Analytics under Journey Analytics. It gives you a global preview about all your Journey's SMS performance (delivered, undelivered,..).
{ "pile_set_name": "StackExchange" }
Q: In Germany, what are you supposed to do if your train station doesn't have any working ticket machines? I recently took a train to Munich from a tiny suburban station that only had a couple of ticket machines. At the time I was there one of the machines was broken, but I was able to get a ticket from the second one. But what is one supposed to do if all the machines at the current station are broken down or if there isn't one altogether? There weren't any MVV personnel at the station and the train I was taking (S-Bahn) likewise doesn't have any conductors selling tickets. To avoid an overly narrow question about S-Bahn trains in Munich, it would be nice to get a general answer about Germany as a whole. A: I had this happen with the S-Bahn in Frankfurt and made 'official' enquiries about what sort of action the person should take (I like to play everything strictly by the book). By 'official' I mean I went to the station manager's office and asked the question to him point-blank. Predictably for Germany, there is a brochure that explains the procedure. Each ticket machine has a unique identifier, it's a number on a steel plate (or otherwise affixed) on the front or side. You take a sheet of paper and write down the number and the date/time and your destination. When (and if) challenged, you produce the sheet of paper. The revenue protection staff will know what to do after that and you will be off the hook (all other things being equal). End of story. I suppose that a mobile photo of the machine and a close up of the unique identifier will also do, but that's a pure guess. A: Write down or memorise the number of the ticket machine (Automatennummer, Automaten-Nr. or similar) as well as time and date. For a typical Deutsche Bahn machine, it is the number on white background in a window that looks like this: If possible, take a picture showing that it isn’t working. On each machine there is a number to contact in this event; call it if possible. Especially with smaller companies, you have to expect that the person answering will speak little or no English. In this case, consider asking locals to do this for you. If there are any locals suffering from the same problem as you, try to stick to them. This way you can benefit from them being familiar with the circumstances, the language, and similar. Also, the more people there are reporting the same problem, the more convincing you are. After entering the train, search for the conductor immediately. If there is none (e.g., on short-distance trains) wait and approach them directly if they enter the train. It is most important that you show clear intent to buy a ticket without being checked. In most cases (going by personal experience and stories of others), the conductor will sell you a ticket at the regular price. To this end it helps if the conductor is convinced that the machine is not working (here, steps 1–4 come into play). However, if the conductor isn’t convinced, they may charge you the increased fare for dodgers, which is usually 60 €. In most cases, you can reclaim this (again, the previous steps help), but it may be a rather tedious procedure for a traveller, particularly a foreign one. Also, prepare for major annoyances if you cannot pay this fare (remember that credit cards may not be accepted). All of this assumes that there is not a single working automatic or human vendor of tickets at the station. Note that in some cases, you may also find a ticket machine on the train. Sources (all in German) Deutsche Bahn (former state monopolist, operator of most non-local trains in Germany) arbiter association for mass transit in Nordrhein-Westfalen (Germany’s most populous state) Stiftung Warentest (prominent consumer organisation) A: Deutsche Bahn has an app for Android, iOS and Windows called DB Navigator, and according to the official site, this app lets you buy tickets. It also features English language. Here is an example for an MVV journey similar to the one described in OP: Of course, DB cannot expect all travelers to have a smartphone to buy tickets on, and therefore the other answers here are completely valid. However, if you happen to have a smartphone with a data plan with you and simply want to buy a ticket, avoiding any explanations and/or hassle, purchasing a ticket through this app may be the simplest solution.
{ "pile_set_name": "StackExchange" }
Q: Simple Virus Remover I am trying to create a simple virus remover. The algorithm I developed is meant to: inspect the original file and the infected file separate the virus from the infected file use same algorithm for repairing other files infected with the virus I know this is possible, since this is the same way patches are created, but I am a little bit lost on how to go about with this. Any help around?? A: You'll have to put more intelligence than simply do some pattern matching and remove the isolated virus code. The viruses you are aiming at are files infectors which are rarely used in our days. Most of the time their replication process is as follow: They copy themselves at the beginning or at the end of the PE files Locate the entry point of the PE files Put a jump instruction to this location pointing at theirs code Disinfecting a file is the most difficult part for any anti-virus. It relies on the quality of the virus code: if it's buggy, the host file will just be unrecoverable. In any case, you are entering a world of machine instructions where disassemblers (IDA, PE Explorer ...), and debuggers will be your dearest friends.
{ "pile_set_name": "StackExchange" }
Q: JSON Cannot Deserialize JSON array into type I keep having issues trying to get this JSON to deserialize, even after trying multiple approaches. Here is the JSON that is returned by the web service: [ { "data":[ { "osis":"Matthew 5:5-8", "content":"<p><span id=\"unique-id-23240\" class=\"text Matt-5-5\"><span class=\"woj\"><sup class=\"versenum\">5\u00a0<\/sup>\u201cBlessed are the <sup class='crossreference' value='(<a href=\"#cunique-id-23240A\" title=\" A\">A<\/a>)'>(<a href=\"#cunique-id-23240A\" title=\" A\">A<\/a>)<\/sup>meek, for they <sup class='crossreference' value='(<a href=\"#cunique-id-23240B\" title=\" B\">B<\/a>)'>(<a href=\"#cunique-id-23240B\" title=\" B\">B<\/a>)<\/sup>shall inherit the earth.<\/span><\/span><\/p> <p><span id=\"unique-id-23241\" class=\"text Matt-5-6\"><span class=\"woj\"><sup class=\"versenum\">6\u00a0<\/sup>\u201cBlessed are those who hunger and <sup class='crossreference' value='(<a href=\"#cunique-id-23241C\" title=\" C\">C<\/a>)'>(<a href=\"#cunique-id-23241C\" title=\" C\">C<\/a>)<\/sup>thirst <sup class='crossreference' value='(<a href=\"#cunique-id-23241D\" title=\" D\">D<\/a>)'>(<a href=\"#cunique-id-23241D\" title=\" D\">D<\/a>)<\/sup>for righteousness, for they shall be satisfied.<\/span><\/span><\/p> <p><span id=\"unique-id-23242\" class=\"text Matt-5-7\"><span class=\"woj\"><sup class=\"versenum\">7\u00a0<\/sup>\u201cBlessed are <sup class='crossreference' value='(<a href=\"#cunique-id-23242E\" title=\" E\">E<\/a>)'>(<a href=\"#cunique-id-23242E\" title=\" E\">E<\/a>)<\/sup>the merciful, for they shall receive mercy.<\/span><\/span><\/p> <p><span id=\"unique-id-23243\" class=\"text Matt-5-8\"><span class=\"woj\"><sup class=\"versenum\">8\u00a0<\/sup>\u201cBlessed are <sup class='crossreference' value='(<a href=\"#cunique-id-23243F\" title=\" F\">F<\/a>)'>(<a href=\"#cunique-id-23243F\" title=\" F\">F<\/a>)<\/sup>the pure in heart, for <sup class='crossreference' value='(<a href=\"#cunique-id-23243G\" title=\" G\">G<\/a>)'>(<a href=\"#cunique-id-23243G\" title=\" G\">G<\/a>)<\/sup>they shall see God.<\/span><\/span><\/p>", "footnotes":[ ], "crossrefs":[ "<li id=\"cunique-id-23240A\"><a href=\"#unique-id-23240\" title=\" Matthew 5:5\">Matthew 5:5<\/a> : <a href=\"\/passage\/?search=Ps 37:11&version=ESV\" data-bibleref=\"Ps.37.11\">Ps. 37:11<\/a><\/li>\n", "<li id=\"cunique-id-23240B\"><a href=\"#unique-id-23240\" title=\" Matthew 5:5\">Matthew 5:5<\/a> : <a href=\"\/passage\/?search=Ps 37:11&version=ESV\" data-bibleref=\"Ps.37.11\">Ps. 37:11<\/a><\/li>\n", "<li id=\"cunique-id-23241C\"><a href=\"#unique-id-23241\" title=\" Matthew 5:6\">Matthew 5:6<\/a> : <a href=\"\/passage\/?search=Ps 42:2, Isa 55:1-Isa 55:2, John 7:37&version=ESV\" data-bibleref=\"Ps.42.2,Isa.55.1-Isa.55.2,John.7.37\">Ps. 42:2; Isa. 55:1, 2; John 7:37<\/a><\/li>\n", "<li id=\"cunique-id-23241D\"><a href=\"#unique-id-23241\" title=\" Matthew 5:6\">Matthew 5:6<\/a> : <a href=\"\/passage\/?search=2Tim 2:22, Matt 6:33&version=ESV\" data-bibleref=\"2Tim.2.22,Matt.6.33\">2 Tim. 2:22; [ch. 6:33]<\/a><\/li>\n", "<li id=\"cunique-id-23242E\"><a href=\"#unique-id-23242\" title=\" Matthew 5:7\">Matthew 5:7<\/a> : <a href=\"\/passage\/?search=Matt 18:33, Matt 25:34-Matt 25:36, Prov 19:17, Luke 6:36, 2Tim 1:16, Heb 6:10&version=ESV\" data-bibleref=\"Matt.18.33,Matt.25.34-Matt.25.36,Prov.19.17,Luke.6.36,2Tim.1.16,Heb.6.10\">ch. 18:33; 25:34-36; Prov. 19:17; Luke 6:36; 2 Tim. 1:16; Heb. 6:10<\/a><\/li>\n", "<li id=\"cunique-id-23243F\"><a href=\"#unique-id-23243\" title=\" Matthew 5:8\">Matthew 5:8<\/a> : <a href=\"\/passage\/?search=Ps 24:4, 2Tim 2:22, 1Pet 1:22&version=ESV\" data-bibleref=\"Ps.24.4,2Tim.2.22,1Pet.1.22\">Ps. 24:4; 2 Tim. 2:22; [1 Pet. 1:22]<\/a><\/li>\n", "<li id=\"cunique-id-23243G\"><a href=\"#unique-id-23243\" title=\" Matthew 5:8\">Matthew 5:8<\/a> : <a href=\"\/passage\/?search=Heb 12:14, 1John 3:2-1John 3:3, Rev 22:4, 1Cor 13:12&version=ESV\" data-bibleref=\"Heb.12.14,1John.3.2-1John.3.3,Rev.22.4,1Cor.13.12\">Heb. 12:14; 1 John 3:2, 3; Rev. 22:4; [1 Cor. 13:12]<\/a><\/li>\n" ] }, { "osis":" Mark 3:9", "content":"<p><span id=\"unique-id-24294\" class=\"text Mark-3-9\"><sup class=\"versenum\">9\u00a0<\/sup>And he told his disciples to <sup class='crossreference' value='(<a href=\"#cunique-id-24294A\" title=\" A\">A<\/a>)'>(<a href=\"#cunique-id-24294A\" title=\" A\">A<\/a>)<\/sup>have a boat ready for him because of the crowd, lest they <sup class='crossreference' value='(<a href=\"#cunique-id-24294B\" title=\" B\">B<\/a>)'>(<a href=\"#cunique-id-24294B\" title=\" B\">B<\/a>)<\/sup>crush him,<\/span><\/p>", "footnotes":[ ], "crossrefs":[ "<li id=\"cunique-id-24294A\"><a href=\"#unique-id-24294\" title=\" Mark 3:9\">Mark 3:9<\/a> : <a href=\"\/passage\/?search=Mark 6:32, Mark 6:45, Mark 8:10&version=ESV\" data-bibleref=\"Mark.6.32,Mark.6.45,Mark.8.10\">ch. 6:32, 45 (Gk.); 8:10 (Gk.)<\/a><\/li>\n", "<li id=\"cunique-id-24294B\"><a href=\"#unique-id-24294\" title=\" Mark 3:9\">Mark 3:9<\/a> : <a href=\"\/passage\/?search=Mark 5:24, Mark 5:31&version=ESV\" data-bibleref=\"Mark.5.24,Mark.5.31\">ch. 5:24, 31<\/a><\/li>\n" ] } ] } ] Very ugly I know. Unfortunately it is someone else's web service, so there isn't much I can do. I've been messing around with the C# model class and can't quite seem to get it to work. Calling Method: 2013-02-08 20:08:32.768 VersesiOS[36931:c07] Unhandled managed exception: Cannot deserialize JSON array into type 'Verses.Core.BibleGatewayVerses'. (Newtonsoft.Json.JsonSerializationException) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureArrayContract (System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract) [0x00000] in <filename unknown>:0 at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, System.Object existingValue, System.String reference) [0x00000] in <filename unknown>:0 at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, System.Object existingValue) [0x00000] in <filename unknown>:0 at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueNonProperty (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract) [0x00000] in <filename unknown>:0 at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00000] in <filename unknown>:0 at Newtonsoft.Json.JsonSerializer.DeserializeInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00000] in <filename unknown>:0 at Newtonsoft.Json.JsonSerializer.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00000] in <filename unknown>:0 at Newtonsoft.Json.JsonConvert.DeserializeObject (System.String value, System.Type type, Newtonsoft.Json.JsonSerializerSettings settings) [0x00000] in <filename unknown>:0 at Newtonsoft.Json.JsonConvert.DeserializeObject[BibleGatewayVerses] (System.String value, Newtonsoft.Json.JsonSerializerSettings settings) [0x00000] in <filename unknown>:0 at Newtonsoft.Json.JsonConvert.DeserializeObject[BibleGatewayVerses] (System.String value) [0x00000] in <filename unknown>:0 at Verses.Core.BibleGateway+Response.GetVerseText (System.String requestUrl) [0x00047] in /Users/pierceboggan/Desktop/Verses/Verses.Core/Verses.Core/Web Services/BibleGateway.cs:111 at Verses.Core.BibleGateway.GetVerseText (System.String searchKeywords) [0x00012] in /Users/pierceboggan/Desktop/Verses/Verses.Core/Verses.Core/Web Services/BibleGateway.cs:43 Model Class: [JsonObject(MemberSerialization.OptIn)] public class BibleGatewayVerse { [JsonProperty("osis")] public string Reference { get; set; } [JsonProperty("content")] public string Content { get; set; } [JsonProperty("footnotes")] public List<string> Footnotes { get; set; } [JsonProperty("crossrefs")] public List<string> CrossReferences { get; set; } } [JsonObject(MemberSerialization.OptIn)] public class BibleGatewayVerses { [JsonProperty("data")] public List<BibleGatewayVerse> Verses; } I've used tools such as json2csharp.com and they generate the same thing. I've also toyed around with using arrays instead of List, but to no avail. Additionally, I've also tried replacing the Footnotes List with the type object (as recommended by json2sharp). Any help would be greatly appreciated. A: Your Json data is wrapped in an array, so you need to deserialize to an array of your type JsonConvert.DeserializeObject<BibleGatewayVerses[]>(jsonData); Hope this helps
{ "pile_set_name": "StackExchange" }
Q: exclude multiple files with one sentence in grunt I wanna exclude multiple files with specific file name in grunt copy task, and the config now is this: src: [ '**', '!**/{master, client, socket}.*', '!**/*.map' ] but it only excludes file named with "master". It there a way to exclude all of this files in one declaration? Or can I use regular expression here? A: Remove the space character inside the expression. This will work src: [ '**', '!**/{master,client,socket}.*', '!**/*.map' ]
{ "pile_set_name": "StackExchange" }
Q: ImportError: DLL load failed: %1 is not a valid Win32 application in importing tkinter- python3.4.1 I have windows 7 64 bit and I am using python 3.4.1 for 64bit but still I am getting import error. I have searched and found tkinter folder in my python34/Lib/ directory but still I cannot get tkinter working. I am a newbie in python so any idea how can i get around with this issue? ImportError DLL load failed importing _tkinter Also this link provides some views on this issue but its related to 32 bit python on 64 bit windows and mine is 64 bit A: I was able to resolve this issue. I re-installed python once but that did not worked but when I again re-installed python on my system and then this issue was resolved but I still could not figure out what was wrong earlier
{ "pile_set_name": "StackExchange" }
Q: Load view from helper Codeigniter? Can i load view from helper in codeigniter? I have been looking for a present, but it seems no one has discussed it. A: Yes, you can. Create your helper, say views_helper.php: if(!function_exists('view_loader')){ function view_loader($view, $vars=array(), $output = false){ $CI = &get_instance(); return $CI->load->view($view, $vars, $output); } } $view is the view file name (as you would normally use), and $vars an array of variables you want to pass (as you would normally do), pass a true as optional third parameter to have it returned (as it would normally happen) as content instead of it just being loaded; Just load your helper (or autoload it): $this->load->helper('views'); $data = array('test' => 'test'); view_loader('myview', $data)
{ "pile_set_name": "StackExchange" }
Q: Scaling navigation height based on page location I am trying to create a navigation that grows when your at the top of the screen, and shrink as you scroll down (popular on many sites. I have an example that I found which is close to what I want http://jsfiddle.net/seancannon/npdqa9ua/ my HTML <div class="container-fluid"> <div class="row"> <div class="col-md-12" data-0="opacity:1;" data-75="opacity:0;"> <nav class="navbar navbar-custom" role="navigation"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <a class="navbar-brand" href="<?php echo home_url(); ?>"></a> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse navbar-right"> <?php /* Primary navigation */ wp_nav_menu( array( 'menu' => 'top_menu', 'depth' => 2, 'container' => false, 'menu_class' => 'nav navbar-nav', //Process nav menu using our custom nav walker 'walker' => new wp_bootstrap_navwalker()) ); ?> </div> </nav> <div class="hr"></div> </div> </div><!-- /row --> </div><!-- /container --> I want it to work with the responsiveness of my Wordpress and Bootstrap 3 default navigation that I am using. Adding a height to my current navigation stops the mobile navigation from opening. I'd prefer there not to be a defined height, my current nag-default height is based on padding above and below the links. A: HTML <body> <nav> <!-- menu elements --> </nav> </body> CSS nav { height: 200px; width: 100%; transition: height .5s; } nav.small { height: 50px; position: fixed; top: 0; } JS var $window = $(window), $menu = $('nav'), windowWidth = $window.width(); $window.on('scroll', function(e) { if (windowWidth < 768) // maybe you calculate the width on `resizing` event return; var y = $window.scrollTop(); if (y > 0 && $menu.hasClass('small')) return; $menu.toggleClass('small', y > 0); }); Just for an idea, hope this help. UPDATE Just you need protect the code from < 768px, you can use modernizr and check if user using mobile, don't run the code. or calculate window width by yourself. (as I added to code)
{ "pile_set_name": "StackExchange" }
Q: Some simple questions about geolocation (GPS) values from Android The long/lat coords format that I seem to get back from Android (Phonegap) are decimal. May I know what are the ranges of both the longitude and latitude values? Also, how can I find distance between 2 points in the decimal format? Thanks! A: Latitude and longitude are specified in millionths of a degree: divide each value by 1000000 (and convert to float or double) to get the true degrees. Similar question: Android GeoPoint with lat/long values
{ "pile_set_name": "StackExchange" }
Q: Probability in a deck of cards to have two jacks in a row In a deck of $36$ cards ($9$ cards per color, $4$ colors) what is the probability to have $2$ jacks (or more) that follow each other? A: There are $36\choose 4$ ways to position the jacks. There are $33\choose 4$ ways to position the jacks without adjacencies (imagine to first lay aside three neutral cards and later insert them after the first three jacks). Therefore the answer is $$1-\frac{33\choose 4}{36\choose 4}=1-\frac{33\cdot 32\cdot 31\cdot 30}{36\cdot 35\cdot 34\cdot 33}=\frac{109}{357}. $$ A: Lets count the possibilities that all jacks are separated. Put the 32 non-jacks into a row. Now there are $\binom{33}{4} = 40920$ possibilities to choose the positions of the jacks. The total number of possibilities is $\binom{36}{4} = 58905$. So the result is $$1 - \frac{40920}{58905} = \frac{109}{357} \approx 30.5\%. $$
{ "pile_set_name": "StackExchange" }
Q: Embedded Browser Downloads on Local Machine but not on Windows Server c# I'm trying to automate some functions on a web page (download an Excel document from QuickBooks online). I've got the script working fabulously on my local development machine (running Windows 8.1), but when I compiled it and ran it on our server (running Windows Server 2012 R2), it runs okay until I need to actually download the file. No prompts pop up, and the Navigating handler just freezes on a URL looking like the following: https://qbo.intuit.com/c1/v82.221.1234567890123/1342890533/reports/execute?rptid=1342890533-PANDL-export-1423773529093 This is the type of URL that gets generated when you click on the "Export to Excel" button. Unfortunately, there isn't an easy URL with a ".xls" at the end, or else I'd handle that in the Navigating event. I'm running Visual Studio 2013, and I'm using the webBrowser control in a Windows Form application as an embedded browser. I'll attach code if you feel it's necessary. My main question is this: Why does it work on my home computer and not on our server? Also, I've made sure that my Internet Explorer > Internet Options match for both my home computer and the server. I've additionally turned off IE Enhanced Protected Mode on the server. Is there another setting somewhere that would prevent the save dialog box (see pic attached) from appearing like it does on a normal home computer running Windows 8.1? Thanks in advance! A: Alright, in case anyone needs this in the future. It ended up being a Group Policy Object that was overriding the Internet Options.
{ "pile_set_name": "StackExchange" }
Q: Browser compatibility/support table for JavaScript methods/properties I found a few days ago a nice site with a big table with all the javascript proprieties/methods and the availability to all major browser. My problem is that I can't find that site any more. Where can I find such a list? UPDATE: Of course I've searched history and google before. Anyway here is the site I was looking for in case someone is interested: https://kangax.github.io/compat-table/es5/ A: My bet would be quirksmode or pointedears.de ? A: sounds like this is what you're looking for (or maybe this or this or this) A: There's loads of these. A couple I found with a 2 second google search: http://caniuse.com/ http://www.quirksmode.org
{ "pile_set_name": "StackExchange" }
Q: Eigenvectors and linear operators (Mistake) I was solving the following problem from Artin and think there might be a mistake Let $T$ be a linear operator on a finite dimensional vector space $V$ such that $T^2$ is the identity operator. Prove that for any $v\in V$, $v-T(v)$ is either $0_V$ or is an eigenvector with eigenvalue $-1$. My attempt: Since $T(v)=\lambda v$. We substitute this in out expression which yields $v-\lambda v$ =0. This implies $v=0$ or $\lambda=1$. Thus is there a mistake in the question asked as we get our eigenvalue 1 and not -1 A: Suppose $v-T(v)$ is not $0_V$. Then $T(v-T(v))=T(v)-T(T(v))=T(v)-v$ (since $T^2$ is the identity operator). In particular, $T(v-T(v))=-(v-T(v))$, which shows that $v-T(v)$ is an eigenvector (since it is non-zero) with eigenvalue $-1$.
{ "pile_set_name": "StackExchange" }
Q: why I received the error "uninitialized constant SecureRandom? I am using Ruby 1.9.3 and using the following puts SecureRandom.uuid but I received the error uninitialized constant SecureRandom How to fix this issue? A: You need to add a require statement in the beginning of the file: require 'securerandom'
{ "pile_set_name": "StackExchange" }
Q: How does one get table name in SoQL? Newbie question. How does one get the table name for your object? Or is there a way to get the list of all the available table names with soql? A: Go to: Setup. On the left, you will have the navigation pane. Go to: Create -> Objects. Select your object and the object name should show up.
{ "pile_set_name": "StackExchange" }
Q: Blind and Marriage The Gemara tells us that a man may not marry a woman without first seeing her because if she turns out to be displeasing to him then he will transgress the mitzvah of "Ve'ahavtah lerei'acha kamocha"(loving one's fellow as himself). The assumption is that this refers to whatever may be seen by him within the bounds of the laws of Tzniyus (loosely translated as "modesty") Since a blind man cannot see, does this not apply and may he therefore get married without "seeing" his prospective bride? Or do we say that a blind man "sees" with his hands and if she would be displeasing to him there would be the problem of Ve'ahavta? If that is the case is there now a heter for him to touch her in order to fulfill the mitzvah of getting married and in order to not transgress the mitzvah of ve'ahavta? A: Certainly the literal sight issue is moot. But we'd apply the same principle, he should not marry someone unless he has good reason to believe it will be a happy marriage. A blind man in fact asked this question of Rabbi Yuval Cherlow of Petach Tikva, explaining that he would normally feel a woman's face to determine if she is attractive. Rabbi Cherlow, in this context, allowed him to briefly feel his date's face, if they are seriously marriage-minded. If you view all touching between genders as absolutely prohibited, this wouldn't fly. (And indeed I think many right-wingers completely dismissed Rabbi Cherlow's ruling.) But if you follow the opinions that the prohibitions there are more nuanced, Rabbi Cherlow's psak makes a lot of sense. (Of course then some wiseguy asked -- I'm blind in one eye; can I touch her with one hand?
{ "pile_set_name": "StackExchange" }
Q: Index or size is negative or greater than allowed amount (non-negative indices) While using Firefox, I keep getting the error described in the subject line for this block of code: for(var i = 0; i < tables.length; i++) { var j = rows.length - 1; while(j--) { if(hideDP && tables[i].innerHTML.indexOf(">D<") != -1) { if(!platTag && !soulSilverTag && pearlTag) { tables[i].deleteRow(j);//ERROR IS ON THIS LINE } } }//end while loop (rows) }//end for loop (tables) I suspect that this error is because I'm somewhat new to making reverse loops, but I specifically made a reverse loop in this instance because it made deleting rows from a table easier. Note also that j is something like 24 and i is 0, so they're non-negative. Could someone shed some light on this for me? EDIT : The full code can be found here. A: Strictly working off of the currently posted code, here are the issues I see: The posted code looks incomplete. Where is rows being initialized? This could cause the stated error. Given while(j--);   The var j = rows.length - 1; line is incorrect. That is, unless you know that the last row will never need deleting. But if that is the case, then comment the code to make it clear. For example, if there were 4 rows, the current code initializes j to 3, but because of the location of the -- operator, the inside of the loop sees: 2, 1, 0.   For the code as shown, use var j = rows.length; or add a comment to show that the logic is deliberate. The 2 if() statements do not depend on j at all! (At least as the code is posted here.) If this is true, then move the conditionals outside of the j loop. Consider posting the full, unedited, code. Or linking to it on a site like Pastebin. Update for full script, now that it's been linked to: Scanning the complete code, it looks like tables[i].deleteRow(j); can be called multiple times for the same row. The easy solution, that should be done anyway, is to add a continue statement after each row delete. For extra credit, reanalyze and simplify the flag and if logic too. :) Update for target page, now that it's been linked to: Examining the target page, the tables being looped by this script contain nested tables. That throws off the row count in this line: var rows = tables[i].getElementsByTagName("tr"); Sometimes making it seem like table[i] has more rows than it really directly owns. Solution, use the built in rows array; so the line becomes: var rows = tables[i].rows; ~~~~ While examining the script relative to the target page, a few other issues seemed apparent: It's not best to loop through all tables. Target just the ones you need. So this: tables = document.getElementsByTagName("table"); Should be changed to: var tables = document.querySelectorAll ("div.KonaBody > table.roundy"); ...which will select just the 4 payload tables, and not their subtables or the other tables scattered about. By fine-tuning the initial table selection, the following, problamatic, test is not needed: if(tables[i].getAttribute("style").indexOf("border: 3px solid") != -1) Missing var in front of the majorSections initialization.
{ "pile_set_name": "StackExchange" }
Q: Web API + Azure App Insights pass the data from ActionFilter to ITelemetryProcessor I'd like to customize my Application Insights logging behavior. So I'd like to set some sort of flag in my ActionFilter and then read that flag in ITelemetryProcessor. public class MyCustomFilterAttribute: ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext filterContext) { //perform some logic and set the flag here } } and then public class TelemetryFilter : ITelemetryProcessor { public void Process(ITelemetry item) { var request = item as RequestTelemetry; //read the flag here and terminate processing } } Is that possible ? Is there some sort of TempData that's shared between those two types ? I'd like to avoid kind of hacks like setting temporary header and so on. Thanks in advance. A: I'm not sure this will be useful. But I hope will be. Using Activity.Current public void Initialize(ITelemetry telemetry) { Activity current = Activity.Current; if (current == null) { current = (Activity)HttpContext.Current?.Items["__AspnetActivity__"]; //put your code here } } Refer this SO
{ "pile_set_name": "StackExchange" }
Q: Duplicate sources.list entry Using Ubuntu 14.04 LTS. sudo apt-get update thats all i ran, and it'd start off real smooth, then it'd get to a part where it gets stuck for like a fair ammount of time after which it'd display this error. W: Duplicate sources.list entry http://archive.ubuntu.com/ubuntu/ trusty/restricted amd64 Packages (/var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_trusty_restricted_binary-amd64_Packages) W: Duplicate sources.list entry http://archive.ubuntu.com/ubuntu/ trusty/restricted i386 Packages (/var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_trusty_restricted_binary-i386_Packages) W: Duplicate sources.list entry http://archive.ubuntu.com/ubuntu/ trusty-updates/restricted amd64 Packages (/var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_trusty-updates_restricted_binary-amd64_Packages) W: Duplicate sources.list entry http://archive.ubuntu.com/ubuntu/ trusty-updates/restricted i386 Packages (/var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_trusty-updates_restricted_binary-i386_Packages) W: Duplicate sources.list entry http://archive.ubuntu.com/ubuntu/ trusty-backports/restricted amd64 Packages (/var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_trusty-backports_restricted_binary-amd64_Packages) W: Duplicate sources.list entry http://archive.ubuntu.com/ubuntu/ trusty-backports/multiverse amd64 Packages (/var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_trusty-backports_multiverse_binary-amd64_Packages) W: Duplicate sources.list entry http://archive.ubuntu.com/ubuntu/ trusty-backports/restricted i386 Packages (/var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_trusty-backports_restricted_binary-i386_Packages) W: Duplicate sources.list entry http://archive.ubuntu.com/ubuntu/ trusty-backports/multiverse i386 Packages (/var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_trusty-backports_multiverse_binary-i386_Packages) W: Duplicate sources.list entry http://archive.ubuntu.com/ubuntu/ trusty-security/restricted amd64 Packages (/var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_trusty-security_restricted_binary-amd64_Packages) W: Duplicate sources.list entry http://archive.ubuntu.com/ubuntu/ trusty-security/restricted i386 Packages (/var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_trusty-security_restricted_binary-i386_Packages) W: You may want to run apt-get update to correct these problems of course the suggestion it suggested isnt going to work, as it's that very command after running which i came across the error. I've tried creating a new sources.list file, and also, in the 'other software' tab in the updater settings, i found two "canonical Partners" and thus i eradicated one of them. Still it wont work. there are a number of lists that the error tells of... I checked one and couldnt make any sense out of it. Also, I installed the 32bit architecture manually so as to be able to use skype A: You state: "Also, I installed the 32bit architecture manually so as to be able to use skype" If you need full compatibility with 32 bit code you should install the i386 version. Regardless you can solve this problem by carefully editing /etc/apt/sources.list sudo gedit /etc/apt/sources.list make sure every repository appears once and only once. or copy the original sources.list file from a live cd/dvd/usb at the same location. Or even better consult this: How to fix Duplicate sources.list entry? A closer look at your warnings make it clear. Look closely at this example and you'll see you have dusplicate sources for differing architectures: W: Duplicate sources.list entry http://archive.ubuntu.com/ubuntu/ trusty-updates/restricted amd64 Packages (/var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_trusty-updates_restricted_binary-amd64_Packages) W: Duplicate sources.list entry http://archive.ubuntu.com/ubuntu/ trusty-updates/restricted i386 Packages (/var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_trusty-updates_restricted_binary-i386_Packages)
{ "pile_set_name": "StackExchange" }
Q: Can Stand-alone deb packages be updated? I've downloaded and installed a deb package of Ubuntu Tweak from its website: http://ubuntu-tweak.com/. Is there a way to watch for updates for the package like packages which are in a repository? A: No, manually installed packages can not be updated automatically. However whenever a package we had installed manually will become available through our software sources we will get an update if the version in the repositories was higher. To obtain similar comfortable updates for any application that did not make its way to the repositories we can watch out for a personal package archive (PPA) that may provide up-to-date versions of an application we need. For ubuntu-tweak the "offcial" PPA repository with build for Ubuntu <= 14.04 can be added by: sudo add-apt-repository ppa:tualatrix/ppa or through the Software Center File > Edit > Software Sources.... We then also have to update our apt cache and can install the application with: sudo apt-get update sudo apt-get install ubuntu-tweak
{ "pile_set_name": "StackExchange" }
Q: structure with pointer through FIFO pipe in C I am trying to setup a FIFO pipe with one server and one client. client.c #include<stdio.h> #include<fcntl.h> #include<stdlib.h> #include<string.h> typedef struct buffer { int pid; char *buffer; } my_buffer; /* void removefifo() { unlink("fifo_server"); unlink("fifo_client"); } */ main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "usa: %s text \n", argv[0]); return EXIT_FAILURE; } FILE *file1; int fifo_server,fifo_client; char *buf_in; buf_in = malloc(20*sizeof(char)); //send PID and content my_buffer * buf_out; buf_out = (my_buffer *)malloc(sizeof(my_buffer)); buf_out->pid = getpid(); buf_out->buffer = (char *) calloc(20,sizeof(char)); strcpy(buf_out->buffer,argv[1]); fifo_server=open("fifo_server",O_RDWR); if(fifo_server < 0) { printf("Error in opening file"); exit(-1); } printf("buffer has PID %d and content %s \n",buf_out->pid,buf_out->buffer); write(fifo_server,buf_out,sizeof(struct buffer)); fifo_client=open("fifo_client",O_RDWR); if(fifo_client < 0) { printf("Error in opening file"); exit(-1); } read(fifo_client,buf_in,10*sizeof(char)); printf("\n * Reply from server: %s * \n",buf_in); close(fifo_server); close(fifo_client); } server.c #include<stdio.h> #include<fcntl.h> #include<stdlib.h> #include<string.h> #define FIFO_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) //0666 typedef struct buffer { int pid; char *buffer; } my_buffer; int main() { int fifo_server,fifo_client; char *buf_out; int i; int file1,file2; my_buffer * buf_in; buf_in = (my_buffer *)malloc(sizeof(my_buffer)); buf_in->buffer = (char *) calloc(20,sizeof(char)); buf_out = malloc(20*sizeof(char)); //create fifo-server with p-flag file1 = mkfifo("fifo_server",FIFO_MODE); if(file1<0) { printf("FIFO_SERVER already exists \n"); } fifo_server = open("fifo_server",O_RDWR); if(fifo_server<1) { printf("Error opening file"); } read(fifo_server,buf_in,sizeof(struct buffer)); //read PID and content if(fifo_server<1) { printf("Error opening file"); } printf("pid %d \n",buf_in->pid); printf("content %s \n",buf_in->buffer); //write strcpy(buf_out,buf_in->buffer); for (i = 0; buf_in->buffer[i] != '\0'; i++) { buf_out[i] = toupper(buf_in->buffer[i]); } //create fifo-client with p-flag file2 = mkfifo("fifo_client",FIFO_MODE); if(file2<0) { printf("FIFO_CLIENT already exists \n"); } fifo_client = open("fifo_client",O_RDWR); write(fifo_client,buf_out,10*sizeof(char)); printf("\n Data sent to client \n"); close(fifo_server); close(fifo_client); } I first start the server, then the client. In particular, when I run the client with ./client "the fox" buffer has PID 14491 and content the fox the server correctly displays the PID but crashes at printing buf_in->buffer. ./server pid 14491 Errore di segmentazione Kindly ask for your advice. A: Your struct buffer contains a pointer among its members. That's fine, but you need to recognize that whatever that points to, if anything, is not part of the struct, and the pointer itself is at best invalid on the other end of the pipe. You have two main alternatives: Give your struct an array member instead of a pointer member: typedef struct buffer { int pid; char buffer[20]; } my_buffer; Be more careful with how you write your data. For example: unsigned buf_size = strlen(buf_out.buffer); write(fifo_client, &buf_out.pid, sizeof(buf_out.pid)); write(fifo_client, &buf_size, sizeof(buf_size)); write(fifo_client, buf_out.buffer, buf_size); Naturally, the latter must be paired with a corresponding read mechanism.
{ "pile_set_name": "StackExchange" }
Q: HBase - rowkey basics NOTE : Its a few hours ago that I have begun HBase and I come from an RDBMS background :P I have a RDBMS-like table CUSTOMERS having the following columns: CUSTOMER_ID STRING CUSTOMER_NAME STRING CUSTOMER_EMAIL STRING CUSTOMER_ADDRESS STRING CUSTOMER_MOBILE STRING I have thought of the following HBase equivalent : table : CUSTOMERS rowkey : CUSTOMER_ID column family : CUSTOMER_INFO columns : NAME EMAIL ADDRESS MOBILE From whatever I have read, a primary key in an RDBMS table is roughly similar to a HBase table's rowkey. Accordingly, I want to keep CUSTOMER_ID as the rowkey. My questions are dumb and straightforward : Irrespective of whether I use a shell command or the HBaseAdmin java class, how do I define the rowkey? I didn't find anything to do it either in the shell or in the HBaseAdmin class(some thing like HBaseAdmin.createSuperKey(...)) Given a HBase table, how to determine the rowkey details i.e which are the values used as rowkey? I understand that rowkey design is a critical thing. Suppose a customer id is receives values like CUST_12345, CUST_34434 and so on, how will HBase use the rowkey to decide in which region do particular rows reside(assuming that region concept is similar to DB horizontal partitioning)? ***Edited to add sample code snippet I'm simply trying to create one row for the customer table using 'put' in the shell. I did this : hbase(main):011:0> put 'CUSTOMERS', 'CUSTID12345', 'CUSTOMER_INFO:NAME','Omkar Joshi' 0 row(s) in 0.1030 seconds hbase(main):012:0> scan 'CUSTOMERS' ROW COLUMN+CELL CUSTID12345 column=CUSTOMER_INFO:NAME, timestamp=1365600052104, value=Omkar Joshi 1 row(s) in 0.0500 seconds hbase(main):013:0> put 'CUSTOMERS', 'CUSTID614', 'CUSTOMER_INFO:NAME','Prachi Shah', 'CUSTOMER_INFO:EMAIL','[email protected]' ERROR: wrong number of arguments (6 for 5) Here is some help for this command: Put a cell 'value' at specified table/row/column and optionally timestamp coordinates. To put a cell value into table 't1' at row 'r1' under column 'c1' marked with the time 'ts1', do: hbase> put 't1', 'r1', 'c1', 'value', ts1 hbase(main):014:0> put 'CUSTOMERS', 'CUSTID12345', 'CUSTOMER_INFO:EMAIL','[email protected]' 0 row(s) in 0.0160 seconds hbase(main):015:0> hbase(main):016:0* scan 'CUSTOMERS' ROW COLUMN+CELL CUSTID12345 column=CUSTOMER_INFO:EMAIL, timestamp=1365600369284, [email protected] CUSTID12345 column=CUSTOMER_INFO:NAME, timestamp=1365600052104, value=Omkar Joshi 1 row(s) in 0.0230 seconds As put takes max. 5 arguments, I was not able to figure out how to insert the entire row in one put command. This is resulting in incremental versions of the same row which isn't required and I'm not sure if CUSTOMER_ID is being used as a rowkey ! Thanks and regards ! A: You don't, the key (and any other column for that matter) is a bytearray you can put whatever you want there- even encapsulate sub-entities Not sure I understand that - each value is stored as key+column family + column qualifier + datetime + value - so the key is there. HBase figures out which region a record will go to as it goes. When regions gets too big it repartitions. Also from time to time when there's too much junk HBase performs compactions to rearrage the files. You can control that when you pre-partition yourself, which is somehting you should definitely think about in the future. However, since it seems you are just starting out with HBase you can start with HBase taking care of that. Once you understand your usage patterns and data better you will probably want to go over that again. You can read/hear a little about HBase schema design here and here
{ "pile_set_name": "StackExchange" }
Q: Dynamically show/hide input with shinyjs and flexdashbord Trying to update Sidebar in flexdashboard when click on a tab. Can't get it to work. --- title: "Test Sidebar" output: flexdashboard::flex_dashboard: orientation: rows runtime: shiny --- ```{r setup} library(flexdashboard) library(shiny) library(shinyjs) useShinyjs(rmd = TRUE) ``` Sidebar {.sidebar data-width=250} ======================================================================= ```{r} div(id = "one", selectInput("input1",label= "Show Always",choices=c("a","b","c"))) div(id = "two",selectInput("input2",label = "Show only on Tab 1", choices=c("d","e","f"))) ``` <!-- Update the sidebar based on the tab chosen. Generated HTML code shown for tabs--> Tab 1 <!-- <a href="#section-tab-1" aria-expanded="true" data-toggle="tab"> --> ======================================================================= ```{r} useShinyjs(rmd = TRUE) shinyjs::onclick("#section-tab-2",shinyjs::hide(id = "two")) shinyjs::onclick("#section-tab-1",shinyjs::show(id = "two")) ``` Tab 2 <!-- <a href="#section-tab-2" aria-expanded="true" data-toggle="tab"> --> ======================================================================= ```{r} useShinyjs(rmd = TRUE) actionButton("hideSlider", "Hide Input Two") observeEvent(input$hideSlider, { shinyjs::toggle(id = "two", anim = TRUE) }) ``` Works okay with actionButton() and observerEvent(). Any suggestions appreciated. A: A few comments: You only need to call useShinyjs() once, no need to call it in every code chunk onclick() takes the ID of the element. Not the selector - the ID. This means that you call onclick("element") rather than onclick("#element") If you look at the HTML that gets generated by the dashboard, you'll see that there is no element with id "section-tab-2", so what you're trying to do won't work In regular shiny apps, when I use a tabsetPanel(), the way I do what you're trying to do is by using the value of the selected tab. Whenever a tab is selected, there's an input value that gives you the value of what is selected. I haven't used flexdashboard extensively so I'm not sure if there's a similar way to get the value of the selected tab in a flexdashboard.
{ "pile_set_name": "StackExchange" }
Q: IntelliJ: debugging Web App which is using embedded server It is very easy to debug Web applications using common application servers (Tomcat, Jetty, GlassFish, Google App Engine ...) in IntelliJ Ultimate as Run/Debug configurations are provided for them. What I find difficult and inconvenient is debugging an application which is using embedded server. I can found a configuration for debugging either the server (it is debugged as an ordinary JVM application) or the client (as JavaScript Debug), but I did not find anything which would both run the application and open a debuggable browser. An example of the project I would like to debug is Akka HTTP with Scala.js. How can I do this? A: I have posted the same question to the support and their answer was this is currently not possible. I have created a feature request at the IDEA issue tracker.
{ "pile_set_name": "StackExchange" }
Q: How to Download Files From 115.com? I am trying to download a file from 115.com , I have created a login credentials on their webites , but still I am not able to download file from that website. The project I am downloading is mentioned in this link : http://115.com/file/e74944rn#cocos2dSpaceGameDemo.zip I googgled alot, go through certain blogs but still not able to download that file. Please suggest an approach to download this file. Regards, Pardeep sharma A: Here's a quick step-by-step guide: (Got it from here: http://hostmypicture.com/images/115downloa.png.) A: click 存至网盘 (1st button) to copy the file to your own 115.com account. click top left 网盘 logo to return to homepage. download accordingly for free from your file directory. the 离线下载 (orange button) allows for direct downloading but is a paid vip service.
{ "pile_set_name": "StackExchange" }
Q: How does the Majority Judgment voting system fare? Following this question on the Gibbard-Satterthwaite (GB) theorem, I was wondering how the Majority Judgment (MJ) voting system fits in. Quick summary of how the MJ works: you attribute each candidate with a mention. The candidate with the highest median mention wins. The GB theorem states that, for three or more candidates: The rule is dictatorial There is some candidate who can never win, under the rule, or The rule is susceptible to tactical voting. The MJ, according to its creators, does not follow this theorem. The first two points are obvious, and for the third, they claim it is system affected the least by strategical voting. What does the Gibbard-Satterthwaite theorem mean applied to the Majority Judgment voting system? A: The correct answer is: assertion 3. In all my answer, I will assume that there are 3 voters or more. (With 1 voter, the system is obviously dictatorial. And with 2 voters, the answer to your question depends on the exact tie-breaking rule that is used.) Remark that a subset consisting of more than half the voters can always choose the winning candidate by giving her the best grade and attributing the worst grade to all the other candidates. This precludes the existence of a dictatorial voter, so assertion 1 is false. This proves that any candidate can be elected, so assertion 2 is false. Hence (still with the assumption of having 3 voters or more), Gibbard's theorem implies that as soon as there are 3 candidates or more, MJ is susceptible to tactical voting. But there is worse. For example, consider the following situation. I use grades for clarity, but the example can be immediately translated with appreciations instead. Voter 1: A 10, B 0. Voter 2: B 7, A 0. Voter 3: B 9, A 8. Candidate A's median: 8. Candidate B's median: 7. So, A wins. But voter 3 can manipulate toward the following situation. Voter 1: A 10, B 0. Voter 2: B 7, A 0. Voter 3: B 9, A 0. Candidate A's median: 0. Candidate B's median: 7. So candidate B wins. Conclusion: MJ is manipulable even when there are only 2 candidates! I never understood why Balinski and Laraki base a large part of their argumentation in favor of MJ on the issue of manipulability. Although MJ does have some interesting features, immunity to manipulation is certainly not one of them.
{ "pile_set_name": "StackExchange" }
Q: Microsoft Education - School Data Sync (SDS) to Microsoft Graph Mapping We are working with schools who use Microsoft Education and School Data Sync (SDS) to load their teachers, students and groups. In SDS there are some properties such as Grade, GraduationYear etc. and we´ve been trying to figure out if these are accessible via the Microsoft Graph API. With a bit of experimentation and via this article, we can see on Groups and Users certain properties we can get prefixed with extension_fe2174665583431c953114ff7268b7b3_Education_. fe2174665583431c953114ff7268b7b3 seems to be the app id for SDS. We were wondering if this is a sensible route to get at these properties from SDS or if there is a better route for getting these? We can, for example, see the term information available in classes but we don´t see the subject information there. For groups: Groups: https://graph.microsoft.com/v1.0/groups/{Id}?$select=extension_fe2174665583431c953114ff7268b7b3_Education_{Name} Note: Groups in SDS are called sections Status (e.g.extension_fe2174665583431c953114ff7268b7b3_Education_Status) Period - This seems to be called periods in the import files CourseSubject - e.g. History CourseDescription - e.g. History of the World CourseName CourseNumber TermEndDate TermStartDate TermName SyncSource_CourseId SyncSource_TermId SectionName - this is the name that comes from the SDS file Users: https://graph.microsoft.com/v1.0/users/{Id}?select=$extension_fe2174665583431c953114ff7268b7b3_Education_{Name} Grade GraduationYear SyncSource_StudentId ObjectType - Shows if this a teacher or a student DateOfBirth A: The only supported route to access this information is through the Education Graph APIs documented here. Right now that is a subset of the properties imported by School Data Sync. The underlying extension properties should be considered a point-in-time implementation detail and not relied upon in production apps. Current plan as of Feb 2019 is to add the course information to the educationClass object in the next couple of months. That just leaves a few properties different across the education entities which we don't have a concrete plan for yet.
{ "pile_set_name": "StackExchange" }
Q: How to keep last selected cell in ListView selected after clicking a button in JavaFX? I have a JavaFX that displays 2 separate ListViews like so: There are 2 buttons to move the selected cell into the right list. Right now if I select a cell, say "Amazon Web Services" on the right and then press the "<< Keep List" button, then it will move it to the left. However, if I want to now move the 2nd item which is "Rita M. Powell" also to the Keep List, I have to then select that cell and press the Keep List button again. What I would like to do is to keep the top row of that ListView selected even after pressing the buttons so that I don't have to come back and select the top cell again. At the moment how I'm doing this is in my controller is keeping an instance variable private ListServer selected; and assigning that variable whenever I click on a cell: deleteListView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { selected = newValue; }); keepListView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { selected = newValue; }); Then the 2 buttons are handling the moving of these cells by changing the properties attached to them: @FXML public void moveKeep() { if (selected != null) { selected.setKeep(true); wrapKeepList(); } } @FXML public void moveDelete() { if (selected != null) { selected.setKeep(false); wrapDeleteList(); } } The rest of the controller code: public class ListServerOverviewController { @FXML private JFXListView<ListServer> deleteListView; @FXML private JFXListView<ListServer> keepListView; @FXML private JFXButton scanButton; @FXML private JFXButton pauseButton; @FXML private JFXButton moveDeleteButton; @FXML private JFXButton moveKeepbutton; private BooleanProperty isScanning = new SimpleBooleanProperty(false); private MainApp mainApp; private FilteredList<ListServer> keepList; private FilteredList<ListServer> deleteList; private AtomicBoolean paused = new AtomicBoolean(false); private Thread thread; private ListServer selected; public ListServerOverviewController() { } @FXML public void initialize() { scanButton.setContentDisplay(ContentDisplay.RIGHT); } public void setMainApp(MainApp mainApp) { this.mainApp = mainApp; wrapDeleteList(); wrapKeepList(); scanButton.visibleProperty().bind(isScanning.not()); pauseButton.visibleProperty().bind(isScanning); deleteListView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { selected = newValue; }); keepListView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { selected = newValue; }); } private void wrapKeepList() { keepList = new FilteredList<>(mainApp.getListServerList(), p -> p.getKeep()); if (!keepList.isEmpty()) { keepListView.setItems(keepList); keepListView.setCellFactory(param -> new ListCell<ListServer>() { @Override protected void updateItem(ListServer item, boolean empty) { super.updateItem(item, empty); if (empty || item == null) { setText(null); } else { setText(item.getName()); } } }); } } private void wrapDeleteList() { deleteList = new FilteredList<>(mainApp.getListServerList(), p -> !p.getKeep()); if (!deleteList.isEmpty()) { deleteListView.setItems(deleteList); deleteListView.setCellFactory(param -> new ListCell<ListServer>() { @Override protected void updateItem(ListServer item, boolean empty) { super.updateItem(item, empty); if (empty || item == null) { setText(null); } else { setText(item.getName()); } } }); } } @FXML public void moveKeep() { if (selected != null) { selected.setKeep(true); wrapKeepList(); } } @FXML public void moveDelete() { if (selected != null) { selected.setKeep(false); wrapDeleteList(); } } @FXML public void handleScanInbox() { isScanning.set(true); if (thread == null) { thread = new Thread() { public void run() { mainApp.handleScanInbox(paused); } }; thread.setDaemon(true); thread.start(); } else { synchronized (paused) { if (paused.get()) { paused.set(false); paused.notify(); } } } } @FXML public void handlePauseScanInbox() { paused.compareAndSet(false, true); isScanning.set(false); } } A: Using a listener to put the selected value in a field is not a good idea. Both listeners use the same field, so the last selection change determines the item to move, not the last change for a ListView. Furthermore the cost of retrieving the value is minimal and could easily be done in a event handler using the value. Furthermore there shouldn't be a need to update the lists every time you change the keep property. Use the selection model to select the transferred item after moving it between the lists: public static class Item { private final String text; private final BooleanProperty keep = new SimpleBooleanProperty(); public Item(String text) { this.text = text; } @Override public String toString() { return text; } public BooleanProperty keepProperty() { return keep; } public boolean isKeep() { return keep.get(); } public void setKeep(boolean value) { keep.set(value); } } private static void move(ListView<Item> source, ListView<Item> target) { Item item = source.getSelectionModel().getSelectedItem(); if (item != null) { item.setKeep(!item.isKeep()); target.getSelectionModel().clearSelection(); target.getSelectionModel().select(item); } } @Override public void start(Stage primaryStage) { ObservableList<Item> data = FXCollections.observableArrayList(new Callback<Item, Observable[]>() { @Override public Observable[] call(Item param) { return new Observable[] { param.keepProperty() }; } }); FilteredList<Item> keep = data.filtered(item -> item.isKeep()); FilteredList<Item> remove = data.filtered(item -> !item.isKeep()); ListView<Item> leftList = new ListView<>(keep); ListView<Item> rightList = new ListView<>(remove); Button moveLeft = new Button("<<"); moveLeft.setOnAction(evt -> move(rightList, leftList)); Button moveRight = new Button(">>"); moveRight.setOnAction(evt -> move(leftList, rightList)); for (int i = 0; i < 40; i++) { data.add(new Item(Integer.toString(i))); } Scene scene = new Scene(new HBox(10, leftList, moveLeft, moveRight, rightList)); primaryStage.setScene(scene); primaryStage.show(); } If there may be different items Item that could yield true when compared using equals, you should use TransformationList's methods to find the index to select and do the selection by index instead: private static void move(ListView<Item> source, ListView<Item> target) { FilteredList<Item> sourceList = (FilteredList<Item>) source.getItems(); FilteredList<Item> targetList = (FilteredList<Item>) target.getItems(); Item item = source.getSelectionModel().getSelectedItem(); if (item != null) { int index = sourceList.getSourceIndex(source.getSelectionModel().getSelectedIndex()); item.setKeep(!item.isKeep()); index = targetList.getViewIndex(index); target.getSelectionModel().clearAndSelect(index); } }
{ "pile_set_name": "StackExchange" }