text
stringlengths
64
81.1k
meta
dict
Q: In WPF is there a way to determine if another control captures the mouse? I have a control in my application that needs to know when any other control in the visual tree captures the mouse. Is this possible? A: Use the Mouse.GotMouseCapture attached event. public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } static MainWindow() { EventManager.RegisterClassHandler(typeof(UIElement), Mouse.GotMouseCaptureEvent, new MouseEventHandler(MainWindow_GotMouseCapture)); } static void MainWindow_GotMouseCapture(object sender, MouseEventArgs e) { // e.OriginalSource is a captured element } } Note, that the captured element is available via the Mouse.Captured static property.
{ "pile_set_name": "StackExchange" }
Q: $a:A$ in $\Gamma$ I am taking an introductory course on type theory. I find the following sentence in my handout: ''$a:A$ in $\Gamma$'' or ''$\Gamma\vdash a:A$'' is equivalent to the following judgment ''$a(x_1,...x_n):A(x_1,...,A_n)<x_1:A,...x_n:A_n(x_1,...,x_{n-1})>$'', where $\Gamma=<x_1:A,...x_n:A_n(x_1,...,x_{n-1})>$. I understand that the latter hypothetical judgment simply makes explicit the assumptions contained in $\Gamma$. But I am wondering how we shall interpret $a(x_1,...x_n)$ in the latter notation. It is clear that $a$ in $a:A$ is a constant, but what about $a(x_1,...,x_n)$ if they are taken to be equivalent? How does $a(x_1,...,x_n)$ differ from a pure variable such as $x_{n+1}$? Thanks! A: Thinking of $\Gamma$ as a list of assumptions, the types and terms to the right of the $\vdash$ may vary depending on what assumptions are made. Thinking of $\Gamma$ as a list of variables, the types and terms of the right of the $\vdash$ may depend on the variables in $\Gamma$. So it's not that the '$a$' in $\Gamma \vdash a:A$ is constant—rather, it depends on the context. For example, consider $$x : \mathbb{N} \vdash \langle 1, 2, \dots, x \rangle : \mathrm{List}_x(\mathbb{N})$$ Here $\mathrm{Lin}_x(\mathbb{N})$ refers to the type of lists of natural numbers of length $x:\mathbb{N}$. Both the term $\langle 1, 2, \dots, x \rangle$ and the type $\mathrm{List}_x(\mathbb{N})$ depend on the variable $x:\mathbb{N}$; but that isn't to say that the term is the same thing as a pure variable of type $\mathrm{Lin}_x(\mathbb{N})$.
{ "pile_set_name": "StackExchange" }
Q: EF Lambda include navigation properties I have the following object, called Filter with the following properties: public int Id { get; set; } public string Name { get; set; } public virtual ICollection<Type> Types{ get; set; } public virtual ICollection<Step> Steps { get; set; } public virtual ICollection<Flow> Flows { get; set; } public virtual ICollection<Room> Rooms { get; set; } When I select a list of Filters from the database, I have no idea how to include the collections (Types, Steps, Flows, Rooms). My code is as follows: var filters = ( from filter in dbContext.DbSet<Filter>() let rooms = ( from r in dbContext.DbSet<Room>() select r ) let eventTypes = ( from t in dbContext.DbSet<Type>() select t ) let processFlows = ( from f in dbContext.DbSet<Flow>() select f ) let processFlowSteps = ( from s in dbContext.DbSet<Step>() select s ) select filter ).ToList(); My collection of Filter is returned, but the collections inside are empty. Could you please tell me how can I achieve this? Ps: I do not want to use Include because of performance issues, I don't like how Entity Framework generates the query and I would like to do it this way. A: Your method works, you are just doing it slighly wrong. To include a navigation property, all you have to do is a subselect (using linq), example: var filters = (from filter in dbContext.DbSet<Filter>() select new Filter { filter.Id, filter.Name, Rooms = (from r in dbContext.DbSet<Room>() where r.FilterId == filter.Id select r).ToList() }).ToList(); Keep in mind that EF won't execute the query until you call a return method (ToList, Any, FirstOrDefault, etc). With this, instead of doing those ugly queries you want to avoid by not using Include(), it will simply fire two queries and properly assign the values in the object you want.
{ "pile_set_name": "StackExchange" }
Q: converting base 10 to base 2 in prolog am trying to convert base 10 to base 2 using prolog this is my code : binary(X,B) :- X > -1 , tobin(B,X,1). tobin(S,0,1) :- S is 0. tobin(S,0,V) :- V>1 , S is 1. tobin(S,X,V) :- X > 0 , X1 is X // 2 , V1 is V * 10 , tobin(S1,X1,V1), S is X mod 2 , S is S + S1 * V1 . it's not working :/ can you help me ? thank you a lot :D A: If you want to know what was wrong with you original code, study this: binary(X,B) :- X > -1 , tobin(B,X). /*tobin(S,0,1) :- S is 0.*/ /* tobin(S,0,V) :- V>1 , S is 1.*/ tobin(0,0). tobin(S,X) :- X > 0 , X1 is X // 2 , /*V1 is V * 10 , */ tobin(S1,X1), S0 is X mod 2 , S is S0 + S1 * 10 . There are two main changes: I've renamed S to S0 in one place as without that one of the statements is always false (S is S +...); I've removed third argument from tobin as it wasn't really necessary to pass positional value to recurrent calls and in all this recurrency some error crept in which wasn't clear to me. After the fixes your code looks nicer that from @damianodamiano (in my opinion): binary(X,B) :- X > -1 , tobin(B,X). tobin(0,0). tobin(S,X) :- X > 0 , X1 is X // 2 , tobin(S1,X1), S0 is X mod 2 , S is S0 + S1 * 10 . Actually, you can skip binary and call tobin directly (arguments are in reversed order) which makes it even simpler: tobin(0,0). tobin(S,X) :- X > 0 , X1 is X // 2 , tobin(S1,X1), S0 is X mod 2 , S is S0 + S1 * 10 . Main advantage of @damianodamiano would be runtime optimization by tail recursion.
{ "pile_set_name": "StackExchange" }
Q: how to number rows in a data table and how to get data from textbox I have been searching through the net to see if I can figure out how to number rows in visualforce but I cannot find a way that will automatically increment when a row is added. I also cannot find out how to utilize data that is put into a text box. I want the users to be able to type in a number that corresponds to an entry in the list and that number will be input into a method called DeleteEntry() that does something like this public void DeleteEntry() { Queue.remove(textbox1.text); } this is my code Visualforce Page <apex:page standardController="Case_Note__c" recordSetVar="MassAddCaseNotes" tabStyle="Case_Note__c" extensions="MassAddCaseNotes"> <apex:sectionHeader title="Mass Add Case Notes" /> <apex:panelGrid columns="2" cellpadding="5" style="margin-bottom: 15px;"> <apex:form style="width:450px" > <apex:pageBlock title="Case Notes" id="block1"> <apex:pageBlockSection title="Enter Your Notes " columns="2" id="section1"> <script> twistSection(document.getElementById('{!$Component.block1.section1}').getElementsByTagName('img')[0]) </script> <apex:panelGrid columns="1" cellpadding="5" style="margin-bottom: 15px;"> <apex:outputLabel for="CaseNote">Notes: </apex:outputLabel> <apex:inputField style="width:300px;height:100px;" value="{!Case_Notes.Note__c}" id="CaseNote" /> <apex:outputLabel for="CaseNote">Date: </apex:outputLabel> <apex:inputField value="{!Case_Notes.Date__c}" id="Date" /> </apex:panelGrid> </apex:pageBlockSection> <apex:pageBlockSection title="Find Cases" columns="1"> <apex:panelGrid columns="1" cellpadding="5" style="margin-bottom: 5px;"> <apex:outputLabel for="contactFilter">Contact Search: </apex:outputLabel> <apex:inputField value="{!filtercase.contactid}" id="contactFilter" /> <apex:commandButton action="{!selectCases}" value="Filter" /> </apex:panelGrid> <apex:panelGrid columns="1" cellpadding="5" style="margin-bottom: 5px;"> <apex:PageBlockTable value="{!cases}" var="case" id="case"> <apex:column > <apex:inputCheckbox value="{!selectedCases[case.Id]}" /> </apex:column> <apex:column > <apex:facet name="header"> <apex:commandLink value="Case Number" action="{!sortCases}"> <apex:param name="productSortField" value="CaseNumber" assignTo="{!sortField}"/> </apex:commandLink> </apex:facet> <apex:outputLabel value="{!case.CaseNumber}" /> </apex:column> <apex:column > <apex:facet name="header"> <apex:commandLink value="Record Type" action="{!sortCases}"> <apex:param name="productSortField" value="RecordType.Name" assignTo="{!sortField}"/> </apex:commandLink> </apex:facet> <apex:outputLabel value="{!case.RecordType.Name}" /> </apex:column> <apex:column > <apex:facet name="header"> <apex:commandLink value="Contact" action="{!sortCases}"> <apex:param name="productSortField" value="Contact.Name" assignTo="{!sortField}"/> </apex:commandLink> </apex:facet> <apex:outputLabel value="{!case.Contact.Name}" /> </apex:column> <apex:column > <apex:facet name="header"> <apex:commandLink value="Account" action="{!sortCases}"> <apex:param name="productSortField" value="Account.Name" assignTo="{!sortField}"/> </apex:commandLink> </apex:facet> <apex:outputLabel value="{!case.Account.Name}" /> </apex:column> <apex:column > <apex:facet name="header"> <apex:commandLink value="Date Opened" action="{!sortCases}"> <apex:param name="productSortField" value="Opened_Date__c" assignTo="{!sortField}"/> </apex:commandLink> </apex:facet> <apex:outputLabel value="{!case.Opened_Date__c}" /> </apex:column> </apex:PageBlockTable> <apex:commandButton action="{!save}" value="Save To Case Queue" status="retrieveSaveStatus" id="btnSave" immediate="false" /> </apex:panelGrid> </apex:pageBlockSection> </apex:pageBlock> </apex:form> <apex:form style="width:400px" > <apex:pageBlock title="Case Queue" > <apex:pageBlockButtons location="top" > <apex:commandButton action="{!submitCases}" value="Submit Notes" status="retrieveSaveStatus" id="btnSubmitCases" immediate="false" /> </apex:pageBlockButtons> <apex:actionStatus layout="block" startText="Saving notes. . . " stopText="" id="retrieveSaveStatus" startStyle="color:green; font-style:italic" stopStyle="color:black;"/> <apex:pageMessages showDetail="false" /> <br/> <br/> <apex:pageBlockSection title="Case Queue" columns="1"> <apex:pageblocktable value="{!queue}" var="que"> <apex:column headervalue="Contact Name" value="{!que.Contact_Name__c}"/> <apex:column headervalue="Case Number" value="{!que.Case__c}"/> <apex:column headervalue="Date" value="{!que.Date__c}"/> </apex:pageblocktable> <apex:panelGrid columns="2" cellpadding="5" style="margin-bottom: 15px;"> <apex:commandButton action="{!removelast}" value="remove Last" id="removelast" immediate="false" /> <apex:commandButton action="{!removeall}" value="remove all" id="removeall" immediate="false" /> </apex:panelGrid> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:panelGrid> </apex:page> Apex Controller public class MassAddCaseNotes { public Case_Note__c Case_Notes {get; set;} public List<Case> cases {get; private set;} public Map<Id, Boolean> selectedCases {get; set;} public Case filterCase {get; set;} public String sortField {get; set;} public boolean direction {get; set;} public List<Case_Note__c> queue {get; set;} private ApexPages.StandardSetController allCases {get; set;} private final String selectCasesQuery = 'SELECT Id, CaseNumber, RecordType.Name, Contact.Name, Account.Name, Opened_Date__c, ClosedDate, Program_Location_Assignment__c, Referring_Agency__r.Name ' + 'FROM Case ' + 'WHERE Status=\'Open\' AND RecordTypeId IN (SELECT Id FROM RecordType WHERE SObjectType = \'Case\' AND IsActive = true)'; public MassAddCaseNotes (ApexPages.StandardSetController controller) { queue = new List<case_Note__c>(); Case_Notes = new Case_Note__c(); filterCase = new Case(); direction = true; //selectCases(); direction = false; } public void selectCases() { if (sortField == null) sortField = 'CaseNumber'; String filter = ''; if (filterCase.RecordTypeId != null) filter += ' AND RecordTypeId = \'' + filterCase.RecordTypeId + '\''; if (filterCase.ContactId != null) filter += ' AND ContactId = \'' + filterCase.ContactId + '\''; if (filterCase.AccountId != null) filter += ' AND AccountId = \'' + filterCase.AccountId + '\''; allCases = new ApexPages.StandardSetController(Database.getQueryLocator(selectCasesQuery + filter + ' ORDER BY ' + sortField + (direction ? ' ASC' : ' DESC'))); allCases.setPageSize(1); updateCases(); } public void sortCases() { direction = !direction; selectCases(); } public Boolean hasPrevious {get {return allCases.getHasPrevious();}} public Boolean hasNext {get {return allCases.getHasNext();}} public void previous() { allCases.previous(); updateCases(); } public void next() { allCases.next(); updateCases(); } private void updateCases() { cases = allCases.getRecords(); selectedCases = new Map<Id, Boolean>(); for (Case c : cases) { selectedCases.put(c.Id, false); } } public void addtoqueue() { for (Case c : cases) { if (selectedCases.get(c.Id)) { Case_Note__c items = new Case_Note__c( Case__c = c.Id, Date__c = Case_Notes.Date__c, Contact_Name__c = filtercase.contactid, Note__c = Case_Notes.Note__c ); queue.add(items); } } } public void removelast() { queue.remove(queue.size()-1); } public void removeall() { queue.clear(); } public PageReference save() { addtoqueue(); return null; } public PageReference submitCases() { integer i = 0; while(i<queue.size()) { insert queue[i]; i++; } queue.clear(); PageReference pg = new PageReference('/apex/MassAddCaseNotes'); pg.setRedirect(true); return pg; } } A: For adding row numbers in pure Visualforce, you can use apex:variable. Like any other variable, you first declare it, then increment it. <apex:variable var="rowcount" value="{!0}" /> <apex:dataTable ...> <apex:column> {!rowcount} <apex:variable var="rowcount" value="{!rowcount+1}" /> </apex:column> ... </apex:dataTable> For the second question, simply declare the a value for use in your controller: public Integer rowToRemove { get; set; } Then, in your page, reference the value: public void removeDesiredRow() { if(queue.size()>rowToRemove) { queue.remove(rowToRemove); } } The Visualforce page will note that it's bound to an integer and automatically do conversion for you (and provide a friendly error if the number isn't a number). In practice, you'll find it easier to use some data-grid library and link the entire thing up with action functions, but if you can't (e.g. company policy against OSS), you can achieve your goals with some fairly simple JavaScript or native Visualforce, although Visualforce tends to be very unresponsive for most demands today.
{ "pile_set_name": "StackExchange" }
Q: Why is there a string ID in the data model of Azure Mobile Apps? I'm working the C# in Azure Mobile Apps trying to learn them. I created the Model to link to my Azure SQL DB, created a DataObject like this: public class Account : EntityData { //public int id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string PhoneNumber { get; set; } public string Password { get; set; } public DateTime dtCreated { get; set; } public Guid oGuid { get; set; } } Notice that I commented out the public int id above; it was giving me a duplicate column error on the query. Finally, I created a controller using the newly created Account DataObject. So I ran the application and hit the "tables/Account" function and it returned zero rows (but there is data and I can query it with the user I'm using in the azure mobile app). I then noticed the model schema as this: [ { "id": 0, "FirstName": "string", "LastName": "string", "PhoneNumber": "string", "Password": "string", "dtCreated": "2016-07-06T17:45:47.114Z", "oGuid": "string", "Id": "string", "Version": "string", "CreatedAt": "2016-07-06T17:45:47.114Z", "UpdatedAt": "2016-07-06T17:45:47.114Z", "Deleted": true } ] There's a couple of issues I see with the configured model (and I don't know where some of the columns are coming from...) First, the id is listed twice, once as an int (which has to be mine) and another id as string and I have no idea where that came from. Also, in the DB, the oGuid is of type uniqueIdentifier; not string. This may or may not be an issue because I can't test yet. Then there are the other columns that just do not exist in my DB including CreatedAt (datetime), UpdatedAt (datetime), Version (string) and Deleted (bit). I'm thinking the issue / reason why I'm not getting any data back from that call is that there is a data mismatch. Do I need to add the other columns that are listed in the model in the api test? I've also tested trying to call the /table/Account/3 to load a specific account and it returns no rows... I'm guessing it's a model mismatch but I'm not sure if that's the issue or something else causing it? I'm not seeing any errors or warnings. Update I figured out what is going on with model first and Azure and how to attach an existing DB in Azure to new code. I'm going to post this here for the hopes that it saves other's time. This really should have been easier to do. I'm not a fan of codefirst (yet) as I like to control the DB by hand... So this makes it a lot easier for me to work with the db backend. First I created a new project (Azure Mobile App) then under models I right clicked the model and add->new entity data model then added in the azure db name, password and gave it my "user created profile name" as used below. This connection must be edited in the web.config as shown below. I then had to create the model for the table in DataObjects (without the MS required columns) and create a controller off of the dataobject. I then had to edit the web.config and set a non-entity DB connection string: eg: <add name="[user created preset name]" providerName="System.Data.SqlClient" connectionString="Server=[Azuredb server connection];initial catalog=[DBName];persist security info=True;user id=[user];password=[pass];MultipleActiveResultSets=True"/> Finally, in the MobileServiceContext, I had to map the DataObject model to the table in Azure sql and set the connection string to use from the default MS_TableConnectionString to the connectionstring in web.config. private const string connectionStringName = "Name=[user created preset name]"; and under OnModelCreating() I added: modelBuilder.Entity<Account>().ToTable("tblAccount"); Where Account was the model (class) I created in DataObjects and the tblAccount is the table name in AzureDB. A: The EntityData abstract class contains the additional fields - there are five fields for Mobile offline sync Id (a string - normally a GUID - must be globally unique) UpdatedAt (DateTimeOffset - maintained automatically via a database trigger - used for incremental sync) CreateAt (DateTimeOffset - used as the key into the database partition to optimize reading, but unused otherwise) Version (a byte[] - timestamp - used for optimistic concurrency / conflict resolution) Deleted (a Boolean - used to update other clients when a record is deleted - known as soft delete). Your client needs all these fields in its client model except for Deleted (which isn't transferred unless requested and is dealt with automatically via the Mobile Apps SDK for clearing the offline sync of deleted records). You haven't said what languages are in use on backend or frontend. However, logging is available in both cases - you just have to turn it on, capture the exceptions, etc. Some references for you: Node (backend): https://azure.microsoft.com/en-us/documentation/articles/app-service-mobile-node-backend-how-to-use-server-sdk/ .NET (backend): https://shellmonger.com/2016/05/11/30-days-of-zumo-v2-azure-mobile-apps-day-19-asp-net-table-controllers/
{ "pile_set_name": "StackExchange" }
Q: Select Duplicate Sub String of Records to Single Record Using Group By Is it possible writing SQL to select duplicate sub string of records from a table into single records ? I just want to group the month and year so the result look like this picture: I try this, but it didn't work. SELECT DATE, SUBSTRING(DATE, 3, 6) as Addrow FROM dbo.n4abs_premi_olah GROUP BY Addrow Any advice will be appreciated. Thank you ! A: SELECT DISTINCT(DATE_FORMAT(date, '%m/%Y')) month FROM Table If you actually need to use GROUP BY (because you're also selecting other aggregates), do: SELECT DATE_FORMAT(date, '%m/%Y')) month, other stuff... FROM Table GROUP BY month
{ "pile_set_name": "StackExchange" }
Q: Reverse the directed graph I have to reverse a given directed graph, so that the vertices remain the same, but edges are in opposite direction. My graph is represented with a Graph class, which contains an ArrayList of vertices, and each Vertex object has it's number and ArrayList of it's adjacent vertices. My code gives wrong answer, because in each iteration of loop, vertex's adjacent list's size changes. How can I fix my code? public void reverse() { ArrayList < Vertex > adjacentOfi = new ArrayList < Vertex > (); int k; for (int i = 1; i < verticesSize; i++) { adjacentOfi = vertices.get(i).getAdjacent(); for (int j = 0; j < adjacentOfi.size(); j++) { k = adjacentOfi.get(j).getNumber(); adjacentOfi.remove(j); vertices.get(k).getAdjacent().add(vertices.get(i)); } } } Here is Vertex class public class Vertex { private int number; private boolean marked; private int finishingTime; private ArrayList<Vertex> adjacent; public Vertex(int num) { this.number = num; this.marked = false; this.finishingTime = 0; this.adjacent = new ArrayList<Vertex>(); } } plus of course it's getters and setters. Problem is that when the loops starts from Vertex number 1, and it's adjacency list contains Vertex 5, it adds 1 to 5's adjacency list and deletes 5 from 1's adjacency list. Next time, when loop reaches 5, it adds 5 to 1'a adjacency list and deletes 1 from 5's adjacency list. I need to maintain the initial size of each list, before the loop modifies it. A: Goal: performing an atomic operation one time on every edge in a graph. Pseudocode: function reverse(graph G) v = any vertex in G reverseVertex(v) end function function reverseVertex(vertex v) mark v as visited E = set of all outward edges from v N = { } // empty set, will contain all neighbors for each edge e in E, q = vertex reached by e from v if q is not visited, add q to N reverse direction of e end if end for for each vertex q in N, reverseVertex(q) end function What you should do: Since I assume you're a student with an assignment (usually the case with questions beginning with "I have to..."), I'll quickly explain my pseudocode so you get the overarching idea and have the ability to implement it yourself. You can't just loop through the vertices and reverse each edge, because reversing an edge makes it an outgoing edge to some other vertex, and if you haven't looked at that other vertex yet with your loop, you'll end up reversing it again, which will result in the edge being the same direction as it started. Or, you'll have already looked at the other vertex, in which case it will be fine. But both possibilities exist if you're looping randomly through the vertices, so looping randomly through all the vertices doesn't work. A more intuitive solution would be to start at any vertex in the graph, and label it visited. Then, for each unvisited neighbor of the vertex, add the neighbor to a list and reverse the edge going to the neighbor (i.e. by deleting it and adding it as you've done in your code). Then, call this function recursively on all the neighbors in the list of unvisited neighbors. Eventually, the recursive calls will terminate once you reach a vertex with all of its neighbors visited, or a leaf. I'm sure that an inductive proof of this algorithm wouldn't be too hard to come up with. Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: How many confirmations do I need to ensure a transaction is successful? As a regular user of Bitcoin, I often send bitcoins to other, or receive BTC from others, sometimes this might be a trade or deposit. Some traders require at least 6 confirmation, some require at least 3. I want to how many confirmation is enough to ensure the transaction is successful? A: It depends on your risk model. If you can trust the person paying you, you can accept payment on 0/unconfirmed if you want. As a merchant or trader, you want to use the configuration that is more secure (no incoming connections permitted, explicity connect to well-connected nodes). With zero confirmations you are vulnerable to the race attack and the Finney attack, as well as the 51% attack. With one confirmation you are vulnerable to the 51% attack. There could also be a miner with a lot of hashing power who could get a couple blocks in a row, so three confirmations removes most of them. With six confirmations it is essentially mathematically impossible for an attacker with less than 51% of all mining capacity to get six blocks in a row. and still surpass the longest block chain. With 51% or a lot more than 51% the attacker can get six confirmations by creating a parallel blockchain in which only transactions approved by the attacker get included in blocks. A merchant like a retailer can likely accept even on 0/unconfirmed in most instances (e.g., purchases up to $100 worth). A merchant that ships e-commerce might hold off until the transaction has three confirmations. A cash, face-to-face cash trade will probably be best if three confirmations for a large amount, maybe one confirmation for small amounts. Any recommendation would need to come only after determining which risks are deemed acceptible. A: The lesson of the recent v0.7/v0.8 fork issue is that simply waiting for 6 or more confirmations is insufficient. You also need to satisfy yourself that there are no competing blockchain forks e.g. this thread discusses a double spend proof-of-concept that was executed during the chain fork: https://bitcointalk.org/index.php?topic=152348.0
{ "pile_set_name": "StackExchange" }
Q: How to use xkcd together with matplotlib and PyQt I want to plot a graph in xkcd style in my PyQt application. Since it is not recommended to use pyplot together with the Qt5Agg-backend I am struggling to find a right way to import the xkcd package so that I can use it without pyplot. The normal way to use the xkcd-package would be from matplotlib import pyplot as plt plt.xkcd() But I am using import matplotlib from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg So is there a way plotting in xkcd style without using pyplot? A: There is no danger in importing pyplot. You may just be recommended not using pyplot for plotting tasks when working with figures inside GUIs. I guess this recommendation is the more valid the less experienced you are. Even using pyplot for plotting tasks in GUIs is in general possible as long as you know what you're doing. But in any case there is no danger in using plt.xkcd(), since it does not interfere with anything and justs sets the rcParams to follow a certain style.
{ "pile_set_name": "StackExchange" }
Q: How to get the elementwise day of the year from an numpy datetime array? Do you have an idea, how I can get the elementwise day of the year from an numpy datetime array? With my code I can only receive the day of the year for one element in the array.How can I get the day of the year for each element in the array? Here is my code (including your code): #import modules import numpy as np import pandas as pd import datetime from datetime import datetime #date values in an numpy array as int data_int = np.array([[20131001, 20131001, 20131001], [20131002, 20131002, 20131002], [20131002, 20131002, 20131002]]) #transform the data_int array in a datetime list data_list = [pd.to_datetime(pd.Series(x), format="%Y%m%d") for x in data_int] #transform the datetime list back to an datetime array with dtype='datetime64[ns]') data = np.asarray(data_list, dtype='datetime64', order=None) #convert dtype='datetime64[ns]' into a datetime.date object data_date = data.astype('M8[D]').astype('O') #get the day of the year from the the data_date array. day_of_year = data_date[0,1].timetuple().tm_yday #274 It would be great if you or someone else has an good idea for me!! Thank you! A: import numpy as np import pandas as pd #date values in an numpy array as int data_int = np.array([[20131001, 20131001, 20131001], [20131002, 20131002, 20131002], [20131002, 20131002, 20131002]]) #transform the data_int array in a datetime list data_list = [pd.to_datetime(pd.Series(x), format="%Y%m%d") for x in data_int] doy = pd.DataFrame([x.apply(lambda x: x.timetuple().tm_yday) for x in data_list]).values print(doy) Output: [[274 274 274] [275 275 275] [275 275 275]]
{ "pile_set_name": "StackExchange" }
Q: How do I most quickly delete an entire row/column from an array? E.g. I want to turn a 360x160 array into a 360x159 array. A: you can select only the rows you need: a = ones(360,160); b = a(:,1:159); size(b) ans = 360 159
{ "pile_set_name": "StackExchange" }
Q: How to split images using ImageMagick? I have an image which contains multiple images in it. I want to split the image into multiple image files, one file per image. How do I do this using ImageMagick? I have attached a sample image file. A: To simply split your image into quadrants (same size) use crop+repage: convert image.jpg -crop 50%x50% +repage piece_%d.jpg If you need different size quadrants you could cut around a single point: convert image.jpg -crop 240x280+0+0 +repage piece_1.jpg convert image.jpg -crop 0x280+240+0 +repage piece_2.jpg convert image.jpg -crop 240x0+0+280 +repage piece_3.jpg convert image.jpg -crop +240+280 +repage piece_4.jpg
{ "pile_set_name": "StackExchange" }
Q: NSURLConnection finished with error - code -1002 when trying to encode URL in iOS I was trying to encode a URL. The code works fine when I encode files in my bundle. But when I tried to encode the files written to Documents and Cache, the program fails to encode. Here is my encoder: private class func EncodeURL(_ url:URL,encoding:UInt) ->String { do{ return try NSString(contentsOf: url, encoding: encoding) as String }catch{} return "" } I'm using the following three: content = EncodeURL(url, encoding: String.Encoding.utf8.rawValue) content = EncodeURL(url, encoding: 0x80000632) content = EncodeURL(url, encoding: 0x80000631) And none of them work. Here is the code I use to generate files. I'm putting them in the Documents Folder. func writeFile(fileName:String,data:NSData)->Bool{ guard let filePath = createFilePath(fileName: fileName) else{ return false } return data.write(toFile:filePath,atomically:true) } func createFilePath(fileName:String)->String?{ let dir = getCachePath() if(!dirExists(dir: dir) && !createDir(dir: dir)){ return nil } let filePath = dir + fileName if(fileExists(path: filePath)){ do{ try getFileManager().removeItem(atPath: filePath) }catch{ return nil } } return filePath } func getCachePath()->String{ var cacheDir = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, .userDomainMask, true).first! if(!cacheDir.hasSuffix("/")){ cacheDir += "/" } cacheDir += CACHEPATH + "/" //CACHEPATH is just NSHomeDirectory() return cacheDir } writeFile(fileName: String(timeInterval)+"_"+somestring+".txt", data: data! as NSData) Above is how I generate the files. And how I passed URL is: url = URL(string:getCachePath()+bookname+".txt") passing this to EncodeURL(url:URL,encoding:UInt) My URL is: /Users/houki/Library/Developer/CoreSimulator/Devices/67C921C8-18A3-4A3F-81FF-C3AF04E88049/data/Containers/Data/Application/85633861-90E6-4DB8-95B0-86C359C74C6B/Documents//Users/houki/Library/Developer/CoreSimulator/Devices/67C921C8-18A3-4A3F-81FF-C3AF04E88049/data/Containers/Data/Application/85633861-90E6-4DB8-95B0-86C359C74C6B/1511757881.83107_bigbrother.txt Does this look weird? I'm testing it on a simulator though. But actually this worked just fine when I tried to read files through the path. The following code is working. let contentsofPath = try FileManager.default.contentsOfDirectory(atPath: getCachePath()) A: You are not creating your URL correctly. You are passing a path to the string argument. You need to use the URL(fileURLWithPath:) initializer. let url = URL(fileURLWithPath: path) Only use the URL(string:) initializer if the string you pass is a valid URL beginning with a URL scheme.
{ "pile_set_name": "StackExchange" }
Q: Security Model in Rails Question I am reading a great Rails tutorial and came across a passage that I had a question about: Box 9.2.Sessions and cookies Because HTTP is a stateless protocol, web applications requiring user signin must implement a way to track each user’s progress from page to page. One technique for maintaining the user signin status is to use a traditional Rails session (via the special session function) to store a remember token equal to the user’s id: session[:remember_token] = user.id This session object makes the user id available from page to page by storing it in a cookie that expires upon browser close. On each page, the application can simply call User.find_by_id(session[:remember_token]) to retrieve the user. Because of the way Rails handles sessions, this process is secure; if a malicious user tries to spoof the user id, Rails will detect a mismatch based on a special session id generated for each session. For our application’s design choice, which involves persistent sessions—that is, signin status that lasts even after browser close—storing the user id is a security hole. As soon as we break the tie between the special session id and the stored user id, a malicious user could sign in as that user with a remember_token equal to the user’s id. To fix this flaw, we generate a unique, secure remember token for each user based on the user’s salt and id. Moreover, a permanent remember token would also represent a security hole—by inspecting the browser cookies, a malicious user could find the token and then use it to sign in from any other computer, any time. We solve this by adding a timestamp to the token, and reset the token every time the user signs into the application. This results in a persistent session essentially impervious to attack. I don't understand what this is saying. I take from it that a unique session ID is created and stored on the client in a cookie. Then when that cookie is sent to the server on a request, the server knows that is the user in question so that the login can be persisted. However, if a malicious user stole the cookie, I don't understand why they can't log in from another computer. The author says this is solved by adding a timestamp, but I don't see how that helps. Further, the author says that the token is reset every time the user signs in, but the whole point is a persistent sign in, so I don't understand. Please help! A: You are correct—a "Remember Me" cookie can be used to steal a login. The issue that they're trying to resolve are if someone steals your cookie, containing your unique identifier, and hangs on to it—they'd then be able to log into your account at any point in the future. The usual solution is to invalidate all previous cookies every time that you log into your account using either the username/password or the "Remember Me" cookie, so that a given cookie will allow you to login a single time. The timestamp is how they're ensuring the uniqueness of each cookie. If you're worried about cookies being stolen, a typical solution is to also store the IP address that the request came from, and if the IP address that the cookie is coming from doesn't match the IP address that the cookie was created from, deny the login and force the user to sign in. This can be inconvenient to users who are behind dynamic proxies, or who carry their laptop to and from work/home/coffee-shop, since their IP address will change all the time. "Remember Me" is a security hole by design. The goal is to limit how much of a hole it is, and if you're designing a system that requires absolute security, it's not a good choice. If convenience is more relevant than security, using timestamps and cookie invalidation limits the potential security issues. If you're interested in more information on this topic, the Security Guide section of Rails Guides has an entire section on sessions.
{ "pile_set_name": "StackExchange" }
Q: Bootstrap Carousel Active Thumbnail Styles I have this custom bootstrap carousel I am trying to work with and make the active thumbnail style change when it is active. I need to keep the thumbnail list using div vs li so that I can keep them in the responsive grid. $('#myCarousel').carousel({ interval: 4000 }); var clickEvent = false; $('#myCarousel').on('click', '.thumbs a', function() { clickEvent = true; $('.thumbs .item').removeClass('active'); $(this).parent().addClass('active'); }).on('slid.bs.carousel', function(e) { if(!clickEvent) { var count = $('.thumbs').children().length -1; var current = $('.thumbs .item.active'); current.removeClass('active').next().addClass('active'); var id = parseInt(current.data('slide-to')); if(count == id) { $('.thumbs .item').first().addClass('active'); } } clickEvent = false; }); I've put together this jsfiddle to demonstrate what I'm attempting to achieve: http://jsfiddle.net/vr3xyqpv/3/ The red border on the thumbnail should stay visible while it is on each slide. It appears to be working when first viewed, but it jumps around weird and once you click a thumbnail, it stops remaining active for long. A: Here is a way : Fiddle : http://jsfiddle.net/ewx61o1k/1/ Js : $('#myCarousel').carousel({ interval: 4000 }); $('#myCarousel').on('slid.bs.carousel', function(){ var index = $('.carousel-inner .item.active').index(); $('.thumbs .item[data-slide-to="'+index+'"]').addClass('active'); });
{ "pile_set_name": "StackExchange" }
Q: Mysql ORDER BY using date data row I have a query something like this: SELECT title, desc, date FROM tablename ORDER BY date ASC, title ASC; Works fine when the data actually has a date. Issue is, date submission is optional, so I sometimes get 0000-00-00 as a date, which has the unfortunate effect of placing all nondated rows on top. So, I then tried this: SELECT title, desc, date FROM tablename ORDER BY date DESC, title ASC; Which sort of works, but not really -- all items with dates (non 0000-00-00) get listed in descending order, followed by all items with 0000-00-00. What I want to do is order by date ASC, title ASC, but only if the date != 0000-00-00, but if date is = 0000-00-00, then just ORDER BY title ASC on those (I think I explained that correctly). The only ways I can think to do this are non-SQL based (either 2 queries, or, each query just populates an in-memory array, and then I sort using PHP). Is there a SQL query that can do this? A: ORDER BY date = '0000-00-00' ASC, date ASC, title ASC A: Your 2 query solution is a good one, you can do it all in SQL using the UNION command. The first query will be for dates that are non-zero, then UNION in the query for dates that are zero. Edit: Something like: SELECT * FROM tbl WHERE DATE != '0000-00-00' ORDER BY date ASC UNION SELECT * FROM tbl WHERE DATE = '0000-00-00' ORDER BY title ASC This may not be very useful in this instance, but for complex queries, UNION can come in handy.
{ "pile_set_name": "StackExchange" }
Q: Apply regular expression to a pandas dataframe column Im trying to apply some regular expressions that I have coded up and can run against a variable but I would like to apply it on a dataframe column and then pass the results out to a new column df["Details"] is my dataframe df["Details"] is my dataframe and it contains some text similar to what I have created below as details import re details = '1st: Batman 01:12.98 11.5L' position = re.search('\w\w\w:\s', details) distance = re.search('(\s\d\d.[0-9]L)', details) time = re.search(r'\d{2}:\d{2}.\d{2}',details) print(position.group(0)) print(distance.group(0)) print(time.group(0)) output is then 1st: 11.5L 01:12.98 I would like to then be able to add those values to new columns in the dataframe called position,distance,time respectively matching the output A: I believe you need Series.str.extract: details = '1st: Batman 01:12.98 11.5L' df = pd.DataFrame({"Details":[details,details,details]}) df['position'] = df['Details'].str.extract(r'(\w\w\w:\s)') df['distance'] = df['Details'].str.extract(r'(\s\d\d.[0-9]L)') df['time'] = df['Details'].str.extract(r'(\d{2}:\d{2}.\d{2})') print(df) Details position distance time 0 1st: Batman 01:12.98 11.5L 1st: 11.5L 01:12.98 1 1st: Batman 01:12.98 11.5L 1st: 11.5L 01:12.98 2 1st: Batman 01:12.98 11.5L 1st: 11.5L 01:12.98
{ "pile_set_name": "StackExchange" }
Q: Trying to create a deck of cards using For Loop I am trying to create a deck of cards using 2 arrays. One array is the suits and the other is the values. My thought was to use a for loop to iterate through an array to create the 52 cards deck. However, I can't seem to get the syntax right. I tried using forEach method. var deck = []; var suits = ["diamonds", "spades", "hearts", "clubs"]; var values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]; suits.forEach(function(suits) { deck.push(suits); deck.push(values); }); console.log(deck) A: You need two loops, one over the suits, and one over the face values, e.g. var deck = []; var suits = ["diamonds", "spades", "hearts", "clubs"]; var values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]; suits.forEach(function(suit) { values.forEach(function(value) { deck.push(`${value} of ${suit}`); }); }); console.log(deck); Alternatively, you can use flatMap: var suits = ["diamonds", "spades", "hearts", "clubs"]; var values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]; var deck = suits.flatMap(suit => values.map(value => `${value} of ${suit}`)); console.log(deck); Note: flatMap is not supported by some older browsers, so you may need polyfill. And just for demonstration purposes, you could also do this with Ramda's map and xprod: var suits = ["diamonds", "spades", "hearts", "clubs"]; var values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]; var deck = R.map(([suit, value]) => `${value} of ${suit}`, R.xprod(suits, values)); console.log(deck); <script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
{ "pile_set_name": "StackExchange" }
Q: SQL Server: when Else is case it is showing 0 as default in CASE clause This query is run on AdventureWorks2014.Sales.SalesOrderDetail table. My query: in the CASE clause I have clearly stated to show - when it is the ELSE case. This query removes the repeating SalesOrderID and after 1st time shown it should be replaced with "-" this character. SELECT CASE WHEN ROW_NUMBER() OVER(PARTITION BY SalesOrderID ORDER BY SalesOrderID ASC) = 1 THEN SalesOrderID ELSE '-' END AS SalesOrderID, R.ProductID, R.OrderQty, R.UnitPrice, R.LineTotal FROM AdventureWorks2014.Sales.SalesOrderDetail AS R currently showing 0 even though i said in the ELSE to show me - A: Below query will solve your issue SELECT CASE WHEN ROW_NUMBER() OVER(PARTITION BY SalesOrderID ORDER BY SalesOrderID ASC) = 1 THEN CONVERT(varchar(10),SalesOrderID) ELSE '-' END AS SalesOrderID, R.ProductID, R.OrderQty, R.UnitPrice, R.LineTotal FROM AdventureWorks2014.Sales.SalesOrderDetail AS R
{ "pile_set_name": "StackExchange" }
Q: Fixie chain stuck between cog and hub I had my chain jump off on my fixed gear when I hit a pothole, and it's gotten completely wedged between the cog and the flange of the hub. I've removed the lockring but can't get a chain whip around the cog to loosen it and the chain is completely wedged tight in there – no amount of force I've been able to generate has budged it at all. Any suggestions for how I might get the cog loose to free the chain? A: Yeah, I managed to do this one one of my bikes once. There was no way I could brute force the chain from between the cassette and the spokes. My suggestion would be to use a vice, or do you have one of those Workmate things? The first thing I'd do is to break the chain and get the whole "wheel and chain" mess away from the frame. It just gives you more room to work. Then, I'd clamp the teeth of the cog in the vice (as I say, I've had good results with my Workmate). Then you undo the lockring, which admittedly can be fiddly. If it has been on a while it will be tight, as you have discovered, and you might need to use a mallet to coax it loose. (I have tried chain whips in the past too, but never even bother nowadays, a vice is far more efficient.) If you don't have any way of clamping the cog, the only other suggestion is to take the wheel to a shop, who will use their vice to loosen it. With the right tools, it is really only a 30-second job so you may be able to sweettalk them into doing it for free. Lastly, you should probably spend some time thinking about how this happened. Could be you just got a jump because the chain was loose, but it is probably worth checking your chainline to satisfy yourself that everything is ok. You might also want to check your spokes for any damage from the chain.....better to replace them now, while you've taken things apart, than have them break later.
{ "pile_set_name": "StackExchange" }
Q: Force absolute path for shared library without LD_RUN_PATH I am trying to link a locally installed shared library (./vendor/lib/libfoo.so) with my binary, ./bar. Unfortunately, none of my attempts generates a link with an absolute path to libfoo.so. As a consequence I need to use LD_LIBRARY_PATH=vendor/lib ./bar to run it, which I want to avoid. ldd bar shows me this: linux-vdso.so.1 => (0x00007ffed5fd8000) libbar.so.2 => not found libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007fb9ea787000) libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fb9ea47d000) libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fb9ea267000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fb9e9e9d000) /lib64/ld-linux-x86-64.so.2 (0x000055f326761000) A word about libbar.so.2: the file exists (in vendor/lib) alongside libbar.so. Both are actually symlinks to libhts.so.1.6. That file also exists, and is the actual shared library. Here’s the different ways I’ve tried: FULL_PATH="$(pwd -P)/vendor/lib" g++ -o bar bar.o -Lvendor/lib -lfoo # 1 g++ -o bar bar.o -L$FULL_PATH -lfoo # 2 g++ -o bar bar.o $FULL_PATH/libfoo.so # 3 g++ -o bar bar.o $FULL_PATH/libfoo.so.1.6 # 4 All of these variants produce identical ldd output, even the last line (does ld insist on using the highest version of a library?). The only way I’ve found to make this work is to use LD_RUN_PATH=$FULL_PATH g++ -o bar bar.o -Lvendor/lib -lfoo (I can’t use -rpath because my version of g++ doesn’t understand this argument, and I’m using g++ instead of ld to get the libstdc++ dependencies right — I could use -Wl,-rpath of course.) But I can’t help but feel that there should be a way of making this work without the use of environment variables/-rpath. I’ve found an answer specifically referencing symlinks to libraries but unfortunately it doesn’t help me (see attempt 4 above). This is on Ubuntu 16.04, g++ 5.4.0, GNU ld 2.26.1, in case it matters. A: It sounds likely that you didn't update the ldconfig cache after installing your shared library in the non-standard location /what/ever/vendor/lib:- sudo ldconfig /what/ever/vendor/lib Until you do that the runtime linker will be unaware that libfoo.so is in /what/ever/vendor/lib, even if it is, unless you prompt it at runtime through the LD_LIBRARY_PATH environment variable. Incidentally, it isn't a shortcoming of your version of g++ that it doesn't recognize -rpath. This has only ever been a linker (ld) option, never a GCC frontend option. So -Wl,-rpath=/what/ever/vendor/lib is the conventional way of tacking the non-standard runtime library path to your program so as to avoid relying on either the ldconfig cache or LD_LIBRARY_PATH For out-of-the ordinary linkages it may be considered better to use -rpath rather than extend the ldconfig cache, which has less discriminate effects.
{ "pile_set_name": "StackExchange" }
Q: Seeking QGIS equivalent to Focal Statistics of ArcGIS Spatial Analyst? I'm attempting to use QGIS v2.0.1 to accomplish the same tasks that I can do using ArcMap v10.1 and I'm running into some trouble finding equivalent tools. In ArcMap I am using the Focal Statistics (mean) Spatial Analyst tool and I do not know if GRASS or SAGA has an equivalent in QGIS. Does anyone know what the tool would be called if it exists? A: Sure, have for instance a look at the r.neighbors tool available through the processing-toolbox with GRASS support enabled. It has a similar functionality as the Focal Statistics tool. I will also soon add a generic filter function to my QGIS plugin LecoS (needs installed Scipy), which can do the same stuff, but uses python+scipy as backbone. A: Still in QGIS 2.4 there are no focal statistics, i.e. filters, per se, and I do not think that there will be any in the future. However, SAGA can be reached via the Processing tool box. In the SAGA command list you can choose Grid - Filter and then you have plent of a choice. I suggest using the "user defined filter" if you know what you are doing or the "simple filter" if it is all about smoothing. cheers
{ "pile_set_name": "StackExchange" }
Q: Can Dante Alighieri be compared to Shakespeare as both fathers of their respective languages on the lexical level? Many people say that Dante Alighieri is "the father of Italian" and his name is widely known and appreciated. Motivated by Does the German language have a Shakespeare?, asked on the German SE, which got very interesting answers, I would like to ask the same for Italian. The Wikipedia article about Shakespeare's influence on the English language claims that this writer created a great deal of neologisms, phraseological expressions, sayings that became part of the language, enriching it and providing it with great literary content. This phenomenon has to be better understood with in the complete framework of the history of the English language (a good summary can be read here). On the other hand, nobody can question Dante's grandeur, his works are considered masterpieces not only within Italy but also abroad. But the history is pretty different: standard Italian was born out of the Florentine dialect. Dante is considered his father right because his literary work has shaped the educated content of a language and the particular language he spoke was then chosen to be the representative language of the whole peninsula. Both have worked in an era of rather confused set of linguistics canons and both have put those into a well-defined form. If we focus on the lexical level, was Dante a creator of neologisms like Shakespeare or not? Did he insert expressions we still use today in the language? A: If we focus on the lexical level, the answer is yes, Dante was a creator of many words and expressions that we use. First, according to some statistic here, 90% of the basic Italian lexicon in use nowadays (that is, 90% out of 2000 most common words, which are in turn 90% of what is said, read, and written every day) are already in Commedia. Second, Dante's neologisms include accidioso, cencro, contrappasso, imparadisare, indiarsi, indovarsi, inforsarsi, infuturarsi, inmiarsi e intuarsi, e anche inluiarsi e inleiarsi, inmillarsi, inurbarsi, inzaffirarsi, lonza, squadernare, trascolorare, trasmodare, trasmutare, trasumanare, trasvolare, veltro, and many others. Yes, they were mainly derivatives from the words already known to the reader at the time, but that was exactly the point: to invent some new words but to make sure that the readers would still be able to understand them. A vast majority of 1700 words that are allegedly invented by Shakespeare consists also of derivatives. Third, just like Shakespeare, Dante has made popular many phrases, which are now used as idioms. The (more or less) full list of his expressions is here. For more information on the topic, one may consult: Baldelli, Ignazio (1996), Dante e la lingua italiana, Firenze, Accademia della Crusca. Fauriel, Claude Charles, Ardizzone, Girolamo (1856), Dante e le origini della lingua e della letteratura italiana, Palermo, La Societa libraria, A. Russo e comp.
{ "pile_set_name": "StackExchange" }
Q: Weird access with external pointers I made a small reproducible example: #include <Rcpp.h> using namespace Rcpp; class Index { public: Index(int i_) : i(i_) {} int getI() { return i; } private: int i; }; // [[Rcpp::export]] SEXP getXPtrIndex(int i) { Rcout << "getXPtrIndex: i = " << i << std::endl; Index ind(i); Rcout << "getXPtrIndex: ind.i = " << ind.getI() << std::endl; return XPtr<Index>(&ind, true); } // [[Rcpp::export]] void getXPtrIndexValue(SEXP ptr) { XPtr<Index> ind_ptr(ptr); Rcout << "getXPtrIndexValue: ind_ptr->i = " << ind_ptr->getI() << std::endl; Index ind = *ind_ptr; Rcout << "getXPtrIndexValue: ind.i = " << ind.getI() << std::endl; } Basically, I define a small class, along with a function to get an external pointer of an element of this class. The last function is used to print the weird accessor when returning the class element back to C++. Results in R: > (extptr <- getXPtrIndex(10)) getXPtrIndex: i = 10 getXPtrIndex: ind.i = 10 <pointer: 0x7ffeeec31b00> > getXPtrIndexValue(extptr) getXPtrIndexValue: ind_ptr->i = 33696400 getXPtrIndexValue: ind.i = 0 Why can't I access 10? I'm using Rcpp version 0.12.12 (the latest I think). A: It seems to have something to do with the temporary object---by the time your second function runs the "content" of the first is already gone. So either just make Index ind(10); a global, and comment out the line in your first function. Then all is peachy (I changed the R invocation slightly): R> extptr <- getXPtrIndex(10) getXPtrIndex: i = 10 getXPtrIndex: ind.i = 10 R> getXPtrIndexValue(extptr) getXPtrIndexValue: ind_ptr->i = 10 getXPtrIndexValue: ind.i = 10 R> Or it also works the same way when you make you Index object static to ensure persistence. Corrected example below. #include <Rcpp.h> using namespace Rcpp; class Index { public: Index(int i_) : i(i_) {} int getI() { return i; } private: int i; }; // [[Rcpp::export]] SEXP getXPtrIndex(int i) { Rcout << "getXPtrIndex: i = " << i << std::endl; static Index ind(i); Rcout << "getXPtrIndex: ind.i = " << ind.getI() << std::endl; return XPtr<Index>(&ind, true); } // [[Rcpp::export]] void getXPtrIndexValue(SEXP ptr) { XPtr<Index> ind_ptr(ptr); Rcout << "getXPtrIndexValue: ind_ptr->i = " << ind_ptr->getI() << std::endl; Index ind = *ind_ptr; Rcout << "getXPtrIndexValue: ind.i = " << ind.getI() << std::endl; } /*** R extptr <- getXPtrIndex(10) getXPtrIndexValue(extptr) */
{ "pile_set_name": "StackExchange" }
Q: Estimate for de Bruijn function with small fixed smoothness bound Let $\Psi(x,B)$ denote the number of $B$-smooth numbers less than $x$. Wikipedia gives the following "good estimate" for small, fixed $B$: $$\Psi(x,B) \sim \frac{1}{\pi(B)!} \prod_{p\le B}\frac{\log x}{\log p}$$ However, no citation or further discussion is given. Where does this estimate come from? How good an estimate is it? Anyone know a reference for this? A: This is discussed in chapter III.5 of Tenenbaum Intro to analytic and probabilistic number theory (Cambridge, 1995). The estimate up to a factor $1+O(B^2/\log x\log B)$ uniform in $2 \le B \le \sqrt{\log x\log\log x}$ is attributed to Ennola 1969.
{ "pile_set_name": "StackExchange" }
Q: Converting elevations into correct units with pyproj? I am converting a point from wgs84 into a state plane coord system (epsg: 32051, which is defined in US survey feet) using pyproj, but the transform isn't changing the z values into feet: point_4326 = (-81.23127933,37.70957554,668.105) proj1 = pyproj.Proj(init='epsg:4326') proj2 = pyproj.Proj(init='epsg:32051') print pyproj.transform(proj1, proj2, *point_44326) $ (589192.2346128735, 78765.53566868477, 668.105) I have also tried specifying the exact proj4 string for the new coord system (which includes the USft scaling factor), but get the exact same result: proj2 = pyproj.Proj('+proj=lcc +lat_1=37.48333333333333 +lat_2=38.88333333333333 +lat_0=37 +lon_0=-81 +x_0=609601.2192024384 +y_0=0 +ellps=clrk66 +datum=NAD27 +to_meter=0.3048006096012192 +no_defs') print pyproj.transform(proj1, proj2, *point_4326) $ (589192.2346128735, 78765.53566868477, 668.105) Any ideas how I can get pyproj to convert the elevation values to the correct units, or if there are similar tools / libraries which can do this? A: Look at Proj4 String for NAD83(2011) / Louisiana South (ftUS) preserve_units=True fix the problem (pyproj silently changes '+units=' parameter) import pyproj proj2 = pyproj.Proj(init='epsg:32051',preserve_units=True) proj1 = pyproj.Proj(init='epsg:4326') print pyproj.transform(proj1, proj2, *point_4326) (1933041.523059067, 258416.59493967678, 2191.941154166668) Control with GDAL/OSR from osgeo import osr wgs84 = osr.SpatialReference() wgs84.ImportFromEPSG(4326) proj2= osr.SpatialReference() proj2.ImportFromEPSG(32051) transformation = osr.CoordinateTransformation(wgs84,proj2) result = transformation.TransformPoint(*point_4326) print result (1933041.5230590631, 258416.59493967678, 2191.941154166668) And 2192 feets = 668.122 meters
{ "pile_set_name": "StackExchange" }
Q: Opening an attached pdf file on wiki page outside of browser I have set up a personal wiki on a localhost using drupal. I have attached pdf's that open in the browser window which is generally ok but I'd rather be able to open them in Preview so I get all the usability benefits of that app (without downloading them and thus creating a 2nd version outside the wiki directory). Anyone have a suggestion? A: I don't think you can open them in Preview without downloading them. Also - by merely opening or viewing the document at all, you are actually downloading it. It's stored in a temp directory somewhere, and likely trashed when you close your browser.
{ "pile_set_name": "StackExchange" }
Q: How to send big endian to network stream using c# I try to transfer a filedata with sockets via a sslStream. It seems that I must send the file data length before the data. The problem is that the code Byte [] size = BitConverter.GetBytes(fileData.Length) Returns in little endian but internet protocols are using big endian. How I can convert this to big endian and write it to stream; A: I assume that you want to send just one int value. The order of the bytes should be reversed before transmitting: byte[] bytes = BitConverter.GetBytes(fileData.Length); if (BitConverter.IsLittleEndian) Array.Reverse(bytes); Check this MSDN page to get more information about BitConverted. You could also convert it using HostToNetworkOrder, for example: int reversed = IPAddress.HostToNetworkOrder(fileData.Length); byte[] bytes = BitConverter.GetBytes(reversed); To send these bytes use the Write method: stream.Write(bytes, 0, bytes.Length);
{ "pile_set_name": "StackExchange" }
Q: Matplotlib: how to add xlabel, title to each subplot I'm trying to plot multiple heatmaps using the plt.subplots. An example I found is as follows: import numpy as np import matplotlib.pyplot as plt # Generate some data that where each slice has a different range # (The overall range is from 0 to 2) data = np.random.random((4,10,10)) data *= np.array([0.5, 1.0, 1.5, 2.0])[:,None,None] # Plot each slice as an independent subplot fig, axes = plt.subplots(nrows=1, ncols=4,figsize=(12,3)) i=0 for dat, ax in zip(data, axes.flat): # The vmin and vmax arguments specify the color limits im = ax.imshow(dat, vmin=0, vmax=2,cmap='Reds') # ax.xlabel(str(i)) # ax.ylabel(str(i)) i += 1 # Make an axis for the colorbar on the right side cax = fig.add_axes([0.95, 0.155, 0.03, 0.67]) fig.colorbar(im, cax=cax) figtype = 'jpg' fig.savefig('aaa.jpg',format = figtype,bbox_inches='tight') fig.tight_layout() The code succeeds if I comment the following two lines (which is done in the above example): ax.xlabel(str(i)) ax.ylabel(str(i)) If I use the two lines, I get errors saying: AttributeError: 'AxesSubplot' object has no attribute 'xlabel' How can I make it correct? Thank you all for helping me!!! A: When using the matplotlib object-oriented interface, the correct commands to use are ax.set_xlabel and ax.set_ylabel. (Compare these to plt.xlabel, etc., for the state-machine interface). Likewise, to set a title, you need ax.set_title You can see all the available methods for an axes instance here: http://matplotlib.org/api/axes_api.html#axis-labels-title-and-legend
{ "pile_set_name": "StackExchange" }
Q: Why use repressive actions instead of constructive? I posted two questions yesterday that was closed/put on hold. The question If $p$ is a prime then $p^2+26$ is not a prime was marked as a duplicate of On the primality of integers of the form $p^2+k$, a question that not gives an answer to my question as far as I can see. The question For which $n\in\mathbb N$ exist a unique prime $p$ such that $p^2+2n\in \mathbb P$ was put on hold as off topic for the site, but is just an abstraction of concrete tests. Technocracy is supposed to mean 'ruled by experts', which seems to be the right thing for MSE, but how come that my questions are closed instead of answered or edited? I suppose that the meta site is the right place to deal with such technocracy problems. A: (this answer is directed at the specific topic of labeling "closing as duplicate" a 'repressive' action) Marking as duplicate is a constructive action — it creates the connection between the new post and the established post, which, for example, has effects like Directing the marked questions' poster (and everyone else who comes across the marked question) to a place where there are already answers to the question Ensures new answers on the topic are posted in a place where they can be found by people who come across the other question. A: The OP asks: ...but how come that my questions are closed instead of answered or edited? Setting aside the matter of the question closed-as-duplicate, putting on-hold Questions that are not up to Math.SE standards is by design to allow the OP (with assistance) to edit the Question and make it suitable for good Answers. It often happens that a Question is so clear in the mind of the OP that requests for clarification (or worse, misunderstandings by Readers) seem "to be deliberately provocative" (to borrow a phrase). But it does seem to me that the OP's second Question (closed as "off-topic") needs improvement. I don't think this is the best place to discuss the specifics, but the notion expressed there of having "a unique solution $p$" begs for some clarification. Putting all the Comments into perspective, what is being defined is a property of (natural number) $n$ but this is only discovered in a somewhat roundabout fashion. If the OP wishes, I would undertake to edit the Question myself toward that end. However I think a better approach in most cases is for the OP to undertake the editing and improvements that are realized from Comments upon closure of a Question.
{ "pile_set_name": "StackExchange" }
Q: pyplot combine multiple line labels in legend I have data that results in multiple lines being plotted, I want to give these lines a single label in my legend. I think this can be better demonstrated using the example below, a = np.array([[ 3.57, 1.76, 7.42, 6.52], [ 1.57, 1.2 , 3.02, 6.88], [ 2.23, 4.86, 5.12, 2.81], [ 4.48, 1.38, 2.14, 0.86], [ 6.68, 1.72, 8.56, 3.23]]) plt.plot(a[:,::2].T, a[:, 1::2].T, 'r', label='data_a') plt.legend(loc='best') As you can see at Out[23] the plot resulted in 5 distinct lines. The resulting plot looks like this Is there any way that I can tell the plot method to avoid multiple labels? I don't want to use custom legend (where you specify the label and the line shape all at once) as much as I can. A: I'd make a small helper function personally, if i planned on doing it often; from matplotlib import pyplot import numpy a = numpy.array([[ 3.57, 1.76, 7.42, 6.52], [ 1.57, 1.2 , 3.02, 6.88], [ 2.23, 4.86, 5.12, 2.81], [ 4.48, 1.38, 2.14, 0.86], [ 6.68, 1.72, 8.56, 3.23]]) def plotCollection(ax, xs, ys, *args, **kwargs): ax.plot(xs,ys, *args, **kwargs) if "label" in kwargs.keys(): #remove duplicates handles, labels = pyplot.gca().get_legend_handles_labels() newLabels, newHandles = [], [] for handle, label in zip(handles, labels): if label not in newLabels: newLabels.append(label) newHandles.append(handle) pyplot.legend(newHandles, newLabels) ax = pyplot.subplot(1,1,1) plotCollection(ax, a[:,::2].T, a[:, 1::2].T, 'r', label='data_a') plotCollection(ax, a[:,1::2].T, a[:, ::2].T, 'b', label='data_b') pyplot.show() An easier (and IMO clearer) way to remove duplicates (than what you have) from the handles and labels of the legend is this: handles, labels = pyplot.gca().get_legend_handles_labels() newLabels, newHandles = [], [] for handle, label in zip(handles, labels): if label not in newLabels: newLabels.append(label) newHandles.append(handle) pyplot.legend(newHandles, newLabels) A: Numpy solution based on will's response above. import numpy as np import matplotlib.pylab as plt a = np.array([[3.57, 1.76, 7.42, 6.52], [1.57, 1.20, 3.02, 6.88], [2.23, 4.86, 5.12, 2.81], [4.48, 1.38, 2.14, 0.86], [6.68, 1.72, 8.56, 3.23]]) plt.plot(a[:,::2].T, a[:, 1::2].T, 'r', label='data_a') handles, labels = plt.gca().get_legend_handles_labels() Assuming that equal labels have equal handles, get unique labels and their respective indices, which correspond to handle indices. labels, ids = np.unique(labels, return_index=True) handles = [handles[i] for i in ids] plt.legend(handles, labels, loc='best') plt.show() A: So using will's suggestion and another question here, I am leaving my remedy here handles, labels = plt.gca().get_legend_handles_labels() i =1 while i<len(labels): if labels[i] in labels[:i]: del(labels[i]) del(handles[i]) else: i +=1 plt.legend(handles, labels) And the new plot looks like,
{ "pile_set_name": "StackExchange" }
Q: php preg_match at sign Hello I want to match "@" in the following line, create@create_time:"2012-05-30 21:14:35.0",update_time:"2012-05-31 22:05:46.0" preg_replace("@", "", $content) preg_replace("\@", "", $content) Neither of them are working. A: For posterity: In case anyone stumbles across this because they are confused by usage of at-signs in regular expressions which are part of somebody else's code, @ is occasionally used as a starting and ending regex-delimiter. The below quote also relates to why OP's attempts at matching a literal '@' were unsuccessful (emphasis mine): When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character. In other words, any regular-expression string must start and end with a matching character identified by either the character-class [^A-Za-z\s\\] or – if you feel like you can deal with any headaches their usage might cause you – a pair of matching grouping characters <> {} [] ().
{ "pile_set_name": "StackExchange" }
Q: Difference of wrapping ternary conditional in squared and round brackets What is the difference between using squared and round brackets when used within a ternary conditional? For example: squared: [ x == y ? 1 : 0 ] round: ( x == y ? 1 : 0 ) I know that [ ] are used for getting a arrays variable or a key from an associative array. Often however they are used in conjunction with things that have little to do with an array. For example here is a small piece of a plugin I wrote: (x.nodeType == 3 ? textContent : innerHTML) The same only works using squared brackets but not round ones like above. It is as if the first returns something and the second one actually displays it. A: Rounded brackets are used to evaluate a certain expression (in this case a ternary conditional) while square ones are used for creating an array, for accessing an array's position (for example if you have var a = [1, 2, 3]; then a[0] is 1, a [1] is 2 and so on.) or for accessing object properties (in case you have var a = {name : "John", age : 25}; then a["age"] is 25) Take this as an example : var b = [x == y ? 1 : 0] will assign b to a new array having either 1 or 0 var b = (x == y ? 1 : 0) will assing b either 1 or 0 (depending on x == y) Hope it's clear
{ "pile_set_name": "StackExchange" }
Q: onTouch event in achartengine seems to be dephased I made a simple chart and added an onTouchListener like this: @Override public boolean onTouch(View arg0, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { if (mGraphPopup.isShowing()) { //close popup window } else { SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint(); if (seriesSelection != null) { // open popupwindow } } return false; } And I expected perform like this: 1) tap on the chart point - show popup 2) tap again everywhere - close popup but what is really happening: 1*) tap on a chart point: nothing happens - because seriesSelection is null 2*) tap again far from any chart point - seriesSelection is valid and loads the data of the point clicked on step 1*) it looks like the chart is late with one touch event. I even tried to call getCurrentSeriesAndPoint() twice :D but no result. A: I have meet this problem too recently,and i have find a solution to solve it.Maybe you had solved the problem, I also answer it to help others who meet the problem in the future.Here is the solution: paintBarView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { paintBarView.onTouchEvent(event); This is code is important `paintBarView.onTouchEvent(event); this code is to make sure the view get your input,and you also can solve it like this : try { Field fieldX = paintBarView.getClass().getDeclaredField("oldX"); Field fieldY = paintBarView.getClass().getDeclaredField("oldY"); fieldX.setAccessible(true); fieldY.setAccessible(true); fieldX.set(paintBarView, event.getX()); fieldY.set(paintBarView, event.getY()); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } SeriesSelection ss = paintBarView.getCurrentSeriesAndPoint(); this two solution to solve it,hope can help others
{ "pile_set_name": "StackExchange" }
Q: IE10 on Windows 7 Side-by-Side IE8 Can I install IE10 Preview for Windows 7 and keep the previous IE8 version for development testing? A: I don't believe you will be able to run IE8 and IE10 side-by-side on the same machine. Instead, I would encourage you to use the browser-emulation options found within the F12 Developer Tools. From there you can instruct IE10 to behave as though it were IE8. If emulation isn't desirable, and you're not interested in downloading a virtual machine image, you could also consider exploring the BrowserStack service. It will allow you to spin up IE8 on multiple versions of Windows, and view both remote and local files. A: I think this is a more reliable option for developers IE 1-8 Standalones it contains Internet Explorer 1.0 (4.40.308) Internet Explorer 1.5 (0.1.0.10) Internet Explorer 2.01 (2.01.046) Internet Explorer 3.0 (3.0.1152) Internet Explorer 3.01 (3.01.2723) Internet Explorer 3.03 (3.03.2925) Internet Explorer 4.01 (4.72.3110.0) Internet Explorer 5.01 (5.00.3314.2100) Internet Explorer 5.5 (5.51.4807.2300) Internet Explorer 6.0 (6.00.2800.1106) Internet Explorer 6.0 (6.00.2900.2180) Internet Explorer 7.0 (7.00.5730.13) Internet Explorer 8.0 (8.00.6001.18702) A: Also consider IETester - http://my-debugbar.com/wiki/IETester/HomePage You can run tabs side by side in different browser versions. Works well for my web dev testing.
{ "pile_set_name": "StackExchange" }
Q: How can I determine the structure of complexes with ethylenediamine as a ligand? I am a bit confused about how to solve this problem. I can interpret coordination complexes like $\ce{[CoCl6]^4-}$ but I just came across a coordination complex that I am unsure of how to solve. It is $\ce{[Mn(en)3]^3+}$ where en stands for ethylenediamine. The problem first asks that I draw the structure (not sure how to do this as ethylenediamine is a large molecule). I would also like to know whether this complex would be tetrahedral, octahedral, trigonal planar, etc. I'm just kind of confused as to how to solve this problem when its a large molecule as the ligand rather than a molecule like $\ce{Cl6}$. A: In principle, there is no difference between having monodentate ligands such as chlorido ligand or more complex ligands such as ethylenediamine. The first step is always to draw out the structure of the ligand by itself. Then, identify how many coordinating entities it contains. Ethylenediamine is $\ce{H2N-CH2-CH2-NH2}$ and both nitrogens can form coordinate bonds. In the next step, identify how many coordinating entities you have in total and thus what the maximum coordination number is. As mentioned, each $\ce{en}$ has two potentially coordinating nitrogens for a total of six dative bonds. Thus, a hexacoordinated octahedron is the maximum possible. Continue by looking at the metal. What do you know about its properties in complexes? Does it prefer any type of complex? In this case, manganese(III) is absolutely fine with having an octahedral geometry, so that’s taken care of. Once you’ve done all this, you will notice that the metal enjoys octahedral coordination and there are enough Lewis bases for octahedral coordination to occur — the complex will likely be octahedral. If the complex had been $\ce{[Ni(en)2]^2+}$, we would have arrived at ‘square planar’ by the same methodology. Next, draw the complex. Start with the metal and the octahedral geometry and put a nitrogen at the end of each line. Then, try to connect the nitrogens with $\ce{CH2-CH2}$ fragments. There should be two possible, enantiomeric outcomes.
{ "pile_set_name": "StackExchange" }
Q: Avoid creation of object wrapper type/value in MOXy (JAXB+JSON) I'm using MOXy 2.6 (JAXB+JSON). I want ObjectElement and StringElement to be marshalled the same way, but MOXy creates wrapper object when fields are typed as Object. ObjectElement.java public class ObjectElement { public Object testVar = "testValue"; } StringElement.java public class StringElement { public String testVar = "testValue"; } Demo.java import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import org.eclipse.persistence.jaxb.JAXBContextFactory; import org.eclipse.persistence.jaxb.MarshallerProperties; import org.eclipse.persistence.oxm.MediaType; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContextFactory.createContext(new Class[] { ObjectElement.class, StringElement.class }, null); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON); System.out.println("ObjectElement:"); ObjectElement objectElement = new ObjectElement(); marshaller.marshal(objectElement, System.out); System.out.println(); System.out.println("StringElement:"); StringElement stringElement = new StringElement(); marshaller.marshal(stringElement, System.out); System.out.println(); } } When launching Demo.java, here's the output ... ObjectElement: {"testVar":{"type":"string","value":"testValue"}} StringElement: {"testVar":"testValue"} How to configure MOXy/JaxB to make ObjectElement render as StringElement object ? How to avoid the creation of object wrapper with "type" and "value" properties ? A: you can use the Annotation javax.xml.bind.annotation.XmlAttribute. This will render ObjectElement and StringElement to the same output. See the following example: import javax.xml.bind.annotation.XmlAttribute; public class ObjectElement { @XmlAttribute public Object testVar = "testValue"; } I've used the following test class to verify the correct behaviour. EDIT after the question was updated: Yes it's possible. Instead of using XmlAttribute like before, I switched to javax.xml.bind.annotation.XmlElement in combination with a type attribute. The class is now declared as: public class ObjectElement { @XmlElement(type = String.class) public Object testVar = "testValue"; }
{ "pile_set_name": "StackExchange" }
Q: How can I combine GROUP_CONCAT and LEFT JOIN? This is my table animals: ╔══════════╦══════╗ ║ animal ║ id ║ ╠══════════╬══════╣ ║ dog ║ 1 ║ ║ cat ║ 4 ║ ║ cat ║ 3 ║ ║ bird ║ 1 ║ ╚══════════╩══════╝ This is my table names: ╔═══════╦══════╗ ║ id2 ║ name ║ ╠═══════╬══════╣ ║ 1 ║ alan ║ ║ 2 ║ bob ║ ║ 3 ║ john ║ ║ 4 ║ sam ║ ╚═══════╩══════╝ This is my expected result: ╔══════════╦═════════════╗ ║ dog ║ alan ║ ║ cat ║ sam,john ║ ║ bird ║ alan ║ ╚══════════╩═════════════╝ I tried this solution: $sql = ' SELECT n.*, x.grouped_name FROM names n LEFT JOIN (SELECT a.id, GROUP_CONCAT(a.animals) AS grouped_name FROM animals a GROUP BY a.id) x ON x.id = n.id2'; foreach ($pdo->query($sql) as $row) { echo '<td>'.$row['animal'].' </td>'; echo '<td>'.$row['grouped_name'].' </td>'; } But I do not get a result. I also tried this solution: $sql = ' SELECT n.*, (SELECT GROUP_CONCAT(a.id) FROM animals a WHERE a.id = n.id2) AS grouped_name FROM names n'; But my result is this: ╔══════════╦═════════════╗ ║ ║ 1,1 ║ ║ ║ 3 ║ ║ ║ 4 ║ ╚══════════╩═════════════╝ A: SELECT t1.animal, GROUP_CONCAT(COALESCE(t2.name, "") separator ',') AS grouped_name FROM animals t1 LEFT JOIN names t2 ON t1.id = t2.id2 GROUP BY t1.animal Have a look at the Fiddle to see the behavior when an animal does not match to anyone in the names table. To handle this case, I use COALESCE() on the name to replace a NULL value by an empty string before group concatenating. SQLFiddle
{ "pile_set_name": "StackExchange" }
Q: In Stargate: Atlantis, How are they able to disconnect the ZPM despite being under water? I am watching Stargate: Atlantis episode "Critical Mass" (S2E13). In this episode a bomb is placed on Atlantis and is set to go off should someone dial the gate back to Earth, which they do once a month. Once they find out-as a way to prevent someone from dialing back to Earth and intentionally triggering the bomb-they entirely disconnect the ZPM, the only power source capable of doing so. The problem with this is that they established earlier in the series that the ZPM is the only way they are able to maintain shields and submerge the city under the water safely. At the time the city was submerged as a way to fool the Wraith into thinking Atlantis was destroyed, so they very much needed the ZPM power to maintain the shields in that episode. How is it possible that the ZPM was disconnected and Atlantis was still able to remain hidden under the water? A: Nevermind, my mistake. This episode apparently took place before Atlantis was submerged. So there was no dilema to begin with.
{ "pile_set_name": "StackExchange" }
Q: How to change hero image based on html page? I've got a website I'm trying to build. The main page has a hero image, and on the second page I want to display a different hero image. For index.html: <!--Hero Section--> <header id="about"> <div class="header-content"> <div class="header-content-inner"> <h1 id="homeHeading">Hone is home</h1> <hr> <p>this text is ontop of the hero image</p> <a href="#deal" class="btn btn-primary btn-xl page-scroll">Find Out More</a> </div> </div> </header> CSS: header { min-height: auto; -webkit-background-size: cover; -moz-background-size: cover; background-size: cover; -o-background-size: cover; background-position: center; background-image: url(../img/header.jpg); color: #fff; } For membership.html (the page where I'd like the hero image to change): <!--Hero Section--> <header id="member"> <div class="header-content"> <div class="header-content-inner"> <h1 id="homeHeading">Hone is home</h1> <hr> <p>This text is on top of the hero image</p> <a href="#deal" class="btn btn-primary btn-xl page-scroll">Find Out More</a> </div> </div> </header> <!-- / Hero section--> I tried to override the hero image using the id='member': header #member { background-image: url(../img/header2.jpg) !important; } But that doesn't work. So I thought maybe I could try some JavaScript: window.onload = function(){ #member { background-image: url('./img/header2.jpg'); } } and $(function() { $("header").attr("src", "../img/header2.jpg") }) But neither worked. Please note that this isn't a website that's going live, it's for practice and for me to try and figure things out if I can. A: You can use two classes, one common to both header tags and another specific to the id of the header. Also there is no need for !important as id has higher specificity. Note that there is no space between tag and id in CSS, that is, it should be header#id. HTML: <!--Hero Section--> <header id="about" class="commonHeader"> // rest of code </header> <!--Hero Section--> <header id="member" class="commonHeader"> // rest of the code </header> CSS: .commonHeader { min-height: auto; -webkit-background-size: cover; -moz-background-size: cover; background-size: cover; -o-background-size: cover; background-position: center; color: #fff; } header#member { background-image: url(../img/header2.jpg); } header#about{ background-image: url(someOtherImage); }
{ "pile_set_name": "StackExchange" }
Q: 5/7b in figured bass What does 5/7b mean in figured bass? If it is just a 7th chord in root position, then why is it not just 7b? In other places in the same score, 7 or 7b are used to denote a 7th chord. Here is the example, from Vivaldi's "Filiae maestae Jerusalem" (source): A: The 5 is not redundant, and it doesn't mean you have "a four note chord." The point of the notation is that the 7b 5 intervals from the new bass note are the same notes as the 6b 4 intervals from the previous bass note. In other words, since the continuo is for organ (which can sustain notes indefinitely), you simply hold those two notes down, and only the bass note moves. That is exactly the same as what the violins are playing, of course. What is more interesting about this example is that the second chord played by the strings is actually a 6b 4 2 chord, which then becomes a complete 7 5 3 dominant 7th. But Vivaldi wanted the D played only the viola, not by the organ continuo. Otherwise the figuring would have been 6b 4 2 followed by just 7b. A typical organ continuo registration might have made the complete 6b 4 2 chord sound muddy, especially if a cloth-eared organist voiced it with the D in the tenor, a second above the bass C! Re the edition, you can view an alternative professionally published edition here - though I don't agree with the continuo realization: https://www.prestomusic.com/sheet-music/works/52700--vivaldi-introduzione-al-miserere-rv-638-filiae-maestae-jerusalem/browse A: I wish the IMSLP had another source beside the Martin Straeten version. It could help confirm the meaning. I notice the key is C minor and this notation uses the modern three flats rather than two flats which was common in the Baroque era. Straeten may have modernized some things in the score. Perhaps too he changed bass figures? Usually a modification of the numeric figure with b, #, + means an alteration from the key signature. In this case both the 6b and 7b refer to the A and that is already a flat from the key signature. So I think this may mean two things: It simply confirms the flat of the key signature. If the original score was for a key signature of two flats, it would have been Eb and Bb, in which case these figure would require the flat to mean Ab, because the flat wasn't in the key signature. (I suspect this is the actual case, but we would need to see the original score to confirm.) EDIT About the 5 figure. As far as I can tell the 5 is redundant. Plain 7 means a root position seventh chord and 7/5 also means a root position seventh chord. The 5 doesn't seem necessary to clear up some possible confusion from the previous chord. Either way a Bb dominant seventh chord should be played.
{ "pile_set_name": "StackExchange" }
Q: Proving inequalities on $L^P$ spaces Suppose $p,q,r \in[1,\infty)$ and $ 1/r = 1/p +1/q$. Prove that $$\|fg\|_r \leq \|f\|_p*\|g\|_q.$$ I am assuming that this proves involves using Hölder inequality , but so far I am unable to proceed in the proof. Maybe so because this is my first problem about using the Hölder/Minkowski inequaltiy. A: Clearly $p,q>r$, so one may apply Holder's inequality to $|f|^r$, $|g|^r$ with $p'=\frac{p}r$, $q'=\frac{q}r$.
{ "pile_set_name": "StackExchange" }
Q: What does 'require: false' in Gemfile mean? Does this: gem 'whenever', require: false mean that the gem needs to be installed, or does it mean it is not required? A: This means install the gem, but do not call require when you start Bundler. So you will need to manually call require "whenever" if you want to use the library. If you were to do gem "whenever", require: "whereever" then bundler would download the gem named whenever, but would call require "whereever" This is often used if the name of library to require is different than the name of the gem. A: You use :require => false when you want the gem to be installed but not "required". So in the example you gave: gem 'whenever', :require => false when someone runs bundle install the whenever gem would be installed as with gem install whenever. Whenever is used to create cron jobs by running a rake task but isn't usually used from within the rails (or other framework if not rails) application. So you can use :require => false for anything that you need to run from the command line but don't need within your code. A: require: false tells Bundler.require not to require that specific gem: the gem must be required explicitly via require 'gem'. This option does not affect: bundle install: the gem will get installed regardless the require search path setup by bundler. Bundler adds things to the path when you do either of: Bundle.setup which is called by require bundler/setup which is called by bundle exec Example Gemfile source 'https://rubygems.org' gem 'haml' gem 'faker', require: false main.rb # Fail because we haven't done Bundler.require yet. # bundle exec does not automatically require anything for us, # it only puts them in the require path. begin Haml; rescue NameError; else raise; end begin Faker; rescue NameError; else raise; end # The Bundler object is automatically required on `bundle exec`. Bundler.require Haml # Not required because of the require: false on the Gemfile. # THIS is what `require: false` does. begin Faker; rescue NameError; else raise; end # Faker is in the path because Bundle.setup is done automatically # when we use `bundle exec`. This is not affected by `require: false`. require 'faker' Faker Then the following won't raise exceptions: bundle install --path=.bundle bundle exec ruby main.rb On GitHub for you to play with it. Rails usage As explained in the initialization tutorial, the default Rails template runs on startup: config/boot.rb config/application.rb config/boot.rb contains: ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE']) which does the require 'bundler/setup' and sets up the require path. config/application.rb does: Bundler.require(:default, Rails.env) which actually requires the gems.
{ "pile_set_name": "StackExchange" }
Q: PDE multiplicity problem I need help with the following question, any help is appreciated. Show that $0$ is an eigenvalues of multiplicity $1$ for the problem $-\triangle u=\lambda u$ in D $\triangledown u*\eta^\rightarrow =0$ on 2D where D is a smooth Bounded Domain in $R^3$ Thank you for any help. A: Assuming you mean a Neumann problem this follows from Green's identities: $$ \int_D \nabla u\cdot \nabla v = -\int_D v\Delta u +\int_{\partial D} v\frac{\partial u}{\partial n} $$ where $\frac{\partial u}{\partial n} = \nabla u \cdot n$ is the partial derivative with respect to the exterior normal vector $n$. Now just put $u=v$ to conclude that $\nabla u=0$ in $D$, and so $u$ is constant.
{ "pile_set_name": "StackExchange" }
Q: Gelfand's Formula. $r(T)=\lim_{n \to\infty}\sqrt[n]{\|T^{n}\|}$ Can you indicate me a material where I cand find the proof of Gelfand's Formula. I heard that there is a proof with polynomials. Gelfand's Formula : If $T \in B(X)$ then: $$r(T)=\lim_{n \to\infty}\sqrt[n]{\|T^{n}\|}$$ thanks for your help :-) A: I do not know of any proof using just polynomials. All the proofs I have seen involve complex analysis to a certain extent, either Laurent series expansions, Liouville's theorem, or Hadamard's Theorem. I am pretty sure that most books on functional analysis which cover Banach spaces and/or Banach algebras will contain a proof, for example: G. F. Simmons - Introduction to Topology and Modern Analysis - page 312 in my (old) edition. Riesz and Nagy - Functional Analysis - section 149 (page 425 in my Dover edition).
{ "pile_set_name": "StackExchange" }
Q: Reference counting using PyDict_SetItemString I'm wondering how memory management/reference counting works when a new value is set into an existing field within a PyDict (within a C extension). For instance, assume a dictionary is created and populated in the following way: myPyDict = PyDict_New(); tempPyObj = PyString_FromString("Original Value"); PyDict_SetItemString(myPyDict,"fieldname",tempPyObj); Py_DECREF(tempPyObj); From a memory and reference counting perspective, what happens when there is a subsequent tempPyObj = PyString_FromString("New Value"); PyDict_SetItemString(myPyDict,"fieldname",tempPyObj); Py_DECREF(tempPyObj); Is the reference count for the original value automatically decremented (and the memory automatically released)? The doc for PyList_SetItem specifically mentions what happens for lists: This function “steals” a reference to item and discards a reference to an item already in the list at the affected position. But neither PyDic_SetItem nor PyDict_SetItemString say how the replacement is handled for dictionaries. A: The ref count of the old value is decremented automatically by logic of PyList_SetItem function. You shouldn't be decrementing the old value by yourself. If you want to know details, take a look at CPython source code, specifically at the Objects/dictobject.c file. 1) The PyDict_SetItemString() https://github.com/python/cpython/blob/c8e7c5a/Objects/dictobject.c#L3250-L3262 It it's a thin wrapper around PyDict_SetItem() 2) The PyDict_SetItem() https://github.com/python/cpython/blob/c8e7c5a/Objects/dictobject.c#L1537-L1565 Is still quite simple and it's obvious that all the heavy-lifting related to inserting/replacing values in a dict is actually done by insertdict(). 3) The insertdict() https://github.com/python/cpython/blob/c8e7c5a/Objects/dictobject.c#L1097-L1186 is the function which gives us the answer. In this function you can find the crucial code and especially the call: Py_XDECREF(old_value); /* which **CAN** re-enter (see issue #22653) */ which decrements the ref count of old value.
{ "pile_set_name": "StackExchange" }
Q: How can I convince my boss that we need better machines? Possible Duplicate: How do I request new equipment for the office? My boss strongly feels that if we keep the machines clean which to him means: not installing any unnecessary programs and formatting the computer routinely, there is no need to purchase a new machine at least until it has been used for ten years. I tried to tell him that slow machines really hinder productivity and software gets heavier over time, but he would reiterate his argument. What is a good way to convince my boss to buy us a new machine? A: Everything is about Money. So you need to show that the machines will pay for themselves better then what you currently have. One way to do this is to determine the average spent per employee on their machine compiling code, AND other functions which take time. Do it for a week or two (or a month), get a report from each engineer of the amount of time involved. Then work that amount of time out for the year and equate it to lost productivity. Example: Let's say each engineer compiles their code 10 times a day. So you have lost 20-30 minutes per engineer a day. Let's pick the average and say 25 minutes per engineer. That works out to 4.5 days a year per engineer is lost productivity. For 6 engineers that is 27 days of productivity lost. A: Wow, I thought I was crazy sticking with a 2005 PC.. In addition to the fine answer by Simon, I would like to add my own points. With such an old machine, Repair costs are likely to be much higher, especially compared to repair under warranty. You have not given any specifics, but if you have situations or data regarding this, you can use that to further your case. Newer Machines and LCD monitors might consume lower power, low enough to be significant over 3-5 years. Additionally, when presenting your case, take a mid-range machine as the ideal case, a high-end one might be going into diminishing returns area for a small company. A: Be careful how you try to present any ROI argument. There are a lot of purchases that could be made to help the bottom line over time, but are no good right now if your company doesn't have the cash or if venture capital is restricted. You may be able to prevent wasting a certain amount of time per day/per programmer, but there are other factors: Does your boss expect you to just work longer hours without extra pay because you're on salary? You boss thinks each programmer already has several minutes of unproductive time, so you might as well be compiling at the same time. Your company can't find any more billable hours or additional work to justify the time savings. More productive hours may not directly create revenue. Projects are not behind, so why bother saving the extra time? (Would be hard to believe.). Part of me thinks you're arguing with an idiot or someone who has been beaten up too often and has developed penny wise and pound foolish thinking. I don't agree with the arguments I presented nor do I know if your boss thinks this way. The slow computers are probably another symptom about the problems with working for this company. Your boss is giving the impression he just doesn't care to try and make employees happy. It's not all about money. There are other 'perks' he could offer that don't require as much company cash (e.g. flex-time, telecommute, free muffins on Tuesday, allow you to try and find other solutions/buy just one machine for compiling.).
{ "pile_set_name": "StackExchange" }
Q: Angularjs Control the expand and collapse of an acordion I am trying to understand how works the ui.bootstrap accordion in angularjs. In my case of use, I have three accordions of which only the first is allowed to open. The rest of them should not open when the user click on their header until an option is selected from the previous accordion. Now, I am experimenting with a controller which shows a error message when the user click on the second and third accordeon and, after that, it close them. This is my Plunker with my code: http://plnkr.co/edit/rSg6Az?p=preview The part of the error message works fine but I can not get that the accordeon selected is closed when I click it. Any idea? Regards: Adrian Ferreres A: First I give you the thanks for your answer and my apologies for my delay to answer it. I didn't tested your solutions because I found two solutions which I like more than you told me. The first was given by Vanya Dineva in the official mail group of Angular: Here's a couple of things you can try: Notice the accordionGroup directive uses the collapse directive in its template (https://github.com/angular-ui/bootstrap/blob/master/template/accordion/accordion->group.html ) You can modify and instead of having collapse="!isOpen" you can replace the isOpen with a new variable that you would set to false until your condition is met Notice the ng-click="toggleOpen()" in the accordion group template (https://github.com/angular-ui/bootstrap/blob/master/template/accordion/accordion-group.html ). Try creating a custom function e.g. ng-click="openIfConditionMet()" and put your logic inside the function The second was found by myself. I add a modal window to show the error message when a user tries to open an accordion. In the function which closes the window I put the code to close the accordion: http://plnkr.co/edit/rSg6Az?p=preview
{ "pile_set_name": "StackExchange" }
Q: Android: Adding text to a textview in different xml layout by clicking button I just need a little help with the android program that I am making. Basically, I have a button in one of my XML layouts, and when that button is pressed, it should add the name of that activity into a TextView which is located in another XML layout. So this is the button that needs pressing. <Button android:id="@+id/add_to_schedule" android:layout_width="150dp" android:layout_height="30dp" android:layout_below="@+id/widget44" android:layout_centerHorizontal="true" android:text="@string/add_to_schedule" android:textColor="#ffffffff" android:textSize="12sp" android:typeface="serif" /> And this is the TextView which is in a different XML Layout that I want it to display the information to. <TextView android:id="@+id/txtview" android:layout_width="300dp" android:layout_height="200dp" android:layout_alignLeft="@+id/textview" android:layout_alignParentBottom="true" android:layout_marginBottom="76dp" android:text="@string/textview" /> This is the class where the Button will be pressed from. public class Aerobic_Steps extends Activity{ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.aerobic_steps); } } And this is the Class which the TextView will belong to. public class Training_Schedule extends Activity{ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.training_schedule); } } A: In class Aerobic_Steps, call Training_Schedule activity in OnClick of Button public class Aerobic_Steps extends Activity implements OnClickListener { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.aerobic_steps); Button btn = (Button) findViewById (R.id.buttonName); btn.setOnClickListener(this); } } @Override public void onClick(View view) { // TODO Auto-generated method stub String className = Aerobic_Steps.this.getClass().getSimpleName(); Intent i = new Intent(this, Training_Schedule.class); i.putExtras("name",className); startActivity(i); } Now in Training_Schedule Activity, use below code in OnCreate() //Get the bundle Bundle bundle = getIntent().getExtras(); //Extract the data… String name = bundle.getString(“name”); TextView tv = (TextView) findViewByID(R.id.yourTextView); tv.setText(name);
{ "pile_set_name": "StackExchange" }
Q: Query returning every cover in db for each entry? My query seems to be returning 1 entry for each cover. That is, if I have 3 covers in the database, then the query will return entry #1 three times with each of the different covers. Since I have 7 entries, I'm getting 21 results. How do I structure my query to return the cover associated with the entry? Here's what I have: @app.route('/list', methods=['GET', 'POST']) def list(): entries = Book.query.order_by(Book.id.desc()).all() cvr_entries = Cover.query.filter(Cover.book).all() ### Other queries I've tried ### # cvr_entries = Cover.query.join(Cover.book).all() # cvr_entries = Cover.query.filter(Cover.book.any()) # cvr_entries = Cover.query.filter(Cover.book.any()).all() return render_template( 'list.html', entries=entries, cvr_entries=cvr_entries) Here's the /list output page: {% for entry in entries %} {% for cvr in cvr_entries %} <article class="entry"> <img src="/static/data/covers/{{ cvr.name }}" alt="Cover for {{ entry.title }}" /> <ul class="entry-info"> <li class=""><h2>{{ entry.title }}</h2></li> <li class="">Summary: {{ entry.summary|truncate( 30, true ) }}</li> </ul> </article> {% endfor %} {% endfor %} Switching the order of the entries and cvr_entries for loops changes nothing. I've also tried adding first() instead of all(), but that leads to an error where it says TypeError: 'Cover' object is not iterable so that was a bust. I don't understand how to build the query. Here is my model, as requested by @jonafato: book_to_cover = db.Table('book_to_cover', db.Column('cover_id', db.Integer, db.ForeignKey('cover.id')), db.Column('book_id', db.Integer, db.ForeignKey('book.id')) ) class Book(db.Model): __tablename__ = 'book' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String()) summary = db.Column(db.Text) book_to_cover = db.relationship('Cover', secondary=book_to_cover, backref=db.backref('book', lazy='dynamic')) def __repr__(self): return "<Book (title='%s')>" % (self.title) class Cover(db.Model): __tablename__ = 'cover' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String()) def __repr__(self): return "<Cover (name='%s')>" % self.name A: Generally, you iterate over the model-- your relationships should allow you to do: books = Book.query.all() return render_template('list.html', books=books) Then in your Jinja2 list.html template: {% for book in books %} <h3>{{ book }}</h3> <ul> {% for cover in book.book_to_cover %} <li>{{ cover }}</li> {% endfor %} </ul> {% endfor %} It'd be more natural to rename the book_to_cover to covers to make it more like natural language when you access the model.
{ "pile_set_name": "StackExchange" }
Q: How to use uncss by addy osmani with a Single Page MEAN stack application I've created a application using the MEAN stack which was generated by Yeoman angular-fullstack I would love to include uncss to my grunt build. Unfortunately, this is not possible given that the site is SPA. I've read that I can generate a site map and then use that through uncss; however, could someone please implement uncss and help me through this process for I dont know how to really start? A: This can be done with uncss at a command line or with grunt-uncss...although the latter has open issues. The example on the grunt-uncss page you mention, using a WordPress sitemap , is helpful but doesn't clearly explain what to do about SPA's. Hopefully this helps. 1) Command line As the docs on the github page explain, you can now pass URL's directly into uncss to generate css output. You can pass URL's to uncss instead of files... Thus, if your SPA is simple enough, you could use the core uncss app like this: uncss http://localhost:3000/mycoolapp > stylesheet.css 2) grunt-uncss At the time of writing this answer, there is an open issue with grunt-uncss that needs to be known to use uncss via grunt. While the url option is depreciated, the alternative approach to put the URL's into the file array won't work because of the open issue. However, the url option can still be used so that an array of URL's can be checked. In this case, the Gruntfile.js would have a section like this: uncss: { dist: { options: { ...some options... urls : ['http://localhost:3000/mycoolapp', '...'], // This is the line you need ...even more options... }, The array in urls would need to contain a list of urls. Given that this plugin is still in development, you should watch the github page so you are notified of potentially breaking changes as it builds upon v.0.3.x... Two notes: phantom.js will be used for this processing, so as long as your SPA is friendly enough that phantom can do it's work...this should work for you. you have to enter the array of urls by hand, which is what the WordPress example off the grunt-css page is automating...so if you can similarly automate, life will be easier.
{ "pile_set_name": "StackExchange" }
Q: Will WPA Enterprise give any advantage on home network with one user? I understand some of the reasons why WPA Enterprise is more secure from this question: Why is WPA Enterprise more secure than WPA2? However, given a home network with only one single user where that user has a long and complex password (at least 28 random chars), is there any advantage for WPA Enterprise? From what I read, I believe that in this specific situation, there is no meaningful advantage for WPA Enterprise. I wonder if the increased complexity of WPA Enterprise might actually work against security in this scenario (single user, home network). Am I right or wrong? A: The main benefit of WPA Enterprise is that it uses a radius server for authentication, which allows you more control on a per user basis. Each user gets their own key to secure their connection. This means a user can't Snoop on other people using the same network (in WPA2 Personal you can read all users wifi traffic if you have the PSK). Each user can be assigned a VLAN, further segregating the traffic, and allowing you to partition your network based on the user. If a device is lost or stolen it won't cause you to reconfigure the other devices, you would simply deactivate that user. While most benefits apply to multiple devices/user scenarios, there is one benefit for a single user, which is that it disables WPS, which is only available on personal. I'm your case it seems like the benefit is minimal, and the overhead of setting up and maintaining a radius server likely isn't worth it. Overview of enterprise http://techgenix.com/why-use-enterprise-wi-fi-security/
{ "pile_set_name": "StackExchange" }
Q: Determine the line count of a specific line from a text file in .NET I want to get the count of a specific line in .NET. Currently I have been using the below code:- Do While sr.Peek >= 1 sr.ReadLine() NumberOfLines += 1 Loop Is there any other way to do this as I want to avoid looping. A: Assuming you have the position in the file you can do this: Dim pos As Integer = 10 Dim subStr As String = System.IO.File.ReadAllText("C:\\path\\x.txt").Substring(0, pos) Dim lineNo As Integer = subStr.Split(vbCrLf).Count If you don't have the position but you have the content of your line you can do the below. Note that if there are lines looking the same you will always find the first line. Dim content As String = System.IO.File.ReadAllText("C:\\...\\x.txt") Dim pos As Integer = content.IndexOf("<<the content of your line goes here>>") Dim lineNo As Integer = content.Substring(0, pos).Split(vbCrLf).Count To get total line count in a file: Dim lines As Integer = System.IO.File.ReadAllLines("C:\\...path...\\x.txt").Length
{ "pile_set_name": "StackExchange" }
Q: parsing a table with jsoup I'm trying to extract the e-mail adress and the phone number from a linkedin profile using jsoup, each of these informations is in a table. I have written a code to extract them but it doesn't work, the code should work on any linkedin profile. Any help or guidance would be much appreciated. public static void main(String[] args) { try { String url = "https://fr.linkedin.com/"; // fetch the document over HTTP Document doc = Jsoup.connect(url).get(); // get the page title String title = doc.title(); System.out.println("Nom & Prénom: " + title); // first method Elements table = doc.select("div[class=more-info defer-load]").select("table"); Iterator < Element > iterator = table.select("ul li a").iterator(); while (iterator.hasNext()) { System.out.println(iterator.next().text()); } // second method for (Element tablee: doc.select("div[class=more-info defer-load]").select("table")) { for (Element row: tablee.select("tr")) { Elements tds = row.select("td"); if (tds.size() > 0) { System.out.println(tds.get(0).text() + ":" + tds.get(1).text()); } } } } } here is an example of the html code that i'm trying to extract (taken from a linkedin profile) <table summary="Coordonnées en ligne"> <tr> <th>E-mail</th> <td> <div id="email"> <div id="email-view"> <ul> <li> <a href="mailto:[email protected]">[email protected]</a> </li> </ul> </div> </div> </td> </tr> <tr class="no-contact-info-data"> <th>Messagerie instantanée</th> <td> <div id="im" class="editable-item"> </div> </td> </tr> <tr class="address-book"> <th>Carnet d’adresses</th> <td> <span class="address-book"> <a title="Une nouvelle fenêtre s’ouvrira" class="address-book-edit" href="/editContact?editContact=&contactMemberID=368674763">Ajouter</a> des coordonnées. </span> </td> </tr> </table> <table summary="Coordonnées"> <tr> <th>Téléphone</th> <td> <div id="phone" class="editable-item"> <div id="phone-view"> <ul> <li>0021653191431&nbsp;(Mobile)</li> </ul> </div> </div> </td> </tr> <tr class="no-contact-info-data"> <th>Adresse</th> <td> <div id="address" class="editable-item"> <div id="address-view"> <ul> </ul> </div> </div> </td> </tr> </table> A: To scrape email and phone number, use css selectors to target the element identifiers. String email = doc.select("div#email-view > ul > li > a").attr("href"); System.out.println(email); String phone = doc.select("div#phone-view > ul > li").text(); System.out.println(phone); See CSS Selectors for more information. Output mailto:[email protected] 0021653191431 (Mobile)
{ "pile_set_name": "StackExchange" }
Q: Error trying to programmatically add a controller file to a navigation controller without creating storyboard I am trying to push a view controller onto a navigation controller without designing a storyboard. Is this possible as I am new to Swift? I created my navigation controller in appdelegate.swift file: let viewController: UIViewController = ViewController(nibName: nil, bundle: nil) viewController.view.backgroundColor = UIColor.white let navController: UINavigationController = UINavigationController(rootViewController: viewController) self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.backgroundColor = UIColor.darkGray self.window?.rootViewController = navController self.window!.makeKeyAndVisible() And now in ViewController.swift file, when the user clicks the button below is the file when I try to add the signInController: func SignIn(sender: UIButton!) { print("Im, here") let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "signInController") as! signInController self.navigationController?.pushViewController(controller, animated: true) } Below is my Error: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Storyboard (<UIStoryboard: 0x608000269600>) doesn't contain a view controller with identifier 'signInController'' Question: Do I have to create a storyboard and go to the inspector Id to add the storyboard Id? But what if I wanted to accomplish this without creating a storyboard file? A: If you are not using a storyboard then you shouldn't attempt to create your sign-in view controller from a storyboard. Change the code to create the view controller directly: func SignIn(sender: UIButton!) { print("I'm, here") let controller = signInController() self.navigationController?.pushViewController(controller, animated: true) } BTW - you need to rename everything to follow standard naming conventions. Classnames should start with uppercase letters. All method, variable, and parameters names should start with lowercase letters.
{ "pile_set_name": "StackExchange" }
Q: How to create several stored procedure using SQL I have a vb.net function that creates several Stored Procedures based on parameters being passed into the function. I want to move this vb.Net into a single SQL file (for maintenance reasons) but I am not sure how I can re-create it in SQL without creating 7 separate stored procedures. I create a total of 20 Stored Procedures and I don't really want to create this many in a SQL file as maintenance will be a nightmare. I am wondering if there is a solution similar to how I have done it VB.Net below: Private Sub CreateStoredProcedures() CreateSP("SummaryNone", "YEAR([sale].[DateTime])") CreateSP("SummaryUser", "[sale].[User]") CreateSP("Summarysale", "[sale].[sale]") CreateSP("SummaryBatch", "[sale].[Batch]") CreateSP("SummaryDay", "dbo.FormatDateTime([sale].[DateTime], 'yyyy-mm-dd')") CreateSP("SummaryMonth", "dbo.FormatDateTime(dbo.DateSerial(YEAR([sale].[DateTime]), MONTH([sale].[DateTime]), 1), 'yyyy-mm-dd')") CreateSP("SummaryYear", "Year([sale].[DateTime])") Return End Sub Private Sub CreateSP(ByVal vName As String, ByVal vGroup As String) Dim CommandText As String = _ "CREATE PROCEDURE " & vName _ & " @StartDate varchar(50)," _ & " @EndDate varchar(50)" _ & " AS " _ & " SELECT " & vGroup & " AS GroupField," _ & " Sum([Project].[NumProject]) AS TotalProject," _ & " Sum([Project].[Title]) AS SumTitle," _ & " Sum([Project].[Duration]) AS SumDuration," _ & " Sum([Project].[Info]) AS SumInfo," _ & " Sum([Customer].[NumCustomer]) AS TotalNumCustomer," _ & " Sum([Orders].[NumOrders]) AS TotalNumOrders," _ & " Sum([OrderInspection].[NumInspects]) AS TotalNumInspects," _ & " Sum([OrderInspection].[NumFails]) AS TotalNumFails," _ & " Sum([CustomerInspection].[NumInspects]) AS TotalNumCustomerInspectionInspects," _ & " Sum([CustomerInspection].[NumFails]) AS TotalNumCustomerInspectionFails," _ & " Sum([Measurements].[NumMeasurements]) AS TotalNumMeasurementss" _ & " FROM ((((((sale LEFT JOIN Project ON [sale].[saleId]=[Project].[saleId])" _ & " LEFT JOIN Customer ON [Project].[PrintId]=[Customer].[PrintId])" _ & " LEFT JOIN Orders ON [Project].[PrintId]=[Orders].[PrintId])" _ & " LEFT JOIN OrderInspection ON [Project].[PrintId]=[OrderInspection].[PrintId])" _ & " LEFT JOIN CustomerInspection ON [Project].[PrintId]=[CustomerInspection].[PrintId])" _ & " LEFT JOIN Measurements ON [Project].[PrintId]=[Measurements].[PrintId])" _ & " WHERE [sale].[DateTime] BETWEEN dbo.FormatDateTime((@StartDate), 'yyyy-mm-dd')" _ & " AND dbo.FormatDateTime((@Enddate),'yyyy-mm-dd')" _ & " GROUP BY " & vGroup & "" _ & " ORDER BY " & vGroup & ";" SqlExecuteNonQuery(CommandText) return End Sub I look forward to your comments and replies. Thanks A: You could store a template in a text file as an embedded resource in your .NET DLL. Have some placeholders for your dynamic bits. Which would make your current solution a lot more maintainable. Then you load the stream from the DLL and keep your current implementation. Editing the text file is easier than that big chunk of SQL which is embedded in your C# file. You will probably get a performance hit if you move this to a single proc, you may be happy with it but keep in mind that the proc will also have some maintenance issues. We usually like to avoid dynamic SQL in stored procs. And a 7 way IF branch is a maintenance nightmare.
{ "pile_set_name": "StackExchange" }
Q: Create quote without stock validation For my project I need to empty current quote and add new products from quotation (custom module, and all programmatically). But, when I add some products (5000 for my tests), I have an error because I don't have stock for this product. For my test, I need to add product with custom price and custom quantity. At this moment, I have this code : $cart = Mage::getModel('checkout/cart'); $quoteItems = Mage::getSingleton('checkout/session')->getQuote()->getItemsCollection(); foreach($quoteItems as $item) $cart->removeItem($item->getId()); // Nouveau panier $devisItems = Mage::getModel('devis/detail')->getCollection()->addFieldToFilter('devis_id', (int)$quote_id); foreach($devisItems as $item) { $product = Mage::getModel('catalog/product')->load($item->getOfferId()); $cart->addProduct($product, 1); } $cart->save(); Mage::getSingleton('customer/session')->setCartWasUpdated(true); Can you help me ? Thanks A: You made me on the good road ! Here the solution I found : $cart = Mage::getModel('checkout/cart'); $quoteItems = Mage::getSingleton('checkout/session')->getQuote()->getItemsCollection(); foreach($quoteItems as $item) $cart->removeItem($item->getId()); // Nouveau panier $devisItems = Mage::getModel('devis/detail')->getCollection()->addFieldToFilter('devis_id', (int)$quote_id); foreach($devisItems as $item) { $product = Mage::getModel('catalog/product')->load($item->getOfferId()); $stock_item = $product->getStockItem(); $stock_item->setData('is_in_stock', true); $stock_item->setData('use_config_backorders', false); $stock_item->setData('backorders', '1'); $stock_item->save(); $cart->addProduct($product, 5000); } $cart->save(); Mage::getSingleton('customer/session')->setCartWasUpdated(true); I have to reactivate backorders for this product when I'll end my process. Thanks
{ "pile_set_name": "StackExchange" }
Q: Casting result from random() to int causes GCC to say "warning: implicit function definition". Why? Possible Duplicate: Why can’t gcc find the random() interface when -std=c99 is set? I'm new to C, so I just went into man stdlib.h, searched for "random", saw that random() returned long, and, because it's just a learning exercise, thought I'd just cast to int (instead of bothering to look up one which returns int - rand() is the one). Anyway, the program compiles and runs correctly. But: $ gcc -std=c99 part1.c part1.c: In function 'main': part1.c:44:5: warning: implicit declaration of function 'random' It goes away if I remove the -std=99 flag. Here is the "offending" code: int test6[1000]; for(i = 0; i < 1000; i++) { test6[i] = (int) random(); printf("it is %d\n", test6[i]); //check random() is working (it isn't seeded) } printf("%d\n", largest(test6, 1000)); So I just wondered if anyone knew why this was, as I thought it might be interesting. A: You get the warning: implicit function definition message because the function random() isn't declared before you use it. It isn't a standard C function (not in ISO/IEC 9899:2011 or its predecessor versions). You'll need to know which header declares it; you might need to #define something to make the declaration visible. In C99, you have to declare all functions before using them; that's why the -std=c99 mode objects (though having issued the mandatory diagnostic, it can continue to compile, probably making the backwards-compatible assumption that the function returns an int). In older versions of C, you did not have to pre-declare functions; undeclared functions were implicitly declared as extern int function();, which means 'a function with unspecified (but not variable) argument list that returns an int'. That's why the compilation continues making that assumption; it used to be the standard assumption to make. With C99 and C2011, it is officially an error. My confusion is that the program still compiles and runs correctly though (random() does return pseudorandoms as well)! I have #include <stdlib.h> at the top of the file. Is it possible that my #include isn't working, but make is doing something clever to work out where to get it? The other thing (which I forgot to put in the question), is that, I thought, the warning initially disappeared when I removed the cast to int. I can't replicate that though, so I guess there must be some other explanation for it. Perhaps I accidentally removed the -std=c99 from the makefile or something. I said 'Standard C does not define it'; it doesn't, but POSIX does. So, by including the correct header (which is <stdlib.h>), and by ensuring that the declaration is seen, the function is picked up from the C library (which is not a pure Standard C library, but rather contains a lot of POSIX functions too, and a lot of other functions specific to GLIBC). So, it works because the libraries contain the function. You may want/need to compile with -std=gnu99 or specify #define _XOPEN_SOURCE 700 or #define _POSIX_C_SOURCE 200809L or something similar (before you include any system headers) to get the declaration of random() visible under -std=c99. I use a header posixver.h to get the information into my programs. /* @(#)File: $RCSfile: posixver.h,v $ @(#)Version: $Revision: 1.1 $ @(#)Last changed: $Date: 2010/08/29 00:27:48 $ @(#)Purpose: Request appropriate POSIX and X/Open Support @(#)Author: J Leffler */ #ifndef JLSS_ID_POSIXVER_H #define JLSS_ID_POSIXVER_H /* ** Include this file before including system headers. By default, with ** C99 support from the compiler, it requests POSIX 2001 support. With ** C89 support only, it requests POSIX 1997 support. Override the ** default behaviour by setting either _XOPEN_SOURCE or _POSIX_C_SOURCE. */ /* _XOPEN_SOURCE 700 is loosely equivalent to _POSIX_C_SOURCE 200809L */ /* _XOPEN_SOURCE 600 is loosely equivalent to _POSIX_C_SOURCE 200112L */ /* _XOPEN_SOURCE 500 is loosely equivalent to _POSIX_C_SOURCE 199506L */ #if !defined(_XOPEN_SOURCE) && !defined(_POSIX_C_SOURCE) #if __STDC_VERSION__ >= 199901L #define _XOPEN_SOURCE 600 /* SUS v3, POSIX 1003.1 2004 (POSIX 2001 + Corrigenda) */ #else #define _XOPEN_SOURCE 500 /* SUS v2, POSIX 1003.1 1997 */ #endif /* __STDC_VERSION__ */ #endif /* !_XOPEN_SOURCE && !_POSIX_C_SOURCE */ #endif /* JLSS_ID_POSIXVER_H */ This is rather conservative and doesn't request POSIX 2008 support because some of the machines I work on don't have that available — still! You can use it as a basis for your version which can be more aggressive if you prefer. I used to have the stanza directly in the programs, but that becomes a nightmare to fix when it is safe to change to POSIX 2008 (and maintaining the comments sensibly in many source files would have been plain silly — so the files usually contained just #define _XOPEN_SOURCE 600 with minimal or no commentary, but it is still a fiddle to change when the time comes to change).
{ "pile_set_name": "StackExchange" }
Q: onRequestPermissionsResult doesn't work I have this code that asks you for permission to take the user's location, but when the user accepts, it does not go to the function "onRequestPermissionsResult", I have checked it with the "logi", I want that when the user accepts the request, "onRequestPermissionsResult" was called of that function, thank you all! public class PerdidosMapa_Fragment extends Fragment { // BitmapDescriptor pin = BitmapDescriptorFactory.fromResource(R.drawable.pin); public PerdidosMapa_Fragment() { // Required empty public constructor } MapView mMapView; private GoogleMap googleMap; ArrayList<LatLng> markerPoints; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_perdidosmap, container, false); mMapView= (MapView) rootView.findViewById(R.id.mapView); mMapView.onCreate(savedInstanceState); mMapView.onResume(); try { MapsInitializer.initialize(getActivity().getApplicationContext()); } catch (Exception e) { e.printStackTrace(); } mMapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(GoogleMap mMap) { googleMap = mMap; if (checkLocationPermission()) { if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { //Request location updates: googleMap.setMyLocationEnabled(true); } } markerPoints = new ArrayList<LatLng>(); googleMap.getUiSettings().setCompassEnabled(true); googleMap.getUiSettings().setMyLocationButtonEnabled(true); googleMap.getUiSettings().setRotateGesturesEnabled(true); //PER CRIDAR BASE DE DADES FIREBASE PERDIDOS BASE DADES FIREBASE DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference(); DatabaseReference perdidosUbiRef = rootRef.child("Perdidos"); ValueEventListener eventListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { LatLng ubicacion;//ubicacion va canviant a mesurea recorrent base de dades for(DataSnapshot ds : dataSnapshot.getChildren()) { String name = ds.child("name").getValue(String.class); String descripcion = ds.child("descripción").getValue(String.class); Float Lat = ds.child("ubicación").child("lat").getValue(Float.class); Float Long = ds.child("ubicación").child("long").getValue(Float.class); ubicacion = new LatLng(Float.parseFloat(String.valueOf(Lat)), Float.parseFloat(String.valueOf(Long)));//crea markers googleMap.addMarker(new MarkerOptions() .position(ubicacion). title(name) .snippet(descripcion) .icon(BitmapDescriptorFactory.fromResource(R.drawable.icomap)) ); } } @Override public void onCancelled(DatabaseError databaseError) { } }; perdidosUbiRef.addListenerForSingleValueEvent(eventListener); //AGAFA UBICACIÓ INICIAL USUARI I DIRECCIONA CAMARA LocationManager mgr = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE); boolean network_enabled = mgr.isProviderEnabled(LocationManager.NETWORK_PROVIDER); Location location; if(network_enabled) {//si internet va if (checkLocationPermission()) { location = mgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);// i permis concedit et pilla ultima ubicacio if (location != null) { //agafa posició de location que agafa ubicació per la xarxa no pel GPS. al carregar el mapa i posa la camara CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(location.getLatitude(), location.getLongitude())).zoom(12).build(); googleMap.animateCamera(CameraUpdateFactory.newCameraPosition (cameraPosition)); } mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1f, new LocationListener() { @Override public void onLocationChanged(Location location) {//cada vegada qe es canvia ubicació crida aquesta funció } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }); } } } }); return rootView; } public boolean checkLocationPermission() { if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) { // Show an explanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. new AlertDialog.Builder(getActivity()) .setTitle("") .setMessage("") .setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //Prompt the user once explanation has been shown ActivityCompat.requestPermissions(getActivity(),new String[] {Manifest.permission.ACCESS_FINE_LOCATION},1); } }) .create() .show(); } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1); } return false; } else { return true; } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { Log.i("locationPermission", "onRequestPermissionsResult: Entra a la funció "); switch (requestCode) { case 1: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the // location-related task you need to do. if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { googleMap.setMyLocationEnabled(true); Log.i("locationPermission", "onRequestPermissionsResult: Dóna localització al permetre el permis "); } } else { } return; } } } } And onRequestPermissionsResult method: @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { Log.i("locationPermission", "onRequestPermissionsResult: Entra a la funció "); switch (requestCode) { case 1: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the // location-related task you need to do. if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { googleMap.setMyLocationEnabled(true); Log.i("locationPermission", "onRequestPermissionsResult: Dóna localització al permetre el permis "); } } else { } return; } } } A: try overriding onRequestPermissionResult in parent Activity of fragment instead of the fragment.
{ "pile_set_name": "StackExchange" }
Q: What is a Reciprocal Word?™ This is in the spirit of the What is a Word™/Phrase™ series started by JLee with a special brand of Phrase™ and Word™ puzzles. If a word conforms to a special rule, I call it a Reciprocal Word™. Use the examples below to find the rule. $$\begin{array}{|c|c|}\hline \bbox[yellow]{\textbf{Reciprocal Words }^™}& \bbox[yellow]{\textbf{Not Reciprocal Words }^™}\\ \hline \text{ COMMENT }&\text{ REPLY }\\ \hline \text{ PULP }&\text{ FICTION }\\ \hline \text{ FOOL }&\text{ JOKER }\\ \hline \text{ STARTS }&\text{ BEGINS }\\ \hline \text{ REGGAE }&\text{ DANCEHALL }\\ \hline \text{ FLUID }&\text{ SOLID }\\ \hline \text{ INTERNAL }&\text{ EXTERNAL }\\ \hline \text{ RESEARCHER }&\text{ INVESTIGATOR }\\ \hline \text{ OUZO }&\text{ SAMBUCA }\\ \hline \text{ POSTMAN }&\text{ TAMPONS }\\ \hline \text{ ACHING }&\text{ HURTING }\\ \hline \text{ TEST }&\text{ DRIVE }\\ \hline \text{ PECAN }&\text{ WALNUT }\\ \hline \text{ INTEND }&\text{ AIM }\\ \hline \text{ WRECKING }&\text{ BASHING }\\ \hline \text{ FAMINE }&\text{ HUNGER }\\ \hline \text{ SCALE }&\text{ MODEL }\\ \hline \end{array}$$ In case you want it in CSV: Reciprocal Words™,Not Reciprocal Words™ COMMENT,REPLY PULP,FICTION FOOL,JOKER STARTS,BEGINS REGGAE,DANCEHALL FLUID,SOLID INTERNAL,EXTERNAL RESEARCHER,INVESTIGATOR OUZO,SAMBUCA POSTMAN,TAMPONS ACHING,HURTING TEST,DRIVE PECAN,WALNUT INTEND,AIM WRECKING,BASHING FAMINE,HUNGER SCALE,MODEL The puzzle relies on the series' inbuilt assumption, that each word can be tested for whether it is a Reciprocal Word™ without relying on the other words. These are not the only examples of Reciprocal Words™, many more exist. Hint: You'd better not suffer from aibohphobia if you want to solve this puzzle. A: A Reciprocal Word™ is one that When written in morse code is a palidrome. Example RESEARCHER in morse code is $.-.......-.-.-.-.......-.$ which reads the same backwards and forwards. Other examples COMMENT = $-.-.-------.-.-$ PULP is $.--...-.-...--.$ FOOL is $..-.------.-..$ STARTS is $...-.-.-.-...$ REGGAE is $.-..--.--..-.$ FLUID is $..-..-....-..-..$ INTERNAL is $..-.-..-.-..-.-..$ The are called Reciprocal because When translated to morse, the word is its own reciprocal, i.e, a palindrome.
{ "pile_set_name": "StackExchange" }
Q: How to connect local private geth nodes to the web page without using metamask or mist? I'm developing a web wallet similar to meta mask that can make transactions or can create accounts from UI. Frontend is developed using React, blockchain is implemented in geth. I'm using truffle react box. else if (window.web3) { // Use Mist/MetaMask's provider. const web3 = window.web3; console.log("Injected web3 detected."); resolve(web3); } // Fallback to localhost; use dev console port by default... else { const provider = new Web3.providers.HttpProvider( "http://127.0.0.1:8545" ); const web3 = new Web3(provider); console.log("No web3 instance injected, using Local web3."); resolve(web3); } }); According to this code, my local provider should work when there is no metamask extension, but my code only works when I have the meta mask extension installed. Are there any way to get connection to my blockchain and can control from web page? Please help me. A: If you do not have a MetaMask extension, then you need to include a web3 in your html file: <script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script> More details: https://github.com/ethereum/web3.js/#in-the-browser
{ "pile_set_name": "StackExchange" }
Q: SQL Server : TOP along with Distinct I have two tables Products and PurchaseDetails. The schema for Products table is ProductId (primary key) ProductName CategoryId Price QuantityAvailable The schema for PurchaseDetails table is PurchaseId EmailId ProductId QuantityPurchased DateOfPurchase The question asks me to find out the TOP 3 products that are purchased in large quantity. I wrote this SQL query: Select TOP 3 Distinct(ProductName), Price, QuantityPurchased from Product, PurchaseDetails where Product.ProductId = PurchaseDetails.ProductId order by QuantityPurchased DESC But the above query throws an error. I fail to see why the error is being generated by the above query ? A: Below query will give you the top 3 products that are purchased in large quantity Select TOP 3 ProductName,sum(Price) as [price],sum(QuantityPurchased) as QuantityPurchased from Product , PurchaseDetails where Product.ProductId=PurchaseDetails.ProductId group by ProductName order by QuantityPurchased DESC
{ "pile_set_name": "StackExchange" }
Q: Are CBCentral and CBPeripheral identifiers the same for one device The title explains it all. All I want to know is that if a device is being used as a peripheral and a central and gets near another device being used as a peripheral and a central, would the peripheral manager and central manager on each device see the same "identifier" property on the CBPeripheral and the CBCentral objects corresponding to the to the other device in the area? A: There's no official statement but experience shows that a remote device is identified by a single UUID. That is, the CBPeripheral and the CBCentral corresponding to the same remote device will have the same UUID. However, these values will be different on each host. E.g. an iPhone will never have the same UUID on different iOS devices that discover it.
{ "pile_set_name": "StackExchange" }
Q: Why is the container overlapping my sidebar-ish ? Why is the fluid-container overlapping like that, but others don't? Is that correct, or am I missing something? Looks wrong to me. <nav class="nav flex-column float-left"> {links} </nav> <div class="container-fluid"><!-- overlapping --> <div class="row"><!-- fine --> <div class="col"><!-- fine --> <main role="main"><!-- fine --> {content} </main> </div> </div> </div> https://jsfiddle.net/w3LwwxL7/ Edit: Just for you to know: I want to achieve a static left sidebar/nav with a fixed width (see image). Everything on the right is main content. That's why I didn't used col-1 (nav) and col-11 (main). Hope this helps :-) A: Give your sidenav a fixed width and set a padding-left (same amount of sidebar width) Here is an example: https://jsfiddle.net/w3LwwxL7/3/
{ "pile_set_name": "StackExchange" }
Q: How can I break down this sentence to translate it 'literally' one piece at a time? I would appreciate if you could help me to translate this and also if you could refer me to any important grammatical structures in here that I should learn. I understand the meaning - but I want to try translate it "directly" into English - one small piece at a time - so it's easy for me to match the original text to the translation. My second attempt: 모든 단어의 끝소리는 • The ending sound of all words, 모음으로 시작되는조사나 어미(와) • Postposition particles (조사) or the end of a word(어미), THAT begins with a vowel (i.e. 으세요 in the example), AND 결합하는 경우 받침이 • scenario in which it’s combined with Patchim 뒤 음절 • In next syllable (i.e. after the Patchim) 첫소리로 옮겨 발음됩니다. • (Patchim) moves (옮겨) to the “first(첫소리) (postion)” when pronounced. Please note I am trying to translate it "directly" into English so it's easy to match the Korean content to the English translation. And then after translating it directly I want to try to re-arrange it of course. A: I find this quite hard to break down too - it's a reasonably long sentence, which makes it hard to hold it all in your head, and it's hard to spot the points where you can break it up. However, breaking the sentence down at conjunctions is still our best tactic. First of all, the '는' topic particle provides an easy place to split : 모든 단어의 끝소리는 ("we're talking about") all words' ending sounds... Ok, let's read on a bit... 모음으로 시작되는 조사나 어미 particles or word endings that start with a vowel That's not too bad, but we're starting to look for the next place to break up the sentence. The best place here is probably 는 경우, a construction meaning 'in this situation'; 'when'. So let's split there, and pretend that the sentence just ends with '결합한다'. That gives us: 모든 단어의 끝소리는 모음으로 시작되는 조사나 어미 와 결합한다 All words' ending sounds are joined to particles or word endings that start with a vowel. Bearing in mind that 는 경우 means 'when', let's look at the rest of the real sentence: 받침이 뒤 음절 첫소리로 옮겨 발음됩니다. the final consonant is pronounced as if moved to the first sound of the next syllable Putting it all together: 모든 단어의 끝소리는 모음으로 시작되는 조사나 어미 와 결합하는 경우 받침이 뒤 음절 첫소리로 옮겨 발음됩니다. we get a literal translation something like: When all words' ending sounds are joined to particles or word endings that start with a vowel, the final consonant is pronounced as if moved to the first sound of the next syllable. Or, with the English made a bit more natural: When a word's final consonant is joined to a particle or word ending that starts with a vowel, it is pronounced as if moved to the first sound of the next syllable.
{ "pile_set_name": "StackExchange" }
Q: Leaflet map with embedded Bootstrap Switch toggle I am trying to add a bootstrap switch inside my leaflet.js map. So far I have a working button (see snippet) but I want to use a switch instead. See attached image: So far it is a complete failure. Among the things I have tried is the code below (which obviously does not work): var customControl_2 = L.Control.extend({ options: { position: 'topright' }, onAdd: function (map) { var container = L.DomUtil.create('input', 'mySwitch'); container = $("[class='mySwitch']").bootstrapSwitch({}) //container.onclick = function(){ // console.log('buttonClicked'); //} return container; } }); map.addControl(new customControl_2()); Does anyone know how this should work please? As always, any help is greatly appreciated. If the same toggle switch can be achieved in some other way (ie without bootstrap) that is also going to be fine. Many thanks! <!DOCTYPE html> <html> <head> <title>Leaflet</title> <meta charset="utf-8" /> <!--jquery --> <script src="https://code.jquery.com/jquery-3.3.1.js"></script> <!-- bootstrap --> <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> <!-- bootstrap switch --> <link rel="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.2/css/bootstrap3/bootstrap-switch.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.2/js/bootstrap-switch.js"></script> <!--d3 --> <script src='https://d3js.org/d3.v4.min.js'></script> <!-- leaflet --> <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" /> <script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script> <style> html, body { height: 100%; margin: 0; } #map { width: 600px; height: 400px; } </style> </head> <body> <div id='map'></div> <script type="text/javascript"> var map = L.map('map', { minZoom: 0, }).setView([37, -103], 3); var positron = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', { attribution: "CartoDB" }).addTo(map); // Toggle button to turn layers on and off var customControl = L.Control.extend({ options: { position: 'topright' }, onAdd: function(map) { var container = L.DomUtil.create('input'); container.type = "button"; container.title = "Some title"; container.value = "Off"; container.style.backgroundColor = 'white'; container.style.backgroundSize = "80px 30px"; container.style.width = '80px'; container.style.height = '30px'; function toggle(button) { if (button.value == "Off") { button.value = "On" button.innerHTML = "On" removeLayers(); } else if (button.value == "On") { button.value = "Off" button.innerHTML = "Off" addLayers(); } } container.onclick = function() { toggle(this); console.log('buttonClicked'); } return container; } }); map.addControl(new customControl()); </script> </body> </html> A: The $("[class='mySwitch']") finds Elements based on the string selector. You have to adjust the Bootstrap Switch example to your usage. In your case, you do not need a selector but you can directly pass the HTML Element you created, so that it is wrapped by jQuery and can be transformed by Bootstrap Switch: $(container).bootstrapSwitch({}) Do not try to transform your Control container directly, but embed a child checkbox input into that container: var container = L.DomUtil.create('div'); // Use a child input. var input = L.DomUtil.create('input'); input.type = "checkbox"; // Insert the input as child of container. container.appendChild(input); // Transform the input, not the container. $(input).bootstrapSwitch({}); You have a typo in: <link rel="https:....css"> …should be: <link rel="stylesheet" href="https:....css"> Live result: var map = L.map('map', { minZoom: 0, }).setView([37, -103], 3); var positron = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', { attribution: "CartoDB" }).addTo(map); // Toggle button to turn layers on and off var customControl = L.Control.extend({ options: { position: 'topright' }, onAdd: function(map) { var container = L.DomUtil.create('div'); // Use a child input. var input = L.DomUtil.create('input'); input.type = "checkbox"; input.title = "Some title"; input.value = "Off"; // Insert the input as child of container. container.appendChild(input); jQuery(input).bootstrapSwitch({ // http://bootstrapswitch.site/options.html onSwitchChange: function(event) { console.log('buttonClicked', event.target.checked); } }); return container; } }); map.addControl(new customControl()); html, body, #map { height: 100%; margin: 0; } <!--jquery --> <script src="https://code.jquery.com/jquery-3.3.1.js"></script> <!-- bootstrap --> <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--> <!-- bootstrap switch --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.2/css/bootstrap3/bootstrap-switch.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.2/js/bootstrap-switch.js"></script> <!-- leaflet --> <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" /> <script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script> <div id='map'></div>
{ "pile_set_name": "StackExchange" }
Q: Is this question off topic on Stack Overflow? I accessed an article on the web and really liked the graphics it contained. I'd like to post a question on SO containing the graphs from the original article asking if anybody knows the tools that were used to generate them (e.g. matlab or Inkscape,...). Do you think this question would be considered Off Topic on Stack Overflow? A: Yes, it’s off-topic, because it doesn’t have anything to do with programming. It’s probably unanswerable, too, unless the generator has put its signature somewhere. Asking how to make that type of graph with an example of what you’ve tried, however, would probably be fine! =) A: Yes, that question is off-topic for StackOverflow. Please check the Help Center first; read this Help Center topic on which topics are acceptable. Your question falls into none of these categories.
{ "pile_set_name": "StackExchange" }
Q: Problems using a couchbase view with a boolean parameter I having problems using couchbase map functions with boolean key. I wrote a map function with a boolean parameter, but when I try to use this function passing the value "false" as key the function returns nothing Sample Document: { "name": "lorem ipsum", "presentationId": "presentation_24e53b3a-db43-4d98-8499-3e8f3628a9c6", "fullPrice": 8, "isSold": false, "buyerId": null, "type": "ticket", } Map Function: function(doc, meta) { if (doc.type == "ticket" && doc.isSold && doc.presentationId) { emit([doc.isSold, doc.presentationId], null); } } http://localhost:8092/default/_design/tickets/_view/by_presentation_and_isSold?key=[false,"presentation_24e53b3a-db43-4d98-8499-3e8f3628a9c6"] Result: {"total_rows":10,"rows":[]}]} A: You are having this problem due to the check you do for the doc.isSold before the emit statement, the check means that only documents where doc.isSold == TRUE are passing through. What you need to do is this which will check that the variable has been set rather than evaluating the boolean value: function(doc, meta) { if (doc.type == "ticket" && doc.isSold != null && doc.presentationId) { emit([doc.isSold, doc.presentationId], null); } } Hope that helps :)
{ "pile_set_name": "StackExchange" }
Q: J.Doe should be able to localize On the registration page (open in private mode) Display Name field's placeholder (J. Doe) doesn't exist in transifex, i.e. impossible to localize it. Another string with "John Doe" already translated in transifex. A: There you Doe
{ "pile_set_name": "StackExchange" }
Q: Rotating a curve by a certain angle (rotating a parabola) I have a parabola $y^2=4x$, and I have to rotate this by $120^\circ$ in the anticlockwise direction. What my book does is, it takes a point $(x,y)$ in the complex form, ie, $z=x+\iota y$, and then by rotation, the new point is $z_1=ze^{\frac{2\pi}{3}} = \bigg(-\frac{x}{2}-\frac{\sqrt3 y}{2}\bigg)+\iota \bigg(\frac{\sqrt3x}{2}-\frac{y}{2}\bigg)$ So the equation of the new curve, the book says is $\bigg(\frac{\sqrt3x}{2}-\frac{y}{2}\bigg)^2=4\bigg(-\frac{x}{2}-\frac{\sqrt3 y}{2}\bigg)$ But the axis of this curve is $\sqrt3 x = y$, which has a slope of $\sqrt3$, ie it makes an angle of $60^\circ$ with the positive direction of the $x$-axis. My question is, is rotating the point on the curve by an angle (as the book does), same as rotating the axis of a curve by that angle? If not, why? In what "sense" is this rotation? A: I believe they may have mixed up the original and new co-ordinates in the book. Just as, if you want to translate the graph of $y=f(x)$ by $a\in\mathbb R$ horizontally, the resulting graph has the equation $y=f(x-a)$ and not $y=f(x+a)$. The correct solution would be not to express $z_1=x_1+iy_1=ze^{2\pi i/3}$, but to express $z=x+iy=z_1e^{-2\pi i/3}$, which gives you $x, y$ expressed via $x_1, y_1$, and then, the original equation $y^2=4x$, by substituting, gives you the equation of the rotated curve in terms of $x_1, y_1$.
{ "pile_set_name": "StackExchange" }
Q: WHERE IN (a,b,c...) or WHERE= in loop, which one usually performs better? We use SELECT * FROM profile WHERE id IN (1,2,3...) to get all results in ResultSet. It is essentially SELECT * FROM profile WHERE id='1' OR id='2' OR id='3'... We write a loop like: foreach(int id: ids) {execute(SELECT * FROM profile WHERE id='i')} As far as I consider, since requests sent DB takes a lot of time, we should reduce the number of times we visit DB, so the first method is better. However, I am not sure whether it's true or not in the industry and is there's a better solution. Please enlight me, thank you :) A: From a performance point of view, I think your first query using WHERE IN (...) is the preferred way to go here. As you and the comments have pointed out, calling many queries in a loop from PHP has a big overhead, because each new call to the DB takes network time among other things. On top of this, MySQL can internally optimize a WHERE IN clause. For instance, it can create a map of the IN values which allows for fast lookup. In an ideal case, making a single query using WHERE IN might not peform much worse than searching for a single value.
{ "pile_set_name": "StackExchange" }
Q: express project prints "linux is NOT supported" without explanation I have built a NodeJS express project on windows environment, and it running without any problems. After I have finished I tried uploading the project to a Linux server to run. Somewhy, after running "npm start" command, the project prints a new line which says: "linux is NOT supported" As you can see here: I have tried searching with visual studio in entire project for this string but couldn't find which module does that problem. Here is my package.json: { "name": "api", "version": "0.0.0", "private": true, "scripts": { "start": "nodemon bin/www" }, "dependencies": { "base64topdf": "^1.1.8", "bcrypt-nodejs": "0.0.3", "cookie-parser": "~1.4.3", "cors": "^2.8.4", "csv-parse": "^2.5.0", "csv-parser": "^1.12.1", "debug": "~2.6.9", "express": "~4.16.0", "http-errors": "~1.6.2", "https": "^1.0.0", "iconv-lite": "^0.4.23", "image-to-base64": "^1.3.5", "json2csv": "^4.1.6", "jsonwebtoken": "^8.3.0", "moment": "^2.22.2", "morgan": "~1.9.0", "multer": "^1.3.0", "mysql": "^2.15.0", "node-xlsx": "^0.12.1", "nodemon": "^1.17.5", "path": "^0.12.7", "pdf-image": "^2.0.0", "pdf-poppler": "^0.2.1", "pdf2img": "^0.5.0", "pug": "2.0.0-beta11", "uuid": "^3.3.2" } } Can you help me find what module does not supported? Or maybe the solution is not the one I am thinking of? A: After doing a long research for each of the dependencies and after trying to remove each of them separately, it turns out that 'pdf-poppler' was the one that doesn't support Linux.
{ "pile_set_name": "StackExchange" }
Q: Validation on deleting record ActiveJDBC What would be the best approach if I want to put validation upon record deletion? Here is the reason why. I have two tables, Store and Staff. Structure of Store: ID Store Code Store Name Structure of Staff: ID Staff Code Staff Name Store Code As you can see, table store is related to table staff. What if the user tries to delete a store that is already used on table staff? If no validation, my data would be broken. How can I prevent it? Thanks. A: The best way to implement it is through the referential integrity in the database, not in framework. Structure of STORE: id code name Structure of STAFF: id code name store_id As you can see, the STAFF table "belongs" to STORE because it contains the ID of a parent record. This is a classical One-to-many association: http://javalite.io/one_to_many_associations You can do one of two things: Throw exception from DB in case you are deleting a parent without deleting a child Cascade deleting a child in case a parent is deleted automatically (in DB) A few links suggested by Google: https://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html http://www.mysqltutorial.org/mysql-on-delete-cascade/
{ "pile_set_name": "StackExchange" }
Q: Swift - Updating values of a multidimensional NSMutableDictionary In the Playground example below I'm trying to modify a multidimensional NSMutableDictionary. Can someone please explain the correct way to modify a multidimensional mutable dictionary? import Cocoa let player = "Player 1" let characterName = "Magic Glop" let strength = 23 let defense = 220 let type = "fire" var example: NSMutableDictionary = ["id":1, "player":player, "characters": ["character-name":characterName, "stats": ["strength":strength, "defense":defense, "type":type ] ] ] // My first attempt to update character-name. example["characters"]!["character-name"] = "New Name" // Error: Cannot assign to immutable expression of type 'AnyObject?!' // Next I tried updating the value of "characters">"stats">"type" with .setObject example["characters"]!["stats"]!!.setObject("water", forKey: "type") // Documentation: .setObject adds a given key-value pair to the dictionary. If the key already exists in the dictionary, the object takes its place. // Error: Execution was interrupted, reason: EXC_BAD INSTRUCTION (code=EXC_i386_INVOP, suncode=0x0). Thanks in advance! A: Class approach: You can update var to let for non-editable parameters. class Player { let id: Int var name: String var characters = [Character]() init(id: Int, name: String) { self.id = id self.name = name } /** Add new char to Player */ func addNewCharacter(new: Character) { self.characters.append(new) } } class Character { var name: String var strength: Int var defense: Int var type: String init(name: String, strength: Int, defense: Int, type: String) { self.name = name self.strength = strength self.defense = defense self.type = type } } func createPlayer() { let player1 = Player(id: 1, name: "Bodrum") // create new char and add to the player1 named Bodrum let char1 = Character(name: "Magic Glop", strength: 23, defense: 220, type: "fire") player1.addNewCharacter(char1) print("old name:\(player1.characters[0].name), old type:\(player1.characters[0].type)") // update char1's parameters player1.characters[0].name = "Yalikavak" player1.characters[0].type = "water" print("new name:\(player1.characters[0].name), new type:\(player1.characters[0].type)") } // old name:Magic Glop, old type:fire // new name:Yalikavak, new type:water
{ "pile_set_name": "StackExchange" }
Q: Regular expression needs an extra whitespace at the end Consider this code: #include <pcre.h> #include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char **argv) { char **ret = NULL, **t; char *buffer; pcre *re; const char *error; int erroffset, rc = 1, arraylength = 0, ovector[2], i = 0; const char *string = "WORD"; buffer = malloc(strlen(string)+1); re = pcre_compile("[A-Za-z0-9]+|\\\"[A-Za-z0-9\\s\\.'\\?]+\\\"", PCRE_MULTILINE, &error, &erroffset, NULL); if (re == NULL ) printf ("pcre_compile error: %s\n", error); while (rc > 0) { rc = pcre_exec(re, NULL, string, strlen(string), i, 0, ovector, 2); bzero(buffer, strlen(string)); pcre_copy_substring(string, ovector, rc, 0, buffer, strlen(string)); if (rc > 0) { printf("BUFFER: %s\n", buffer); } i = ovector[1]; } return 0; } The output of this is: [bart@localhost tests]$ ./pcre BUFFER: I expect to get WORD. When I added a whitespace character after WORD: const char *string = "WORD "; it does work: [bart@localhost tests]$ ./pcre BUFFER: WORD Also, when I add more words, it works. I tried to test my regular expression here, and it tells me it should work without the whitespace character. What am I missing here? Update When I change my regex to [A-Za-z0-9]+ it still doesn't work without the whitespace. A: The problem was in pcre_copy_substring, the buffer was too small. This: pcre_copy_substring(string, ovector, rc, 0, buffer, strlen(string)+1); fixed it.
{ "pile_set_name": "StackExchange" }
Q: Creating a meshgrid, without mesh command I am trying to create an array that looks like this (as an example) X = | 1 2 3 | | 1 2 3 | | 1 2 3 | Y = | 1 1 1 | | 2 2 2 | | 3 3 3 | I tried doing a nested for loop inside a while loop, with this method, the Y array works but not the X array, I sort of understand why its not working but I dont know how to fix it. this is what I got X = []; Y = []; c=1; while c<=3; for i=1:3 for j=1:3 X(i,c)=j; Y(i,c)=i; end end c=c+1; end I understand that the meshgrid command will do this for me with one line of code, but I have to do it with a nested for loop. Any suggestions? A: Maybe try this : startIter = 1; endIter = 3; X = []; Y = []; line = startIter:endIter for i = 1:endIter X = [X;line]; Y = [Y,line']; end
{ "pile_set_name": "StackExchange" }
Q: Why isn't Split optimized? Consider the following code. 's' is splitted twice to two different arrays. string s = "1,2,3"; string[] arr = s.Split(','); string[] arr2 = s.Split(','); foreach (..) { // do something } When compiling this in release mode the IL looks like this, so Split is actually called twice. Is there a reason why this isnt optimized? IL_0008: newarr [mscorlib]System.Char IL_000d: stloc.s CS$0$0000 IL_000f: ldloc.s CS$0$0000 IL_0011: ldc.i4.0 IL_0012: ldc.i4.s 44 IL_0014: stelem.i2 IL_0015: ldloc.s CS$0$0000 IL_0017: callvirt instance string[] [mscorlib]System.String::Split(char[]) IL_001c: stloc.1 IL_001d: ldloc.0 IL_001e: ldc.i4.1 IL_001f: newarr [mscorlib]System.Char IL_0024: stloc.s CS$0$0001 IL_0026: ldloc.s CS$0$0001 IL_0028: ldc.i4.0 IL_0029: ldc.i4.s 44 IL_002b: stelem.i2 IL_002c: ldloc.s CS$0$0001 IL_002e: callvirt instance string[] [mscorlib]System.String::Split(char[]) A: Distilling comments down to an answer: The compiler, in general, has no special knowledge on the contents of a method - even if it could analyze the current implementation, it has no way to know whether that implementation would change in important details. The two most obvious issues with the optimization you assume the compiler could perform are determinism and the presence of side effects. Determinism - there's no guarantee that two successive calls to the same function will produce identical results, even in the absence of any (obvious) shared state. Side effects - the function in question (or functions that it calls) could produce visible side effects - even as little as incrementing a call counter - such that calling it once or twice would have different overall effects. Now, it is true that at times, the compiler can pull off tricks that we aren't able to ourselves - e.g. it could have knowledge that two successive calls to Split(), using a local reference that couldn't have been assigned a copy of a more visible reference, should produce the same result. But that's an incredibly specific optimization that's probably not worth the engineering effort. In general, the compiler has no more knowledge than the method signatures. And, in the current incarnation of .NET, the method signatures provide no information on determinism and side effects.
{ "pile_set_name": "StackExchange" }
Q: WMI The RPC server is unavailable. (Exception from HRESULT: 0x800706BA) My application requirement is like below. Application will run on domain admin system which will ping all machine under that domain, it will take disk drive, CPU and RAM details from all domain systems. Whenever I'm trying to ping machine I'm getting error that "The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)" Code I'm using to connect remote machine is ConnectionOptions options = new ConnectionOptions(); options.EnablePrivileges = true; options.Impersonation = ImpersonationLevel.Impersonate; options.Username = System.Configuration.ConfigurationSettings.AppSettings["AccessUserName"].ToString(); options.Password = System.Configuration.ConfigurationSettings.AppSettings["AccessPassword"].ToString(); options.Authority = "ntlmdomain:" + System.Configuration.ConfigurationSettings.AppSettings["DomainName"].ToString(); options.Authentication = AuthenticationLevel.Packet; ManagementScope scope = new ManagementScope("\\\\" + sMachineIP + "\\root\\cimv2", options); scope.Connect(); A: I found the solution for this. I did it by enabling Windows Management Instrumentation (WMI) rule in Windows Firewall. Open Windows Firewall. Allow app or feature through Windows Firewall. Enable Domain Privilege for Windows Management Instrumentation(WMI). There are some other things also that you can check. The remote computer is blocked by the firewall. Solution: Open the Group Policy Object Editor snap-in (gpedit.msc) to edit the Group Policy object (GPO) that is used to manage Windows Firewall settings in your organization. Open Computer Configuration, open Administrative Templates, open Network, open Network Connections, open Windows Firewall, and then open either Domain Profile or Standard Profile, depending on which profile you want to configure. Enable the following exception: Allow Remote Administration Exception and Allow File and Printer Sharing Exception. Host name or IP address is wrong or the remote computer is shutdown. Solution: Verify correct host name or IP address. The "TCP/IP NetBIOS Helper" service isn't running. Solution: Verity that "TCP/IP NetBIOS Helper" is running and set to auto start after restart. The "Remote Procedure Call (RPC)" service is not running on the remote computer. Solution: Open services.msc using Windows Run. In Windows Services, Verify that Remote Procedure Call (RPC) is running and set to auto start after restart. The "Windows Management Instrumentation" service is not running on the remote computer. Solution: Open services.msc using Windows Run. Verity that Windows Management Instrumentation service is running and set to auto start after restart.
{ "pile_set_name": "StackExchange" }
Q: Java: Building an array of Point2D.Double In a constructor I am trying to build an array of Point2D.Double from an Point2D array. Basically I want to add coordinates to a graph. I did this: private Point2D.Double [] points; public EmbeddedGraph(Point2D[] pointArray){ super(pointArray.length); for (int i=0; i<pointArray.length; i++){ points[i] = new Point2D.Double(); points[i].setLocation(pointArray[i].getX(), pointArray[i].getY()); } } But I'm getting a NullPointerException. The array of coordinates (pointArray) comes from the given code of the exercise. So I'm guessing the error is on my part. Point2D[] coordinates = new Point2D[4]; coordinates[0] = new Point2D.Double(-14,0); coordinates[1] = new Point2D.Double(0,10); coordinates[2] = new Point2D.Double(0,-10); coordinates[3] = new Point2D.Double(14,0); EmbeddedGraph g = new EmbeddedGraph( coordinates ); A: You are trying to fill points[] array when it is null. You should do this first: `points = new Point2D[pointArray.length]` (in case it is not done in super());
{ "pile_set_name": "StackExchange" }
Q: For an infinitesimal transformation in phase space, what functions are allowed for this to be a canonical transformation? Consider an infinitesimal transformation: $$(q_{i},p_{j}) \quad\longrightarrow \quad(Q_{i},P_{j}) ~=~ \left(q_{i} + \alpha F_{i}(q,p),~p_{j} + \alpha E_{j}(q,p)\right) $$ where $α$ is considered to be infinitesimally small. Now, if we construct Jacobian matrix, we will have: $$ \jmath =\begin{pmatrix} \delta_{ij}+ \alpha{\frac{\partial F_{i} }{\partial q_{j}}} & \alpha{\frac{\partial F_{i} }{\partial p_{j}}} \\ \alpha{\frac{\partial E_{i} }{\partial q_{j}}} & \delta_{ij}+ \alpha{\frac{\partial E_{i} }{\partial p_{j}}} \end{pmatrix}.$$ What functions $F_{i} (q, p)$ and $E_{i} (q, p)$ are allowed for this to be a canonical transformation? To be canonical transformation, it's required to hold: $$\jmath j \jmath^{T} = j$$ in which $ j = \begin{pmatrix} 0 & 1\\ -1&0 \end{pmatrix}$. To hold the canonical transformation, there should be: $$\frac {\partial F_{i}}{\partial q_{j}} = - \frac {\partial E_{i}}{\partial p_{j}} $$ which is true if $$F_{i} = \frac {\partial G}{\partial p_{i}} \; \; , \; \; E_{i} = - \frac {\partial G}{\partial q_{i}} $$ for some function $G(q, p)$. Now my problem is that by calculating everything I can't figure out how to reach to last two formulas. The formulas which shows the possibilities for $F_{i}$ and $E_{i}$? A: First of all, be aware that there exist various different definitions of canonical transformations (CT) in the literature, cf. e.g. this Phys.SE post. What OP (v3) above refers to as a CT, we will in this answer call a symplectomorphism for clarity. What we in this answer will refer to as a CT, will just be a CT of type 2. It is possible to show (see e.g. Ref. 1) that an arbitrary time-dependent infinitesimal canonical transformation (ICT) of type 2 with generator $G=G(z,t)$ can be identified with a Hamiltonian vector field (HVF) $$ \delta z^I~=~\varepsilon\{ z^I,G\}_{PB}~\equiv~ \sum_{K=1}^{2n} J^{IK} \frac{\partial G}{\partial z^K} , $$ $$ X_{-G}~\equiv~-\{G,\cdot\}_{PB}~\equiv~\{\cdot,G\}_{PB},\tag{1} $$ with (minus) the same generator $G$. Here $z^1,\ldots, z^{2n}$, are phase space variables, $t$ is time, $\varepsilon$ is an infinitesimal parameter, and $J$ is the symplectic unit matrix, $$\tag{2} J^2~=~-{\bf 1}_{2n\times 2n}.$$ A general time-dependent infinitesimal transformation (IT) of phase space can without loss of generality be assumed to be of the form $$ \tag{3} \delta z^I~=~\varepsilon \sum_{K=1}^{2n} J^{IK} G_K(z,t) ,\qquad I~\in~\{1,\ldots, 2n\}, $$ because the matrix $J$ is invertible. It is possible to show that a time-dependent infinitesimal symplectomorphism (IS) [written in the form (3)] satisfies the Maxwell relations$^1$ $$\tag{4} \frac{\partial G_I(z,t)}{\partial z^J}~=~(I \leftrightarrow J),\qquad I,J~\in~\{1,\ldots, 2n\}. $$ Eq. (4) states that the one-form $$\tag{5} \mathbb{G}~:=~ \sum_{I=1}^{2n}G_I(z,t) \mathrm{d}z^I$$ is closed $$\tag{6} \mathrm{d}\mathbb{G}~=~0. $$ It follows from Poincare Lemma, that locally there exists a function $G$ such that $ \mathbb{G}$ is locally exact $$\tag{7} \mathbb{G}~=~\mathrm{d}G. $$ Or in components, $$\tag{8} G_I(z,t)~=~\frac{\partial G(z,t)}{\partial z^I},\qquad I~\in~\{1,\ldots, 2n\} .$$ In summary we have the following very useful theorem for a general time-dependent infinitesimal transformation (IT). Theorem. An infinitesimal canonical transformation (ICT) of type 2 is an infinitesimal symplectomorphism (IS). Conversely, an IS is locally a ICT of type 2. References: H. Goldstein, Classical Mechanics; 2nd eds., 1980, Section 9.3; or 3rd eds., 2001, Section 9.4. -- $^1$ OP already listed some (but not all) of the Maxwell relations (4) in his second-last equation. All of the Maxwell relations (4) are necessary in order to deduce the local existence of the generating function $G$.
{ "pile_set_name": "StackExchange" }
Q: fuelphp html email issue I ran into a problem what i cant solve. i took a look at the fuelphp documentation, made it that way, but i get an error with passed walue code $email_data = array(); //echo Config::get('base_url'). "user/activate/". $user['hash']; $email = Email::forge(); $email->from('[email protected]', Config::get('site_name')); $email->to(Input::post('email'), Input::post('first_name') . " " . Input::post('last_name')); $email->subject('Regisztráció'); $email_data['name'] = "Kedves " . Input::post('first_name'). " " .Input::post('last_name') ."<br><br>" ; $email_data['title'] = "Üdvözöllek a ".Config::get('site_name')." oldalán" ."<br>"; $email_data['link'] = '<a href="'.Config::get('site_url'). "user/activate/". $user['hash'].'">Fiókod mherősítéséhez kérlek kattints ide</a>'; $email->html_body(\View::forge('email/activation', $email_data)); $email->send(); $response->body(json_encode(array( 'status' => 'ok', ))); the email template file <?php print_r($email_data); ?> and the email sends me out this Notice! ErrorException [ Notice ]: Undefined variable: email_data APPPATH/views/email/activation.php @ line 3: 2:3:print_r($email_data);4:?> could please someone give me a hint what im doing wrong? A: $email->html_body(\View::forge('email/activation', $email_data)); Should be $email->html_body(\View::forge('email/activation', array('email_data' => $email_data)));
{ "pile_set_name": "StackExchange" }
Q: How to escape special characters in Windows batch? How to replace the string 1234567890 by !@#$%^&*() in Windows batch file? set temp_mm=1234567890 echo befor:%temp_mm% set temp_mm=%temp_mm:1=!% set temp_mm=%temp_mm:2=@% set temp_mm=%temp_mm:3=#% set temp_mm=%temp_mm:4=$% set temp_mm=%temp_mm:5=^%% set temp_mm=%temp_mm:6=^^% set temp_mm=%temp_mm:7=^&% set temp_mm=%temp_mm:8=^*% set temp_mm=%temp_mm:9=^(% set temp_mm=%temp_mm:0=^)% echo after:%temp_mm% A: @ECHO Off SETLOCAL set temp_mm=12345678901234567890 echo befor:%temp_mm% set "temp_mm=%temp_mm:1=!%" set "temp_mm=%temp_mm:2=@%" set "temp_mm=%temp_mm:3=#%" set "temp_mm=%temp_mm:4=$%" set "temp_mm=%temp_mm:6=^%" set "temp_mm=%temp_mm:7=&%" set "temp_mm=%temp_mm:8=*%" set "temp_mm=%temp_mm:9=(%" set "temp_mm=%temp_mm:0=)%" SETLOCAL enabledelayedexpansion FOR %%a IN (%%) DO set "temp_mm=!temp_mm:5=%%a!" ENDLOCAL&SET "temp_mm=%temp_mm%" echo after:"%temp_mm%" SET temp_ GOTO :EOF You appear to have non-ANSI characters in your post. Personally, I'd use sed since actually using the variable thus-converted may be problematic. The substitute construct targets the nominated string and replaces it with the second string. This is all well and good for most characters, but fails for some specials (like %) because the syntax doesn't distinguish between % being a substitute character (even when escaped by the normal %) and being end-of-replacement-string. The syntax of "temp_mm=%temp_mm:a=%%" and "temp_mm=%temp_mm:a=%%%" is ambiguous - is it replace with "%" or replace with escaped "%" or replace with *nothing*, then add "%", "escaped-%" or "%%"? By using the setlocal/endlocal bracket, you can use two-stage replacement, the first stage sets the replacement string to % as that is the content of %%a, but the initial parsing has then been completed, so % is no longer a special character. The second parsing phase occurs using % as the replacement. Then all you need is to return the modified variable to the original context.
{ "pile_set_name": "StackExchange" }
Q: Method to remove nodes I have a *, and I'm trying to get my remove method to removes and returns a specific targeted items. I tried a lot of different way trying to make it work, but it keeps giving me the NPE. Here is my first remove(): Here is my second remove() that was able to make the code compile: Here is my LinearNode: Student class: A: To remove should be fairly straightforward and you already have the general idea: public Student remove(Student items) { LinearNode previous = null, current = head; // iterate over all the nodes starting at the head, maintaining a reference to the previous node as you go while (current != null && current.items.compareTo(items) != 0) { previous = current; current = current.next; } // At this point you have either a) found the Node with matching items or b) not found it if (current == null) { // not found in the list return null; } // At this point you know where the Node is, and you have a reference previous node as well // so it's easy to reattach the linked list to remove the node if (previous == null) { // The head node was the match if previous is not set, so make sure to update the head Node accordingly head = current.next; } else { previous.next = current.next } return current.items; }
{ "pile_set_name": "StackExchange" }
Q: Bootstrap 3 - set height of modal window according to screen size I am trying to create a kind of responsive megamenu using Bootstrap 3 modal dialog. I would like to set the width and height of the whole modal window to 80% of the viewport, while setting the modal-body to a max-height in order not to populate the whole screen on large viewports. My HTML: <div class="modal fade"> <div class="modal-dialog modal-megamenu"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button> <h4 class="modal-title">Modal Mega Menu Test</h4> </div> <div class="modal-body"> <div class="row"> <div class="col-md-3"></div> <div class="col-md-3"></div> <div class="col-md-3"></div> <div class="col-md-3"></div> </div> </div> </div> <div class="modal-footer"> <button type="button" data-dismiss="modal" class="btn btn-primary">close</button> </div> </div> </div> My CSS: .modal-megamenu { width:80%; height:80%; } .modal-body { max-height:500px; overflow:auto; } This works as intended for the width, but the "height" parameter doesn't give any result. Like that, the height of the modal window is always set to the max-height value. Does anybody have an idea of how to set the height dynamically according to the viewport height? A: Pure CSS solution, using calc .modal-body { max-height: calc(100vh - 200px); overflow-y: auto; } 200px may be adjusted in accordance to height of header & footer A: Similar to Bass, I had to also set the overflow-y. That could actually be done in the CSS $('#myModal').on('show.bs.modal', function () { $('.modal .modal-body').css('overflow-y', 'auto'); $('.modal .modal-body').css('max-height', $(window).height() * 0.7); }); A: Try: $('#myModal').on('show.bs.modal', function () { $('.modal-content').css('height',$( window ).height()*0.8); });
{ "pile_set_name": "StackExchange" }
Q: Complex numbers, how cand I show that $|z_1|=|z_2|=|z_3|$? Show that if $z_1,z_2,z_3$ are complex numbers, $z_1+z_2+z_3=0$ and $z_1^2+z_2^2+z_3^2=0$ then: $|z_1|=|z_2|=|z_3|$ A: $$z_3=-z_1-z_2\\ z_3^2=z_1^2+2z_1z_2+z_2^2$$ Since $z_3^2=-z_1^2-z_2^2$ you get $$z_1^2+z_1z_2+z_2^2=0$$ Multiplying by $z_1-z_2$ you get $$z_1^3=z_2^3$$ Applying absolute values you get $$|z_1|^3=|z_2|^3$$ and hence $$|z_1|=|z_2|$$ The equality $|z_1|=|z_3|$ can be obtained same way. A: $$z_1 z_2 + z_2 z_3 + z_3 z_1 = \big((z_1 + z_2 + z_3)^2 - (z_1^2 + z_2^2 + z_3^2)\big)/2 = 0.$$ So $(z-z_1)(z-z_2)(z-z_3)=z^3-z_1 z_2 z_3$ for any $z$, and $z_1^3=z_2^3=z_3^3(=z_1 z_2 z_3)$. A: Let $f=(t-z_1)(t-z_2)(t-z_3)$. Then $f$ is a cubic polynomial in $t$, with roots $z_1,z_2,z_3$. In expanded form, $f$ can be expressed as $$f=t^3-at^2+bt-c$$ where \begin{align*} a&=z_1+z_2+z_3\\[4pt] b&=z_1z_2+z_2z_3+z_3z_1\\[4pt] c&=z_1z_2z_3\\[4pt] \end{align*} From $z_1+z_2+z_3=0$, we get $a=0$, and since we also have $z_1^2+z_2^2+z_3^2=0$, the identity $$(z_1+z_2+z_3)^2=z_1^2+z_2^2+z_3^2+2(z_1z_2+z_2z_3+z_3z_1)$$ yields $b=0$. Thus, $f=t^3-c$, hence, since $$f(z_1)=f(z_2)=f(z_3)=0$$ we get $$z_1^3=z_2^3=z_3^3=c$$ so $|z_1|^3=|z_2|^3=|z_3|^3$, which yields $|z_1|=|z_2|=|z_3|$.
{ "pile_set_name": "StackExchange" }
Q: .xml views alignment I have a problem and I really don't know now how to deal with it.This is my .xml file: <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/ScrollView01" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_gravity="top" android:fillViewport="true" android:overScrollMode="always" android:scrollbarAlwaysDrawVerticalTrack="false" > <RelativeLayout xmlns:tools="http://schemas.android.com/tools" android:id="@+id/rlActivityDetails" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#000000" android:overScrollMode="always" > <ImageButton android:id="@+id/ibStartTrip" android:layout_width="95dp" android:layout_height="80dp" android:layout_marginLeft="16dp" android:layout_marginTop="10dp" android:src="@drawable/car" /> <TextView android:id="@+id/tvStartTrip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/ibStartTrip" android:layout_marginLeft="35dp" android:textColor="#FFFFFF" /> <ImageButton android:id="@+id/ibStartActivity" android:layout_width="95dp" android:layout_height="80dp" android:layout_alignTop="@+id/ibStartTrip" android:layout_toRightOf="@+id/ibStartTrip" android:src="@drawable/tools" /> <TextView android:id="@+id/tvStartActivity" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/ibStartActivity" android:layout_centerHorizontal="true" android:textColor="#FFFFFF" /> <ImageButton android:id="@+id/ibEndActivity" android:layout_width="95dp" android:layout_height="80dp" android:layout_alignTop="@+id/ibStartActivity" android:layout_toRightOf="@+id/ibStartActivity" android:src="@drawable/finish" /> <TextView android:id="@+id/tvEndActivity" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/ibEndActivity" android:layout_below="@+id/ibEndActivity" android:layout_marginRight="16dp" android:textColor="#FFFFFF" /> <TableLayout android:id="@+id/tableLayoutInfo" android:padding="10dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:layout_below="@+id/tvStartActivity" android:layout_centerHorizontal="true" > <TableRow android:id="@+id/tableRow1" android:layout_marginTop="5dp" android:layout_width="fill_parent" android:layout_height="wrap_content" > <ImageView android:id="@+id/imageView1" android:layout_width="24dp" android:layout_height="24dp" android:layout_column="0" android:src="@drawable/number" /> <TextView android:id="@+id/tvActivityIdValue" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="1" android:layout_weight="1" android:layout_marginLeft="10dp" android:text="aaaaaaaaaaaaaaaa" android:textColor="#FFFFFF" android:textSize="16dp" /> </TableRow> <TableRow android:id="@+id/tableRow5" android:layout_marginTop="5dp" android:layout_width="wrap_content" android:layout_height="wrap_content" > <ImageView android:id="@+id/imageView2" android:layout_width="24dp" android:layout_height="24dp" android:layout_column="0" android:src="@drawable/activity_type" /> <TextView android:id="@+id/tvActivityTypeValue" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_column="1" android:layout_weight="1" android:text="aaaaaaaaaaaaaaaa" android:textColor="#FFFFFF" android:textSize="16dp" /> </TableRow> <TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content" android:layout_height="wrap_content" > <ImageView android:id="@+id/imageView3" android:layout_width="24dp" android:layout_height="24dp" android:layout_column="0" android:src="@drawable/site" /> <TextView android:id="@+id/tvSiteNameValue" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="1" android:layout_weight="1" android:layout_marginLeft="10dp" android:textColor="#FFFFFF" android:text="aaaaaaaaaaaaaa" android:textSize="16dp" /> </TableRow> <TableRow android:id="@+id/tableRow3" android:layout_marginTop="5dp" android:layout_width="wrap_content" android:layout_height="wrap_content" > <ImageView android:id="@+id/imageView4" android:layout_width="24dp" android:layout_height="24dp" android:layout_column="0" android:src="@drawable/brand" /> <TextView android:id="@+id/tvBrandValue" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="1" android:layout_marginLeft="10dp" android:gravity="fill_horizontal" android:text="aaaaaaaaaaaaaaaaaa" android:layout_weight="1" android:textColor="#FFFFFF" android:textSize="16dp" /> </TableRow> <TableRow android:id="@+id/tableRow4" android:layout_marginTop="5dp" android:layout_width="wrap_content" android:layout_height="wrap_content" > <ImageView android:id="@+id/imageView5" android:layout_width="24dp" android:layout_height="24dp" android:layout_column="0" android:src="@drawable/subject" /> <TextView android:id="@+id/tvSubjectValue" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:layout_column="1" android:textColor="#FFFFFF" android:layout_marginLeft="10dp" android:text="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" android:textSize="16dp" /> </TableRow> <TableRow android:id="@+id/tableRow5" android:layout_width="wrap_content" android:layout_height="wrap_content" > <ImageView android:id="@+id/imageView6" android:layout_width="24dp" android:layout_height="24dp" android:layout_column="0" android:src="@drawable/text" /> <TextView android:id="@+id/tvTextValue" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="1" android:layout_marginLeft="10dp" android:text="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasssssssssssssssssss" android:textColor="#FFFFFF" android:layout_weight="1" android:textSize="16dp" android:width="0dip" /> </TableRow> </TableLayout> <TableLayout android:id="@+id/tableLayoutAssets" android:padding="10dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/tableLayoutInfo" android:layout_centerHorizontal="true" > <TableRow android:id="@+id/tableRow6" android:layout_width="wrap_content" android:layout_height="wrap_content" > </TableRow> </TableLayout> <HorizontalScrollView android:id="@+id/horizontalScrollImageView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_below="@+id/tableLayoutAssets" android:layout_marginTop="10dp"> <LinearLayout android:id="@+id/myGallery" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" > </LinearLayout> </HorizontalScrollView> <ProgressBar android:id="@+id/progressBarAttachment" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_centerHorizontal="true" android:layout_below="@+id/tableLayoutAssets" android:visibility="gone" /> <ImageButton android:id="@+id/ibAddImage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/horizontalScrollImageView" android:src="@drawable/add_button" android:layout_marginBottom="50dp"/> </RelativeLayout> </ScrollView> As you can see I have 3 image buttons.Under them a table layout with 6 rows.After that another table layout which is populated dynamically and under that a horizontal scroll view which is populated dynamically with pictures,and an image button for adding new pictures. Now,my problem is that every time i open the activity,after the pictures are loaded in the horizontal scroll view, the last row from my first table layout is disappearing(is not disappearing completely but its width is getting very small and it only fits one letter per row). I think that after the pictures are loaded the entire layout is redrawing itself and the first table doesn't maintain his properties(the "weight" property also does't apply anymore after the pictures are loaded).I could really use some help. Any suggestions will be appreciated. Thx. A: There is no need for the android:width attribute on the last TextView. Remove it and the TextViews should behave.
{ "pile_set_name": "StackExchange" }
Q: I installed an app from an untrusted source? What to do now? As an Ubuntu/Linux newbie, I am not exactly accustomed with security. I tried to install Gimpshop from this URL: http://www.ubuntugeek.com/images/gimpshop_2.2.11-1_i386.deb It was processed by Ubuntu Software Center, but before the end, it disappeared from Ubuntu Software Center and also from my Download folder. I'm afraid I allowed a virus or something dangerous onto my computer... What can I do now? Is there a security software I could run to get rid of this? How to know if the package was harmful or not? Thank you very much in advance. A: Gimpshop is just a little bit modified version of Gimp for Windows and Mac. On Ubuntu, please just use the plain Gimp which is packaged fine in the main repositories and available straight form the Software Centre. The package you downloaded appears to be a very blunt single package of Gimp 2.2 (really old!), built in 2006 (!) with all its dependencies in it. The README files reads The GNU Image Manipulation Program Version 2.2 This is version 2.2 of The GIMP. It looks harmless by looking at the content. It has no install script hooks (preinst, postinst, etc.) in place. This means it's just a simple unpacking of files. The above makes it very clear: it's not responsible for removing the package from your download folder. The binaries themselves are hard to check. If you haven't run the program then you don't have to worry about it. The quality of the package is really poor and it appears to be built by a very simple "checkinstall" script. This may explain why Software Centre wasn't able to handle it properly. So, just remove it completely using your package management: sudo apt-get remove --purge gimpshop
{ "pile_set_name": "StackExchange" }
Q: How can a GpioCallback register "false" twice in a row? I have a very simple setup android-things setup where a GPIO (output) generates very short (10u) pulse, and I'm trying to read that pulse through another GPIO (input). However, my logs are weirding me out: how could I get two "false" readings in a row? If I have a light switch, I can't turn it off twice in a row... I need to turn it on in between, right? Can the GpioCallback drop events? Is my time too short? Can there be a soft ramp between voltages that doesn't ever count as an "edge"? val gpioIn = PeripheralManagerService().openGpio(gpioPinName) gpioIn.setEdgeTriggerType(Gpio.EDGE_NONE) // reset for Android Things bug gpioIn.setDirection(Gpio.DIRECTION_IN) gpioIn.setActiveType(Gpio.ACTIVE_HIGH) gpioIn.setEdgeTriggerType(Gpio.EDGE_BOTH) // I should get all changes, right? gpioIn.registerGpioCallback(object : GpioCallback() { override fun onGpioEdge(gpio: Gpio?): Boolean { netLog((gpio?.value ?: "null").toString()) return true } override fun onGpioError(gpio: Gpio?, error: Int) { netLog("GPIO $gpio Error event $error") } }) results in 06-02 06:33:37.052 I/NetGpioListener: NET GPIO LISTENER: 118730013 true 06-02 06:33:37.091 I/NetGpioListener: NET GPIO LISTENER: 118769152 false 06-02 06:33:37.094 I/NetGpioListener: NET GPIO LISTENER: 118772102 false A: Yes, this is fairly common with noisy input signals like pushbuttons, relay contacts, and "wiggly wires". The signal bounce that occurs during contact closure can happen very rapidly such that not every edge trigger event is captured by the input registers. This is true of all GPIO systems (not just Android Things), and one reason why signal debounce is such a common practice. The debounce code in the button driver was actually written to handle cases like this to ensure they didn't generate false events.
{ "pile_set_name": "StackExchange" }
Q: What new content does City of Heroes: Going Rogue have for existing toons? Can anyone run through what changes this expansion makes to the game? I have a number of existing characters and I am unable to find any information about how the new content works for existing characters. I'm currently unsubscribed, but I'm tempted to buy a month to have a run around again. I've had a poke about in various wiki's and not managed to turn up anything. So does anyone know what changes have been made or how they work with the existing characters? A: Going Rogue adds a new zone (Praetoria), which was initially only accessible to new characters created there. As of the current issue, it is now possible for existing characters to travel to the new area. As for effects for existing characters, provided that you have the expansion all existing characters will gain access to the alignment system which allows characters to change alignments ranging between hero, vigilante, rogue, and villain by completing missions with an associated moral choice (tip missions / morality missions). If you have the expansion, you automatically gain access to the new powersets, but be aware that much of the content added is in the new zone, so you will either need to start a character there, or move a character there. Praetoria currently (issue 19) has only content in the lower levels (up to about 20) after which point you move to Paragon City or the Rogue Isles. Finally, to access the new post-50 content (the Incarnate system, which includes additional buffs, and level shifts) you must have going rogue. This applies to both new characters and existing characters.
{ "pile_set_name": "StackExchange" }
Q: How to show that this limit $\lim_{n\rightarrow\infty}\sum_{k=1}^n(\frac{1}{k}-\frac{1}{2^k})$ is divergent? How to show that this limit $\lim_{n\rightarrow\infty}\sum_{k=1}^n(\frac{1}{k}-\frac{1}{2^k})$ is divergent? I applied integral test and found the series is divergent. I wonder if there exist easier solutions. A: We can estimate. Note that $2^k \ge 2k$, and therefore $$\frac{1}{k}-\frac{1}{2^k} \ge \frac{1}{k}-\frac{1}{2k}=\frac{1}{2k}.$$ It is a familiar fact that $\sum \frac{1}{2k}$ diverges. Thus by Comparison so does our series.
{ "pile_set_name": "StackExchange" }
Q: How do I trap OCUnit test pass/failure messages/events I'm trying to use xcodebuild and OCUnit with my Continuous Integration server (TeamCity). JetBrains offers test observer implementations for boost::test and CppUnit that format test output in a way that TeamCity can interpret. I need to do something similar for OCUnit if I want to use it. There appears to be a SenTestObserver class in OCUnit but I'm ignorant of how exactly it should be used, and the OCUnit homepage doesn't seem to provide any documentation on the matter. A: You can write your own observer by extending the SenTestObserver class and implementing the notification listeners (void) testSuiteDidStart:(NSNotification *) aNotification (void) testSuiteDidStop:(NSNotification *) aNotification (void) testCaseDidStart:(NSNotification *) aNotification (void) testCaseDidStop:(NSNotification *) aNotification (void) testCaseDidFail:(NSNotification *) aNotification then add an entry to the info.plist SenTestObserverClass with the name of your class. At least in the version of OCUnit i'm familiar with SenTestObserver is equal parts useful/equal parts broken. I just skip it altogether and register for the notifications myself in my own class. (see SenTestSuiteRun.h and SenTestCaseRun.h for the defines of the notification names). You can use the test and run properties of the notification to access the SenTestSuite and SenTestSuiteRun instances, and the run instance contains the info needed on the actual results.
{ "pile_set_name": "StackExchange" }
Q: Removing unneeded zeroes How to delete zeroes in java (android) only if there is no non-zero value following them? The value is stored in double and then later in string, so working on these variables would be best. Example: I have 12.50000 I want to have 12.5 Example2: I have 65.4030 I want to have 65.403 A: Try this : String s = 12.50000; s = s.indexOf(".") < 0 ? s : s.replaceAll("0*$", "").replaceAll("\\.$", "");
{ "pile_set_name": "StackExchange" }
Q: References to intimacy between God and the Jewish people There's a Baal HaTurim on Exodus 19:4: ואביא אתכם אלי מה אשה נקנית בכסף ובשטר ובביאה אף ישראל כן. ... בביאה זהו שנא' ואפרוש כנפי עליך וגו' ואבא בברית אתך לכן אמר הושע ג''פ וארשתיך לי: ואביא בגימ' בביאה I found this quite surprising, as while there are many references to God and Israel being married, I don't recall seeing intimacy referenced before. That's in line with how Chazal generally avoid ascribing such intensely physical things to God, even as an anthropomorphism (e.g. God smells our offerings, but does not taste them). The Artscroll Baal HaTurim does not say this is based on any prior source. Is there any place in which intimacy with the Jewish People is described in Tanach or Chazal? A: WARNING: THIS ANSWER CAN NOT BE UNREAD. IF YOU THINK HOW YOU RELATE TO A POPULAR TEFILLAH AND SONG WILL NEVER RECOVER FROM BEING ANALYZED IN THIS CONTEXT -- SKIP READING THIS!!!! Aside from Shir haShirim (see R' Al Berko's answer), there is another example in Tanakh that would more famous -- if people paid more attention to what they're saying in tefillah. Yeshaiah 62:5 is explicit: כִּֽי־יִבְעַ֤ל בָּחוּר֙ בְּתוּלָ֔ה, יִבְעָל֖וּךְ בָּנָ֑יִךְ; וּמְשׂ֤וֹשׂ חָתָן֙ עַל־כַּלָּ֔ה, יָשִׂ֥ישׂ עָלַ֖יִךְ אֱלֹקיִךְ׃ For as a young man consummates his marriage with a maiden, so shall You consummate your marriage with us; and as a groom rejoices on his bride, so shall your G-d Rejoice upon you. The "על" in the second half of the verse could have been taken to mean "about", figuratively "over" -- meaning "as a groom rejoices about his bride". But is pretty clear from the context of the first clause talking about בעילה (marital intimacy) that the clause means "on", literally. From which Rav Shelomo haLevi al-Qabetz (16th cent Tzefat) paraphrases in Lekha Dodi: יָשיש עָלַיִךְ אֱלקיִךְ. כִּמְשוש חָתָן עַל כַּלָּה. Your G-d should rejoice on you the way a groom rejoices on a bride. Most siddurim translate it "rejoice over", with a figurative connotation. Ignoring the scriptural source, or perhaps aware that siddurim have younger readers. But given that the author of the poem was one of the leading Qabbalists of Tzefas, erotic imagery is far more likely. And in any case, R Shlomo al-Qabetz's familiarity with the pasuq in Yeshaiah is a given. However, the songwriters who put melodies to this line of Lekha Dodi couldn't possibly be aware of the original in Yeshaiah. Because as a song to sing at weddings, these words are incredibly inappropriate.
{ "pile_set_name": "StackExchange" }
Q: Ruby specific thread semantics I just ran across an issue that probably exposes my ignorance of common threading semantics. I assumed that the following ruby was valid: d = Thread.new{ Thread.stop } d.join That is, I thought that joining a stopped thread would simply be a NOP - the thread is already finished, so join should return immediately. Instead, Ruby-1.8.6 (irb) on Mac returns the following: deadlock 0x569f14: sleep:- - (irb):1 deadlock 0x35700: sleep:J(0x569f14) (main) - (irb):2 fatal: Thread(0x35700): deadlock from (irb):2:in `join' from (irb):2 Can anyone briefly explain why this is so? Is this just an implementation issue or a higher-level semantic that has gone over my head? A: Your code creates a new Thread object with the corresponding block but never runs it, so when you do the join, you're waiting for a thread to complete that is never started. Start the thread before you do the join and it should be fine: d = Thread.new{ Thread.stop } d.run d.join
{ "pile_set_name": "StackExchange" }
Q: MimeMessageParser unable to fetch from address We have been stuck with this issue for quite some time now.In our project we are trying to parse an email that is written on to a file and get the data into the pojo. It works for most cases but when the email id is too long the mail id goes to the next line due to which the from address is not fetched instead the name is fetched.We are using commons-email-1.4. The input file containing the emailmessage has case1: From: "def, abc [CCC-OT]" <[email protected]> //here it fetches the mail id properly In the case of longer mail id the file has case2: From: "defxacdhf, abc [CCC-OT]" <[email protected]>// here the mail id jumps to the next line so the from address fetched contains the name Here is the sample code ByteArrayInputStream byteArrayStream = new ByteArrayInputStream(FileUtils.getStreamAsByteArray(buffInStream, lengthOfFile)); // MimeMessage message = new MimeMessage(mailSession, byteArrayStream); MimeMessageParser mimeParser = new MimeMessageParser(MimeMessageUtils.createMimeMessage(mailSession, byteArrayStream)); MimeMessageParser parsedMessage = mimeParser.parse(); when we try to get the from address emailData.setFromAddress(parsedMessage.getFrom()); In case1 it returns [email protected] and case2 it returns "defxacdhf, abc [CCC-OT]". Any help here is appreciated. EDIT the script files reads and write like below. while read line do echo "$line" >> /directory/$FILE_NAME done A: I don't understand why you're using a shell while loop to read the data instead of just using cat or something like that, but the problem is in your use of "read". By default, read splits the input line into fields, separated by the field separators specified by the shell IFS environment variable. Leading field separators are ignored, so when you read a line that starts with white space, the white space is ignored. Change your loop to: while IFS= read -r line do echo "$line" >> /directory/$FILE_NAME done That sets IFS to the empty string before each read, and specifies a "raw" read so that backslash characters aren't special. But unless you're doing something else in that read loop, it would be much simpler to do just cat > /directory/$FILE_NAME
{ "pile_set_name": "StackExchange" }
Q: How did Skynet know about Kyle Reese? In Terminator Salvation, Skynet casts Kyle Reese and John Connor as its two most wanted humans. How did it know about Kyle Reese's existence? John Connor's story as something of a messiah appears to be well known. But is the fact that he was fathered by a time-travelling soldier from the resistance public knowledge? He is shown keeping his mother's tapes something of a secret. (I haven't watched Terminator 3: Rise of the Machines.) A: This exact question is covered on SE SciFi & Fantasy quite extensively, but I don't think it was ever resolved. There is a lot of speculation about this, but some just think that paradoxes ensue where time travel is used. In another post on SF&F, they talk about an episode on T:TSCC where they show Kyle Reese being captured and at the Skynet facility. Here he is interrogated. They make mention of why he was there, primarily to force John Connor to attempt a rescue, but not to kill him. There is plenty of speculation, but nothing hard and fast as to why or how Skynet knows about Kyle and why they are after him. As for T3, it was the only showing (TV or movie) which did not feature Kyle Reese in some way (he was in out takes in T2), so it would not be of much help.
{ "pile_set_name": "StackExchange" }
Q: getting error:-Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/hadoop/io/Writable I am trying to connect to hive from java but getting error. I searched in google but not got any helpfull solution. I have added all jars also. The code is:- package mypackage; import java.sql.SQLException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.sql.DriverManager; public class HiveJdbcClient { private static String driver = "org.apache.hadoop.hive.jdbc.HiveDriver"; public static void main(String[] args) throws SQLException, ClassNotFoundException { Class.forName("org.apache.hadoop.hive.jdbc.HiveDriver"); try { Class.forName(driver); } catch (ClassNotFoundException e) { e.printStackTrace(); System.exit(1); } Connection connect = DriverManager.getConnection("jdbc:hive://master:10000 /default", "", ""); Statement state = connect.createStatement(); String tableName = "mytable"; state.executeQuery("drop table " + tableName); ResultSet res=state.executeQuery("ADD JAR /home/hadoop_home/hive/lib /hive-serdes-1.0-SNAPSHOT.jar"); res = state.executeQuery("create table tweets (id BIGINT,created_at STRING,source STRING,favorited BOOLEAN,retweet_count INT,retweeted_status STRUCT<text:STRING,user:STRUCT<screen_name:STRING,name:STRING>>,entities STRUCT<urls:ARRAY<STRUCT<expanded_url:STRING>>,user_mentions:ARRAY<STRUCT<screen_name:STRING,name:STRING>>,hashtags:ARRAY<STRUCT<text:STRING>>>,text STRING,user STRUCT<screen_name:STRING,name:STRING,friends_count:INT,followers_count:INT,statuses_count:INT,verified:BOOLEAN,utc_offset:INT,time_zone:STRING>,in_reply_to_screen_name STRING) ROW FORMAT SERDE 'com.cloudera.hive.serde.JSONSerDe' LOCATION '/user/flume/tweets'"); String show = "show tables"; System.out.println("Running show"); res = state.executeQuery(show); if (res.next()) { System.out.println(res.getString(1)); } String describe = "describe " + tableName; System.out.println("Running describe"); res = state.executeQuery(describe); while (res.next()) { System.out.println(res.getString(1) + "\t" + res.getString(2)); } } } I am getting these errors:- run: SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found binding in [jar:file:/home/hadoop/hive/lib/slf4j-log4j12-1.6.1.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: Found binding in [jar:file:/home/hadoop/lib/slf4j-log4j12-1.4.3.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: Found binding in [jar:file:/home/GlassFish_Server/glassfish/modules/weld-osgi-bundle.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation. Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/hadoop/io/Writable at org.apache.hadoop.hive.jdbc.HiveStatement.executeQuery(HiveStatement.java:198) at org.apache.hadoop.hive.jdbc.HiveStatement.execute(HiveStatement.java:132) at org.apache.hadoop.hive.jdbc.HiveConnection.configureConnection(HiveConnection.java:133) at org.apache.hadoop.hive.jdbc.HiveConnection.(HiveConnection.java:122) at org.apache.hadoop.hive.jdbc.HiveDriver.connect(HiveDriver.java:106) at java.sql.DriverManager.getConnection(DriverManager.java:571) at java.sql.DriverManager.getConnection(DriverManager.java:215) at dp.HiveJdbcClient.main(HiveJdbcClient.java:35) Caused by: java.lang.ClassNotFoundException: org.apache.hadoop.io.Writable at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) ... 8 more Java Result: 1 A: I got the answer. One jar file was missing now it is solved. This file was missing. hadoop-common-2.1.0-beta.jar
{ "pile_set_name": "StackExchange" }
Q: Count number of unique levels of a variable I am trying to get a simple way to count the number of distinct categories in a column of a dataframe. For example, in the iris data frame, there are 150 rows with one of the columns being species, of which there are 3 different species. I want to be able to run this bit of code and determine that there are 3 different species in that column. I do not care how many rows each of those unique entries correspond to, just how many distinct variables there are, which is mostly what I found in my research. I was thinking something like this: df <- iris choices <- count(unique(iris$Species)) Does a solution as simple as this exist? I have looked at these posts, but they either examine the entire data frame rather than a single column in that data frame or provide a more complicated solution than what I am hoping for. count number of instances in data frame Count number of occurrences of categorical variables in data frame (R) How to count number of unique character vectors within a subset of data A: The following should do the job: choices <- length(unique(iris$Species)) A: If we are using dplyr, n_distinct would get the number of unique elements in each column library(dplyr) iris %>% summarise_each(funs(n_distinct)) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species #1 35 23 43 22 3
{ "pile_set_name": "StackExchange" }
Q: What happens to a non-matching regex in a Perl subroutine call? I'm trying to make sense of what's happening with a non-matching regex in a subroutine call. Consider this script: sub routine{ print Dumper(\@_); } my $s = 'abc123'; # These pass a single element to &routine &routine( $s =~ /c/ ); # 1. passes (1) &routine(2 == 3); # 2. passes ('') &routine(3 == 3); # 3. passes (1) # The following two calls appear to be identical &routine( $s =~ /foobar/ ); # 4. passes () &routine(); # 5. passes () In the above script, numbers 1, 2 and 3 all pass a single value to &routine. I'm surprised that number 4 doesn't pass a false value, but rather passes nothing at all! It doesn't seem possible that the non-matching regex evaluates to nothing at all, since the same sort of signature in a conditional isn't valid: # This is fine if( $s =~ /foobar/ ){ print "it's true!\n"; } # This is a syntax error if( ){ print "Hmm...\n"; # :/ } What happens to the non-matching regex when it's used in a subroutine call? Further, is it possible for &routine to figure out whether or not it's been called with a non-matching regex, vs nothing at all? A: When the match operator =~ is used in list context it returns a list of matches. When there are no matches this list is empty (also called the empty list), and the empty list is passed to your sub routine which in turn causes @_ to be empty. If you explicitly want to pass the false value of "Did this expression return any matches?" you need to perform your match in scalar context. You can do this by using the scalar keyword &routine( scalar $s =~ /foobar/ ); which will pass the value ''(false) to your routine sub. Calling a sub without any arguments effectively passes this empty list, so your final example would be correctly written: if ( () ) { print "Hmm...\n"; } which is not a syntax error because in Perl 0, '', and () all represent false.
{ "pile_set_name": "StackExchange" }