text
stringlengths
64
81.1k
meta
dict
Q: Are the Yang-Mills equation and its generalization gauge invariant? I have derived the Yang-Mills equation and its generalization coupled to a current of a scalar field $\phi$ by extremalizing the action describing a $\mathrm{SU}(2)$ scalar field gauge theory: $$\partial_\mu F^{\mu\nu} +ig\left[ A_{\mu},F^{\mu\nu}\right] = j^\nu$$ where, $\phi$ is a two components scalar field, $$j^\nu = -ig\left[ (D_\nu \phi)^\star T^a\phi -\phi^\star T^a(D_\nu \phi)\right]T^a$$ where $D_\nu = \partial_\nu + ig A_\nu$. But when I take a gauge transformation: $$\phi' = e^{-i\omega_a T_a}\phi = U\phi, \quad A'_\mu = UA_\mu U^{-1} -\frac{i}{g}U\partial_\mu U^{-1}$$ I find I can not take same formalism from $j'^{\nu}$ as the original $j^{\nu}$. I think there must be something wrong with my calculation, because the current should be gauge invariant. My question is therefore whether the Yang-Mills equation and its generalization is gauge invariant and how one would show this invariance. More about my calculation, please comment @ACuriousMind, Thanks you help and analysis.Now I will write down more of my calculation: When I calculate the $j^{\nu}$', I find that the term : $${\phi}^{*\alpha}{\partial _{\upsilon}\phi}^{\alpha }$$ always contains the quality: $${ U }^{ -1 }{ T }^{ a }U$$ as $${\phi}^{*\alpha}{\partial _{\upsilon}\phi}^{\alpha }{ U }^{ -1 }{ T }^{ a }U$$ the ${ U }^{ -1 }{ T }^{ a }U$can not be cancelled by the commutator calculation. Base on your above answer, can I think this phenomena is correct? I'm never work for QFT, and I learning the classical gauge field theory by my-self, please point out my mistake,Please, theanks. A: No, the gauge current need not be gauge invariant, since it carries a group index in non-abelian theories. You should recall that both sides of the Yang-Mills equation (and therefore the current itself) are Lie-algebra valued and therefore transform in the adjoint representation. Not even the field strength $F^a_{\mu\nu}$ is gauge invariant, but transforms in the adjoint representation of the gauge group, which is why your action should (hopefully) contain only its trace as $\mathrm{Tr}(F_{\mu\nu}F^{\mu\nu})$. It is to be noted that, since the current is not invariant, it is not observable.
{ "pile_set_name": "StackExchange" }
Q: Are batchlets the correct way of implementing ETL steps in JavaEE Batch? I am studying Javaee Batch API (jsr-352) in order to test the feasibility of changing out current ETL tool for our own solution using this technology. My goal is to build a job in which I: get some (dummy) data from a datasource in step1, some other data from other data-source in step2 and merge them in step3. I would like to process each item and not write to a file, but send it to the next step. And also store the information for further use. I could do that using batchlets and jobContext.setTransientUserData(). I think I am not getting the concepts right: as far as I understood, JSR-352 is meant for this kind of ETL tasks, but it has 2 types of steps: chunk and batchlets. Chunks are "3-phase-steps", in which one reads, processes and writes the data. Batchlets are tasks that are not performed on each item on the data, but once (as calculating totals, sending email and others). My problem is that my solution is not correct if I consider the definition of batchlets. How could one implement this kinf od job using Javaee Batch API? A: I think you better to use chunk rather than batchlet to implement ETLs. typical chunk processing with a datasource is something like following: ItemReader#open(): open a cursor (create Connection, Statement and ResultSet) and save them as instance variables of ItemReader. ItemReader#readItem(): create and return a object that contains data of a row using ResultSet ItemReader#close(): close JDBC resources ItemProcessor#processItem(): do calculation and create and return a object which contains result ItemWriter#writeItems(): save calculated data to database. open Connection, Statement and invoke executeUpdate() and close them. As to your situation, I think you have to choose one data which considerble as primary one, and open a cursor for it in ItemReader#open(). then get another one in ItemProcessor#processItem() for each item. Also I recommend you to read useful examples of chunk processing: http://www.radcortez.com/java-ee-7-batch-processing-and-world-of-warcraft-part-1/ http://www.radcortez.com/java-ee-7-batch-processing-and-world-of-warcraft-part-2/ My blog entries about JBatch and chunk processing: http://www.nailedtothex.org/roller/kyle/category/JBatch
{ "pile_set_name": "StackExchange" }
Q: Ctrl-Alt-T stopped working after installing GNOME Shell on Ubuntu 18.04 After I installed GNOME Shell, CTRL + ALT + T combination stopped working. How could I fix it? A: Go to Settings -> Devices -> Keyboard, then add Ctrl + Alt + T if it does not exist.
{ "pile_set_name": "StackExchange" }
Q: Retrofitting an old XHTML site for mobile? I have an old site that needs a quick mobile upgrade. I've researched this and found many great answers about how to do this when starting a new project. I was curious to see if anybody had any experience doing this and if so what methods are best for this kind of job? I tried Modernizer and can't get it to return true on any media queries (Modernizer.mq) Here is the code i tried: Modernizr.load([ { test : Modernizr.mq('screen and max-device-width: 480px'), yep : 'css/mobile.css', nope : 'css/styles.css' ]); A: The valid media query is only screen and (max-device-width: 480px). The only is used for a bug I cannot recall now, but it doesn't break anything in another browser, so that's okay. You have to wrap the max-width specification between brackets. However, you shouldn't rely on Javascript to load your css files. You can include them with <link rel="stylesheet" type="text/css" href="mobile.css" media="only screen and (max-device-width: 480px)" <link rel="stylesheet" type="text/css" href="screen.css" media="only screen and (min-device-width: 481px)" You might need a fallback for non-media-query supporting browsers.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to cut out a triangle section from a div using CSS? Is it possible to cut a triangle from a <div> like in the picture below? The background is actually not just colour, but in my case is a blurred picture, so I can’t simply cover the green <div> with a brown triangle image. Is there some other CSS way to achieve this effect? Thanks. A: The illusion of it is possible: http://jsfiddle.net/2hCrw/4/ Tested with: IE 9, 10, Firefox, Chrome, Safari on PC and iPad. ::before and ::after pseudo elements are skewed to provide a side of the triangle each. Wrapper used for clipping skewed pseudo elements. You may be able to avoid this by using your outer container as the wrapper. Elements can still be styled with borders, shadows, etc. Anything underneath will show through properly. Demo with borders and drop shadow: http://jsfiddle.net/2hCrw/8/ This demo also adds a tweak for iPad with Retina to prevent a gap between the element and the pseudo elements (either caused by drop shadow bleed or sub-pixel rendering behavior). <div id="wrapper"> <div id="test">test</div> </div> #wrapper { overflow: hidden; height: 116px; } #test { height: 100px; background-color: #ccc; position: relative; } #test::before { content:""; position: absolute; left: -8px; width: 50%; height: 16px; top: 100px; background-color: #ccc; -webkit-transform: skew(-40deg); -moz-transform: skew(-40deg); -o-transform: skew(-40deg); -ms-transform: skew(-40deg); transform: skew(-40deg); } #test::after { content:""; position: absolute; right: -8px; width: 50%; height: 16px; top: 100px; background-color: #ccc; -webkit-transform: skew(40deg); -moz-transform: skew(40deg); -o-transform: skew(40deg); -ms-transform: skew(40deg); transform: skew(40deg); } As an alternative, you can use a transparent image and "extend" the element above it with pseudo elements. I have answered a similar question regarding a circle cut from an element and show support options down to IE7 (as well as future options for true clipping/masking in CSS). A: You can do something like this with CSS masks (examples): http://codepen.io/anon/pen/vgbEH (anti-triangle mask) http://codepen.io/anon/pen/pEufn (triangle mask) I used clip-path: polygon(…) property but only my Chrome seems to support it; you could instead create polygon images and reference them with mask-image for broader support.
{ "pile_set_name": "StackExchange" }
Q: Power 12v Pump with two PSUs that may or may not both be on Not an electrical engineer at all, however i will be in need of something like this. I have two systems that will share a liquid cooling system. They both run off of their own respective PSU's. I want the pump to run while they are both on or while only one of them is powered on. As far as I can tell all I would need to do is run the PSU's in parallel with diodes to prevent feedback. Would this work for this? A: You only need two diodes. You can get dual diodes in a single package, and perhaps consider getting Schottky diodes with very low forward voltage drop. Depending on the current drawn by the pump perhaps something like the MBR4060 dual diode in a TO220 style case. simulate this circuit – Schematic created using CircuitLab
{ "pile_set_name": "StackExchange" }
Q: checking equality of string containing characters such as "-","+","/" fails I'm trying to check console output by redirecting the standard output to a ByteArrayOutputStream object. I found this little code snipped that lets me do just that. However, usage of characters such as "-","+" etc. fail the tests. I was wondering why: Here's the jUnit Test: import static org.junit.Assert.*; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import org.junit.After; import org.junit.Before; import org.junit.Test; //This test is try and test output against the console output, //but the inclusion of characters '-', '*', '+', and '/' makes //it especially hard to implement correctly. So abandoning public class ApplicationTest { private final ByteArrayOutputStream outContent=new ByteArrayOutputStream(); @Before public void setUpStreams(){ System.setOut(new PrintStream(outContent)); } @After public void cleanUpStream(){ System.setOut(null); } @Test public void test_Test1() { //Lexer lex=new Lexer("a+b*c"); //System.out.print("a b c * + "); System.out.format("%s ", "a"); System.out.format("%s ", "- "); String str="a - "; //Test Fails. assertEquals(outContent.toString(),str); } } A: You have an extra space in the output. System.out.format("%s ", "a"); System.out.format("%s ", "- "); // ^ String str="a - ";
{ "pile_set_name": "StackExchange" }
Q: How can I get row's index from a table in SQL Server? I have a Toplist table and I want to get a user's rank. How can I get the row's index? Unfortunately, I am getting all rows and checking in a for loop the user's ID, which has a significant impact on the performance of my application. How could this performance impact be avoided? A: You can use ROW.NUMBER This is a example syntax for MySQL SELECT t1.toplistId, @RankRow := @RankRow+ 1 AS Rank FROM toplist t1 JOIN (SELECT @RankRow := 0) r; This is a example syntax for MsSQL SELECT ROW_NUMBER() OVER(ORDER BY YourColumn) AS Rank,TopListId FROM TopList A: ROW_NUMBER() MS SQL Use in your code analytic functions
{ "pile_set_name": "StackExchange" }
Q: If and definedness of ENV variables I'm a little perplexed (note this is not about the use of $ with ENV and if). cmake_minimum_required(VERSION 3.14) set(CMAKE_CONFIGURATION_TYPES Debug) message("-->$ENV{foobar}<--") if (DEFINED ENV{foobar}) message("$foobar is defined") else() message("$foobar is not defined") endif() Run via bash and cmake -DCMAKE_BUILD_TYPE=Debug with no $foobar set, predictably the relevant output is: --><-- $foobar is not defined And subsequent to export foobar=1: -->1<-- $foobar is defined But now: > export foobar= I realize this does leave the variable in the environment (vs. totally removing it with, eg., the bash built-in unset), but it is with a value that would be conventionally considered by many or most users as "undefined". Unfortunately, cmake doesn't see it that way, however: > export foobar= > cmake -DCMAKE_BUILD_TYPE=Debug --><-- $foobar is defined While I can remember this, there is no way I am going to presume normal users building my project are. So that means no more if (DEFINED ENV{foobar}). Fortunately there are simple work-arounds to this, such as testing via a proxy variable: set(Foobar $ENV{foobar}) message("==>${Foobar}<==") if (DEFINED Foobar) message("Internal Foobar defined") else() message("Internal foobar is not defined") endif() The output is now --><-- $foobar is defined ==><== Internal foobar is not defined To be fair to cmake, this is not inconsistent -- the internal foobar would be defined as an empty string too if $ENV{foobar} were quoted in the assignment. My question is just to verify that I have not missed something. A: When you do the following: > export foobar= CMake's ENV recognizes foobar as defined, but it is simply defined as an empty string. Thus, you can expand your if-statement to include an empty string check using STREQUAL: if (DEFINED ENV{foobar} AND NOT "$ENV{foobar}" STREQUAL "") message("$foobar is set") else() message("$foobar is not set") endif()
{ "pile_set_name": "StackExchange" }
Q: Circularity in identity definition It is written in the SEP: Identity is often said to be a relation each thing bears to itself and to no other thing (e.g., Zalabardo 2000). This characterization is clearly circular (“no other thing”)'. The question is: what is circular here? Deutsch, Harry and Garbacz, Pawel, "Relative Identity", The Stanford Encyclopedia of Philosophy (Fall 2018 Edition), Edward N. Zalta (ed.), URL = https://plato.stanford.edu/archives/fall2018/entries/identity-relative/. A: It's circular because "no other thing" just means "no non-identical thing" which uses the identity relation that is to be defined. Another way to define the identity relation is to say that it's the smallest equivalence relation (e.g., in the SEP entry on identity). That's also considered circular because it refers to all equivalence relations, including identity itself. (Definitions of this kind are called impredicative). Whether or not this kind of circularity is bad is another matter. You can read about it in the IEP entry on predicative and impredicative definitions.
{ "pile_set_name": "StackExchange" }
Q: How to rename files in a folder with ".csv" at the end??[R] setwd("C:\\Users\\Note\\Documents\\Folder") n <- dir(pattern = ".csv") names<-as.character(c(1:length(n))) file.rename(n,names) I am trying to rename several worksheets to an id 1,2,3,4,5,6 etc But when I do this the worksheets are no longer ".csv" files. How to add ".csv" to the rename function? Is there any way to make "n" stay in sequence 1,2,3,4,5,6, so that if I add a new spreadsheet it will be the last one in "n"? n = https://imgur.com/Z1KVqh2 A: Try this instead of your third line names <- paste0(1:length(n), ".csv") The numbers will be automatically coerced to character format.
{ "pile_set_name": "StackExchange" }
Q: SQL Find and Insert I have name of client and name of doctor. I want to get there ID from DB and insert IDs into table. CREATE PROCEDURE AddMedicalCard @Client nchar, @Doctor nchar AS BEGIN SELECT Clients.[ClientCode] AS [Code] Into #NewClientCode FROM Clients WHERE Clients.[ClientName]=@Client SELECT Personal.[DoctorCode] AS [Code] Into #NewDoctorCode FROM Personal WHERE Personal.[DoctorName]=@Doctor INSERT INTO MedicalCard VALUES (#NewClientCode.[Code].First, #NewDoctorCode.[Code].First) DROP TABLE #NewClientCode DROP TABLE #NewDoctorCode END GO Errors: The multi-part identifier "#NewDoctorCode.Code.First" could not be bound. The multi-part identifier "#NewClientCode.Code.First" could not be bound. Column name or number of supplied values does not match table definition. MedicalCard table design: RecordingCode(Key), ClientCode, DoctorCode and 5 other nullable columns. A: Error message says it all. There is no such thing as #NewDoctorCode.Code.First. Your job can be easily & cleanly done as follows. Note: It is not very correct to get clientcode and doctorcode by their names as there could be more than 1 client & doctors with the same name. --declare two variables declare @clientCode varchar(50), @doctorCode varchar(50) --assign clientCode SELECT TOP 1 @clientCode = Clients.[ClientCode] FROM Clients WHERE Clients.[ClientName]=@Client --assign doctorCode SELECT TOP 1 @doctorCode = Personal.[DoctorCode] FROM Personal WHERE Personal.[DoctorName]=@Doctor --finally insert them to MedicalCard table INSERT INTO MedicalCard (clientCodeColumn,doctorCodeColumn) --Column Names VALUES (@clientCode,@doctorCode)
{ "pile_set_name": "StackExchange" }
Q: Why do we take $x=\cos t$, $y=\sin t$ for a parametric circle when we can take the opposite? Both $x = \cos t$, $y = \sin t$ and $x = \sin t$, $y = \cos t$ describe a circle So why is the first parameterization so commonly used in mathematics, and not the second? A: Because we usually start the circle at the right. There, the coordinates are $(1, 0)$, which is $(\cos(0), \sin(0))$. If we started it at the top, we would probably use $(\sin(t), \cos(t))$. A: Because $e^{it} = \cos t+i\sin t$ (but not only because of that). A: Because of convension. It is customary to view angles as lying with the vertex at the origin and the right leg along the positive $x$-axis. That means that small angles will have their left leg in the first quadrant, and right angles will have the left leg along the positive $y$-axis. Because of this, the cosine of the angle happens to be the $x$-coordinate of the point on the left leg that is distance $1$ from the vertex, while the sine of the angle is the $y$-coordinate.
{ "pile_set_name": "StackExchange" }
Q: How to freeze browser window intentionally (like alert, confirm and prompt does)? Is there any way of freezing the browser window intentionally like alert, confirm and prompt (in short: "acp") does? I want to show a modal dialog with custom css instead of the native popups for "acp" but also want to have the ability to freeze the browser until I have users feedback just like "acp". But man, why? This is bad practice (uh I have to downvote)! So when it is bad practice - then why does "acp" actually offer this synchronous behavior? Because in some particular scenarios its just exactly the right tool for an appropriate UX. Those native modals do look so ugly and are also very limited at the same time. Here's just one quick and dirty example where it would be totally fine to freeze the browser until the user gives feedback. Lets say we have a form with an input type="reset"-element. So before we really let the form reset we ask the user something like: "Are you sure you want to reset (data will be lost)?". If I would be fine with the native modal look (which I'm not) I could do: var handleSubmit = function( e ) { confirm('Are you sure you want to reset (data will be lost)?') || e.preventDefault() }; $('form').on( 'reset', handleSubmit ); // just using jQuery here for the sake of shortness <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <input placeholder="type something, reset and cancel to keep input value" style="width:100%"> <input type="reset"> </form> So "everybody" should agree (edit: or at least somebody could) this isn't bad practice, right? But how can we achieve the same with a custom styled modal/dialog/popup? I'm -of course- not asking for the HTML/CSS part but for the capability of freezing the browser window via JavaScript! To be honest, I actually expect some downvotes for this but maybe there is this one Killer JavaScript Ninja, who have this one special hack to make it possible... NOTE: I know exactly how to achieve the same result in the end but I'm looking for an actual freeze/synconous feature to keep the code straight forward and less hack-ish. A: You can place everything within a div except for your popup. You can then turn on/off pointer events via css. Everything within the div will no longer be interactable. This will give the appearance of freezing the browser window. .freeze { pointer-events: none; } Note: When adding pointer-events to an element this affects all child elements as well, so placing it on the body would also lock the popup. Once the popup has been closed, we can remove the freeze class from the div and everything will start working again. const content = document.getElementById('content') const overlay = document.querySelector('.overlay') const a = document.querySelector('.open-overlay') const close = document.querySelector('.overlay .close') // Open a popup and freeze the browser content a.addEventListener('click', e => { e.preventDefault() content.classList.add('freeze') overlay.classList.remove('hidden') }) // Close the popup window and unfreeze the browser content close.addEventListener('click', e => { e.preventDefault() content.classList.remove('freeze') overlay.classList.add('hidden') }) .freeze { pointer-events: none; } .hidden { display: none; } .overlay { position: fixed; z-index: 100; padding: 20px; background: white; border: solid 1px #ccc; width: 300px; top: 20px; left: 0; right: 0; margin: auto; } <div class="overlay hidden"> <h1>Overlay</h1> <a href="" class="close">Close</a> </div> <div id="content"> <a href="" class="open-overlay">Open Overlay</a> <p>Hello World</p> <p>Hello World</p> <p>Hello World</p> <p>Hello World</p> <p>Hello World</p> <form> <input type="text"> </form> </div>
{ "pile_set_name": "StackExchange" }
Q: What does the flashing red alert mean? Sometimes during gameplay a red light flashes with an alarm. I can't tell what triggers it, and what makes it go away. So what does the flashing red alert mean? A: A flashing red alert means that your air ventilation is off and needs to be started in order to get the air back to normal. This is an indicator to let you know that if you do not fix the air ventilation you will start to see more hallucinations.
{ "pile_set_name": "StackExchange" }
Q: Difference between extraterrestrial and alien? What is the difference between extraterrestrial and alien in terms of the usage of these two words? A: Extraterrestrial very specifically refers to something which is not from planet Earth. Alien is a more general word which can be used in many contexts.
{ "pile_set_name": "StackExchange" }
Q: What counts as activity on SE sites for consecutive visits? As per Jeff's reply here: login pages, along with a number of other homepage style pages, don't count as "access" So, what exactly are the pages/actions that can count my visit as "access"? Can I just go visit any question and cast and upvote/downvote on it to have the day counted? Is the same applicable for comment votes? As far as I understand, any activity which gets logged in the activity tab (here for me) is counted as a successful visit. If that is so, I'd be more than glad to upvote one or two posts everyday. If not, can someone please provide a detailed/short list(probably as community wiki) of accepted measures which may lead to fanatic badges? P.S.: I know any kind of posting is always counted for this; be it a question, reply or a comment. A: If I log in and go to my profile page, the number of consecutive visits increments before I do anything, so I think just doing that is sufficient and self-confirmatory.
{ "pile_set_name": "StackExchange" }
Q: Deciding whether to use a one-to-many, many-to-many, or one-to-one relationship with Parse.com for iOS photo sharing app I am creating a photo sharing app for the iPhone using Parse.com and so far everything has been pretty easy and I just finished writing the code for uploading photos to the Parse server. So far, I have been using the default "_User" class. Here are some of the key types of data that are being stored for each user: objectId, username, email, and an array object called "friends" that contains the usernames of other users in the database that the user has added to their friends list. Now, I need to setup the actual sharing functionality between users. I have been going through the Parse documentation and I need to decide whether to use a one-to-many, many-to-many, or one-to-one relationship. Depending on which one I end up choosing, I then will need to decide between using pointers, arrays, parse relations, or join tables. I am going to quickly explain the "sharing" functionality that I am trying to achieve: For my photo app, user1 starts the "relationship" by taking a photo and choosing to send it to a friend on their friends list named user2 . The photo is then uploaded to Parse and sent to user2. user2 receives the photo from user1. user2 opens the photo and it is their job to "finish" the "relationship" by using the app's editing tools and drawing something random on the original photo. Example: user2 draws a heart next to user1's face in the photo. When user2 is finished, the final photo is saved to their profile and also sent back to the original sender, user1, and the "relationship" is now finished and completed/closed. After reading through the docs and doing my own research, I have come to the conclusion that I need to use a Many-To-Many relationship using Join Tables so that I can include metadata. However, I am new to objective-c and programming in general and it would be lazy of me if I did not ask for input and advice before getting started when it is possible that I have chosen the wrong solution or an unnecessary solution. A: Your question is more about your DB management than anything to do with Obj-C. Think about using a new class in your DB called SharedImage which hosts the image(s), a link to the originator and the recipient (1 to 1, so could us a pointer or a relationship) and any other data you need. Now you can create these objects are you require and you can fetch them based on queries using the current user. Also, for your existing friends array which you said holds the usernames of the friends - it would probably be better to store the objectIds of the friends instead of the usernames (because the username can usually be changed, but the objectId is static).
{ "pile_set_name": "StackExchange" }
Q: Implementing Kmeans Algorithm in R, results are different in different runs I have implemented kmeans clustering on iris dataset (inbuilt dataset) in R. The code is given below: X=as.matrix(iris[-5]); K=3; prevCentroids=matrix(0,K,dim(X)[2]); centroids=X[sample(1:dim(X)[1],K),]; dot=numeric(3); C=numeric(150); while(!isTRUE(all.equal(centroids,prevCentroids))) { for(i in 1:dim(X)[1]) { for(j in 1:dim(centroids)[1]) { dot[j]=(X[i,]-centroids[j,])%*%(X[i,]-centroids[j,]); } C[i]=which.min(dot); } prevCentroids=centroids; for(k in 1:K) { centroids[k,]=colMeans(X[which(C==k),]); } } print(cbind(iris,C)); Sometimes, with this code, I get 85% clustering correct. But sometimes, I just get 37% clustering correct if I compare it with the already clustered inbuilt iris dataset. Could anyone please tell me where I am going wrong? Should I use set.seed() here to perform partitions in similar manner everytime?? Is this how one should implement kmeans? With set.seed()? So that everytime we get correct clustering? If yes, then how can we set.seed() in unsupervised learning? How will we understand which set.seed() generates the best set of random variables? A: The two comments to the question are very insightful. I am just expanding to to make sure this question has an answer. An important concept for OP to review is local minima / saddle point vs. global minima in optimization context. If the objective function is convex, for example, linear regression with squared loss, logistic regression, then, the fitted model is unique. On the other hand, if the objective function is non-convex, such as sum of the distance in K-means, the fitted model is not unique. It will depends on the initialization of the parameters. Therefore, it is perfectly normal to see different runs with different results on K means. Also really strongly recommend you to read this. How to understand the drawbacks of K-means Also, take a look at R kmeans documentation here, the nstart parameter gives number of random repetitions to over come this local minima / saddle point problem.
{ "pile_set_name": "StackExchange" }
Q: Combining iterations to come up with a final solution For a game I'm building, I need to know how many tries it will take for a player to roll several specific numbers (say 1-30 out of 100 possible numbers). The numbers can be repeated and only need to be rolled once to count, order doesn't matter. Let's say I need a probability of at least 95%. So I came up with the following formula for calculating each iteration: In the picture you can see how the first and last iterations look. Solving for l will give me the solution I need per iteration. The question: How can I combine the iterations in a way that I get one final l value? Thanks! EDIT: I Think I've solved it, here's a wolfram equation for my solution, maybe.. sum(log(-5/(-100+c)))/(log(1-c/100)), c=1 to 30 A: Thanks to André Nicolas for his explanation in the comments! Let $q$ be the probability of "failure" in the geometric distribution with parameter $p=1−q$. So if $p=30/100$, then $q=0.7$. If $l$ is a non-negative integer, then $$\sum_{k=0}^{l} q^k p$$ is the probability that there are $0$ to $l$ failures until the first success. The complement of this event is that the first $l+1$ trials are failures. This has probability $q^{l+1}$. So we want $$1−q^{l+1}=0.95.$$ Usually there is no exact integer solution. But we will not be far off if we solve the equation $q^{l+1}=0.05$. Taking logarithms, we get $(l+1)\log(q)=\log(0.05)$, so $$l=\frac{\log(0.05)}{\log(q)}-1.$$ This matches my predicted solution as posted in the edit above, only it's actually explained instead of extrapolating a formula, so hooray for both of us! Anyway, the final solution looks like this: $$ \sum_{c=1}^{30} \frac{\log(0.05)}{\log(1-\frac{c}{100})}-1\tag{displayed} $$
{ "pile_set_name": "StackExchange" }
Q: How to publish php website under GNU GPL, but keep MySQL password?   I have some website, and I am planning register/login using MySQL for it. My website is licensed under GNU GPLv3.   Is there some way to let users see source code, but to still have the database safe (e.g. keep the php file with MySQL password unpublished)? I really want to share my code, but I don't want to somebody stealing data from my db.   My website isn't e-bank or something, but it can still contain sensitive data.   I am sorry for the license question, but I searched stackexchange for an hour and couldn't find a better place to ask A: If it is your original code, you are free to choose which part to distribute under GPL. Also, if you configure and set up the code on a webserver, you are not distributing a modified version in the terms of the GPL. The actual solution then is really simple: don't include the credentials in the distributed code. Have a look at how Wordpress does it: they include a wp-config-sample.php file, which includes most settings with sane default values. But the database connection is empty. Users just copy this example to wp-config.php and add their needed values for the database connection.
{ "pile_set_name": "StackExchange" }
Q: Switch Case Looping PHP i was very frustated, i've tried many method but didn't find my expexted result. I have this data in my table database: | PartID | HasilProduksi |QtyProduksi| |----------------------|------------------|-----------| | BLAP-FG152-PF-KGX | Repair | 1 | | AWDX-FG002-HN-KGX | Reject | 90 | | HMXX-FG022-EG-KGX | Good | 100 | | ECJX-FG018-AV-MCM | Good | 111 | and i want to create report with result : | | ACTUAL | | PartID | ---------------------| | |Good | Repair | Reject| |----------------------|-----|--------|-------| | BLAP-FG152-PF-KGX | 0 | 1 | 0 | | AWDX-FG002-HN-KGX | 0 | 0 | 90 | | HMXX-FG022-EG-KGX | 100 | 0 | 0 | | ECJX-FG018-AV-MCM | 111 | 0 | 0 | and i'm using switch case method but the result is not like with my expected result. And This is my code : $sqlc = "SELECT * FROM $db_dthp WHERE IdBukti='$id_bukti'"; $qc = mysqli_query($conn, $sqlc); $c = 0; $good=0; $reject=0; $repair=0; while ($rc = mysqli_fetch_assoc($qc)) { switch ($rc['HasilProduksi']) { case 'Good': $good += (int) $rc['QtyProduksi']; $datagood += (int) $rc['QtyProduksi']; break; case 'Reject': $reject += (int) $rc['QtyProduksi']; $datareject += (int) $rc['QtyProduksi']; break; case 'Repair': $repair += (int) $rc['QtyProduksi']; $datarepair += (int) $rc['QtyProduksi']; break; default: break; } $c++; } $res['result'][$i]['data'][$b]['hp'][0]['good'] = number_format($good,0,'.','.'); $res['result'][$i]['data'][$b]['hp'][0]['reject'] = number_format($reject,0,'.','.'); $res['result'][$i]['data'][$b]['hp'][0]['repair'] = number_format($repair,0,'.','.'); Can you help me? A: If you use this other query, you will have already your data and you don't need the switch in php. You will do the case in your query: $sqlc="SELECT PartID, CASE WHEN HasilProduksi='Good' THEN QtyProduksi ELSE 0 END as Good, CASE WHEN HasilProduksi='Repair' THEN QtyProduksi ELSE 0 END as Repair, CASE WHEN HasilProduksi='Reject' THEN QtyProduksi ELSE 0 END as Reject FROM $db_dthp WHERE IdBukti='$id_bukti';"
{ "pile_set_name": "StackExchange" }
Q: Fill a drop down list dynamically using Javascript/jQuery In an ASP .NET MVC Razor view, I have a dropdown list as follows: @Html.DropDownListFor(model => model.SelectedDeviceModel, Model.DeviceModelList) DeviceModelList is just a SelectList. How can I dynamically fill the DeviceModelList depending on a client side action like a button click or another drop down selection using Javascript/jQuery/Ajax? A: You could externalize this dropdown into a partial: @model MyViewModel @Html.DropDownListFor(model => model.SelectedDeviceModel, Model.DeviceModelList) then in your main view include it inside some container: @model MyViewModel ... <div id="ddlcontainer"> @Html.Partial("Foo", Model) </div> ... then you could have a controller action which takes some parameter and based on its value it renders this partial: public ActionResult Foo(string someValue) { MyViewModel model = ... go ahead and fill your view model return PartialView(model); } Now the last part is to send the AJAX request to refresh the drop down list when some event occurs. For example when the value of some other ddl changes (or something else, a button click or whatever): $(function() { $('#SomeOtherDdlId').change(function() { // when the selection of some other drop down changes // get the new value var value = $(this).val(); // and send it as AJAX request to the newly created action $.ajax({ url: '@Url.Action("foo")', type: 'POST', data: { someValue: value }, success: function(result) { // when the AJAX succeeds refresh the ddl container with // the partial HTML returned by the Foo controller action $('#ddlcontainer').html(result); } }); }); }); Another possibility consists into using JSON. Your Foo controller action would only return some Json object containing the new key/value collection and in the success callback of the AJAX request you would refresh the drop down list. In this case you don't need to externalize it into a separate partial. For example: $(function() { $('#SomeOtherDdlId').change(function() { // when the selection of some other drop down changes // get the new value var value = $(this).val(); // and send it as AJAX request to the newly created action $.ajax({ url: '@Url.Action("foo")', type: 'POST', data: { someValue: value }, success: function(result) { // when the AJAX succeeds refresh the dropdown list with // the JSON values returned from the controller action var selectedDeviceModel = $('#SelectedDeviceModel'); selectedDeviceModel.empty(); $.each(result, function(index, item) { selectedDeviceModel.append( $('<option/>', { value: item.value, text: item.text }) ); }); } }); }); }); and finally your Foo controller action will return Json: public ActionResult Foo(string someValue) { return Json(new[] { new { value = '1', text = 'text 1' }, new { value = '2', text = 'text 2' }, new { value = '3', text = 'text 3' } }); } For a similar example you may take a look at the following answer.
{ "pile_set_name": "StackExchange" }
Q: Docker get previous image with FROM Is it possible with Docker to get a previous version of Docker image(not the current one), for example: FROM base:previous or something like this. Unfortunately, I don't know this image digest. A: In your example previous is the tag of the image. If you know the tag of the older image just write that. As an example the official mysql image (https://hub.docker.com/_/mysql/) lists several tags ranging from 5.5 to 8.0 So I can start an instance of mysql 5.5 using docker run mysql:5.5 You could also do that in your Dockerfile, if the older version is 1.0 you would do: FROM base:1.0 If you don't know which tag you used previously you might be able to find it if you list all your images locally docker images Good luck!
{ "pile_set_name": "StackExchange" }
Q: Using Maven shade plugin in a multi module project - NullPointerException I have a scenario where-in I need to create an uber jar of a multi module maven project including all modules and their dependencies. I tried using maven shade plugin. but it seems to work only when I use it at the module level. If I add the plugin entry in parent pom then the build breaks (it tries to shade the parent pom) [INFO] Replacing original artifact with shaded artifact. [INFO] Replacing null with C:\Projects\foo.bar\target\foobar-0.0.1-SNAPSHOT-shaded.pom [INFO] ------------------------------------------------------------------------ [ERROR] BUILD ERROR [INFO] ------------------------------------------------------------------------ [INFO] Error creating shaded jar: null: NullPointerException -> [Help 1] It does seem to make sense since the <packaging> for the parent maven project is pom. But there should be some way to create an uber jar for a multi module project... Any ideas people??? A: You should not be using your parent project's POM file to attempt shading; you should be using a separate aggregator project for this. Parent maven projects are used for inheritance while aggregator projects are used to perform aggregate functions over a group of sub-projects; like shading their JARs together into a uber jar. This project would simply be a pom file at the root directory of your project (the same level as all the sub-modules' folders) which references the sub-projects and has the shade plugin configuration. Make sure the packaing specified for this pom is JAR. Here is the documentation explaining POM relationships and difference between Aggregation and Inheritance. A: Yes ! You can ! :-) Shade has an implementation problem: it doen't know when is running over pom (not jar or web) project. Pom projects don't generate binary artifacts, then shade doesn't find files to merge, move, etc., throwing NPE. To solve this problem, create a parent POM from your aggegate-Pom project. Inside it, put the shade definitions and configuration configuring to some profile (eg. alwaysActiveProfiles) and install/deploy it with command: mvn deploy -P -alwaysActiveProfiles This command will install this shaded parent without running shade plugin pom (-alwaysActiveProfiles option supress shade plugin execution) and after that, your maven dependent projects will work. Your shaded parent pom could looks like this: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>xxxxxxxx</groupId> <artifactId>web-pom</artifactId> <name>web-pom</name> <version>1.0.0-SNAPSHOT</version> <packaging>pom</packaging> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>1.4</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> ... </configuration> </execution> </executions> </plugin> </plugins> </pluginManagement> </build> <dependencies> ... </dependencies> <profiles> <profile> <id>alwaysActiveProfiles</id> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> </plugin> </plugins> </build> </profile> </profiles> Remember that your setting.xml must have alwaysActiveProfiles enabled by default, otherwise shade will not run in your dependences shade-pom projects.
{ "pile_set_name": "StackExchange" }
Q: Convert string to Datetime format dd-MMM-yyyy issue I am getting the account expiry date of the employee from database in a string variable and the values which is in this string variable is in the format : 6/26/2016 9:14:03 AM. Now i want this format to be converted in dd-mmm-yyyy hh:mm:ss am/pm.How can i resolve this. I tried the following code : DateTime passexpiredate = DateTime.ParseExact(app_user.GetPasswordExpiry(empCode), "dd-MMM-yyy hh:mm tt", null); lblPassExpiry.InnerText = "Password Expiry Date: "+passexpiredate.ToString(); A: You've to pass the required date time format in ToString() method as mentioned below: DateTime passexpiredate = DateTime.Parse(app_user.GetPasswordExpiry(empCode)); lblPassExpiry.InnerText = "Password Expiry Date: " + passexpiredate.ToString("dd-MMM-yyy hh:mm tt");
{ "pile_set_name": "StackExchange" }
Q: Convert string to unicode representation Possible Duplicate: Converting Unicode strings to escaped ascii string How can I convert ä... into something like \u0131... ? is there any Function for doing this ? p.s : beside this way : [ sorry @Kendall Frey :-)] char a = 'ä'; string escape = "\\u" + ((int)a).ToString("X").PadLeft(4, '0'); A: Here's a function to convert a char to an escape sequence: string GetEscapeSequence(char c) { return "\\u" + ((int)c).ToString("X4"); } It isn't gonna get much better than a one-liner. And no, there's no built-in function as far as I know. A: There is no built-in function AFAIK. Here is one pretty silly solution that works. But Kendall Frey provided much better variant. string GetUnicodeString(string s) { StringBuilder sb = new StringBuilder(); foreach (char c in s) { sb.Append("\\u"); sb.Append(String.Format("{0:x4}", (int)c)); } return sb.ToString(); }
{ "pile_set_name": "StackExchange" }
Q: Change project nature in a RCP application I have in my RCP application a View that extends the CommonNavigator class. The projects in the workspace of my application should have different icons depending on their location on the disk: the projects that exist locally in the workspace should have a different icon from the projects that were imported. I realised this by defining in the plugin.xml two project natures: MyProjectNature and MyProjectNatureImported with different icons and changing between the natures accordingly with the following method: private void updateProjectNature(final IWorkspace lf_workspace) { String l_workspacePath = lf_workspace.getRoot().getLocation().toString(); IProject[] l_projectsInWorkspace = lf_workspace.getRoot().getProjects(); for (IProject l_project : l_projectsInWorkspace) { try { File l_projectFile = new File(l_workspacePath + l_project.getFullPath().toString()); final IProjectDescription l_projectDescription = l_project.getDescription(); final String[] l_currentNatures = l_projectDescription.getNatureIds(); final String[] l_newNatures = new String[l_currentNatures.length]; int l_index = 0; if (l_projectFile.exists()) { for (String l_nature : l_currentNatures) { if (l_nature.equals(MyProjectNatureImported.NATURE_ID)) { l_newNatures[l_index] = MyProjectNature.NATURE_ID; } else { l_newNatures[l_index] = l_nature; } l_index++; } } else { for (String l_nature : l_currentNatures) { if (l_nature.equals(MyProjectNature.NATURE_ID)) { l_newNatures[l_index] = MyProjectNatureImported.NATURE_ID; } else { l_newNatures[l_index] = l_nature; } l_index++; } } l_projectDescription.setNatureIds(l_newNatures); l_project.setDescription(l_projectDescription, null); } catch (CoreException e) { LOGGER.warning("Error when setting the project nature of the project " + l_project.getName() + ": " + e.getMessage()); } } } When I call this method from the ResourceChangeListener that I added to the workspace, I get an error for each project that it is locked and cannot be editted: final IWorkspace lf_workspace = ResourcesPlugin.getWorkspace(); lf_workspace.addResourceChangeListener(new IResourceChangeListener() { @Override public void resourceChanged(IResourceChangeEvent event) { updateProjectNature(lf_workspace); } }); But when I create a Job that runs each few seconds, then it works: Job l_testJob = new Job("Update navigator") { @Override protected IStatus run(IProgressMonitor monitor) { updateProjectNature(lf_workspace); schedule(1000); return Status.OK_STATUS; } @Override public boolean shouldSchedule() { // Check if the job should be scheduled / executed or not return !PlatformUI.getWorkbench().isClosing(); } }; l_testJob.schedule(1000); I would like to call the method only when changes are made to the workspace and not each second (to save the resources), but I don't understand why I get the error and cannot change the nature from the listener while from the job there is no problem. Any ideas? A: The workspace is locked while the resource change event is sent so that listeners can't make any more changes. You should be able to submit a single Job from your listener with a scheduling rule to delay the job until the workspace is available. You should use a WorkspaceJob to make sure the update is atomic. class UpdateNatureJob extends WorkspaceJob { UpdateNatureJob() { // Scheduling rule setRule(ResourcesPlugin.getWorkspace().getRoot()); } @Override public IStatus runInWorkspace(final IProgressMonitor monitor) { ... your nature update return Status.OK_STATUS; } }
{ "pile_set_name": "StackExchange" }
Q: PhoneGap NativeControls Tabbar selection I am using XCode version 4.2 and PhoneGap version 1.5.0 to develop iOS app. Using the following code, I was able to add tab bar on the page, but I couldn't make it to navigate to another page on selection. I have created the tab bar using NativeControls plugin of PhoneGap. function onDeviceReady() { Cordova.exec("NativeControls.createTabBar" var options = "bottom"; window.onorientationchange = function() { var orientation = window.orientation; switch(orientation) { case 0: Cordova.exec("NativeControls.showTabBar", options); /* Add a descriptive message on "Handling iPhone or iPod touch Orientation Events" */ document.getElementById("currentOrientation").innerHTML="Now in portrait orientation (Home button on the bottom)."; break; case 90: Cordova.exec("NativeControls.showTabBar", options); document.getElementById("currentOrientation").innerHTML="Now in landscape orientation and turned to the left (Home button to the right)."; break; case -90: Cordova.exec("NativeControls.showTabBar", options); document.getElementById("currentOrientation").innerHTML="Now in landscape orientation and turned to the right (Home button to the left)."; break; default: Cordova.exec("NativeControls.showTabBar", options); document.getElementById("currentOrientation").innerHTML="Now the orientation must be -180. default: case: "; break; }//end switch }//end window.orientationchange Cordova.exec("NativeControls.showTabBar", options); Cordova.exec("NativeControls.createTabBarItem", "Wineries", "Wineries", null, "1", options); Cordova.exec("NativeControls.createTabBarItem", "Wines", "Wines", "www/Wine.png", "2", {onSelect: function() {location.href = "Review.html" }}); Cordova.exec("NativeControls.createTabBarItem", "Tours", "Tours", null, "3", options); Cordova.exec("NativeControls.createTabBarItem", "Non-Mobile", "Non-Mobile", null, "4", options); Cordova.exec("NativeControls.showTabBarItems", "Wineries", "Wines", "Tours", "Non-Mobile"); Cordova.exec("NativeControls.selectTabBarItem", "Wineries"); } But this code is not working at all for changing the page on selection. Cordova.exec("NativeControls.createTabBarItem", "Wines", "Wines", "www/Wine.png", "2", {onSelect: function() {location.href = "Review.html" }}); EDIT Same happens when I use the following code. Should I repeat the same code on second page? If so on which method I should invoke this? function onDeviceReady() { var nc = window.plugins.nativeControls; nc.createTabBar(); nc.createTabBarItem("Wineries", "Wineries", "www/grape.png", {onSelect: function() {location.href = "index.html" }}); nc.createTabBarItem("Wines", "Wines", "www/Wine.png", {onSelect: function() {location.href = "Review.html" }}); nc.createTabBarItem("Tours", "Tours", "www/tour.png", null); nc.createTabBarItem("Non-Mobile", "Non-Mobile", "", null); nc.showTabBar(); nc.showTabBarItems("Wineries", "Wines", "Tours", "Non-Mobile"); nc.selectTabBarItem("Wineries"); } A: Just found a way around for my problem. Instead of assigning a new html page to each tab, connected it to functions. On each call, it changes the body content accordingly. But, still I would like to know if any other solution exists!! function onDeviceReady() { var title = "WineWeb"; nc = window.plugins.nativeControls; nc.createTabBar(); nc.createTabBarItem("Wineries", "Wineries", "www/grape.png", {onSelect: Wineries}); nc.createTabBarItem("Wines", "Wines", "www/Wine.png", {onSelect: Review}); nc.createTabBarItem("Tours", "Tours", "www/tour.png", null); nc.createTabBarItem("Non-Mobile", "Non-Mobile", "", null); nc.showTabBar(); nc.showTabBarItems("Wineries", "Wines", "Tours", "Non-Mobile"); nc.selectTabBarItem("Wineries"); } function Wineries () { nc = window.plugins.nativeControls; nc.setNavBarTitle("Wineries"); nc.hideLeftNavButton(); document.getElementById('Review').style.display='none'; document.getElementById('Wineries').style.display='block'; document.getElementById('AboutUs').style.display='none'; }
{ "pile_set_name": "StackExchange" }
Q: Why don't some do yibum today, l'chatchilah? According to the Mishna (Bechorot 1:7) the reason not to perform yibum nowadays is people don't have intention l'shem mitzva when performing yibum. Firstly I would like to know if there are any other reasons recorded for not performing this mitzvah anymore and/or secondly I would like to understand the idea that the Rabbanan uprooted a biblical mitzvah because of people's questionable motives. What does "not l'shem mitzva" mean? Why does the person's intention factor in? As far as I know mitzvot don't need intention (kavvanah) at all. So, as long as the Yavam doesn't have intention to sin (not sure what sin he could even intend) his intentions shouldn't matter at all. So why do we say they do? Let's say someone decides that he does have intention l'shem mitzva, is he allowed to perform yibum today? Why or why not? 3a. If he is not allowed, what would happen if he did so anyway? A: Yevamos 39b: אבא שאול אומר הכונס את יבמתו לשם נוי ולשום אישות ולשום דבר אחר כאילו פוגע בערוה וקרוב אני בעיני להיות הולד ממזר Not l'shem mitzvah means doing Yibbum for the beauty of the woman, for marriage, or for "something else" (which could either literally mean any other reason, or could be a euphemism for intimate relations). This is presumably a list of examples of anything other than the mitzvah. Yibbum is a situation in which a very serious prohibition is overridden/suspended for the Mitzvah being performed. Because this situation is prohibited sans the mitzvah, Abba Shaul felt that one who is not focusing on the mitzvah is as if he is coming into contact with that prohibition. (According to Rashi's comments, it seems as if Abba Shaul held it was literally violating this prohibition - Rashi to Bechoros 13a s.v. עכשיו). Therefore, his intentions make a difference in this case, as it becomes a "mental" אשת אח when he does not intend for the Mitzvah. R' Elchonon Wasserman in Kovetz Ha'aros 36 posits that when it comes to any positive commandment overriding a negative commandment not just Yibbum e.g Shaatnez on tzitzis, metzora or nazir cutting the corners by shaving their heads, even the opinion that normally holds Mitzvos Ein Tzrichus kavana (do not need proper intention) will agree that in this situation it is required for the positive commandment to override the negative completely and for their to be no repercussions having done the Aveira at the same time as the Mitzva. If you follow this to its logical conclusion, this would mean that if someone went ahead and did Yibbum for the wrong reasons, the Yibbum would not take effect as a full Mitzva, as it is in violation at the same time of the prohibition of marrying a brother's wife, in which case marriage bears the iniquity of the Aveira even though it works, The Chazon Ish (Nashim 129:13) understands that Abba Shaul and the Chachomim both understood that on a Biblical level this Yibbum works, and that even the Chachomim agree that ideally you need to have the proper intentions for the Mitzvah. Their argument was that the Chachomim understood this Mitzvah to be no different than any other Mitzvah, in which doing it "shelo lishma" is better than not doing it i.e the greater good of the mitzva supercedes any iniquity of the aveira even if he did it for the wrong intentions, whereas Abba Shaul held that in this particular Mitzvah you are violating the intent of the Torah, and from Heaven's perspective it is as if you have gotten involved with an illicit relationship, and it is therefore better to not do it even though a mitzva is being performed at the same time and the Marriage would fully take effect. The phrasing of the halacha seems to be a blanket rule, not dependent on individual basis. In fact, when the Gemara in Yevamos suggests that the halacha reverted to be that Yibbum takes precedence, Rav Nachman exclaims in surprise "Has the generation improved?" and the response is that the consensus of who's opinion to follow has changed - the implication is that short of a change in the halachic conclusion, it is untenable that we would assume we have reached the point of doing Yibbum with the proper intentions. A: In response to the third question: Per Yabia Omer 6, Even Hoezer 14 Rabbi Ovadia Yosef Zatzal says that Sefardim, Edus Hamizrach, and Yemenites that follow the Rambam and Beis Yosef who hold like the Chachomim that the Mitzva of Yibum takes priority over Chalitza even in today's generation, and even when it is not L'shaim Mitzva. Therefore he concludes that if one is doing it L'shaim Mitzva they should do Yibum and the Bais Din should encourage him to do so.
{ "pile_set_name": "StackExchange" }
Q: Подсчет количества флажков с установленной галочкой на jQuery <ul class="" class="category2"> <li class=""> <a href="#" id="titlecategories"> Титл </a> </li> <li class="subcategory2" > <a href="#"> <input checked="" name="filter[]" id="filtercheckbox11" value="11" type="checkbox"> Текст-Текст-Текст- </a> </li> <li class="subcategory2" > <a href="#"> <input name="filter[]" id="filtercheckbox2" value="2" type="checkbox"> Текст-Текст-Текст-Текст- </a> </li> <li class="subcategory2"> <a href="#"> <input checked="" name="filter[]" id="filtercheckbox4" value="4" type="checkbox"> Текст-Текст-Текст-Текст- </a> </li> </ul> Нужно с помощью jquery подсчитать сколько чекбоксов отмечено на странице. Таких примеров на странице естественно несколько. Они отличаются классами category и subcategory. Например сколько в category2 отмеченных чекбоксов subcategory2 и т. д. A: @Erm, автор все таки хотел подсчет по всем категориям и субкатегориям, возможно что-то подобное? var countChecked = function() { var n = $('.category2 input:checked').length; $('div').text(n + ' выбрано!'); }; countChecked(); $('input[type=checkbox]').on('click', countChecked); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="category2"> <li class=""> <a href="#" id="titlecategories"> Титл </a> </li> <li class="subcategory2"> <a href="#"> <input checked="" name="filter[]" id="filtercheckbox11" value="11" type="checkbox"> Текст-Текст-Текст- </a> </li> <li class="subcategory2"> <a href="#"> <input name="filter[]" id="filtercheckbox2" value="2" type="checkbox"> Текст-Текст-Текст-Текст- </a> </li> <li class="subcategory2"> <a href="#"> <input checked="" name="filter[]" id="filtercheckbox4" value="4" type="checkbox"> Текст-Текст-Текст-Текст- </a> </li> </ul> <div></div> p.s. @Erm переделал ваш код, надеюсь вы не против
{ "pile_set_name": "StackExchange" }
Q: How to check for a value in a list of tuples? I have a list of tuples like this: l = [(10,'bat'), (50,'ball'), (100,'goal')] and I want to check if 100 is in any of the tuples. And if it is there I need to remove its value which is 'goal'. How can I do this? TIA A: You can use list comprehension to filter out the tuple: l = [t for t in l if t[0] != 100] If you want/have to do this with multiple values, you can create a set of them: exclude = set(100, 30, 20) l = [t for t in l if t[0] not in exclude]
{ "pile_set_name": "StackExchange" }
Q: Why use "new" for Route Values in "ActionLink" ---- for example I have 2 examples below: @Html.ActionLink("Create New", "Create", new { id = Model.Id }) and, return RedirectToAction("Index", new { id = review.RestaurantId }); My question is regarding the new { id = xxx} part in object route values. Why do we use "new" in this case? What exactly does it do? Does it initialize "id" variable in this case? Also, it is strange that these methods, create and index definition can only take arguments as defined in the route values... That is, public ActionResult create { int id) { ...} is correct but following is wrong.... public ActionResult create { int somethingelse) { ...} So please tell me what is the new {id = xx} in my first 2 examples is doing? Thanks A: new {} creates a new object of type Object. The type is anonymous. You see that syntax when writing linq queries that end in " select new {x = "foo". y="bar"}". It is often used when setting an object to type "var". What you are doing in your ActionLink is providing Route Values. MVC takes the properties and values in the object and puts them in the QueryString of the request. It is what you might refer to as "magic". You can set a break point in your controller Action and check "HttpContext.Request.QueryString" to see it. The input values for you Action methods have to match the properties that are being passed in via the QueryString.
{ "pile_set_name": "StackExchange" }
Q: What is a good Google Maps Generator? I am looking for a google maps API generator to save time? What do you recommend? Update: I want to generate (using my API key) a map of the US/WORLD and put markers are about 20 locations. Nothing crazy. I am looking for something similar to this http://schogini.us/ajax_google_map_api_code_generator/ajax_google_map_api_code_generator.php A: What language do you need to be working in? There are both client-side and server-side tools for this. For client-side, I like jQuery's plugin jMaps. A: Try http://www.mapsofall.com/map-generator/, I think this is exactly you are looking for
{ "pile_set_name": "StackExchange" }
Q: Javascript Skips Intervals in For Loop I have a for loop in JavaScript that is skipping intervals regularly and I can't determine why. console.log(parseInt($('input.num-to-add').val())); numToAdd = parseInt($('input.num-to-add').val()); console.log(numToAdd); for(i=0;i<numToAdd;i++){ console.log('Running loop for ' + i + '...'); // the following code won't mean much // but it was noted that the full code should be present table.find('tbody').prepend(data.html); var row = table.find('tbody #add-location-row').first(); rowInit(row); } As you can see, I'm, console.loging at just about every step and I just can't identify the issue. The issue itself is pretty well illustrated in the console output. For example, if input.num-to-add has a value of 8, here's what I see in the console: 8 8 Running loop for 0... Running loop for 6... Running loop for 7... I really can't see what the issue would be here. This seems to me to be incredibly simple and basic code but it's breaking in some way I simply can't determine. A: As many others already pointed out in the comments section, that most certainly happens because you use a global variable named i as a loop variable. If you use the same global variable i in rowInit, that will interfere with this loop. Solution is simple, always use correctly scoped variables: for(var i=0;i<numToAdd;i++){ console.log('Running loop for ' + i + '...'); // the following code won't mean much // but it was noted that the full code should be present table.find('tbody').prepend(data.html); var row = table.find('tbody #add-location-row').first(); rowInit(row); } Or even better: for(let i=0;i<numToAdd;i++){
{ "pile_set_name": "StackExchange" }
Q: class Image has no attribute 'open' Possible Duplicate: img = Image.open(fp) AttributeError: class Image has no attribute ‘open’ So I am trying to view pictures in python with tkinter. I installed PIL and I am trying to open a picture but I keep getting an attribute error saying "class Image has no attribute 'open' from __future__ import division from PIL import Image from Tkinter import * import random img = Image.open("majestic creature.jpeg").convert("RGB") This isn't all the code I have but this is the part that the program seems to have trouble with. A: From the looks of what you have said, namely This is not all of the code. You or some other import has declared some variable / class called Image and this has overwritten the Image class that was imported by PIL. To specifically use the PIL Image class use: img = PIL.Image.open("majestic creature.jpeg").convert("RGB")
{ "pile_set_name": "StackExchange" }
Q: iOS - Help Using [NSPredicate predicateWithFormat] Hey so I'm using a NSPredicate to filter an array. Currently I use the following piece of code: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name contains[c] %@", searchText]; This has been working alright as it looks for the attribute .name and checks to see if it is contained in the searchText. I was wondering if there is a way for me to change it from checking if it's contained in the search text to if the search text begins with the search filter. I.E. if the search text is school and I type sc as the filter the search text stays but if I type sco the search text school is filtered out. Is there some sort of beginswith that I can use instead of contains[c]. Thanks! A: Yes, exactly that in fact: BEGINSWITH The left-hand expression begins with the right-hand expression. CONTAINS The left-hand expression contains the right-hand expression. ENDSWITH The left-hand expression ends with the right-hand expression. LIKE The left hand expression equals the right-hand expression: ? and * are allowed as wildcard characters, where ? matches 1 character and * matches 0 or more characters. MATCHES The left hand expression equals the right hand expression using a regex-style comparison according to ICU v3 (for more details see the ICU User Guide for Regular Expressions). Full docs
{ "pile_set_name": "StackExchange" }
Q: Infimum of sum of three terms Let $(X,d)$ be a metric space, $b \in \mathbb{R}$ a constant and $f,g : X \rightarrow \mathbb{R}$. I found the following statement in some notes and I cannot understand how they conclude it : \begin{equation} \inf \limits_{x \in X} \{f(x) + g(x) + b\} = \inf \limits_{x \in X} \{f(x) + b\} + \inf \limits_{x \in X} \{f(x) + g(x) \} \end{equation} Is this possible ? Could someone give me some help ? A: No, it is not true in general. For example, take $f (x)=1$ and $g (x)=-1$.
{ "pile_set_name": "StackExchange" }
Q: Can multiple operations with Streaming break The Law of Demeter? I went little fancy and wrote Selenium page-object with Java 8 streaming as mentioned in below code and got a review comment that my code is breaking Law of Demeter, since I am doing lot of operations in a single line. I was suggested to break the code to first stream to collect to list and run another stream operation to do match( in short break it down into multiple streams as needed). I was not convinced as Stream is introduced for handling data processing and if we break it down into multiple streams, there is no point using stream. Previously I have worked for a cyber security project, where millions of records were processed with streaming with multiple logic operations to sort the data. Please share your thoughts, I have changed it as the reviewer suggested but he couldn't explain why and I want to learn more about streams and right way of utilizing this powerful addition to java 8. Here is the sample code: listOfWebElements.stream().filter(element -> element.getText().contains(name)).findFirst().ifPresent(match -> match.click()); is line I am referring to in this question, providing the method so that it makes more sense. @FindBy(css = "#someTable td.some-name li a") List<WebElement> listOfWebElements; public SomeClass doSomething(String name) { wait.until(visibilityOfAllElements(listOfWebElements)); listOfWebElements.stream().filter(element -> element.getText().contains(name)).findFirst() .ifPresent(match -> match.click()); return new SomeClass(driver); } A: Java 8 streams are an example of a fluent interface, and are intended to allow writing in a functional programming style. There is a lot of disagreement over what breaks the LoD and whether it even matters, but all that aside, the example in the documentation for Stream shows that you are using it as intended by the Java language designers. If that isn't enough for your reviewer, note that the purpose of the Law of Demeter (aka the principle of least knowledge) is to keep programs loosely-coupled by minimizing the number of classes that a class directly communicates with. When A has a B and B has a C, and you want A to make C do something, you should have it tell B to get it done and let B worry about the details of how and when C is used. In this case, every intermediate method on Stream is returning another instance of Stream, so you are still only coupled to the Stream class. I would not consider this a Law of Demeter violation. I would also say that any class in a language should be considered coupled to the language's standard library. Therefore, any standard library objects should be exempt from the Law of Demeter, since you can't uncouple from them anyway. Otherwise, you wouldn't even be able to call get on a List that was returned by an object, or deal with a Set of Map.Entry from Map.entrySet(). This would also cover Stream, of course. I was suggested to break the code to first stream to collect to list and run another stream operation to do match( in short break it down into multiple streams as needed). Storing intermediate objects in local variables does not fix a Law of Demeter violation, you would still be accessing objects returned by other objects. It sounds like your reviewer is just blindly dot-counting.
{ "pile_set_name": "StackExchange" }
Q: How to pipe input to Java program with bash My Java program is listening on standard input: InputStreamReader isReader = new InputStreamReader(System.in); BufferedReader bufReader = new BufferedReader(isReader); while(true){ try { String inputStr = null; if((inputStr=bufReader.readLine()) != null) { ... } else { System.out.println("inputStr is null"); } } catch (Exception e) { ... } } Now, I want to pipe input to this program from bash. I tried the following: echo "hi" | java -classpath ../src test.TestProgram But it's just printing inputStr is null infinite times. What am I doing wrong? Edit 1: Updated question to include more code / context. Edit 2: Looks like I'm experiencing the same issue as this OP: Command Line Pipe Input in Java How can I fix the program so that I can pipe input in for testing, but running the program normally will allow users to enter input on standard input as well? A: You have while(true), so infinite looping is what you're going to get. Adding a break somewhere in the loop is one way to fix it. But it's not good style, because the reader has to hunt around the loop to find out if and when it exits. It's much better to make your while statement show clearly what the exit condition is: String inputStr = ""; while(inputStr != null) { inputStr=bufReader.readLine(); if(inputStr != null) { ... } else { System.out.println("inputStr is null"); } } A: Fixed it. After the piping of input was completed, readLine() kept returning null, so the infinite loop kept looping. The fix is to break from the infinite loop when readLine() returns null. A: I like slim's answer, only I tend handle it a bit differently. this is a basic template I use for reading a stream of text, line by line. try { // Wrap the System.in inside BufferedReader // But do not close it in a finally block, as we // did no open System.in; enforcing the rule that // he who opens it, closes it; leave the closing to the OS. BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line; while ((line = in.readLine()) != null) { // TODO: Handle input line } // Null was received, so loop was aborted. } catch (IOException e) { // TODO: Add error handler } If I am reading a file, I change it slightly, to close the file like this try { File file = new File("some_file.txt"); // Wrap the System.in inside BufferedReader // But do not close it in a finally block, as we // did no open System.in; enforcing the rule that // he who opens it, closes it; leaves the closing to the OS. BufferedReader in = new BufferedReader(new FileReader(file)); try { String line; while ((line = in.readLine()) != null) { // TODO: Handle input line } // Null was received, so loop was aborted. } finally { try { in.close(); } catch (IOException e) { } } } catch (IOException e) { // TODO: Add error handler }
{ "pile_set_name": "StackExchange" }
Q: Change row color of a table based on mysqli value using materializecss I'm using Materialize css on my project, i have a table that shows mysql field called "status" and in this table i want change the color of the row if i change the "status" like "1=blue, 2=red..." Someone here knows how i can make a function to do this? Thank you. table extample: table class="striped bordered responsive-table"> <thead> <tr> <th>ID</th> <th>Cliente</th> <th>Objeto</th> <th>Status</th> </tr> </thead> <tbody> <?php while($row_os = mysqli_fetch_assoc($result_user)){?> <tr> <td><?php echo $row_os["num"]; ?></td> <td><?php echo $row_os["cliente"]; ?></td> <td><?php echo $row_os["object"]; ?></td> <td><?php echo $row_os["status"]; ?></td> </tr> <?php } ?> </tbody> A: One simple way would be: <?php $colorMap = [ 1 => 'blue', 2 => 'red', // add more ]; while ($row_os = mysqli_fetch_assoc($result_user)) { ?> <tr style="background:<?php echo $colorMap[$row_os['status']] ?>"> <td><?php echo $row_os["num"]; ?></td> <td><?php echo $row_os["cliente"]; ?></td> <td><?php echo $row_os["object"]; ?></td> <td><?php echo $row_os["status"]; ?></td> </tr> <?php } ?> Of course you could also add a class depending on status the same way and do the styling in CSS.
{ "pile_set_name": "StackExchange" }
Q: Export HTML table to pdf using jspdf I need to export the HTML table to pdf file using jspdf. I tried the below code but it displays the blank/empty output in pdf file. Any suggestions or sample code for this would be helpful. ` <script type="text/javascript"> function demo1() { $(function () { var specialElementHandlers = { '#editor': function (element,renderer) { return true; } }; $('#cmd').click(function () { var doc = new jsPDF(); doc.fromHTML($('#htmlTableId').html(), 15, 15, { 'width': 170,'elementHandlers': specialElementHandlers }); doc.save('sample-file.pdf'); }); }); } </script> ` A: Here is working example: in head <script type="text/javascript" src="jspdf.debug.js"></script> script: <script type="text/javascript"> function demoFromHTML() { var pdf = new jsPDF('p', 'pt', 'letter'); // source can be HTML-formatted string, or a reference // to an actual DOM element from which the text will be scraped. source = $('#customers')[0]; // we support special element handlers. Register them with jQuery-style // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.) // There is no support for any other type of selectors // (class, of compound) at this time. specialElementHandlers = { // element with id of "bypass" - jQuery style selector '#bypassme': function(element, renderer) { // true = "handled elsewhere, bypass text extraction" return true } }; margins = { top: 80, bottom: 60, left: 40, width: 522 }; // all coords and widths are in jsPDF instance's declared units // 'inches' in this case pdf.fromHTML( source, // HTML string or DOM elem ref. margins.left, // x coord margins.top, {// y coord 'width': margins.width, // max width of content on PDF 'elementHandlers': specialElementHandlers }, function(dispose) { // dispose: object with X, Y of the last line add to the PDF // this allow the insertion of new lines after html pdf.save('Test.pdf'); } , margins); } </script> and table: <div id="customers"> <table id="tab_customers" class="table table-striped" > <colgroup> <col width="20%"> <col width="20%"> <col width="20%"> <col width="20%"> </colgroup> <thead> <tr class='warning'> <th>Country</th> <th>Population</th> <th>Date</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>Chinna</td> <td>1,363,480,000</td> <td>March 24, 2014</td> <td>19.1</td> </tr> <tr> <td>India</td> <td>1,241,900,000</td> <td>March 24, 2014</td> <td>17.4</td> </tr> <tr> <td>United States</td> <td>317,746,000</td> <td>March 24, 2014</td> <td>4.44</td> </tr> <tr> <td>Indonesia</td> <td>249,866,000</td> <td>July 1, 2013</td> <td>3.49</td> </tr> <tr> <td>Brazil</td> <td>201,032,714</td> <td>July 1, 2013</td> <td>2.81</td> </tr> </tbody> </table> </div> and button to run: <button onclick="javascript:demoFromHTML()">PDF</button> and working example online: tabel to pdf jspdf or try this: HTML Table Export A: You can also use the jsPDF-AutoTable plugin. You can check out a demo here that uses the following code. var doc = new jsPDF('p', 'pt'); var elem = document.getElementById("basic-table"); var res = doc.autoTableHtmlToJson(elem); doc.autoTable(res.columns, res.data); doc.save("table.pdf");
{ "pile_set_name": "StackExchange" }
Q: Best Way to Track Brute-Force Username Enumeration / Failed Username Attempts AD We have a Windows Server which has an application that resides on it, which uses domain credentials on login to the application. During a recent pen test, the testers were able to use the application in order to enumerate valid domain usernames based on the application's response (It gave a different response for an invalid username vs. an invalid password). The application is being fixed so it doesn't reveal this information, but I also feel like we should have detected this attack since there were over 2000,000 invalid username attempts over a short period of time. We did not see it, even when our administrators were closely watching Active Directory. Apparently the failures only ever showed up in the local event log of the server where the application was installed. My question: 1) Is there a way to get Active Directory to log these failed username requests in a central location so we can notice a spike in them? 2) If not, what is the best way to monitor and actively detect this type of attack in the future (Hopefully without having to buy too much new equipment). Thanks, for your help. A: Great question. First things first - I consider most "penetration testers" to be script kiddies. My bias may not be fair or accurate but I'm putting in this disclaimer so that if you detect any cynicism in my tone, you know where it's coming from. I'm not saying there are no skilled pentesters, but this is my sweeping generality. (Blue team for life!) My question: 1) Is there a way to get Active Directory to log these failed username requests in a central location so we can notice a spike in them? You did not supply enough information for anyone to be able to answer this question thoroughly and with confidence. You said your application was found to contain a flaw that allowed the attackers to enumerate user accounts. I'm trying to understand in what way you feel that AD needs to perform logging for your application. Apparently the failures only ever showed up in the local event log of the server where the application was installed. Apparently the failures showed up in the event log on the server? Or the failures did show up in the event log on the server? If so, what exactly did the events say? Who logged them? Your application? Or Windows? Go find out and I may be able to add additional clarification to my answer. I'm going to go out on a limb here based on your presumption that these events should have been logged by Active Directory somehow... what if your pentesters weren't actually exploiting a flaw in your application at all, but were instead using a very well-known flaw in Kerberos itself to enumerate usernames? Kerberos itself contains what I would consider a design flaw in which an attacker can attempt thousands and thousands of "pre-authentication" attempts (i.e. a brute force attack) and the KDC will respond differently depending on whether the user account exists or not. This is not Active Directory-specific behavior, but applies just as well to MIT Kerberos, Heimdal, etc. The KDC will respond with KDC_ERR_PREAUTH_REQUIRED if a valid username was presented with no pre-auth data, even without attempting an actual authentication. In this way you can enumerate usernames from a KDC. But because the attacker (or the tool that the attacker is using such as KrbGuess - because pentesters are at their best when they're using other people's tools,) does not have to continue on to a full authentication attempt, nothing is logged because no actual authentication was attempted! Now, on to your next question: 2) If not, what is the best way to monitor and actively detect this type of attack in the future (Hopefully without having to buy too much new equipment). A couple of things. First, there are paid, enterprise-grade products that are designed to detect these sorts of attacks (among much else.) Many vendors offer such products, and product recommendations are off-topic for Serverfault, but suffice it to say that they are out there. Many of these products work by requiring you to configure port mirroring between your domain controllers and these "data collectors" so that they see and analyze literally each and every packet that enters or exits your domain controllers. (Sorry, that kinda' falls in to your "without buying too much new stuff" clause.) Another thing that might help you is the registry entry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\Kerberos\Parameters LogLevel = 1 Documented here. If you enable this registry entry, you should get flooded with events in your Security event log about Kerberos errors that mention that Kerberos pre-authentication is required. An example of such an event: A Kerberos Error Message was received: on logon session DOMAIN\serviceaccount Client Time: Server Time: 12:44:21.0000 10/9/2012 Z Error Code: 0x19 KDC_ERR_PREAUTH_REQUIRED Extended Error: Client Realm: Client Name: Server Realm: DOMAIN Server Name: krbtgt/DOMAIN Target Name: krbtgt/DOMAIN@DOMAIN Error Text: File: e Line: 9fe Error Data is in record data. But this may or may not help you if it doesn't specify where exactly the tsunami of Kerberos requests are coming from. This leads us back to those enterprise intrusion detection products that I mentioned earlier. And dont't forget Windows Event Forwarding that can have your servers forwarding events to a centralized location to be analyzed by whatever tool you may have at your disposal. This entire answer has so far been predicated on the Kerberos protocol, which I can't even really take for granted because you gave so little detail in your post. Nevertheless, I hope this helps at least a little.
{ "pile_set_name": "StackExchange" }
Q: How to use multiple password in php? I have a password protected webpage with one password. But, I want to use multiple passwords on that webpage... I'm very new to PHP... So, can anyone give me some advice on how to do this! Thanks in Advance! here is the code I'm using: <?php $password = "anything"; ?> on that code, I want to use "anything" & also use "mypass" as password same time! I just use this code for multiplying the pass. but, won't work! <?php $password = "anything" + "mypass"; ?> & the full code is: <?php if (isset($_POST["password"]) && ($_POST["password"]=="$password")) { ?> ### anything to hide before password given! <?php } else { if (isset($_POST['password']) || $password == "") { print "<p align=\"center\"><font color=\"red\"><b>Wrong Password !!!</b><br>Please enter the correct Password</font></p>";} print "<form method=\"post\"><p align=\"center\"><b>Please enter the Password</b><br/><br/>"; print "<b>Password </b><input class=\"box\" name=\"password\" type=\"password\" maxlength=\"10\"><input class=\"button\" value=\"Download\" type=\"submit\"></p></form>"; } ?> A: I think you want to do this $passwordList = ['password','secretPassword','anything']; if (isset($_POST["password"]) && in_array($_POST["password"], $passwordList)) { // do protected stuff here } BUT. THERE IS A BIG BUT NEVER EVER STORE PASSOWRDS IN CODE. Use a database for this. I recommend you to follow there tutorials from Laracasts to get more familiar with PHP
{ "pile_set_name": "StackExchange" }
Q: How to make cargo enter the correct path to source files of stdlib while adding debuginfo to exectuable I am debugging a rust program but whenever I try to step into any standard library function, gdb (or lldb) can't find stdlib source files, giving error like this: /rustc/3c235d5600393dfe6c36eeed34042efad8d4f26e/src/libcore/slice/mod.rs: No such file or directory. Steps to reproduce: cargo new test test/src/main.rs: fn main() { let a:Vec<char> = Vec::new(); } $ cd test $ cargo build $ rust-gdb target/debug/test ... (gdb) b main.rs:1 Breakpoint 1 at 0x4a04: file src/main.rs, line 2. (gdb) r Starting program: /home/xyz/code/rust/test/target/debug/test [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1". Breakpoint 1, test::main () at src/main.rs:2 2 let a: Vec<i32> = Vec::new(); (gdb) s alloc::vec::Vec<T>::new () at /rustc/3c235d5600393dfe6c36eeed34042efad8d4f26e/src/liballoc/vec.rs:318 318 /rustc/3c235d5600393dfe6c36eeed34042efad8d4f26e/src/liballoc/vec.rs: No such file or directory. A: In case you are running in vscode on windows you can add the following to your launch.json: "sourceFileMap": { "/rustc/3c235d5600393dfe6c36eeed34042efad8d4f26e": "${env:USERPROFILE}\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\src\\rust" } For further reference see: https://users.rust-lang.org/t/solved-how-to-step-into-std-source-code-when-debugging-in-vs-code/25319/6
{ "pile_set_name": "StackExchange" }
Q: How is the the law of chemical equivalence defined and what are its limitations? I've heard that the law of chemical equivalence states that the gram equivalence of each of the reactants equals the gram equivalence of each of the products. But I'm facing difficulties in understanding double titrations. Moreover, this doesn't work for equations where the n-factor of all the reactants and products don't match. Let's take an example: $$\ce{KIO3 + KI + H2SO4 \to I2 + K2SO4 + H2O}$$ Here, the gram equivalence of $\ce{H2O}$ is $2$ which should match with that of $\ce{KIO3}$. But the gram equivalence of $\ce{KIO3}$ is $5$. Similarly, $\text{g.eq}_{\ce{H2SO4}} \neq \text{g.eq}_{\ce{I2}}$ and so on. When the n-factors don't match, the gram equivalents don't match. Here, we can consider gram equivalent to be $\text{number of moles} \times \text{n-factor}$. Again, this n-factor is what is posing a problem. Can someone define the Law of Equivalence and state its limitations because of which I seem to find problems as I've mentioned above? A: Basically the law of equivalence wants you to balance the equivalents that are involved in your reaction. I'd like you to view you reactions in two parts, the oxidation and reduction halves. I see: $$\begin{align} \ce{I- -> I2} \tag{oxidation} \\ \ce{IO3- -> I2}\tag{reduction} \end{align}$$ In other words, we've just discovered a (reverse disproportionation?) comproportionation reaction. The change in the oxidation state of iodine in the oxidation part is $-1 \to 0 $ ($\Delta_{o.s.} = 1$) and for the reduction half it's $+5 \to 0$ ($\Delta_{o.s.} = 5$). So far so good. Usually, the questioner would provide you with the number of moles of each species and you're done with number of moles times the n-factor. Nevertheless, let's try to give it a shot. I'm balancing this equation: $$\ce{1KIO3 + 5KI + 3H2SO4 \to 3I2 + 3K2SO4 + 3H2O}$$ This means for $1$ mole of $\ce{KIO3}$ to react, you'll need $5$ moles of $\ce{KI}$. As this is a proportion, converting it to an absolute value, I'd say you've $1n$ moles of $\ce{KIO3}$ and $5n$ moles of $\ce{KI}$. So if I try to equate the gram-equivalents, I'll have $1n \times 5 = 5n \times 1$. In other words, $\text{Eq.}_{\ce{KIO3}} = \text{Eq.}_{\ce{KI}}$ I've heard that the law of chemical equivalence states that the gram equivalence of each of the reactants equals the gram equivalence of each of the products. Law of equivalence is even more fun, for a balanced chemical reaction: $$ \ce{aA + bB -> cC + dD}$$ Equivalents of every species will be equal. Mathematically, Equivalents of A = Equivalents of B = Equivalents of C = Equivalents of D will hold. Why aren't the gram equivalents of $\ce{H2SO4}$ equal to that of water? You need to strip your equation of the spectating species. For instance $\ce{H2SO4}$ is primarily here because it acts as a medium-provider, it makes the solution acidic. Neither $\ce{SO4^2-}$ nor $\ce{H+}$ underwent any oxidation/reduction so applying the equivalent concept makes no sense in this case.
{ "pile_set_name": "StackExchange" }
Q: Is There a Better Replacement for ExceptionShielding? Our company is making the switch from Microsoft.Practices.Enterprise.Library logging and exception handling to using Log4Net. I removed all of the standard logging and exception handling calls, replacing them with the Log4Net equivalents, but when I removed the Practices Dlls, I noticed that we were using them for ExceptionShielding: using System; using System.ServiceModel; using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WCF; namespace CRM.WCFServices.LeadIntegration.ServiceContracts { /// <summary> /// Interface for systems external to CRM to interact with outbound calls. /// </summary> [ExceptionShielding("WCF Exception Shielding")] [ServiceContract] public interface IOutboundIntegrationService { #region Contracts [OperationContract] [FaultContract(typeof (Common.Services.WCF.FaultContracts.ServiceFault))] void SendOutboundData(string entityName, Guid entityId, DateTime modifiedOn, Guid modifiedBy, string crmOrganization); #endregion } } The basic question is "How can I safely remove it?" which involves answering most of these questions: What does it do? - From What I've read it allows you to catch any exceptions in your WCF Service before it is returned to the client, allowing you to log the exception and create an exception that doesn't contain any security sensitive information. Is it valid on an Interface (it's not referenced anywhere on the ? Does Log4Net have something similar? A: If I remember correctly, the purpose of the Exception Shielding feature was to Prevent the release of implementation detail across the service boundary, or Allow the developer to be lazy and not add try/catch blocks around all service operations at the service boundary. Make your choice. If my memory is correct, then all you need to do is either turn includeExceptionDetailInFaults to false in the web.config, or to put try/catch blocks around your service methods: try { // service code } catch (Exception ex) { // Log the exception throw new FaultException("Unknown service failure"); }
{ "pile_set_name": "StackExchange" }
Q: Disable button works first time but not after pressed once, how can I fix this? HTML $(document).ready(function() { $("#inputGroupSelect02").change(function() { var str = ""; if ($("#inputGroupSelect02 option:selected").val() == '') { $('#button').attr('disabled', 'disabled'); } else { $('#button').removeAttr('disabled'); } }); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="input-group mb-3"> <select class="custom-select" id="inputGroupSelect02"> <option selected>Choose how many columns you need</option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="4">Four</option> <option value="5">Five</option> <option value="6">Six</option> </select> <div class="input-group-append"> <label class="input-group-text" for="inputGroupSelect02">Columns</label> </div> </div> <div class="input-group mb-3"> <select class="custom-select" id="inputGroupSelect03"> <option selected>Choose how many rows you need</option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="4">Four</option> <option value="5">Five</option> <option value="6">Six</option> </select> <div class="input-group-append"> <label class="input-group-text" for="inputGroupSelect03">Rows</label> </div> </div> <button type="button" class="btn btn-success" onclick="createTable()" id="button" disabled="disabled"> Insert </button> The function works in the beginning, the button is disabled until I choose the option. But as soon as I press INSERT and the table is inserted, the button doesn't become Disabled anymore until I refresh the page. How could I fix this? Thank you! UPDATE WITH WHAT TABLE DO. function createTable(){ $('#myTable').empty(); var rn = $('#inputGroupSelect03').val(); var cn = $('#inputGroupSelect02').val(); for(var r=0;r<parseInt(rn,10);r++){ var x=document.getElementById('myTable').insertRow(r); for(var c=0;c<parseInt(cn,10);c++) { var y= x.insertCell(c); y.innerHTML="<img src='SOURCE IMG HERE' alt='hello'/>"; $("#myTable tr td").rotatable({snap:true }); $("#myTable tr td ").draggable({ appendTo: "#droppable", containment: ".chart-area", cancel:false, start: function(event, ui) { c.tr = this; c.helper = ui.helper; } }); jQuery('#inputGroupSelect03').get(0).selectedIndex = 0; jQuery('#inputGroupSelect02').get(0).selectedIndex = 0; } } } I have updated the question with the "table code and what it does" since I've been asked. A: If you are using jQuery never ever use an onevent attribute: <button onclick='fnc()'> // Use this instead $('#button').on('click', function() {createTable()}); On the first <option> add value="" to each: <option selected value=''>Choose how many columns you need</option> <option selected value=''>Choose how many rows you need</option> Use the following control statement so that the button will only be enabled if both <select> have a value*: if ($("#inputGroupSelect02").val() === '' || $("#inputGroupSelect03").val() === '') {... jQuery considers a HTML attribute a property once it's established so use this: $('#button').prop('disabled', false); *Also don't use the selected <option> to get a value target the <select> (ex. $('select').val()) Demo $(document).ready(function() { $('#button').on('click', function(e) { var rows = Number($("#inputGroupSelect02").val()); var cols = Number($("#inputGroupSelect03").val()); createTable(rows, cols); $(".custom-select").val(''); $('#button').attr('disabled', true); }); $(".custom-select").on('change', function() { if ($("#inputGroupSelect02").val() === '' || $("#inputGroupSelect03").val() === '') { $('#button').attr('disabled', true); } else { $('#button').prop('disabled', false); } }); }); function createTable(rows, cols) { var T = $('.table')[0]; var tB = T.tBodies[0]; var rQTY = rows; var cQTY = cols; for (let r = 0; r < rQTY; r++) { var R = T.insertRow(); for (let c = 0; c < cQTY; c++) { var C = R.insertCell(); C.textContent = 'TD'; } } } <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"> <main class='container'> <section class='row'> <form lass="form-inline col-sm-12"> <fieldset class="form-group"> <label class="input-group-text input-group col-sm-6" for="inputGroupSelect02">Rows</label> <select id="inputGroupSelect02" class="custom-select col-sm-6"> <option selected value=''>Choose how many rows you need</option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="4">Four</option> <option value="5">Five</option> <option value="6">Six</option> </select> </fieldset> <fieldset class="form-group"> <label class="input-group-text input-group col-sm-6" for="inputGroupSelect03">Columns</label> <select id="inputGroupSelect03" class="custom-select col-sm-6"> <option selected value=''>Choose how many columns you need</option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="4">Four</option> <option value="5">Five</option> <option value="6">Six</option> </select> </fieldset> <button id="button" class="btn btn-success float-right" type="button" disabled>Insert</button> </form> </section> <hr> <section class='row'> <figure class='table-responsive'> <table class='table table-hover'> <tbody></tbody> </table> </figure> </section> </main> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
{ "pile_set_name": "StackExchange" }
Q: notification.confirm callback not firing phonegap iOS I'm using Phonegap (Cordova) v1.9, and this app is solely for iPhone4+ use. I've tried the two methods below, on their own and simultaneously. Phonegap's deviceready event has been fired previous to this code. I'm using the iPhone configuration utility to watch the console, but I'm not getting anything from the code below. Also, I'm using Sencha Touch (v1.1) and jQuery. No conflicts noticed throughout the app. Please help? function onConfirmCallback(button){ console.log("onConfirmCallback"); console.log(button); } var toConfirm = navigator.notification.confirm("You don't have a pincode set.\nWould you like to set one now?", onConfirmCallback, "Pincode", "Yes,No"); toConfirm.onAlertDismissed = function(index, label){ console.log("onAlertDismissed"); console.log(index); } A: Have you tried looking for exceptions to see what might be happening? try { var toConfirm = navigator.notification.confirm("You don't have a pincode set.\nWould you like to set one now?", onConfirmCallback, "Pincode", "Yes,No"); toConfirm.onAlertDismissed = function(index, label) { console.log("onAlertDismissed"); console.log(index); } } catch (ex) { console.log(ex.message); } Edit: The example mentioned in the comment below (from https://groups.google.com/group/phonegap/browse_thread/thread/126f56f4e296e555) is for PhoneGap 0.9.2. I have not seen any examples for v1.3 where the confirm function returns an object as your using with 'toConfirm'. Maybe that is causing your problem. Have you tried the following (removing all other code to do with toConfirm to simplify the problem)? navigator.notification.confirm("You don't have a pincode set.\nWould you like to set one now?", onConfirmCallback, "Pincode", "Yes,No"); http://docs.phonegap.com/en/1.3.0/phonegap_notification_notification.md.html#notification.confirm Also, is there any reason your not using a newer version of PhoneGap (Cordova)?
{ "pile_set_name": "StackExchange" }
Q: JS: Calculating values that have dot and comma (i.e 1.000,00) I have a script using jQuery which calculates currency. It works fine, but when I write a value greater than 999,99, it returns a value with error when I use a mask and convert the result to money format. How can I fix that? UPDATED $(document).ready(function() { $('.money').mask("#.##0,00", {reverse: true}); }); accounting.settings = { currency: { symbol : "", // default currency symbol is '$' format: "%s%v", // controls output: %s = symbol, %v = value/number (can be object: see below) decimal : ",", // decimal point separator thousand: ".", // thousands separator precision : 2 // decimal places }, number: { precision : 0, // default precision on numbers is 0 thousand: ".", decimal : "," } } function calc(){ var plano = parseFloat($("#regimento").val().replace(/,/g, '.')); var gasto = parseFloat($("#gasto_contabilidade").val().replace(/\./g, ',').replace(/,/g, '.')); var meses = parseInt( $("#meses").val()); var resultado_gasto = parseFloat(gasto * meses); var resultado_plano = parseFloat(plano * meses); var result = resultado_gasto - resultado_plano; result = accounting.formatMoney(result); console.log(result) } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.js"></script> <script src="http://dubsolucoes.com.br/razonet/wp-content/themes/razonet_wp/assets/javascript/vendor/accounting.min.js"></script> <select name="" id="regimento" class="select"> <option value="19,90">MEI</option> <option value="85,90">SIMPLES SERVIÇO</option> <option value="199,90">SIMPLES COMÉRCIO E INDÚSTRIA</option> </select> <input id="gasto_contabilidade" type="text" class="money" value="100000"> <select id="meses" class="select"> <option value="12">12</option> <option value="13">13</option> </select> <input type="button" onclick="calc()" value="Calculate"> A: FIX: I solve the problem removing the dot before calculate it var gasto = $("#gasto_contabilidade").val().replace(".", ''); Thanks by helping guys! $(document).ready(function() { $('.money').mask("#.##0,00", {reverse: true}); }); accounting.settings = { currency: { symbol : "", // default currency symbol is '$' format: "%s%v", // controls output: %s = symbol, %v = value/number (can be object: see below) decimal : ",", // decimal point separator thousand: ".", // thousands separator precision : 2 // decimal places }, number: { precision : 0, // default precision on numbers is 0 thousand: ".", decimal : "," } } function calc(){ var gasto = $("#gasto_contabilidade").val().replace(".", ''); // FIX plano = parseFloat($("#regimento").val().replace(/,/g, '.')); gasto = parseFloat(gasto.replace(/\./g, ',').replace(/,/g, '.')); var meses = parseInt( $("#meses").val()); var resultado_gasto = parseFloat(gasto * meses); var resultado_plano = parseFloat(plano * meses); var result = resultado_gasto - resultado_plano; result = accounting.formatMoney(result); console.log(result) } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.js"></script> <script src="http://dubsolucoes.com.br/razonet/wp-content/themes/razonet_wp/assets/javascript/vendor/accounting.min.js"></script> <script> </script> <select name="" id="regimento" class="select"> <option value="19,90">MEI</option> <option value="85,90">SIMPLES SERVIÇO</option> <option value="199,90">SIMPLES COMÉRCIO E INDÚSTRIA</option> </select> <input id="gasto_contabilidade" type="text" class="money" value="100000"> <select id="meses" class="select"> <option value="12">12</option> <option value="13">13</option> </select> <input type="button" onclick="calc()" value="Calculate">
{ "pile_set_name": "StackExchange" }
Q: Reference to handsontable grid in the onChange event onChange event does not include a reference to the grid. Almost all of the examples have the grid id hard-coded in the event handlers. I have a use case with multiple grids on a page. Is there a way to get to the id of the grid from the events? A: Fixed here: https://github.com/warpech/jquery-handsontable/issues/152
{ "pile_set_name": "StackExchange" }
Q: How can I access UserId in ASP.NET Membership without using Membership.GetUser()? How can I access UserId in ASP.NET Membership without using Membership.GetUser(username) in ASP.NET Web Application Project? Can UserId be included in Profile namespace next to UserName (System.Web.Profile.ProfileBase)? A: Try this: MembershipUser CurrentUser = Membership.GetUser(User.Identity.Name); Response.Write("CurrentUser ID :: " + CurrentUser.ProviderUserKey); A: Is your reason for this to save a database call everytime you need the UserId? If so, when I'm using the ASP.NET MembershipProvider, I usually either do a custom provider that allows me to cache that call, or a utility method that I can cache. If you're thinking of putting it in the Profile, I don't see much reason for doing so, especially as it also will still require a database call and unless you are using a custom profile provider there, it has the added processing of parsing out the UserId. If you're wondering why they did not implement a GetUserId method, it's simply because you're not always guaranteed that that user id will be a GUID as in the included provider. EDIT: See ScottGu's article on providers which provides a link to downloading the actual source code for i.e. SqlMembershipProvider. But the simplest thing to do really is a GetUserId() method in your user object, or utility class, where you get the UserId from cache/session if there, otherwise hit the database, cache it by username (or store in session), and return it. For something more to consider (but be very careful because of cookie size restrictions): Forms Auth: Membership, Roles and Profile with no Providers and no Session A: I decided to write authentication of users users on my own (very simple but it works) and I should done this long time ago. My original question was about UserId and it is not available from: System.Web.HttpContext.Current.User.Identity.Name
{ "pile_set_name": "StackExchange" }
Q: One-point compactification problem 2 I know that the one-point compactification of $X,$ a topological space, is $Y=X\cup\{\infty\}$ and $\text{Top}_Y=\text{Top}_X\cup\{Y\setminus K: K $ compact in $ X \}.$ Question, is $Y$ compact? My try, write $Y=(Y\setminus K)\cup K$ for $K$ compact in $X$. First component is open by definition, $K$ is compact so we can cover it by a finite number of open sets in $X,$ so open sets in $Y.$ Thus we cover $Y$ by a finite number of open sets. Is this correct? A: To prove compactness you have to start from an arbitrary open cover of the space. If you exhibit a finite open cover it is not enough (every space $X$ would be compact taking the finite open cover $U_1=X$). To prove the one-point compactification $Y$ of $X$ is compact we start from fixing an oper cover $A_i$ of $Y$: now we have to find a finite subcover of $A_i$. $A_i$ cover $Y$ so $\exists j$ such that $\infty \in A_j $. $\bigcup_{i \ne j} A_i$ is an open cover of $Y \setminus A_j$ which is compact (see below), let $A_1, ...,A_n$ finite subcover of $Y \setminus A_j$. We have that $A_j \cup A_1,...,A_n$ is a finite subcover of $Y$. Added: $Y \setminus A_j$ is compact because is an open set which contains $\infty$ so it is of the form $Y \setminus K=Y \cap K^c$ with $K$ compact in $X$. Now $Y \setminus A_j=Y \cap A_j^c=Y \cap Y^c \cap K=K $
{ "pile_set_name": "StackExchange" }
Q: How to Sort Output from several Log Files by date I have got output from several different log files: logfile3 2010/07/21 15:28:52 INFO xxx 2010/07/21 15:31:25 INFO xxx 2010/07/21 15:31:25 DEBUG xxx logfile1 2010/07/21 19:28:52 INFO xxx 2010/07/21 19:31:25 INFO xxx 2010/07/21 19:31:25 DEBUG xxx logfile2 2010/07/21 13:28:52 INFO xxx 2010/07/21 13:31:25 INFO xxx 2010/07/21 13:31:25 DEBUG xxx I would like to sort this output by date, but keep the name of the logfile above the log lines, so it should look like: logfile2 2010/07/21 13:28:52 INFO xxx 2010/07/21 13:31:25 INFO xxx 2010/07/21 13:31:25 DEBUG xxx logfile3 2010/07/21 15:28:52 INFO xxx 2010/07/21 15:31:25 INFO xxx 2010/07/21 15:31:25 DEBUG xxx logfile1 2010/07/21 19:28:52 INFO xxx 2010/07/21 19:31:25 INFO xxx 2010/07/21 19:31:25 DEBUG xxx Do you have any idea how to sort output like this with bash commands, sed or awk? Thanks a lot! UPDATE: This is the source of the output for i in $( find log/ -iname *debug*.log -size +0 );do if [ `grep -c 'ERROR' $i` -gt 0 ];then echo -e "\n$i" grep 'ERROR' --color=auto -A 5 -B 5 $i fi done Martin A: Thank you all. I improved script from Dennis Williamson to sort errors by date. Each log file with error inside is saved in file named by the timestamp of last error occured. These files are later sorted and put together. There may be cleaner solutions for that than to use of temp files. find log/ -iname "*debug*.log" -size +0 | while read -r file do if grep -qsm 1 'ERROR' "$file" then echo -e "$i \t$file" errors=$(grep 'ERROR' --color=auto -C 5 "$file") #get the timestamp of last error occured time=$(echo $errors | head -n 1 | awk '{print $1" "$2}') timestamp=$(date -d "$time" +%s) #save it to temp file echo -e "\n$file\n$errors" > tmp/logs/$timestamp.$i fi let i++ done #put files together rm -f output.txt for i in `ls tmp/logs/*|sort`;do cat $i >> output.txt ; rm $i; done Opinions and suggestions for improvement appreciated!
{ "pile_set_name": "StackExchange" }
Q: My onResume() throws a NullPointerException I am taking accelerometer readings to catch users shaking the phone. When a user shakes the phone, I want to design it to do something. It works fine, but I put in an onPause() method because I don't need the accelerometer detecting any shaking motions when the user isn't within the app, as that would have undesired results. So in the onPause() I unregister the accelerometer from the SensorManager. It was my hope that in onResume() I could re-register the SensorManager, and go about my business. Obviously it isn't quite working that way. I've read the documentation and, honestly, I haven't been able to figure out what is going on. Code: I declare global variable sensorMgr: private SensorManager sensorMgr; Then I register it to the accelerometer: sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE); // Detect if device has accelerometer boolean accelSupported = sensorMgr.registerListener(this, SensorManager.SENSOR_ACCELEROMETER, SensorManager.SENSOR_DELAY_GAME); if (!accelSupported) { // No accelerometer on this device sensorMgr.unregisterListener(this, SensorManager.SENSOR_ACCELEROMETER); } sensorMgr.registerListener(this, SensorManager.SENSOR_ACCELEROMETER, SensorManager.SENSOR_DELAY_GAME); onPause(): protected void onPause() { if (sensorMgr != null) { sensorMgr.unregisterListener(this, SensorManager.SENSOR_ACCELEROMETER); sensorMgr = null; } super.onPause(); } onResume(): protected void onResume() { sensorMgr.registerListener(this, SensorManager.SENSOR_ACCELEROMETER, SensorManager.SENSOR_DELAY_GAME); super.onResume(); } The error: 05-24 14:35:54.058: E/AndroidRuntime(16783): java.lang.RuntimeException: Unable to resume activity : java.lang.NullPointerException I really appreciate any help you guys can give, and thanks in advance! A: sensorMgr is null when you reach onResume(), since you forcibly set it to null in your onPause() method. Reinitialize sensorMgr (getSystemService(...)) before calling registerListener().
{ "pile_set_name": "StackExchange" }
Q: uisegmentedcontrol doesn't detect touch on certain segments I have a uisegmentedcontrol within a horizontally scrolling uiscrollview. The scrollview is working just fine and the content is resized according to the width of the segmentedcontrol. The segmented control detects the touches on those segments that are visible when first displayed. If I scroll to the right I am unable to select the newly displayed segments. The cuttof is not exactly a segment either, its what was initially displayed, like if there was a view clipping it. thanks for the help, i have deselected clip subviews from the scrollview. // creates segmented control to indicate test to show on graph UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:self.labels]; segmentedControl.frame = CGRectMake(15, 41, 285, 30); segmentedControl.autoresizingMask = segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; segmentedControl.selectedSegmentIndex = 0; segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth; [segmentedControl addTarget:self action:@selector(testChange:) forControlEvents:UIControlEventValueChanged]; //checks the length of the text in each segment and asjusts control accordingly int x = 0; segmentWidth = 0.0; for (id segment in [segmentedControl subviews]) { for (id label in [segment subviews]) { if ([label isKindOfClass:[UILabel class]]) { [label setTextAlignment:UITextAlignmentCenter]; [label setFont:[UIFont boldSystemFontOfSize:12]]; CGFloat textWidth = [[segmentedControl titleForSegmentAtIndex:x] sizeWithFont:[UIFont boldSystemFontOfSize:12.0]].width + 20; [segmentedControl setWidth:textWidth forSegmentAtIndex:x]; segmentWidth += textWidth; } } x++; } self.testSegment = segmentedControl; [segmentedControl release]; //adds segmentedcontroll to scrollview, and adjusts contensize [scrollView setContentSize:CGSizeMake(segmentWidth + 45, scrollView.frame.size.height)]; [scrollView showsHorizontalScrollIndicator]; [scrollView addSubview:testSegment]; A: fixed, problem is that I had set the frame of the segmented control before calculating the widths of each segment. segmentedControl.frame = CGRectMake(15, 41, segmentWidth+20, 30); before self.testSegment = segmentedControl;
{ "pile_set_name": "StackExchange" }
Q: Grandstream GXP2000 unresponsive I have two Grandstream GXP2000 hardphones that power on (the LEDs all come on green), but the display is blank, and the switch doesn't recognize the phones as being connected. In the past, this has happened, except the phones still responded to the network, so I was able to reboot them using the web interface, and they worked again. Simply unplugging it, and plugging it back in doesn't help. I can't reset it to the factory settings, because the display is blank. I am fairly certain that the phone is the problem, since I have plugged known good phones into the same power and network connections, and they worked. Likewise, the bad phones connected to known-good power and network don't work. From what I have read online, it sounds like this might be a common problem, but I thought I'd ask here to see if anyone knows any tricks. A: From my experience, the GXP handsets were the worst I've ever used. I found much better results using their ATA converter and a cheap £5 handset. I had problems with the shocking web interface not loading, phones not registering, NAT issues, STUN issues all sorts. May seem slightly ostentatious but I'd replace them all for SPA941 or 942. You'll have much more fun using them than trying to keep them online :)
{ "pile_set_name": "StackExchange" }
Q: Need to store array of an array of class objects in View Controller An iPhone question for you guys! I have an NSURLConnection that downloads XML from a server and processes it into an array which is a part of another array. I have no way of knowing how many objects I will need, so I cannot allocate an NSArray beforehand. My question is: Would it be better to create the parent array as an NSArray at the class level and allocate it after I store the data in a temporary NSMutableArray or just make the NSMutableArray at class level? It is worth noting that I do not need to modify the array other than to release it at the end of the program run. A: I don't think it really matters. I'm reading the Beginning iPhone 3 Development book at the moment, and usually loading the data is done like this: You'd have an NSArray property : @interface { ... NSArray *listOfObjects; ... } @property (nonatomic, retain) NSArray *listObObjects; ... Then you create an NSMutableArray, load your data and set the property: NSMutableArray *array = [[NSMutableArray alloc] init]; // ? // load the XML into array here ... self.listOfObjects = array; [array release]; listOfObjects would then be treated as an NSArray (immutable) although it actually would be an NSMutableArray.
{ "pile_set_name": "StackExchange" }
Q: Laplace transforms: Convolution Find $$1*1*1*\cdots*1\quad n\,\,\text{ factors}$$ that is, a function $f(t)=1$ convolution with itself for a total of $n$ factors. Would anyone mind helping me? I have no idea what I should do. Also, if we define $g(t) = t$, what is $g*g*g$? A: Working from the definition of convolution, $(f*g)(t):=\int_0^t f(s)g(t-s)\,ds$, and using the fact that $*$ is associative, we see \begin{align*} 1*1&=\int_0^t 1\cdot 1\,ds=t\\ 1*1*1&=(1*1)*1=t*1=\int_0^t s\,ds={t^2\over 2}\\ 1*1*1*1&=(1*1*1)*1={t^2\over 2}*1=\int_0^t {s^2\over 2}\,ds={t^3\over 3\cdot 2}\\ 1*1*1*1*1&=(1*1*1*1)*1={t^3\over 3\cdot 2}*1=\int_0^t {s^3\over 3\cdot 2}\,ds={t^4\over 4\cdot3\cdot 2}\\ \vdots\\ \underbrace{(1*1*\cdots*1)}_{n\text{ times}}&={t^{n-1}\over (n-1)!}. \end{align*} A: The Laplace Transform is $$\mathcal{L}(1)^n=\frac{1}{s^n}=\frac{(n-1)!}{s^n}/(n-1)!=\mathcal{L}(x^{n-1})/(n-1)!$$ so it would be $$1*1*\ldots*1=\frac{x^{n-1}}{(n-1)!}$$ Alternatively, note that $$1*(cx^a)=\int_0^x (1)ct^a\,\mathrm{d}t=c\frac{x^{a+1}}{a+1}$$ so by induction you would get $$1*1=x \\ 1*x=\frac{x^2}{2} \\ \vdots \\ 1*\cdots *1=\frac{x^{n-1}}{(n-1)!}$$ A: For two functions $f(t), g(t)$ $$\mathcal{L}((f*g)(t))=\mathcal{L}(f(t))\mathcal{L}(g(t))$$Since $\displaystyle \mathcal{L}(1(t))=\frac{1}{s}$ it follows that $$\mathcal{L}(\underbrace{1*1*\cdots*1}_{n \ \mbox{times}})=\frac{1}{s^n}$$ Now, $$\mathcal{L}(t^{n-1})=\frac{(n-1)!}{s^n}$$ hence comparing, $\displaystyle \underbrace{1*1*\cdots*1}_{n\ \mbox{times}}=\frac{t^{n-1}}{(n-1)!}$
{ "pile_set_name": "StackExchange" }
Q: Custom FOSUserBundle Login Template using Bootstrap I've installed Symfony2, FOS User Bundle and Twitter Bootstrap. Then I setup the /app/Resources/FOSUserBundle/views/layout.html.twig template to override FOSUserBundle to use my site template. It all works if I have a link to /login on the homepage. Now I want to implement a template like the hero template where the login form is part of the main template. The closest I've got is to use this in the main template: {% render controller("FOSUserBundle:Security:login") %} I can override the layout html to not extend main template, but this removes all styling from /login Any ideas how I can handle both scenarios? A: You were almost there :) you can include the login form in any other template using the render function. {% render controller("FOSUserBundle:Security:login") %} ... you just have to create app/Resources/FOSUserBundle/views/Security/login.html.twig and ommit the wrapping {% block fos_user_content %} found in FOSUserBundle's login.html.twig in order to have it return the form directly: {% if error %} <div>{{ error|trans }}</div> {% endif %} <form action="{{ path("fos_user_security_check") }}" method="post"> <input type="hidden" name="_csrf_token" value="{{ csrf_token }}" /> <label for="username">{{ 'security.login.username'|trans }}</label> <input type="text" id="username" name="_username" value="{{ last_username }}" required="required" /> <label for="password">{{ 'security.login.password'|trans }}</label> <input type="password" id="password" name="_password" required="required" /> <input type="checkbox" id="remember_me" name="_remember_me" value="on" /> <label for="remember_me">{{ 'security.login.remember_me'|trans }}</label> <input type="submit" id="_submit" name="_submit" value="{{ 'security.login.submit'|trans }}" /> </form> Then adjust it to fit your template. A: Richard Miller's post has helped me achieve what I was trying to do. http://richardmiller.co.uk/2013/02/18/symfony2-ajax-and-full-page-templates/ {% extends app.request.attributes.get('partial') ? '::ajax-layout.html.twig' : '::full-layout.html.twig' %} I couldn't get app.request.partial to work, and decided choosing based on xmlRequest wasn't ideal.
{ "pile_set_name": "StackExchange" }
Q: Difference between "fluency" and "fluidity" Fluent seems to most commonly refer to language mastery, but in that context isn't it just saying that its delivery is fluid? If so, am I communicating something different when using one over another or are they essentially interchangeable? A: I will compare the adjectives fluent and fluid. The etymologies of the words are shared and so is one of the meanings: smooth and unconstrained in movement So, when you speak about movement (literary or as metaphor), it is interchangeable. Otherwise it is not: fluent - easy and graceful in shape - expressing yourself readily, clearly, effectively fluid - characteristic of a fluid; capable of flowing and easily changing shape - subject to change; variable - affording change (especially in social status) - in cash or easily convertible to cash NOTE: If you read the etymology entry, you will find that fluent was Used interchangeably with fluid in Elizabethan times. A: As a second language teacher, I constantly run into theories about fluidity and fluency. Fluency is a more complicated issue than fluidity. Fluency includes the skill of being able to express specific content (often spontaneously) with ease. Fluidity has more to do with speed of speech, intonation, rhythm. For example, a person who pauses and hesitates a lot would not have achieved fluidity. One can be fluent without being fluid, and one can be fluid without being fluent. Fluidity is more attached to style and delivery, and fluent is more attached to content and ease of communication. Fluidity is often a sub-category of fluency.
{ "pile_set_name": "StackExchange" }
Q: CSS flex-wrap how to make the height do not stretch There are big gaps between box3, box1 and box4, box6 How to get rid of the gap? so each box could have the dynamic height? .wrap { display: flex; align-items: baseline; align-content:flex-start; justify-content: space-between; flex-wrap: wrap; background-color: lightblue; } .box { display: flex; background-color: tomato; box-sizing: border-box; border: 1px solid #C4C4C4; height: 100px; width: 45%; margin-top: 15px; } .box1, .box4 { height: 20px; } <div class="wrap"> <div class="box box1">box1</div> <div class="box box2">box2</div> <div class="box box3">box3</div> <div class="box box4">box4</div> <div class="box box5">box5</div> <div class="box box6">box6</div> </div> Here is the desired layout. Thanks A: The default direction of flex is row, and when you use flex-wrap: wrap push overflowed element downed to another row, and the row height will default always equal to the highest element of that row, that why you seeing the element having that gap. This can be done if you change the flex direction to column and give the wrap element a fixed height so it push overflowed element to it right, from top to bottom. .wrap { /*Added these*/ height: 300px; flex-direction: column; /*-----------*/ display: flex; align-items: baseline; align-content: space-around; flex-wrap: wrap; background-color: lightblue; } .box { display: flex; background-color: tomato; box-sizing: border-box; border: 1px solid #C4C4C4; height: 100px; width: 45%; margin-top: 15px; } .box1, .box5 { height: 20px; } <div class="wrap"> <div class="box box1">box1</div> <div class="box box2">box2</div> <div class="box box3">box3</div> <div class="box box4">box4</div> <div class="box box5">box5</div> <div class="box box6">box6</div> </div>
{ "pile_set_name": "StackExchange" }
Q: Datanucleus: moving from @Transactional to non-transactional I am using Datanucleus, JDO and Spring's declarative @Transactional management woven with Aspect-J. But when a 'normal' method gets a persistent object from a @Transactional method, the object's state will become transient (the persistence manager seems to be removed) and the object is no longer persistent. Example: public class Example { public void test() throws Exception { Login l = getLogin(); JDOHelper.getObjectState(l); // transient instead of persistent l.getSomeOtherPersistentObj().doStuff(); // NullpointerException :( } @Transactional private Login getLogin() { // do transactional stuff here // .. return dao.find(Login.class, 1); } } Why is this and how can I fix it without adding @Transactional in places where transactions are not needed? The following does (obviously) work so this indicates that a transactional as well as a non-transactional connection can be made: A @Transactional method calls a @Transactional method A @Transactional method calls a normal method A normal method calls a normal method If I call dao.refresh(l), I get: 'Object with id "" is managed by a different Object Manager', so maybe Spring is working on a different persistence manager than the DAO, is this the cause? Here's my spring configuration (it might be relevant): <bean id="pmf" class="org.datanucleus.api.jdo.JDOPersistenceManagerFactory" destroy-method="close"> <property name="connectionDriverName" value="com.mysql.jdbc.Driver"/> ... <constructor-arg> <map> <entry key="datanucleus.autoCreateSchema" value="true" /> </map> </constructor-arg> </bean> <bean id="myPmfProxy" class="org.springframework.orm.jdo.TransactionAwarePersistenceManagerFactoryProxy"> <property name="targetPersistenceManagerFactory" ref="pmf" /> </bean> <bean id="transactionManager" class="org.springframework.orm.jdo.JdoTransactionManager"> <property name="persistenceManagerFactory" ref="myPmfProxy" /> </bean> <bean id="JDODao" class="sw.JDODao"> <property name="persistenceManagerFactory" ref="myPmfProxy" /> </bean> A: It turned out that my objects need to be detachable to do this. Iv'e added (detachable="true") to my @PersistenceCapable annotations and set the following datanucleus options: <entry key="datanucleus.DetachAllOnCommit" value="true" /> <entry key="datanucleus.detachedState" value="all" />
{ "pile_set_name": "StackExchange" }
Q: Simulating mouse-down event on another window from CGWindowListCreate You can list the currently open windows using CGWindowListCreate, e.g: CFArrayRef windowListArray = CGWindowListCreate(kCGWindowListOptionOnScreenOnly|kCGWindowListExcludeDesktopElements, kCGNullWindowID); NSArray *windows = CFBridgingRelease(CGWindowListCreateDescriptionFromArray(windowListArray)); // stuff here with windows array CFRelease(windowListArray); With this you can get a specific window, e.g. a window from Chrome that's somewhere in the background of the current workspace, but not minimized. I also found that you can simulate mouse-clicks anywhere on-screen using CGEventCreateMouseEvent: CGEventRef click_down = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseDown, point, kCGMouseButtonLeft); CGEventPost(kCGHIDEventTap, click_down); Instead of sending this event to the front-most window under this point on the screen, can I send this to a window in background? Or is the only way to temporarily switch to that window (bring it to front), click, and switch back to the previous frontmost window? This post suggests the latter is possible: Cocoa switch focus to application and then switch it back Although I'm very interested in seeing whether this can be avoided, whether we can send mouse-clicks directly to a specific window in background without bringing it into view. I can consider any Objective-C, C, or C++ options for this. A: Finally got this working after finding an alternative to the deprecated GetPSNForPID function: NSEvent *customEvent = [NSEvent mouseEventWithType: NSEventTypeLeftMouseDown location: point modifierFlags: NSEventModifierFlagCommand timestamp:[NSDate timeIntervalSinceReferenceDate] windowNumber:[self.windowID intValue] context: nil eventNumber: 0 clickCount: 1 pressure: 0]; CGEvent = [customEvent CGEvent]; CGEventPostToPid(PID, CGEvent); Didn't realise there was a CGEventPostToPid method instead of CGEventPostToPSN. No need for the ProcessSerialNumber struct.
{ "pile_set_name": "StackExchange" }
Q: Database Design: Multiple join tables or one table with identifying 'table' column I'm designing a database where any content can be tagged and I'm likely to want to be able to select all content with a specific tag. I'm struggling with the following two options and would appreciate some advice. If there's a better way please let me know. Option A Multiple 'many to many' join tables. tag: id tag media: id title src creation media_tags: id media_id tag_id article: id title content creation article_tags: id article_id tag_id Options B A single 'tag reference' table, which uses a 'table' column to identify which table to join to. tag: id tag tag_reference: id row_id tag_id table media: id title src creation article: id title content creation From a maintenance point of view option B seems favorable but considering the SQL query to select all content and don't think it's possible without multiple queries. A: When using Option B, you can't set up foreign keys to the other tables. Thus I would go with Option A and one table for each m:n relation. "From a maintenance point of view option B" – is a nightmare. What happens if you delete an article? All the rows with that row_id will persist in tag_reference table. You always need to update those entries manually.
{ "pile_set_name": "StackExchange" }
Q: NSCache-not always cleaned? I have NSCache in which i am loading from and to- images to be displayed in collection view . When i have to reload data to the collection view, i must clean the cache, because otherwise the collection view will find old data in there and reload it instead of the new data. So before i reload the collection i clean my cache : [self.myCache removeAllObjects]; Which sometimes, is not working, and i still see the old images in the collection view . Is there another way to go all over its values and clean them ? Why is it not being cleared ? Here is how i load and get images from and to : -(UIImage*) imageForIndexPathRow:(NSNumber *) number { return [self.myCache objectForKey:[NSString stringWithFormat:@"cache:%d",[number intValue]] ]; } -(void) setImage:(UIImage*) image forIndexPathRow:(NSNumber *) number { if(image) [self.myCache setObject:image forKey:[NSString stringWithFormat:@"cache:%d",[number intValue]] ]; } EDIT: This is how i check the cache before load image to cell(in another thread) : UIImage *imageToSet=nil; UIImage *cacheImg=[self imageForIndexPathRow:[NSNumber numberWithLong:cell.tag]]; if(cacheImg==nil) { UIImage *image=[UIImage imageWithData:data scale:1]; imageToSet=image; //save to cache [self setImage:image forIndexPathRow:[NSNumber numberWithLong:cell.tag]]; } else imageToSet=cacheImg; A: The problem comes from CollectionView cell reusing you need to implement the else case, like this - (UIImage *)imageForIndexPathRow:(NSNumber *) number { UIImage *cachedImage = [self.myCache objectForKey:[NSString stringWithFormat:@"cache:%d", [number intValue]]]; if (cachedImage) { return cachedImage; } // Otherwise load it from web NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://...yourImageURL"]]; UIImage *loadedImage = [UIImage imageWithData:imageData]; // Cache it back [self.myCache setObject:loadedImage forKey:[NSString stringWithFormat:@"cache:%d", [number intValue]]]; return loadedImage; } and the cellForRow should look like this (my example is on UITableView, but you can port it to CollectionView) - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"YourCellId"]; cell.image = nil; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ UIImage *image = [self imageForIndexPathRow:@(indexPath.row)]; dispatch_async(dispatch_get_main_queue(), ^{ cell.image = image; }); }); return cell; }
{ "pile_set_name": "StackExchange" }
Q: cloning a git repository inside a Docker image failed I'm going to create a Docker image based on ubuntu:18.04 image. There are some python packages listed in a requirements.txt file which should be installed in the image. reportlab==2.7 newrelic==2.98.0.81 pympler==0.4.3 unidecode python-dateutil git+ssh://[email protected]/myproject/myprojects-tools.git@master The command to install them is: pip install -r requirements.txt In the last line when it tries to fetch files from the defined repository, it failes, because the key is not installed in the image. Is it good idea to put the key inside the image or there are better ideas? A: Here you can find examples on how to do this: https://github.com/bmihelac/docker-images-with-private-python-packages-example You basically have two alternatives: ssh keys or deploy/access tokens.
{ "pile_set_name": "StackExchange" }
Q: How to show icons in ActionBar overflow menu? I want to display icon in addition to menu item title in overflow dropdown menu. Is is possible? A: put your menu with property android:showAsAction="always" and in xml file of menu add sub menus under that your menu like this <item android:id="@+id/mainMenu" android:icon="@drawable/launcher" android:showAsAction="always"> <menu> <item android:id="@+id/menu_logout" android:icon="@drawable/log_out" android:title="logout"/> </menu> </item> this will show the icons in menus A: There is actually an easy way to achieve it, since what you see is actually a TextView, so you set a span , for example: final MenuItem menuItem=... final ImageSpan imageSpan=new ImageSpan(this,R.drawable.ic_stat_app_icon); final CharSequence title=" "+menuItem.getTitle(); final SpannableString spannableString=new SpannableString(title); spannableString.setSpan(imageSpan,0,1,0); menuItem.setTitle(spannableString); This will put an icon at the beginning of the menu item, right before its original text. A: Maybe you have the same problem as me. So for me solution was easy if you are using AppCompat just dont use this property: android:showAsAction="always" instead use it like this: <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/option" android:title="@string/option" android:icon="@drawable/option" app:showAsAction="always"> </item> </menu> There is difference in aditional xmlns:app and showAsAction is property of app. Hope it helps someone.
{ "pile_set_name": "StackExchange" }
Q: Version not updated in bean after persist I have a JPA entity Person which has a @Version long version field. I do the following: <<transaction - begin>> person.getId() --> == NULL person.setVersion(1); em.persist(person); person.getId() --> returns 1 (this one is generated inside the persist call) person.getVersion(); --> returns 1 <<transaction - end>> Now if I check the DB, the version = 2, but the bean incorrectly contains 1. I see the id of the person entity gets reflected correctly in the person instance. However, the version remains the one before calling persist(). Why? A: Maybe you are "outside" the specification borders: An entity may access the state of its version field or property or export a method for use by the application to access the version, but must not modify the version value. Only the persistence provider is permitted to set or update the value of the version attribute in the object. (Quote from JPA specification)
{ "pile_set_name": "StackExchange" }
Q: MySQL data fetching without page refresh I've recently finished a prototype for a little Raspberry Pi website. The main page of the site displays current users found in the room (through bluetooth). I wanted this list updated regularly from data in a MySQL table, so no refresh is needed. When someone walks into or out of the room, the webpage shows almost instantly. This is the solution I created: index.html <html> <head> <!-- This page uses jQuery to insert PHP files into HTML divs --> </head> <body> <div class="list-group"> <a href="#" class="list-group-item active"> <h4 class="list-group-item-heading"><u>Present:</u></h4> <div class="list-group" id="list1"> <!-- php will be injected here, and it will create html --> </div> </a> </div> <div class="list-group"> <a href="#" class="list-group-item active"> <h4 class="list-group-item-heading"><u>Absent:</u></h4> <div class="list-group" id="list2"> <!-- php will be injected here, and it will create html --> </div> </a> </div> </body> <script> <!-- references :) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> var timer = setInterval(listLoad, 1000); <!-- Every 1s this function is called... --> function listLoad(){ $(function(){ $("#list1").load("herelist.php"); $("#list2").load("notherelist.php"); }); } </script> </html> herelist.php <!DOCTYPE html> <html> <body> <?php $servername = "localhost"; $username = "xxxx"; $password = "xxxx"; $dbname = "xxxx"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT firstname, lastname FROM room_Data WHERE attendance = 1"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row echo("<div id=\"list1\">") while($row = $result->fetch_assoc()) { echo ("<li><h4 class=\"list-group-item-heading\">". $row["firstname"]. " " . $row["lastname"] . "</h4></li>"); } echo("</div>"); } else { echo (""); } $conn->close(); ?> </body> </html> notherelist.php Same as herelist.php, just the where clause is = 0 instead of = 1 This project isn't for some major production scale, which is why I don't really mind hitting my MySQL server every second requesting a read. I actually like this solution a lot since it was my first time ever injecting PHP through jQuery and I thought it was a neat idea. Is this a good solution for a personal project/school project? Or, is there something I should look into to improve this? A: Personally, I hate having a setInterval in JS code, especially to fetch live updates. I hate it even more when it is used for hitting the server for a database read/write operation, irrespective the size of project. The code you have is quite good, considering that it was your first time. There are quite a few suggestions though. Read on: Instead of having 2 separate files to fetch data of attendance = 0 and attendance = 1, use a single file with a parameter passed via a GET or POST request. Instead of dumping the entire data as HTML, I'd suggest outputting the results as JSON so that it might be of use to other applications, without having to resort to HTML parsers. This helps if you think/plan on providing an API for other users to develop on. Since the data for room_data gets updated with an underlying python application, you can modify it to write the output to a static JSON file and hit this JSON content instead of executing a MySQL query every second. This will help as the browser will get a 304 response status from the server if the JSON was not updated since last fetch. Caching FTW ^_^ Put the external script/stylesheets in head. Since all you need for the MySQL to return is concatenated name string, do so in MySQL itself: SELECT CONCAT(firstname, ' ', lastname) AS 'name' FROM room_Data WHERE attendance = :something Do not use h4 tags for list items. If you follow (1) above, you won't need the (3). I strongly recommend using (3) though.
{ "pile_set_name": "StackExchange" }
Q: javascript multiple AND conditions in IF statement inside for loop javascript I feel stupid because I´m stuck with a basic. I have three set of classes that contains paragraphs and I want to change the background color of each one depending on day (with New Dat.getDay(). I dont know how to mix for loop and if statements for each set of classes correctly. I guess it´s something simple but I missing it! function changecolor() { var d = new Date(); var n = d.getDay(); var weekda = document.getElementsByClassName('weekdays'); var sat = document.getElementsByClassName('saturday'); var dom = document.getElementsByClassName('sun-fer'); for (var i = 0; i < weekda.length && i < sat.length && i < dom.length; i++) if (n > 0 || n < 6) { weekda[i].setAttribute("style", "background-color:#0091ea;color:white;"); } else if (n == 6) { sat[i].setAttribute("style", "background-color:#0091ea;color:white;"); } else { dom[i].setAttribute("style", "background-color:#0091ea;color:white;"); } } } changecolor(); A: You need to group conditions. Read more about Operator precedence for (var i = 0;( (i < weekda.length) && (i < sat.length) && (i < dom.length)); i++){ // your code }
{ "pile_set_name": "StackExchange" }
Q: Pentax MX Bulb Setting, what cable do I need? I recently purchased a Pentax MX and am in the dark as to how I can set it up for long exposures using the bulb setting. I have not come up with any clear answers on google, possibly because this is well-known knowledge when using such old camera. I apologize if so. My question is.. If I were to set the camera to "B" in a situation where a handheld meter says to expose the shot for 20 seconds, how would I go about taking the photo? Are there any electronic releases compatible with the MX that will automatically close the mirror upon 20 seconds, or am I limited to buying a manual cable release, holding the button down, and using a handheld timer to know when to let go? In either case, can anyone recommend me compatible accessories for my Pentax MX? Thank you A: Your Pentax MX is an analog camera. It was designed and built in a time when all photography was analog. The only analog electronics in your Pentax MX is the light meter and associated battery. Everything else is purely mechanical. To release the mechanical shutter of your Pentax camera requires mechanical movement of the shutter button. This can be accomplished without touching the shutter button yourself only with a mechanical cable release. The size of the threads for mechanical shutter cables is near universal. The tapered threads such as are found on the example linked above will fit the vast majority of film cameras with threads in the shutter button produced in the last 60-80 years. The design and use of such a cable release was so universal back in the time your Pentax MX was made that it isn't even mentioned in the fairly detailed Owner's Manual. I suppose it would be theoretically possible to design and built an external digital intervalometer that uses some sort of servo motor to actuate a mechanical cable release. But to the best of my knowledge (which may well be too limited at this point as I have never previously looked for such a device) no such product has ever been commercially offered. This DIY project made something similar but only needed to actuate the shutter with a camera set shutter time. It could probably have been modified to enable bulb mode. Battery capacity on both ends might need to be increased to allow holding the shutter open against the spring loaded shutter button. Keep in mind that long exposure times don't have to be minutely precise at all. The difference between two batches of the same film might be greater than a 1/2 second inaccuracy for a 20 second shot. Also keep in mind that the development of film relies on timed processes that are also subject to the same types of inaccuracies: the technician normally uses a freestanding timer to tell them when to stop the development of the film and it takes a time interval for all of the developer to be rinsed from the film's emulsion. Even when film is developed in an automatic developing machine all of the developer doesn't instantly dry from the film when it is removed from the developer bath before entering the rinse bath. If you're not familiar with the Schwarzschild effect you need to consider the necessary adjustment of exposure times over one second when using analog film. This will have a far greater effect on setting proper exposure with film than the imprecision of using analog mechanical shutter control with an unconnected timer.
{ "pile_set_name": "StackExchange" }
Q: What should I study to 'learn' Comp Sci? [This question was originally asked on Stack Overflow, but recommended to move the question here.] I can't find anything quite like the question I'm about to ask, so please forgive me if there's something just like it already, please feel free to point me in the right direction. It'll take a bit of background explaining too, please forgive me for that. [backstory] Basically, I graduated from University about 18 months ago with a degree in Business Information Systems and Japanese. The Japanese took up half of the degree so the BIS was only joint. I only learned PHP in terms of languages and basically no computing theory - everything was vocational (Networking, programming basics, CMS development, Office and VBA and then loads of Business theory courses). Since this, I decided to teach myself C# and ASP.Net and try to get a position as a programmer. I created an online shop style website and a small CRM application in Windows Forms to both teach myself and build a portfolio, and luckily I managed to snag a developer position. Bad side? I'm the only developer at my company. Now don't get me wrong, in the last year I've learned loads and loads, I did some devpt. before Uni so knew the basics anyway, but it was very much a "learning from books" job - every night. Now then... I am now at a point where I'm building software on a regular basis, making good judgements for time scales, and have even been told my code and methodology are good by other professionals that have been in the game longer than me, and they have offered me jobs. [/backstory] What this whole thing boils down to, is that I now want to study up on the topics I'll have missed by not doing CS. More importantly, could you recommend books / free online courses? I want to learn about Computer Science theory, not just better coding. Thank you! A: Math. You need to be really good at math. Not quite as much because you are likely to encounter the need to solve differential equations in order to write your code, but because you need the same skills it takes to solve math problems to be really good at software engineering. I recommend taking a few upper lever math classes at your local community college. Perhaps a numerical methods or discrete math class first. I took a class in software engineering for my degree in computer science a few years ago that the professor used some of the material from MIT's open course-ware. He used course 6.170. I recommend going through that class and a good course on object oriented programming and especially design patterns. If you still have time and want to learn more, move on to artificial intelligence and theory of computation studies. If I had to to pick a single course that was most helpful in my career as a developer, it would be the studies on design patterns. Because I have a low reputation, I can't post more links. Do a Google search for "gang of four design patterns" for the book that is classically used to teach that subject. Good luck! A: The key here is to try to absorb the concepts, rather than the specifics. For example, rather than learning Java, learn about the Virtual Machine that it brings to the table and how that differs from, e.g. the C# CLR. The kind of topics you want to cover are (in no particular order): Algorithms. How does Bubble Sort compare with QuickSort (QS not always fastest), what is a binary search, etc. Compilers. All modern programming languages have some concept of being compiled from source to bytecode or machine code. It helps to understand how to write efficient code if you know the pain the compiler goes through. Some processor architecture theory may help your understanding - see the Andrew Tanenbaum book. Scale. There are some differences between programming for e.g. a supercomputer versus a phone, even though they may both run the same OS. Find out the differences and challenges, for example, why/behaviour when malloc() fails. Concurrency. With multiple cores, desktop PCs can now actually be running different pieces of code simultaneously. This causes all sorts of issues - locking, race conditions, starvation, etc. Debugging. Get good with tools or instrumenting code to work out how best to fix stuff when it goes wrong, particularly when it's live and you can't reboot/restart Databases. It doesn't matter which database, but an understanding of database organisation and how they work helps. The introductory chapters to most Database books give a good overview - pages, rows, locking, optimism, indices, execution plans, etc. SDLC. Learn the Requirements > Specifications > Design > Code > Build > Test > Commit > QA > Deploy > Maintain lifecycle, regardless of actual project methodology. Methodologies. Look at traditional BUFD, Waterfall, Agile, Scrum, XP, etc. Tools. Other than an editor and compiler, there are lots of tools used in SE practices, from code generators to static analysis. Functional vs Procedural. More and more functional programming constructs are making their way into procedural languages lately - with good reason. Go find out why Lisp/Prolog/Haskell are still in use and how things like F# are taking the concepts forward. There are a ton of resources out there - MSDN's Channel 9, Yahoo!/Google videos, YouTube, VideoJug, etc. If you want to actually keep up with a Comp Sci person, then take a look at any university's course prospectus, to get an idea for what topics they cover in their CS course. Personally, I'd pay more attention to the Software Engineering courses than Computer Science as you have a history of programming but perhaps don't need to learn micro electronics to understand them (in the UK, CS = programming + hardware, SE = programming + theory). A: If you can afford it, get an unlimited subscription to Safari Books Online. You will have access to thousands of computer-related (and other technical) books. Pick a topic: algorithms is a good place to start. Then something on data structures and program design. Object oriented programming. Pick a new language, different from what you already know -- such as Ruby or Python. Browse some books on each subject, and those you like, read in depth. From there, pick some topics which interest you, such as operating systems, compilers, cryptography, image processing, etc.
{ "pile_set_name": "StackExchange" }
Q: Android App Not Install. An existing package by the same name i have lost my old debug.keystore file and i generated a new one, when i build my new apk and i want to update the old one in my phone it show me "Android App Not Install. An existing package by the same name". Can any one help me what should i do? can i modify the debug.keystore with the old sha1 ??? A: Can any one help me what should i do? Uninstall the existing app. can i modify the debug.keystore with the old sha1 ? No.
{ "pile_set_name": "StackExchange" }
Q: CoreData and preload sqlite I am trying to preload sqlite for coredata. I tried tutorials like this and it is okay. http://www.appcoda.com/core-data-preload-sqlite-database/ But, for some part, I am a bit unclear. 1) Is coredata layer is on top on sqlite? Or they have separate database? 2) What is the way of preloading sqlite? Is it like reading sqlite row 1 by 1 and save to core data? Or we ask core data to use sqlite file as base database? if managedObjectContext.save(&error) != true {} //From that example, it read csv file and save to core data.. 3) If it is reading sqlite row 1 by 1, and if I have thousands of row, it will be slow. Can I just make core data point to my sqlite file? Modified If I wrote like this, does this mean I am pointing to my existing sqlite? NSURL *applicationDocumentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; NSURL *storeURL = [applicationDocumentsDirectory URLByAppendingPathComponent:@"test.sqlite"]; NSError *error = nil; [self.persistentStoreCoordinator_busservice addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:@{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES} error:&error] A: 1) Core data is a framework that gives you easy way to store and retrieve data from the data store. Now the data store can be SQLite, xml, binary files or in-memory. 2) You can read and write one by one row (I won't recommend this) and the second one is to have the SQLite structure same as created by your core data and the copy your sqlite to the same place where you core data looks for the sqlite file. 3) Already answered, Yes you can place (copy) your sqlite file in same location (document directory) where your core data looks for sqlite file (defined in AppDelegate)
{ "pile_set_name": "StackExchange" }
Q: Implementing 47degree android-swipelistview for swiping android ListViewItem Actually my goal is to implement a ListViewItem Swipe in android. I have tried it and stackoverflow has several examples which can make your ListViewSwipe. Examples. Simple swipe gesture to activity tutorial? Show button in a list view on swiping one item from that list One point is there everyone is giving the code no one is explaining what is happening. Then I asked question for it Android list view Right / Left swipes like call logs on which @CommonsWare have answered with SwipeListView library which has a smooth flow then the accepted answer. The accepted answer is also working fine I am presently using that only. This is the library http://www.androidviews.net/2013/03/swipelistview/ Which provides you listview like this I have tried more then 50 times to run the sample application provided on github here https://github.com/47deg/android-swipelistview-sample But everytime I am facing new problems. Presently the exception which is coming is 05-22 15:35:19.392: E/AndroidRuntime(980): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.fortysevendeg.android.swipelistview.SwipeListView" on path: /data/app/com.fortysevendeg.android.swipelistview-2.apk I don't know what is happening I have checked the buildpath, libraries are also included asked so many people on stackoverflow chat But haven't got any help. Actually on internet there is not a single tutorial for its implementation I have asked to so many peoples. So I want to know if someone have used this library please write an appropriate answer How to use it preporly So with me other future readers can also take the benefit out of it. Or is there any other library to perform to implement this kind of functionality. As @CommonsWare suggested. I have written an email to the author also to write an tutorial for using it. A: Finally, I've managed to integrate Android-SwipeListView library by 47Degrees into my own application. Works like a charm. Thanks to 47Degrees for writing such a wonderful piece of code. Solution: What doesn't work?! Including JAR as dependency and attrs.xml in res/values OR referencing the SwipeListView library as a lib dependency in your project does not work. What works?! Include following classes in your application package. Be sure to correct the package names in these classes to your package name SwipeListView.java SwipeListViewListener.java SwipeListViewListenerBase.java SwipeListViewTouchListener.java Include following xml into your application res/values folder attrs.xml Now you can define and use SwipeListView as follows <au.com.your.package.SwipeListView xmlns:swipe="http://schemas.android.com/apk/res-auto" android:id="@+id/swipe_listview" android:listSelector="#00000000" android:layout_width="match_parent" android:layout_height="match_parent" swipe:swipeFrontView="@+id/front" swipe:swipeBackView="@+id/back" swipe:swipeActionLeft="reveal" swipe:swipeActionRight="choice" swipe:swipeMode="both" swipe:swipeCloseAllItemsWhenMoveList="true" swipe:swipeOpenOnLongPress="true" swipe:swipeAnimationTime="100" swipe:swipeOffsetLeft="50dp" swipe:swipeDrawableChecked="@drawable/item_selected" swipe:swipeDrawableUnchecked="@drawable/item_unselected" /> Activity code you can use same as displayed in the example on SwipeListView github site. You will need to correct some imports from the code above. In addition, you'll need to have NineOldAndroids by Jake Wharton included as a lib dependency in your project.
{ "pile_set_name": "StackExchange" }
Q: How to solve this equation that contains very similar denominators? How to solve this equation for $x$ in reals, without using theory of complex number? $$\frac{a}{\left(x+\frac{1}{x}\right)^{2}}+\frac{b}{\left(x-\frac{1}{x}\right)^{2}}=1$$ Where $a$ and $b$ is some constants Please write down a step-by-step solution with a good explanation to this equation. I spent a lot of time trying to solve it but could not find an answer. According to desmos, it has four roots: I don't know which title and tags I should use for this question, please edit. A: I would start by doing this: $$ \frac{a}{\left(x+\frac{1}{x}\right)^{2}}+\frac{b}{\left(x-\frac{1}{x}\right)^{2}}= \frac{ax^2}{\left(x+\frac{1}{x}\right)^2 x^2}+\frac{bx^2}{\left(x-\frac{1}{x}\right)^2 x^2}= \frac{ax^2}{\left(x^2+1\right)^2}+\frac{bx^2}{\left(x^2-1\right)^2}=1 $$ Now multiply both sides by $(x^2 + 1)^2 (x^2 -1 )^2$: $$ ax^2 (x^2 -1)^2 + bx^2 (x^2 +1)^2 = (x^2 + 1)(x^2 -1 )(x^2 + 1)(x^2 -1 ) = (x^4 -1 )^2 $$ now set $t= x^2$ and open the parentheses on the left-hand side: $$ at^3 - 2at^2 +at+bt^3 + 2bt^2 +bt = t^4 - 2t^2+1 $$ which is a quartic equation. A: Here is an approach yielding solutions by reducing the issue to solve successive quadratic equations : Let us write the expression under the form : $$\frac{a}{X^{2}}+\frac{b}{X^{2}-4}=1\tag{1}$$ where we have set : $$X=x+\frac{1}{x}\tag{2}$$ Let us rewrite (1) under the form : $$\dfrac{a(X^2-4)+bX^2}{X^2(X^2-4)}=1\tag{3}$$ Setting $$Y=X^2\tag{4}$$ (3) amounts to $$aY-4a+bY=Y(Y-4) \ \ \ \iff \ \ \ Y^2-(4+a+b)Y+4a=0\tag{5}$$ It remains to solve (5), then, in a backward way (4), then (2) to obtain the different values of $x$, some of them happening to be complex. Example : Let us take $a=1, b=3$, which gives $Y=4\pm2\sqrt{3}$, i.e., $$Y_1=5.73205 \ \ \text{and} \ \ Y_2=2.26795$$ from which $$X_1=\pm \sqrt{Y_1}=\pm 2.39417 \ \ \text{and} \ \ X_2=\pm \sqrt{Y_2}=\pm 1.50597 \tag{6}$$ It remains to solve the four quadratic equations $$x+\dfrac{1}{x}=X$$ for the different values of $X$ in (6) : the first ones (with $X_1$) will give 4 real roots : $$x = 1.85512, \ \ 0.53905, \ \ -0.53905, \ \ -1.85512$$ the two others (with $X_2$) will give 4 complex roots. Remark : the initial equation (and the equivalent polynomial equation) is such that if $x$ is a solution, then $1/x$ is also a solution : it is said that such a polynomial is "reciprocal" (some say "palindromic"), characterised equivalently by the fact that $a_{k}=a_{n-k}$ for all $k$, if $n$ denotes the degree of the polynomial.
{ "pile_set_name": "StackExchange" }
Q: Copernicus Sentinel - National Mirrors and Collaborative Ground Segments Is there an official list of all national mirrors of the collaborative ground segment members for data from the Copernicus Sentinel satellites? So far I found the following: Copernicus Sentinels Scientific Datahub (SciHub) Australia National Mirror Austria National Mirror Finnish National Mirror French National Mirror (PEPS) German National Mirror (CODE-DE) Greek National Mirror Italian National Mirror I am trying to piece together a list of all national or partial mirrors but could not find any official list or document about the available national mirrors. Since each mirror requires a dedicated access to the central archive I was hoping that there is some kind of documentation about the existing or planned national mirrors. A: I know the Swedish and Norwegian and British ones are operational or about to be operational. I also found this resource which might be useful : https://sentinel.esa.int/web/sentinel/missions/collaborative/national-points-of-contact And there are large differences between Collaborative Ground Segments. Some deliver data all over the world (PEPS and probably Code-DE for instance), while others deliver them in their local area (which might be large, for instance central Europe for the Austrian CGS). A: A few days after the question was asked ESA started populating a list of existing and planned Collaborative Ground Segments and National Mirrors: https://sentinels.copernicus.eu/web/sentinel/missions/collaborative/existing-planned It does not look to be complete (yet) but for now it seems to be the only official source.
{ "pile_set_name": "StackExchange" }
Q: Detect if any element in an array contains a hyphen I have tried using the includes() function but it returns false for me as follows: <script> var fruits = ["Banana-orange", "Orange", "Apple", "Mango"]; console.log(fruits.includes("-")); // returnes false, should be true </script> As you can see, 'banana-orange' contains a hyphen. I expect the result to return true. Am I using the wrong function? A: The Array#includes compare with the element in the array(full string match in your case). To make it work, join the values in the array with empty space(use Array#join) and use String#includes method which searches for a substring. var fruits = ["Banana-orange", "Orange", "Apple", "Mango"]; console.log(fruits.join('').includes("-")); Or use Array#some to iterate and check at least one contains the string using String#includes method. var fruits = ["Banana-orange", "Orange", "Apple", "Mango"]; console.log(fruits.some(v => v.includes("-"))); A: What you are actually checking is if there is an item in the array fruits which is "-", I would use a for loop to check, if there is an item of the array which includes '-'. const fruits = ['Banana-orange', 'Orange', 'Apple', 'Mango']; for (let i = 0; fruits.length; i++) { if (fruits[i].includes('-')) return true; }
{ "pile_set_name": "StackExchange" }
Q: Wordpress gallery ignoring shortcode I am trying to use a gallery to display 3 Images in a grid in the same line and same size and want the images to link to other sites when clicked. I am using the "WP Gallery Custom Links" addon and Juno as my theme. My problem is, that the gallery doesn't change the sizes of the images. In fact the gallery ignores any kind of shortcode other than the images that it should display. I tried deactivating all plugins and using the standard-theme, as well as resizing the thumbnail images and even the images themself. The following call is used: [gallery size="150x150" columns="3" ids="1264,1257,1280"] So i even changed the local files to have 150x150 size and the gallery is now scaling them up to 596x189 px. <img src="..." style="width: 596px; height: 189px;" alt=""> I also changed the options for the standart sizes in the media-options to 150x150 in all sizes. Also the pictures are not displayed in one line, but instead two in the top and one in another row, even thougth i am using 3 columns. So if someone can help me, i probably just dont see something, but i dont know what it is. A: OK i found the error, i added .gallery figure.gallery-item { display: inline-table; padding: 3px; width: 300px; } to the custom-css, seems the width in the gallery-item, that was wrapping the images did scale them down. If someone knows where i can change this parameter in the options, or if there is a way to do so without the custom clause then please answer in a comment.
{ "pile_set_name": "StackExchange" }
Q: Replace an Dictionary object in Array using NSPredicate I have one dictionary object in Array. I want to replace this object with new dictionary. Both have same order_id. Currently I am doing it like, How can I do it with NSPredicate. NSMutableArray *orderList=[[NSUserDefaults standardUserDefaults] objectForKey:@"Orders"]; //2. Find and replace the object/OrdeDetails. for(int i=0;i<orderList.count;i++){ NSDictionary *dictionary=orderList[i]; if([dictionary[@"order_id"] isEqualToString:OrderDetails[@"order_id"]]){ [orderList replaceObjectAtIndex:i withObject:OrderDetails]; break; } } A: Check this code: NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF.order_id contains[cd] %@",OrderDetails[@"order_id"]]; NSMutableArray *arrOrders = [[NSMutableArray alloc]init]; [arrOrders addObjectsFromArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"Orders"]]; NSArray *filteredOrder = [arrOrders filteredArrayUsingPredicate:resultPredicate]; if ([filteredOrder count] > 0) { NSUInteger index = [arrOrders indexOfObject:[filteredOrder objectAtIndex:0]]; if (index != NSNotFound) { [arrOrders replaceObjectAtIndex:index withObject:OrderDetails]; } }
{ "pile_set_name": "StackExchange" }
Q: Convert Xamarin bitmap to byte[] not work or throw exception I tried to convert my image from camera to byte[] and then make request to my server but it is not working so my image from camera is var image = textureView.Bitmap; image = Android.Graphics.Bitmap.CreateBitmap (image, (int)OCR_Rectangle.GetX(), (int)OCR_Rectangle.GetY(), OCR_Rectangle.Width, OCR_Rectangle.Height); My web request is public async static Task<string> ParseAsync(byte[] image) { string id = "my id "; string apiKey = "my api key "; using (var httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.TryAddWithoutValidation("app_id", id); httpClient.DefaultRequestHeaders.TryAddWithoutValidation("app_key", apiKey); var base64 = Convert.ToBase64String(image); var imageUri = "data:image/jpg;base64," + base64; var json = JsonConvert.SerializeObject(new { src = imageUri }); var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"); var response = await httpClient.PostAsync("my website", content); var dynObj = JsonConvert.DeserializeObject<RootObjectLatex>(await response.Content.ReadAsStringAsync()); return dynObj.latex; } } Here is my attempt to convert bitmap to byte[] byte[] bitmapData; using (var stream = new MemoryStream()) { image.Compress(Bitmap.CompressFormat.Png, 0, stream); bitmapData = stream.ToArray(); } And then i want to use bitmapData in my request.But no luck. A: So, I found error this works byte[] bitmapData; using (var stream = new MemoryStream()) { image.Compress(Bitmap.CompressFormat.Png, 0, stream); bitmapData = stream.ToArray(); } but i type wrong api key in my request
{ "pile_set_name": "StackExchange" }
Q: Making Discord bot command case insensitive? I created a "roleinfo" command for my discord bot. I'm not sure how to make the role search case insensitive. See my code below: const Discord = require("discord.js"); module.exports.run = async (bot, message, args) => { //Message checks if (!args[0]) return message.channel.send("You must specify a role name"); //Grab args and specify as rolename let roleName = `${args[0]}` //@rolename let roleMention = message.guild.roles.find(roles => roles.name === roleName) let rolefind = message.guild.roles.find(roles => roles.name === roleName) if (!rolefind) return message.channel.send(`Can't find role ${args[0]}`); //Filter members for role let membersWithRole = message.guild.members.filter(member => { return member.roles.find(roles => roles.name === roleName); }).map(member => { return member.user.username; }) let serverembed = new Discord.RichEmbed() .setColor("#FFD700") .addField("Role name", roleMention) .addField("Number of users with the role", rolefind.members.size) .addField("Users with the role", membersWithRole.join("\n")) message.channel.send(serverembed); } module.exports.help = { name: "roleinfo", usage: "``prefix`` roleinfo or ``prefix`` roleinfo rolename", description: "Displays detailed role information", } I know I have to use .toLowerCase() or .toUpperCase() but i'm not sure how/where in this scenario. Could anyone help me out? Will be greatly appreciated. Thanks in advance! A: As you said yourself, just do roleMention = message.guild.roles.find(roles => roles.name.toLowerCase() === roleName.toLowerCase()) That would make out of : 'Role-name' === 'Role-NAME' 'role-name' === 'role-name'
{ "pile_set_name": "StackExchange" }
Q: Jquery: select only one class onclick - not all I am trying to set a specific css class to some images when clicked. Here is my code: <%= image_tag ('snapchat.png'), class: "img-rounded", id: "icon-hover", width: "50px" %> <%= image_tag ('tinder.png'), class: "img-rounded", id: "icon-hover", width: "50px" %> <%= image_tag ('tumblr.png'), class: "img-rounded", id: "icon-hover", width: "50px" %> And my jquery: $(document).on('click', '.img-rounded', function (){ $('.img-rounded').css({ '-webkit-filter':'grayscale(0%)', 'filter':'grayscale(0%)', }); }); The function works great, the problem is that when I click on one image, it gives the css attribtues to all others images. How could I only targert one element at a time ? Thanks for your help. EDIT: My images are wrapped inside parent elemnts like this: <b href="" class="wechat" id="icon-hover" style="text-decoration:none"> <%= image_tag ('wechat.png'), class: "img-rounded", id: "icon-hover", width: "50px" %> </b> So even when using the "this" handler it doesn't respond: $(document).on('click', '.img-rounded', function (){ $(this).css({ '-webkit-filter':'grayscale(0%)', 'filter':'grayscale(0%)', }); }); A: $(document).on('click', '.img-rounded', function (){ $(this).css({ '-webkit-filter':'grayscale(0%)', 'filter':'grayscale(0%)', }); });
{ "pile_set_name": "StackExchange" }
Q: $4\times4$ determinant trick This link uses a trick to find the determinant of a $3\times3$ matrix that goes like this: Put a copy of the matrix next to it, and now consider this as a $6\times3$ matrix. Find the sum of the product of all numbers in the "first" diagonal and of those in the "second" diagonal and of those in the "third" diagonal. Find the sum of the negatives of the product of all numbers in the "first" mirrored diagonal (from bottom-left to top-right) and of those in the "second" mirrored diagonal and of those in the "third" mirrored diagonal. As I show here: $$\mathrm{determinant}=aei+bfg+cdg-gec-hfa-idb$$ My question is, if this rule applies to other matrices of $n\times n$? I have a faint memory of this trick also working for $4\times 4$ and $5\times 5$, but this link seems to imply that a $4\times 4$ has to be reduced to a $3\times 3$ first before this trick is applicable. Is my memory correct or are there no such tricks for larger $n\times n$ matrices? A: This trick only works for $3 \times 3$ matrices. The determinant of an $n \times n$ matrix can be calculated by looking at all the ways to choose one element per row and column, and taking the sum of these products with a factor of $-1$ for odd permutations. There are $n!$ such choices. When $n=3$, the sum will consist of $3!=6$ products, the ones that appear in your method. But when $n=4$, say, there will be $4!=24$ products, and you can see that there can be no simple trick.
{ "pile_set_name": "StackExchange" }
Q: Automotive Sensor - Excessive Ripple Noise I'm designing an automotive oil temperature sensor based around a 3-wire RTD. This is my analog circuitry: U1 and U2 provide a 1mA bias on the RTD which is measured by U3 and gained up by U4. R5, R10, D1 and D2 are for input protection on the op amps. Op amps are a quad package MCP604 single supply and are properly bypassed with a 0.1u cap. I have the whole thing prototyped out and it works perfectly if Vin to the 7805 circuit is powered by my 12V bench supply, but as soon as I connect it to 12V battery power in my car, I get some sort of ripple voltage or oscillation in the RTD that throws the ADC readings way off. I don't have access to a scope at home to really see what's going on, but there's a small ~10mV ripple voltage on the RTD which is being amplified by the gain stage. I added the 1uF caps in the feedback path to try and remove it, which helped, but the ripple is still bad enough to render the measurements useless. If I disconnect Vin from the vehicle 12V and power it with my bench supply (with GND remaining through the vehicle chassis) the ripple disappears and the temperature reading is spot on. Powering it with a 9V battery also works just fine. This is with the vehicle ignition off, so there shouldn't be any crazy noise present. Also, if I leave it powered by vehicle 12V and replace the RTD with a 100 ohm resistor, it works fine. So it looks like some sort of interaction with either the platinum resistance element or the sensor leads. Is there some sort of interaction I'm not accounting for with vehicle power vs. my bench supply or 9V battery? Or is there a potential stability issue with my circuit that is being pushed over the edge when connected to vehicle power? EDIT: I'm fairly certain this is a ground loop issue. Rewiring the circuit into a star-ground configuration improved the situation, but there are still measurable stray ground currents through the RTD causing unpredictable results. A: Increase R5 and R10 to 50K and add a 1uF ceramic from U3 +input to ground and from U2 +input to a solid analog ground (keep the analog grounds together). Split R8 into two series 50K and add a 1uF ceramic capacitor to ground from the mid point. Lose the two Schottky diodes (too leaky, especially with 50K) and R11 (useless). Make sure your return wire from the RTD (you must have three wires running back to your circuit from the RTD, which must not be grounded at the chassis) is connected to the low side of R14 and thence to circuit ground as I said above about keeping them together. If you don't have access to a 'scope you'll be fairly limited, but if you're still seeing 'noise' try measuring the voltage at each op-amp output (including the current source) using a multimeter on the minimum AC volts range. Many will block the DC and show you some indication of what is going on in the AC world.
{ "pile_set_name": "StackExchange" }
Q: Why didn't others steal Yondu's fins? In Guardians of the Galaxy, Vol. 2, Yondu has at least 3 fins, including the one that Nebula shot off, the prototype with which he was cremated, and the one that was given to Kraglin after Yondu died. If these three existed, no doubt Yondu also had others. Where did Yondu get his fins? And why didn't other crew members steal them? A: Where did Yondu get his fins? Since the Yaka Arrow is Centaurian in origin, I think it can be assumed that Centaurians design and build the fins. Since Yondu is the only Centaurian we've seen he either had backups, or the new prototype was one of his own design. And why didn't other crew members steal them? As we see with Kraglin, it takes time to learn how to master the arrow. And I'm sure Yondu isn't above killing whomever tries to steal it. And because it is challenging to learn, maybe most people don't want to bother. I heard it said once: Ancient weapons and hokey religions are no match for a good blaster at your side. - source unknown
{ "pile_set_name": "StackExchange" }
Q: SharedPreferences code not working as intended All necessary imports are added. public class MainActivity extends AppCompatActivity { SharedPreferences preferences; SharedPreferences.Editor editor; public int i; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); preferences = getSharedPreferences("MyPrefs", MODE_PRIVATE); editor = preferences.edit(); During first time boot the message "First time boot" appears, but should not appear during next times, instead the iterator i, which was saved in sharedPreferences, should appear. try{ i = preferences.getInt("iterator", 0); Toast.makeText(getApplicationContext(), i, Toast.LENGTH_SHORT).show(); }catch(Exception e){ Toast.makeText(MainActivity.this, "First time boot", Toast.LENGTH_SHORT).show(); } final TextView date = (TextView) (findViewById(R.id.textView)); final Calendar c = Calendar.getInstance(); date.setText(DateFormat.getDateFormat(this).format(c.getTime())); final Button mainBtn = (Button) findViewById(R.id.mainBtn); final Button exit = (Button) findViewById(R.id.exit); mainBtn.setText("Clock In"); mainBtn.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ if(mainBtn.getText() == "Clock In"){ mainBtn.setText("Clock Out"); }else{mainBtn.setText("Clock In");} String s = new SimpleDateFormat("yyyy: MM: dd HH: mm: ss").format(Calendar.getInstance().getTime()); My idea is that upon clicking a button, a time stamp would be saved into the sharedPreferences file, which could later on be accessed. editor.putString("Time "+ i, s); i++; editor.putInt("iterator", i); } }); I just recently added this, so that when you click the exit button, everything that was put in the sharedPreferences file would be saved. (earlier the editor.commit() line was inside the mainBtn onClickListener). exit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { editor.commit(); finish(); } }); } The problem is that upon exiting the app and re-launching it, the app does not retrieve the stored data, which was supposed to be saved in the sharedPreferences file, instead it just says "First time boot" every time.. I am extremely new to programming and have tried to overcome this problem in multiple ways, only to arrive at the same problem. Help! A: To my knowledge preferences.getInt("iterator", 0); won't throw an exception if "iterator" doesn't exist. It will return a 0. 0 is the default. I would change your code to be something more like: int iterator = preferences.getInt("iterator", -1); if (iterator == -1) Toast.makeText(this, "First time boot", Toast.LENGTH_SHORT).show(); And if you look at your exception, I would guess that the problem is actual from your Toast after your getInt("Iterator", 0) call that is passing an int instead of a string. Also, I wouldn't hold the editor open throughout your app. I usually would write a function like void savePreference(String key, String value) { SharedPreferences prefs = context.getSharedPreferences(PREFERENCES_NAME, 0); SharedPreferences.Editor editor = prefs.edit(); editor.putString(key, value); editor.commit(); }
{ "pile_set_name": "StackExchange" }
Q: Spring Boot CSS stripped My folder structure ProjectName src/main/java src/main/resources static css styles.css main.css js ... templates All my html files are in the folder templates My HTML file head <!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> ... <link rel="stylesheet" href="../static/css/main.css" /> <link rel="stylesheet" href="../static/css/styles.css" /> I do not have EnableWebMvc in any of my Java classes When I run this as a jar, the page comes up fine, but all the CSS is stripped. It just shows up as plain text. I've tried this in different browsers with the same result. What am I doing wrong? A: If you check your browser console (e.g. in Chrome), my guess you will see HTTP 404 Not found for your CSS files. The problem is with your URL path to CSS. The main point is that there is a difference how files (.html, .css) are stored in your JAR file (or in your source code) and how they are served by HTTP server. As far as I see you are using thymeleafs and therefore (my guess again), your HTML template files can be served for different kind of URLs (like /, /book/23 etc.) and therefore I don't recommend to address CSS files with relative URLs (as you did). As CSS files are stored in static directory, they should be automatically served by spring boot for /** pattern, ie. if you don't use any context path, your CSS should have following URL: /css/main.css. If you want to be very correct and be prepared that your web application can be in different "context", you should use something like <link rel="stylesheet" th:href="@{/css/main.css}">
{ "pile_set_name": "StackExchange" }
Q: SQL query find max row from the aggregated averages Supposed I have the following tables: Sailor(sid, sname, age) Boat(bid, sid) Each boat can have many sailors, and each individual sailor can serve on many boats. What I want to do is to find the boat with the highest average age of sailors. I can find the average age of the sailor on each boat with this subquery: SELECT b.bid, AVG(s.age) AS avg_age FROM sailor s, boat b WHERE b.sid = s.sid GROUP BY b.bid However, I am stuck on how to find the maximum row from this subquery further on. P.S. I'm also looking for MySQL-compatible query, if that makes any difference. A: SELECT t1.* FROM (SELECT b.bid, AVG(s.age) AS avg_age FROM sailor s, boat b WHERE b.sid = s.sid GROUP BY b.bid) t1 LEFT OUTER JOIN (SELECT b.bid, AVG(s.age) AS avg_age FROM sailor s, boat b WHERE b.sid = s.sid GROUP BY b.bid) t2 ON (t1.avg_age < t2.avg_age) WHERE t2.avg_age IS NULL;
{ "pile_set_name": "StackExchange" }
Q: map.setMyLocationEnabled(true); is not working I have just started working on a android project and is using the Google Map API. I am able to fetch the map on my app but when i try to enable the current location with map.setMyLocationEnabled(true);, the app says unfortunately app has stopped working. When I removed the line map.setMyLocationEnabled(true); then it worked fine. Can anyone please help me to get the current location button enabled. A: If you are using android 6.0 or above, you should: Make sure you added ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION in your AndroidManifest file. You need to check permission at run-time in this link: Requesting Permission Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. This approach streamlines the app install process, since the user does not need to grant permissions when they install or update the app. It also gives the user more control over the app's functionality; If you want an easy-to-use library for permission checking, I suggest Permission Dispatcher.
{ "pile_set_name": "StackExchange" }
Q: Jekyll/Liquid Templating: How to group blog posts by year? I'm rewriting my blog to use Jekyll. Jekyll uses the Liquid templating language so it makes it a little more difficult to learn how to customize. I'd like to group my list of blog posts by year. How would I write the Liquid code to be able to do this? {% for post in site.posts %} <li><!-- display post year here (but only once, per year) --></li> <li> <a href="{{ post.url }}">{{ post.title }}</a> </li> {% endfor %} A: It can be done with much, much less Liquid code than in the existing answers: {% for post in site.posts %} {% assign currentdate = post.date | date: "%Y" %} {% if currentdate != date %} <li id="y{{currentdate}}">{{ currentdate }}</li> {% assign date = currentdate %} {% endif %} <li><a href="{{ post.url }}">{{ post.title }}</a></li> {% endfor %} This will return exactly the HTML specified in your question: <li id="y2013">2013</li> <li><a href="/2013/01/01/foo/">foo</a></li> <li id="y2012">2012</li> <li><a href="/2012/02/01/bar/">bar</a></li> <li><a href="/2012/01/01/baz/">baz</a></li> However, this is not the optimal solution, because the year numbers are "only" list items as well. It's not much more Liquid code to put the year into a headline and to begin a new <ul> for each year's posts: {% for post in site.posts %} {% assign currentdate = post.date | date: "%Y" %} {% if currentdate != date %} {% unless forloop.first %}</ul>{% endunless %} <h1 id="y{{post.date | date: "%Y"}}">{{ currentdate }}</h1> <ul> {% assign date = currentdate %} {% endif %} <li><a href="{{ post.url }}">{{ post.title }}</a></li> {% if forloop.last %}</ul>{% endif %} {% endfor %} The generated HTML: <h1 id="y2013">2013</h1> <ul> <li><a href="/2013/01/01/foo/">foo</a></li> </ul> <h1 id="y2012">2012</h1> <ul> <li><a href="/2012/02/01/bar/">bar</a></li> <li><a href="/2012/01/01/baz/">baz</a></li> </ul> You can also group by month and year instead (so that the headlines are February 2012, January 2012 and so on). To do this, you just need to replace date: "%Y" (in the second line of both above examples) by date: "%B %Y". (%B is the full month name, see the documentation) A: If you want to break it down by year, here's the code: {% for post in site.posts %} {% capture this_year %}{{ post.date | date: "%Y" }}{% endcapture %} {% capture next_year %}{{ post.previous.date | date: "%Y" }}{% endcapture %} {% if forloop.first %} <h2 id="{{ this_year }}-ref">{{this_year}}</h2> <ul> {% endif %} <li><a href="{{ post.url }}">{{ post.title }}</a></li> {% if forloop.last %} </ul> {% else %} {% if this_year != next_year %} </ul> <h2 id="{{ next_year }}-ref">{{next_year}}</h2> <ul> {% endif %} {% endif %} {% endfor %} If you want to break it down to year and months it can be achieved like this: {% for post in site.posts %} {% capture this_year %}{{ post.date | date: "%Y" }}{% endcapture %} {% capture this_month %}{{ post.date | date: "%B" }}{% endcapture %} {% capture next_year %}{{ post.previous.date | date: "%Y" }}{% endcapture %} {% capture next_month %}{{ post.previous.date | date: "%B" }}{% endcapture %} {% if forloop.first %} <h2 id="{{ this_year }}-ref">{{this_year}}</h2> <h3 id="{{ this_year }}-{{ this_month }}-ref">{{ this_month }}</h3> <ul> {% endif %} <li><a href="{{ post.url }}">{{ post.title }}</a></li> {% if forloop.last %} </ul> {% else %} {% if this_year != next_year %} </ul> <h2 id="{{ next_year }}-ref">{{next_year}}</h2> <h3 id="{{ next_year }}-{{ next_month }}-ref">{{ next_month }}</h3> <ul> {% else %} {% if this_month != next_month %} </ul> <h3 id="{{ this_year }}-{{ next_month }}-ref">{{ next_month }}</h3> <ul> {% endif %} {% endif %} {% endif %} {% endfor %} It is only a matter of where do you make the cut on the loop. A: These previous solutions are fantastic but luckily in late 2016, Jekyll added a group_by_exp filter that can do this much more cleanly. {% assign postsByYear = site.posts | group_by_exp:"post", "post.date | date: '%Y'" %} {% for year in postsByYear %} <h1>{{ year.name }}</h1> <ul> {% for post in year.items %} <li><a href="{{ post.url }}">{{ post.title }}-{{ post.date }}</a></li> {% endfor %} </ul> {% endfor %} Documentation can be found on the Jekyll Templates page.
{ "pile_set_name": "StackExchange" }
Q: Long exposure mode in Nikon with a Remote shutter control I want to learn and do some long exposure photography from cars in highways, etc. So I got a wireless remote shutter control! Now in the settings of the camera I see two options, one says Long Exposure NR , ON , OFF and then there is also another option that says for example Mirror Up, Shoot after two seconds, shoot immediately. So that's that in the menus,...but on the dial buttons that we can select for example S,A,M,Continues high, etc..so those dials also have a mode with the icon of the wireless remote shutter...So I am confused...What should I do for those cars photography? Is it this? Enable Long Exposure NR from the digital menu Go to "S" mode and set the shutter speed timer to for example 30 seconds. Now turn that physical dial to the mode with the remote control icon Press the remote Control I am using a Nikon D-610 to be specific. A: On the D610, I prefer using the 'Remote Shutter Delay' set to 3s than the Mirror Lock-Up. These two essentially do the same thing but need only one press for the former. This makes it possible to capture sharp long exposures even without a wireless remote. It works with it too though. Having the remote opens you the option to do much longer BULB exposures without risk of vibrations. You set the camera to M mode and dial the shutter-speeds until it says B. Then you press once to start the exposure (after the optional delay, if enabled) and once to end the exposure. So, set the dial to Remote and enable the Delay. Then you press the remote release when ready, either in M or S mode. Enabling Long Shutter noise reduction helps but if you are working in a fast situation, it blocks you from trying another shot right away, so i usually turn it off. A: You are essentially correct, yes. Firstly, you can leave Long Exposure NR on all the time. The 'mirror up' etc settings you are referring to determine what happens when you press the remote control. You want to set it to 'Mirror Up', because the action of raising the mirror causes the camera to vibrate, introducing a slight blur to your shot, which is much more noticeable with long exposures. The process changes slightly once you set this: one press of the remote raises the mirror, then the next press fires the shutter. So you press, pause, and press again to take the shot. You may also want to consider using Manual mode rather than Shutter Priority so that you have more control over the aperture. Another tip for taking shots of car light trails is that you will get better results taking multiple shorter exposures and compositing them together in post rather than taking one very long exposure. Using shorter exposures means less noise and less chance of camera shake.
{ "pile_set_name": "StackExchange" }
Q: Kivy how to use FileBrowser properly inside of a popup I am looking for a way to create a popup box with a filebrowser inside of it by clicking a button from the main app screen. The below snippet is the class that is called when the upload button is clicked from the main app. It will render the popup with the file browser, but the on_* kwargs do not run the respective methods. class UploadPopup: def __init__(self, short_text='heading'): browser = FileBrowser(select_string='Select', cancel_state='down') browser.bind(on_success=self._fbrowser_success, on_canceled=self._fbrowser_canceled, on_submit=self._fbrowser_submit) self.popup = Popup( title=short_text, content=browser, size_hint=(0.9, 0.9), auto_dismiss=False ) self.popup.open() def _fbrowser_canceled(self, instance): print('cancelled, Close self.') self.popup.dismiss() def _fbrowser_success(self, instance): print(instance.selection) self.popup.dismiss() def _fbrowser_submit(self, instance): print(instance.selection) self.popup.open() Any ideas?? A: Where ever you are calling UploadPopup(), you need to save a reference to it, so that it does not get garbage collected. For example, you might want to do self.pop = UploadPopup() in your main app. Also, in your event handling methods, you probably want to replace self.popup.open() with self.popup.dismiss().
{ "pile_set_name": "StackExchange" }
Q: Inner Class vs Static Inner Class I am trying to create a linked list implementation using inner class package linkedlist; public class linkedList { public class Node { int data; public Node next; public Node(int k) { this.data = k; this.next=null; } public Node addToHead(int data) { Node node = new Node(data); Node current = this; node.next=current; return node; } } public static void findn(Node head) { Node previous=head; Node current = head; int i =1; while(current!=null) { if (i==6) { //System.out.println(current.data); previous.next = current.next; break; } previous=current; current = current.next; i++; } } public static void main(String args[]) { linkedList list = new linkedList(); linkedList.Node tail = linkedList.new Node(0); // list.Node tail = list.Node(0); Node head = tail; for (int i=1;i<=20;i++) { head = head.addToHead(i); } findn(head); while(head!=null) { System.out.println(head.data); head = head.next; } } } My question here in the main function i am trying to create a node using the outer class. But the syntax is throwing me an error even though i am following the right syntax. I want to know what is wrong with this statement "linkedList.Node tail = linkedList.new Node(0);" A: A Node, being a non-static inner class, needs an instance of its enclosing class. linkedList is the class name. It doesn't refer to an instance of the class. So it should be list.new Node() It would be much clearer if you respected the Java naming conventions: variables start with a lowercase letter, and classes with an uppercase letter.
{ "pile_set_name": "StackExchange" }
Q: MPD, How to get the name of the current playlist? I am using Python MPD2, is there a way to return the name of the currently selected playlist? Thanks, Mark. A: After more searching, I finally posted on the musicpd forum https://forum.musicpd.org/viewtopic.php?f=7&t=4034 and the response was: "MPD does not remember of the most recently loaded playlist's name, so there's no way to query it.".
{ "pile_set_name": "StackExchange" }
Q: What happens when the buffer pool size is insufficient in mysql Let us assume I run a query for a table whose size is very huge. My buffer pool size is as low as possible. What happens now? whether I will get an error regarding the insufficient space in buffer pool or will mysql fetch the data from the disk ? Just curious to know the behaviour of mysql in this scenario. A: If MySQL properly started and InnoDB initialized with the configured buffer pool size then there is no reason for any error (barring some bug of course). The buffer pool is just that - a memory area used to buffer your IO. When there is not enough of it to keep all the active data, the server just reads them from disk. If you had for example 100GB table then many servers won't have enough RAM to contain it and still you may execute a query running full table scan. The performance will be worse (probably substantially, 1-2 orders of magnitude or more) than in case there were enough memory.
{ "pile_set_name": "StackExchange" }
Q: Nonclustered index in SQL Server 2008 R2 with includes vs non includes Running the advisor it suggests I should create an index on Path, Value and to include Id. Path varchar(250) Value bigint Id uniqueidentifier When using the index in a query, will it be faster having Id in the index rather than as an include? Will inserts be slower having Id as an include rather than in the index? A: 1) Depends on query if it looks like select Id from YourTable WHERE Path = x and Value = y and Id =(or>, <, between etc.) z i.e. - if query involves exact values (not ranges) of Path and Value - then yes, else - no, will be slower because of more thicker non-leaf rows 2) Actually - yes, but it can be negligible, because the sql needs to sort AND by Id, but if your Path and Value is versatile enough - the difference will be very tiny. In IO there will be a little gain if saving Id in INCLUDE section - because no needs to save it on non-leaf pages As you noticed: Query uses Id, Path and Value. Id and Path in join restriction and Value in where. The Id is furthermore a FK on primary table. With this short info, How would you design the index? So, its better include all the rows in index, and the best order of columns will depend on structure/indexes of other table in JOIN. The index should look like (Value, Id, Path) or (Value, Path, Id) - depending on mentioned above.
{ "pile_set_name": "StackExchange" }
Q: Launch multiple Gradle "spring-boot" plugin "bootRun" tasks in parallel I have a multi-project Spring Boot application that is built using Gradle. What I'm trying to do is run the various subprojects using Spring Boot's bootRun task from the command line to do some "ad-hoc" testing via gradle bootRun. However, it seems as though each daemon starts and stops in sequence. Is there a way I can get all of my Boot daemons to run in parallel using the spring-boot plugin? Any advice would be greatly appreciated :) A: Tasks of independent projects may be executed in parallel by using --parallel flag. To execute a multi-project build in parallel the user must declare that they would like their projects executed in parallel, via a command-line switch: --parallel \\ Tells Gradle to execute decoupled projects in parallel. Gradle will attempt to determine the optimal number of executors to use. --max-workers=4 \\ Tells Gradle to execute decoupled projects in parallel, using the specified number of workers. The default is the number of processors. Similar to the Gradle Daemon, it should be possible to enable/configure parallel execution on a per-user and per-project basis. This could be done via a build environment property set in gradle.properties: org.gradle.parallel: When set to `true`, Gradle will execute with the parallel executer org.gradle.workers.max: Specify the maximum number of workers to use for parallel execution. This property does not in itself enable parallel execution, but the value will be used whether Gradle is executed with `--parallel` or `org.gradle.parallel=true`. Resource Links: https://docs.gradle.org/current/userguide/gradle_command_line.html https://docs.gradle.org/current/userguide/build_environment.html A full parallel running example is given here: https://github.com/camiloribeiro/cucumber-gradle-parallel/blob/master/build.gradle#L50 How does parallel execution work? First, you need to tell Gradle to use the parallel mode. You can use the command line argument (Appendix D, Gradle Command Line) or configure your build environment (Section 12.1, “Configuring the build environment via gradle.properties”). Unless you provide a specific number of parallel threads Gradle attempts to choose the right number based on available CPU cores. Every parallel worker exclusively owns a given project while executing a task. This means that 2 tasks from the same project are never executed in parallel. Therefore only multi-project builds can take advantage of parallel execution. Task dependencies are fully supported and parallel workers will start executing upstream tasks first. Bear in mind that the alphabetical scheduling of decoupled tasks, known from the sequential execution, does not really work in parallel mode. You need to make sure the task dependencies are declared correctly to avoid ordering issues. Resource Link: https://docs.gradle.org/current/userguide/multi_project_builds.html Since version 3.5, Gradle can print parallel workers status: <===========--> 90% EXECUTING > :backend-service:bootRun > :frontend-service:bootRun
{ "pile_set_name": "StackExchange" }
Q: Simulating packet encapsulation I am developing an application which aims to simulate a real network. In order to do this, I need to have detailed information about how a packet is formed in a system. Imagine you have an application layer message and you want to encapsulate it in a transport layer payload and add a specific port number for desired process in the header, and then encapsulate it in network layer payload and add IP addresses. My question is that Where does the encapsulation of upper layer protocols' packets to lower layers happen? Is network card driver responsible for that or some other part in OS? and if so, which part? I just want to note that I’ve read computer networks: A top down approach and Foruzan's book on the subject but all the information there ,was so theoretical. Thanks in advance. A: If you are asking about a real implementation, usually every message of a layer is conveyed as the whole payload of the lower layer message. Talking about TCP/IP stack in an OS like Windows or Linux, without SSL/TLS, this depends on the types of sockets you use. Supposing you use TCP, STREAM sockets, the application layer message you send with send or write system calls will become the payload of the TCP message. The processing of a TCP segment and an IP datagram happens in the OS Kernel. The processing of a layer 2 frame happens part in the NIC's device driver (in the kernel) and part in the NIC hardware. This depends on the specific NIC. Something else to add is that some NIC's are able to calculate the checksum of TCP segments and UDP datagrams. Then the kernel offloads this task to the NIC. Only the checksum.
{ "pile_set_name": "StackExchange" }