id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
8,465,508
Can not connect to local PostgreSQL
<p>I've managed to bork my local development environment.</p> <p>All my local Rails apps are now giving the error:</p> <pre><code>PGError could not connect to server: Permission denied Is the server running locally and accepting connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"? </code></pre> <p>I've no idea what's caused this. </p> <p>While searching for a solution I've updated all bundled gems, updated system gems, updated MacPorts. No joy.</p> <p>Others have reported this issue when upgrading from OSX Leopard to Lion, due to confusion over which version of Postgres should be used (i.e., OSX version or MacPorts version). I've been running Lion for several months, so it seems strange that this should happen now.</p> <p>I'm reluctant to mess around too much without first understanding what the problem is. How can I debug this methodically? </p> <p>How can I determine how many versions of PostgreSQL are on my system, which one is being accessed, and where it is located? How do I fix this if the wrong PostgreSQL is being used?</p> <p>Sorry for the noob questions. I'm still learning how this works! Thanks for any pointers.</p> <p>EDIT </p> <p>Some updates based on suggestions and comments below.</p> <p>I tried to run <code>pg_lsclusters</code> which returned a <code>command not found</code> error. </p> <p>I then tried to local my pg_hba.conf file and found these three sample files:</p> <pre><code>/opt/local/share/postgresql84/pg_hba.conf.sample /opt/local/var/macports/software/postgresql84/8.4.7_0/opt/local/share/postgresql84/pg_hba.conf.sample /usr/share/postgresql/pg_hba.conf.sample </code></pre> <p>So I assume 3 versions of PSQL are installed? Macports, OSX default and ???. </p> <p>I then did a search for the launchctl startup script <code>ps -ef | grep postgres</code> which returned</p> <pre><code>0 56 1 0 11:41AM ?? 0:00.02 /opt/local/bin/daemondo --label=postgresql84-server --start-cmd /opt/local/etc/LaunchDaemons/org.macports.postgresql84-server/postgresql84-server.wrapper start ; --stop-cmd /opt/local/etc/LaunchDaemons/org.macports.postgresql84-server/postgresql84-server.wrapper stop ; --restart-cmd /opt/local/etc/LaunchDaemons/org.macports.postgresql84-server/postgresql84-server.wrapper restart ; --pid=none 500 372 1 0 11:42AM ?? 0:00.17 /opt/local/lib/postgresql84/bin/postgres -D /opt/local/var/db/postgresql84/defaultdb 500 766 372 0 11:43AM ?? 0:00.37 postgres: writer process 500 767 372 0 11:43AM ?? 0:00.24 postgres: wal writer process 500 768 372 0 11:43AM ?? 0:00.16 postgres: autovacuum launcher process 500 769 372 0 11:43AM ?? 0:00.08 postgres: stats collector process 501 4497 1016 0 12:36PM ttys000 0:00.00 grep postgres </code></pre> <p>I've posted the contents of postgresql84-server.wrapper at <a href="http://pastebin.com/Gj5TpP62" rel="noreferrer">http://pastebin.com/Gj5TpP62</a>.</p> <p>I tried to run <code>port load postgresql184-server</code> but received an error <code>Error: Port postgresql184-server not found</code>.</p> <p>I'm still very confused how to fix this, and appreciate any "for dummies" pointers.</p> <p>Thanks!</p> <p>EDIT2 </p> <p>This issue began after I had some problems with daemondo. My local Rails apps were crashing with an application error along the lines of "daemondo gem can not be found". I then went through a series of bundle updates, gem updates, port updates and brew updates to try and find the issue.</p> <p>Could this error be an issue with daemondo? </p>
8,481,156
21
7
null
2011-12-11 16:25:06.91 UTC
40
2017-05-07 20:45:43.787 UTC
2011-12-12 08:28:38.76 UTC
null
716,294
null
716,294
null
1
126
ruby-on-rails|macos|postgresql
124,793
<p>This really looks like a file permissions error. Unix domain sockets are files and have user permissions just like any other. It looks as though the OSX user attempting to access the database does not have file permissions to access the socket file. To confirm this I've done some tests on Ubuntu and psql to try to generate the same error (included below).</p> <p>You need to check the permissions on the socket file and its directories <code>/var</code> and <code>/var/pgsql_socket</code>. Your Rails app (OSX user) must have execute (x) permissions on these directories (preferably grant everyone permissions) and the socket should have full permissions (wrx). You can use <code>ls -lAd &lt;file&gt;</code> to check these, and if any of them are a symlink you need to check the file or dir the link points to. </p> <p>You can change the permissions on the dir for youself, but the socket is configured by postgres in <code>postgresql.conf</code>. This can be found in the same directory as <code>pg_hba.conf</code> (You'll have to figure out which one). Once you've set the permissions you will need to restart postgresql.</p> <pre><code># postgresql.conf should contain... unix_socket_directory = '/var/run/postgresql' # dont worry if yours is different #unix_socket_group = '' # default is fine here #unix_socket_permissions = 0777 # check this one and uncomment if necessary. </code></pre> <hr> <p><strong>EDIT:</strong></p> <p>I've done a quick search on google which you may wish to look into to see if it is relavent. This might well result in any attempt to <code>find</code> your config file failing.</p> <p><a href="http://www.postgresqlformac.com/server/howto_edit_postgresql_confi.html">http://www.postgresqlformac.com/server/howto_edit_postgresql_confi.html</a></p> <hr> <p><strong>Error messages:</strong></p> <p>User not found in pg_hba.conf</p> <pre><code>psql: FATAL: no pg_hba.conf entry for host "[local]", user "couling", database "main", SSL off </code></pre> <p>User failed password auth:</p> <pre><code>psql: FATAL: password authentication failed for user "couling" </code></pre> <p>Missing unix socket file:</p> <pre><code>psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? </code></pre> <p>Unix socket exists, but server not listening to it.</p> <pre><code>psql: could not connect to server: Connection refused Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? </code></pre> <p><strong>Bad file permissions on unix socket file</strong>:</p> <pre><code>psql: could not connect to server: Permission denied Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? </code></pre>
8,778,666
Should I use Maven for an Android App?
<p>I code mostly in Java and use Maven for all of my projects. I do really love using Maven since it is easy to download the sources and documentations, and, more importantly, I don't need to keep the copy of the external libraries under my project source code folders.</p> <p>I have started to develop an Android application and I found that the Android plugin for eclipse are terribly good. However, all provided examples are not maven projects so I do not know whether, if I use maven, I would still get all the functionalities from the Android plugin or whether there is any drawback from using Maven.</p> <p>So the questions are:</p> <ol> <li>Do all features from Android plugin for eclipse still work?</li> <li>Is it going to be more difficult than using the normal build (I believe it is Ant but not certain)</li> <li>Any other drawbacks, e.g. the file size of the final application (Maven tends to bundle a lot of things together) or the difficulties of getting the latest libraries on maven repository (which is probably differnt for Android).</li> </ol> <p>Please do not point to this <a href="https://stackoverflow.com/questions/4015036/maven-support-for-android-projects">maven support for android projects?</a></p> <p>I would like an answer from experience developers. I already know that it is possible to use maven for an Android app. All I need to know is whether I should use it.</p>
8,778,728
6
9
null
2012-01-08 15:20:58.473 UTC
8
2020-10-23 12:37:31.18 UTC
2017-05-23 12:17:44.467 UTC
null
-1
null
507,546
null
1
46
java|android|maven
21,133
<p>My teams current task is to develop an Android app. Since it is a small app and also some kind of prototype we decided to evaluate Maven and the Android Eclipse plugin.</p> <p>In short: After two developers spent three days, we were not able to gain the Android Eclipse plugin functionalities in our Maven project.</p> <ul> <li>The R class was not updated according to our resources</li> <li>We were not able to start the application directly from within Eclipse in the emulator and/or an attached device</li> </ul> <p>Because of these issues which impeded our development sincerely we decided to develop the app without Maven. But if any of you knows how to fix these issues I would love to hear a solution!</p>
22,395,311
Difference between pure and impure function?
<p>I assumed that pure functions must always have a return type (i.e., must not be <code>void</code>) and must have the same output regardless of the state of the object and that Impure functions change the state of the object or print the state of the object.</p> <p>But the textbook I use states that: </p> <blockquote> <p>An accessor usually contains a return statement, but a method that prints information about an objects state may also be classified as an accessor.</p> </blockquote> <p>I'm confused. Which one is correct?</p> <p><strong>EDIT</strong></p> <p>A bit of clarification,The thing that makes me ask is this question: <img src="https://i.stack.imgur.com/B23YJ.png" alt=""></p> <p>The last question is to "<em>Give the type of function used</em>", and the people who commented there stated that it is an impure function as it is printing.</p> <p>So is this function pure or impure? </p>
40,277,670
5
4
null
2014-03-14 02:56:42.713 UTC
8
2018-04-13 06:42:44.693 UTC
2018-04-13 06:42:44.693 UTC
user8554766
null
null
835,277
null
1
21
java|accessor
39,659
<p>Content taken from <a href="http://javascript.tutorialhorizon.com/2016/04/24/pure-vs-impure-functions/" rel="noreferrer">this link</a></p> <p><strong>Characteristics of Pure Function:</strong></p> <ol> <li><p>The return value of the pure func­tions solely depends on its arguments Hence, if you call the pure func­tions with the same set of argu­ments, you will always get the same return values.</p></li> <li><p>They do not have any side effects like net­work or data­base calls</p></li> <li>They do not mod­ify the argu­ments which are passed to them</li> </ol> <p><strong>Char­ac­ter­isitcs of Impure functions</strong></p> <ol> <li><p>The return value of the impure func­tions does not solely depend on its arguments Hence, if you call the impure func­tions with the same set of argu­ments, you might get the dif­fer­ent return values For exam­ple, Math.random(), Date.now()</p></li> <li><p>They may have any side effects like net­work or data­base calls</p></li> <li><p>They may mod­ify the argu­ments which are passed to them</p></li> </ol> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function impureFunc(value){ return Math.random() * value; } function pureFunc(value){ return value * value; } var impureOutput = []; for(var i = 0; i &lt; 5; i++){ impureOutput.push(impureFunc(5)); } var pureOutput = []; for(var i = 0; i &lt; 5; i++){ pureOutput.push(pureFunc(5)); } console.log("Impure result: " + impureOutput); // result is inconsistent however input is same. console.log("Pure result: " + pureOutput); // result is consistent with same input</code></pre> </div> </div> </p>
10,952,804
onChange event doesn't trigger
<p>I use Internet Explorer 8 and Sharepoint 2007.</p> <p>Briefing: I have a NewForm with various fields from a list. I need, using javascript, from one of the fields, to get the value introduced by the user (in a textBox) and paste it on other field (other textBox) in the same page, using onChange.</p> <p>Problem: I'm a JavaScript newbie, and I can't set the event 'onChange' to trigger my function, or at least to trigger an 'alert("Test") ... or simply I'm doing it wrong and don't know why (more likely)... </p> <p>Let's assume the field I want to work with has as FieldName="IDTeam", type="text" and id="id_TeamField".</p> <pre><code>//My JS below "PlaceHolderMain" _spBodyOnLoadFunctionNames.push("setTxtBoxesValues"); function setTxtBoxesValues() { //snipped getField('text','IDTeam').onChange = function(){alert('Test')}; //"getField('text', 'IDTeam).onChange = function(){myFunction()};" //If I want to call myFunction() when onChange event is triggered } </code></pre> <p>Also, instead of getField, tried this:</p> <pre><code>document.getElementById('id_TeamField').onChange = function(){alert('Test')}; </code></pre> <p>If I want to call myFunction() when onChange event is triggered</p> <p>Any idea of what I'm doing wrong? </p>
10,953,061
4
0
null
2012-06-08 16:38:47.493 UTC
1
2020-01-14 04:36:38.223 UTC
2012-06-08 16:47:00.337 UTC
null
23,199
null
1,444,851
null
1
5
javascript|sharepoint-2007
45,063
<p>onchange is an event so either you put it in the tag like this:</p> <pre><code>&lt;input type="text" id="IDTeam" onchange="(call function here)" /&gt; </code></pre> <p>or you apply addEventListener to that DOM object:</p> <pre><code>document.getElementById("IDTeam").addEventListener("change", function() {//call function here}); </code></pre> <p>in IE6 you may need: (not sure if it works as few people are using ie6 nowadays)</p> <pre><code>document.getElementById("IDTeam").attachEvent("onchange", function() {//call function here} ) </code></pre>
11,065,919
Read text from edit control in MFC and VS2010
<p>I'm writing a simple MFC application with a Dialog window and some buttons. I added also a edit control in order to let user insert a text string.</p> <p>I'd like to read the value which is present in the edit control and to store it in a string but i do not know how to do this.</p> <p>I have no compilation error, but I always read only a "." mark.</p> <p>I added a variable name to the text edit control which is <code>filepath1</code> and this is the code:</p> <pre><code> // CMFC_1Dlg dialog class CMFC_1Dlg : public CDialogEx { // Construction public: CMFC_1Dlg(CWnd* pParent = NULL); // standard constructor // Dialog Data enum { IDD = IDD_MFC_1_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: HICON m_hIcon; // Generated message map functions virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedButton1(); afx_msg void OnBnClickedButton2(); afx_msg void OnEnChangeEdit1(); CString filePath1; } //... void CMFC_1Dlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID &amp; 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } CMFC_1Dlg::CMFC_1Dlg(CWnd* pParent /*=NULL*/) : CDialogEx(CMFC_1Dlg::IDD, pParent) ,filePath1(("..\\Experiments\\Dirs\\")) { m_hIcon = AfxGetApp()-&gt;LoadIcon(IDR_MAINFRAME); } void CMFC_1Dlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT1, filePath1); } // then i try to get the string value with CString txtname=filePath1; _cprintf("Value %s\n", txtname); // but i always read just a "." </code></pre>
11,066,024
3
4
null
2012-06-16 18:16:08.633 UTC
1
2022-08-28 16:22:34.217 UTC
2012-10-10 20:38:06.717 UTC
null
283,240
null
689,154
null
1
5
c++|visual-studio-2010|user-interface|mfc
43,363
<pre><code>_cprintf(&quot;Value %S\n&quot;, txtname.GetString()); </code></pre> <p>Note the capital 'S'</p> <p>or you can cast:</p> <pre><code>_cprintf(&quot;Value %S\n&quot;, (LPCTSTR)txtname); </code></pre> <p>You would be better off using an edit control. To create a <code>CEdit</code> variable, right click on the edit box in VS and select &quot;Add Member Variable&quot;, give the variable a name and click OK.</p> <p>You can then retrieve the text in the edit box like this:</p> <pre><code>CEdit m_EditCtrl; // .... CString filePath1; m_EditCtrl.GetWindowText(filePath1); </code></pre>
11,070,304
Android developing: restrict user to only run and use my application
<p>I'm developing android application for CAR usage and I need that in phone or tablet the driver can only run and use this application: No calling or running other app. Is that possible? If it is not, is there any way to restrict the user for example uninstallaing other apps and disabling the installation system and disabling the calling system?</p> <p>Thanks in Advance,</p>
11,070,510
2
4
null
2012-06-17 09:34:19.11 UTC
9
2017-07-18 09:50:18.907 UTC
null
null
null
null
1,295,141
null
1
6
android|restriction
5,509
<p>I have done a similar app like this, which is in fact an in-cab entertainment system. I have also written a blog post about it, you can check it out here: <a href="http://arnab.ch/blog/2012/01/android-auto-updating-homescreen-application/" rel="noreferrer">http://arnab.ch/blog/2012/01/android-auto-updating-homescreen-application/</a>.</p> <p>This is a complex application and let me list out the relevant items for you:</p> <ol> <li>Your app should be a HomeScreen application (search google for how to create HomeScreen app for Android)</li> <li>It seems clear that you would have some control over the device, so you can ensure that no additional applications are installed.</li> <li>The homescreen can be dynamically enabled/disabled, check out KytePhone app to see what I meant. In short you would need some password to exit your HomeScreen app.</li> <li>If you want to silently uninstall/install any application, then you'd need root access, or you'd have to have a custom Android build where your app will have System privilege (might not be what you're looking for).</li> </ol> <p>I hope I am able to give you some direction, if anything is not clear then let me know.</p>
10,877,407
T-SQL How to create tables dynamically in stored procedures?
<p>Code like this, but it's wrong:</p> <pre><code>CREATE PROC sp_createATable @name VARCHAR(10), @properties VARCHAR(500) AS CREATE TABLE @name ( id CHAR(10) PRIMARY KEY, --...Properties extracted from @properties ); </code></pre> <p>Could you tell me how to deal with it? It really troubles me.</p>
10,877,522
5
0
null
2012-06-04 06:56:05.177 UTC
9
2019-09-09 12:28:58.89 UTC
null
null
null
null
1,136,826
null
1
21
sql|sql-server|tsql
172,067
<p>You are using a table variable i.e. you should declare the table. This is not a temporary table.</p> <p>You create a temp table like so:</p> <pre><code>CREATE TABLE #customer ( Name varchar(32) not null ) </code></pre> <p>You declare a table variable like so:</p> <pre><code>DECLARE @Customer TABLE ( Name varchar(32) not null ) </code></pre> <p>Notice that a temp table is declared using # and a table variable is declared using a @. Go read about the difference between table variables and temp tables. </p> <p><strong>UPDATE:</strong></p> <p>Based on your comment below you are actually trying to create tables in a stored procedure. For this you would need to use dynamic SQL. Basically dynamic SQL allows you to construct a SQL Statement in the form of a string and then execute it. This is the ONLY way you will be able to create a table in a stored procedure. I am going to show you how and then discuss why this is not generally a good idea.</p> <p>Now for a simple example (I have not tested this code but it should give you a good indication of how to do it):</p> <pre><code>CREATE PROCEDURE sproc_BuildTable @TableName NVARCHAR(128) ,@Column1Name NVARCHAR(32) ,@Column1DataType NVARCHAR(32) ,@Column1Nullable NVARCHAR(32) AS DECLARE @SQLString NVARCHAR(MAX) SET @SQString = 'CREATE TABLE '+@TableName + '( '+@Column1Name+' '+@Column1DataType +' '+@Column1Nullable +') ON PRIMARY ' EXEC (@SQLString) GO </code></pre> <p>This stored procedure can be executed like this:</p> <p><code>sproc_BuildTable 'Customers','CustomerName','VARCHAR(32)','NOT NULL'</code></p> <p>There are some major problems with this type of stored procedure.</p> <p>Its going to be difficult to cater for complex tables. Imagine the following table structure:</p> <pre><code>CREATE TABLE [dbo].[Customers] ( [CustomerID] [int] IDENTITY(1,1) NOT NULL, [CustomerName] [nvarchar](64) NOT NULL, [CustomerSUrname] [nvarchar](64) NOT NULL, [CustomerDateOfBirth] [datetime] NOT NULL, [CustomerApprovedDiscount] [decimal](3, 2) NOT NULL, [CustomerActive] [bit] NOT NULL, CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED ( [CustomerID] ASC ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER TABLE [dbo].[Customers] ADD CONSTRAINT [DF_Customers_CustomerApprovedDiscount] DEFAULT ((0.00)) FOR [CustomerApprovedDiscount] GO </code></pre> <p>This table is a little more complex than the first example, but not a lot. The stored procedure will be much, much more complex to deal with. So while this approach might work for small tables it is quickly going to be unmanageable.</p> <p>Creating tables require planning. When you create tables they should be placed strategically on different filegroups. This is to ensure that you don't cause disk I/O contention. How will you address scalability if everything is created on the primary file group?</p> <p>Could you clarify why you need tables to be created dynamically?</p> <p><strong>UPDATE 2:</strong></p> <p>Delayed update due to workload. I read your comment about needing to create a table for each shop and I think you should look at doing it like the example I am about to give you.</p> <p>In this example I make the following assumptions:</p> <ol> <li>It's an e-commerce site that has many shops</li> <li>A shop can have many items (goods) to sell.</li> <li>A particular item (good) can be sold at many shops</li> <li>A shop will charge different prices for different items (goods)</li> <li>All prices are in $ (USD)</li> </ol> <p>Let say this e-commerce site sells gaming consoles (i.e. Wii, PS3, XBOX360).</p> <p>Looking at my assumptions I see a classical many-to-many relationship. A shop can sell many items (goods) and items (goods) can be sold at many shops. Let's break this down into tables.</p> <p>First I would need a shop table to store all the information about the shop.</p> <p>A simple shop table might look like this:</p> <pre><code>CREATE TABLE [dbo].[Shop]( [ShopID] [int] IDENTITY(1,1) NOT NULL, [ShopName] [nvarchar](128) NOT NULL, CONSTRAINT [PK_Shop] PRIMARY KEY CLUSTERED ( [ShopID] ASC ) WITH ( PAD_INDEX = OFF , STATISTICS_NORECOMPUTE = OFF , IGNORE_DUP_KEY = OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY] ) ON [PRIMARY] GO </code></pre> <p>Let's insert three shops into the database to use during our example. The following code will insert three shops:</p> <pre><code>INSERT INTO Shop SELECT 'American Games R US' UNION SELECT 'Europe Gaming Experience' UNION SELECT 'Asian Games Emporium' </code></pre> <p>If you execute a <code>SELECT * FROM Shop</code> you will probably see the following:</p> <pre><code>ShopID ShopName 1 American Games R US 2 Asian Games Emporium 3 Europe Gaming Experience </code></pre> <p>Right, so now let's move onto the Items (goods) table. Since the items/goods are products of various companies I am going to call the table product. You can execute the following code to create a simple Product table.</p> <pre><code>CREATE TABLE [dbo].[Product]( [ProductID] [int] IDENTITY(1,1) NOT NULL, [ProductDescription] [nvarchar](128) NOT NULL, CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED ( [ProductID] ASC )WITH (PAD_INDEX = OFF , STATISTICS_NORECOMPUTE = OFF , IGNORE_DUP_KEY = OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO </code></pre> <p>Let's populate the products table with some products. Execute the following code to insert some products:</p> <pre><code>INSERT INTO Product SELECT 'Wii' UNION SELECT 'PS3' UNION SELECT 'XBOX360' </code></pre> <p>If you execute <code>SELECT * FROM Product</code> you will probably see the following:</p> <pre><code>ProductID ProductDescription 1 PS3 2 Wii 3 XBOX360 </code></pre> <p>OK, at this point you have both product and shop information. So how do you bring them together? Well we know we can identify the shop by its ShopID primary key column and we know we can identify a product by its ProductID primary key column. Also, since each shop has a different price for each product we need to store the price the shop charges for the product.</p> <p>So we have a table that maps the Shop to the product. We will call this table ShopProduct. A simple version of this table might look like this:</p> <pre><code>CREATE TABLE [dbo].[ShopProduct]( [ShopID] [int] NOT NULL, [ProductID] [int] NOT NULL, [Price] [money] NOT NULL, CONSTRAINT [PK_ShopProduct] PRIMARY KEY CLUSTERED ( [ShopID] ASC, [ProductID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO </code></pre> <p>So let's assume the American Games R Us shop only sells American consoles, the Europe Gaming Experience sells all consoles and the Asian Games Emporium sells only Asian consoles. We would need to map the primary keys from the shop and product tables into the ShopProduct table.</p> <p>Here is how we are going to do the mapping. In my example the American Games R Us has a ShopID value of 1 (this is the primary key value) and I can see that the XBOX360 has a value of 3 and the shop has listed the XBOX360 for $159.99</p> <p>By executing the following code you would complete the mapping:</p> <pre><code>INSERT INTO ShopProduct VALUES(1,3,159.99) </code></pre> <p>Now we want to add all product to the Europe Gaming Experience shop. In this example we know that the Europe Gaming Experience shop has a ShopID of 3 and since it sells all consoles we will need to insert the ProductID 1, 2 and 3 into the mapping table. Let's assume the prices for the consoles (products) at the Europe Gaming Experience shop are as follows: 1- The PS3 sells for $259.99 , 2- The Wii sells for $159.99 , 3- The XBOX360 sells for $199.99.</p> <p>To get this mapping done you would need to execute the following code:</p> <pre><code>INSERT INTO ShopProduct VALUES(3,2,159.99) --This will insert the WII console into the mapping table for the Europe Gaming Experience Shop with a price of 159.99 INSERT INTO ShopProduct VALUES(3,1,259.99) --This will insert the PS3 console into the mapping table for the Europe Gaming Experience Shop with a price of 259.99 INSERT INTO ShopProduct VALUES(3,3,199.99) --This will insert the XBOX360 console into the mapping table for the Europe Gaming Experience Shop with a price of 199.99 </code></pre> <p>At this point you have mapped two shops and their products into the mapping table. OK, so now how do I bring this all together to show a user browsing the website? Let's say you want to show all the product for the European Gaming Experience to a user on a web page – you would need to execute the following query:</p> <pre><code>SELECT Shop.* , ShopProduct.* , Product.* FROM Shop INNER JOIN ShopProduct ON Shop.ShopID = ShopProduct.ShopID INNER JOIN Product ON ShopProduct.ProductID = Product.ProductID WHERE Shop.ShopID=3 </code></pre> <p>You will probably see the following results:</p> <pre><code>ShopID ShopName ShopID ProductID Price ProductID ProductDescription 3 Europe Gaming Experience 3 1 259.99 1 PS3 3 Europe Gaming Experience 3 2 159.99 2 Wii 3 Europe Gaming Experience 3 3 199.99 3 XBOX360 </code></pre> <p>Now for one last example, let's assume that your website has a feature which finds the cheapest price for a console. A user asks to find the cheapest prices for XBOX360.</p> <p>You can execute the following query:</p> <pre><code> SELECT Shop.* , ShopProduct.* , Product.* FROM Shop INNER JOIN ShopProduct ON Shop.ShopID = ShopProduct.ShopID INNER JOIN Product ON ShopProduct.ProductID = Product.ProductID WHERE Product.ProductID =3 -- You can also use Product.ProductDescription = 'XBOX360' ORDER BY Price ASC </code></pre> <p>This query will return a list of all shops which sells the XBOX360 with the cheapest shop first and so on. </p> <p>You will notice that I have not added the Asian Games shop. As an exercise, add the Asian games shop to the mapping table with the following products: the Asian Games Emporium sells the Wii games console for $99.99 and the PS3 console for $159.99. If you work through this example you should now understand how to model a many-to-many relationship. </p> <p>I hope this helps you in your travels with database design.</p>
10,935,593
maven: How to add resources which are generated after compilation phase
<p>I have a maven project which uses <a href="https://docs.oracle.com/javase/8/docs/technotes/tools/unix/wsgen.html" rel="noreferrer">wsgen</a> to generate <a href="https://en.wikipedia.org/wiki/XML_Schema_%28W3C%29" rel="noreferrer">XSD</a> files from the compiled java classes. </p> <p>The problem is that I want to add the generated files to the jar as resources. But since the <code>resource</code> phase runs before the <code>process-classes</code> phase, I can't add them. </p> <p>Is there a way to tell maven to add additional resources that were generated at the <code>process-classes</code> phase?</p>
10,935,782
1
0
null
2012-06-07 16:06:32.653 UTC
10
2019-01-23 12:12:47.647 UTC
2019-01-23 12:12:47.647 UTC
null
770,254
null
927,477
null
1
38
java|maven|jax-ws
25,004
<p>I would suggest to define the output directory for the XSD files into target/classes (may be with a supplemental sub folder which will be packaged later during the package phase into the jar. This can be achieved by using the <a href="http://maven.apache.org/plugins/maven-resources-plugin/" rel="noreferrer">maven-resources-plugin</a>.</p> <pre><code>&lt;project&gt; ... &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-resources-plugin&lt;/artifactId&gt; &lt;version&gt;3.0.2&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;copy-resources&lt;/id&gt; &lt;phase&gt;process-classes&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;copy-resources&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;outputDirectory&gt;${project.build.outputDirectory}&lt;/outputDirectory&gt; &lt;resources&gt; &lt;resource&gt; &lt;directory&gt;${basedir}/target/xsd-out&lt;/directory&gt; &lt;filtering&gt;false&lt;/filtering&gt; &lt;/resource&gt; &lt;/resources&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;/plugins&gt; ... &lt;/build&gt; ... &lt;/project&gt; </code></pre> <p>You need to take care that the resources plugin is positioned after the plugin which is used to call the wsgen part. You can also use the <em>prepare-package</em> phase instead to make sure the resources will be correctly packaged.</p>
10,880,510
Objective-C preprocessor directive for 'if not'
<p>I understand how to use a preprocessor directive like this:</p> <pre><code>#if SOME_VARIABLE // Do something #else // Do something else #endif </code></pre> <p>But what if I only want to do something IF NOT SOME_VARIABLE.</p> <p>Obviously I still could do this:</p> <pre><code>#if SOME_VARIABLE #else // Do something else #endif </code></pre> <p>. . . leaving the if empty, But is there a way to do:</p> <pre><code>#if not SOME_VARIABLE // Do something #endif </code></pre> <p>Apple documentation <a href="https://developer.apple.com/library/mac/#documentation/DeveloperTools/gcc-4.2.1/cpp/Conditional-Syntax.html#Conditional-Syntax">here</a> suggests not, but this seems like a very basic need.</p> <p>Basically I want to do the preprocessor equivalent of:</p> <pre><code>if(!SOME_VARIABLE)( { // Do Something } </code></pre>
10,880,534
3
0
null
2012-06-04 11:30:13.97 UTC
4
2016-07-14 19:57:32.7 UTC
2016-07-14 19:57:32.7 UTC
null
4,370,109
null
138,601
null
1
44
ios|objective-c|iphone|c-preprocessor|preprocessor-directive
27,392
<p>you could try:</p> <pre><code>#if !(SOME_VARIABLE) // Do something #endif </code></pre>
10,867,882
How are tuples unpacked in for loops?
<p>I stumbled across the following code:</p> <pre><code>for i, a in enumerate(attributes): labels.append(Label(root, text = a, justify = LEFT).grid(sticky = W)) e = Entry(root) e.grid(column=1, row=i) entries.append(e) entries[i].insert(INSERT,&quot;text to insert&quot;) </code></pre> <p>I don't understand the <code>i, a</code> bit, and searching for information on <code>for</code> didn't yield any useful results. When I try and experiment with the code I get the error:</p> <blockquote> <p>ValueError: need more than 1 value to unpack</p> </blockquote> <p>Does anyone know what it does, or a more specific term associated with it that I can google to learn more?</p>
10,867,891
8
0
null
2012-06-03 04:24:10.313 UTC
30
2022-05-04 07:23:13.273 UTC
2022-05-04 07:23:13.273 UTC
null
2,745,495
null
1,333,030
null
1
82
python|python-3.x|tuples|iterable-unpacking
230,866
<p>You could google <a href="https://stackabuse.com/unpacking-in-python-beyond-parallel-assignment/" rel="noreferrer">&quot;tuple unpacking&quot;</a>. This can be used in various places in Python. The simplest is in assignment:</p> <pre><code>&gt;&gt;&gt; x = (1,2) &gt;&gt;&gt; a, b = x &gt;&gt;&gt; a 1 &gt;&gt;&gt; b 2 </code></pre> <p>In a for-loop it works similarly. If each element of the iterable is a <code>tuple</code>, then you can specify two variables, and each element in the loop will be unpacked to the two.</p> <pre><code>&gt;&gt;&gt; x = [(1,2), (3,4), (5,6)] &gt;&gt;&gt; for item in x: ... print &quot;A tuple&quot;, item A tuple (1, 2) A tuple (3, 4) A tuple (5, 6) &gt;&gt;&gt; for a, b in x: ... print &quot;First&quot;, a, &quot;then&quot;, b First 1 then 2 First 3 then 4 First 5 then 6 </code></pre> <p>The <code>enumerate</code> function creates an iterable of tuples, so it can be used this way.</p>
12,754,314
Using Inno Setup, how to import a certificate .cer file?
<p>Can I use Inno Setup to import a <code>.cer</code> file (a certificate)?</p> <p>How can I do it? </p> <p>I need to create a certificate installer for Windows XP, Windows Vista and Windows 7.</p>
17,991,224
2
2
null
2012-10-05 21:31:08.553 UTC
11
2016-10-21 11:49:19.937 UTC
2016-10-21 11:48:10.11 UTC
null
850,848
null
396,200
null
1
13
installation|certificate|distribution|inno-setup
9,366
<p>Add Certmgr.exe and yourcertificate.cer into setup:</p> <pre><code>[Files] Source: CertMgr.exe; DestDir: {app}; Flags: deleteafterinstall Source: yourcertificate.cer; DestDir: {app}; Flags: deleteafterinstall </code></pre> <p>And in [Run] section, write something like this:</p> <pre><code>Filename: {app}\CertMgr.exe; Parameters: "-add -all -c yourcertificate.cer -s -r localmachine trustedpublisher"; Flags: waituntilterminated runhidden; </code></pre>
12,703,757
android themes - defining colours in custom themes
<p>I am sure there is a simple answer to that yet I just cant find it so I throw it into stackoverflow ... ;-)</p> <p>I will just put it into an example. I have an android app where the user can choose the theme in the preferences - dark or light theme. Depending on the chosen theme I have to adjust 20 colors in my app. So I have the hope that I can define colours in the theme and then use the names of this so defined colours in the my TextViews etc. Yet so far I cant figure out how to do that and can't find any solution here and there. I really dont want to define an extra dark and light style for each of these 20 colours yet so far that seems the only solution I can find.</p> <p>Big thanks for any hint</p> <p>martin:</p> <p><strong>UPDATE:</strong></p> <p>In pseudo syntax is that is what I am looking for. Is it possible?</p> <pre><code>&lt;style name="AppTheme.MyDark" parent="android:Theme"&gt; -?-&gt; titleColor = "#ffffff" -?-&gt; introColor = "#ffaaaa" &lt;/style&gt; &lt;style name="AppTheme.MyLight" parent="android:Theme.Light"&gt; -?-&gt; titleColor = "#000000" -?-&gt; introColor = "#004444" &lt;/style&gt; &lt;TextView android:id="@+id/quoteTitle" android:textColor=@titleColor ... &lt;/TextView&gt; &lt;TextView android:id="@+id/quoteIntro" android:textColor=@introColor ... &lt;/TextView&gt; </code></pre>
12,704,879
1
4
null
2012-10-03 07:26:57.757 UTC
9
2013-05-05 05:10:33.787 UTC
2012-10-03 07:52:42.71 UTC
null
1,621,859
null
1,621,859
null
1
24
android|android-theme
11,491
<p>I found a solution which seems to work. First you need to define the custom color fields in attr.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;resources&gt; &lt;attr name="titleColor" format="reference|color" /&gt; &lt;attr name="introColor" format="reference|color" /&gt; &lt;/resources&gt; </code></pre> <p>Next you define your themes</p> <pre><code>&lt;style name="AppTheme.MyDark" parent="android:Theme"&gt; &lt;item name="titleColor"&gt;#FFFFFF&lt;/item&gt; &lt;item name="introColor"&gt;#FFFFFF&lt;/item&gt; &lt;/style&gt; &lt;style name="AppTheme.MyLight" parent="android:Theme"&gt; &lt;item name="titleColor"&gt;#000000&lt;/item&gt; &lt;item name="introColor"&gt;#004444&lt;/item&gt; &lt;/style&gt; </code></pre> <p>and finally in your layout</p> <pre><code>&lt;TextView android:id="@+id/quoteTitle" android:textColor="?titleColor" ... &lt;/TextView&gt; &lt;TextView android:id="@+id/quoteIntro" android:textColor="?introColor" ... &lt;/TextView&gt; </code></pre> <p>i found the solution mainly <a href="https://stackoverflow.com/questions/10545039/android-how-can-i-define-custom-colors-drawables-etc-in-themes">here</a></p> <p>There seems to be no explanation in the official android documentation about using attributes. Best resource I found is <a href="https://stackoverflow.com/questions/3441396/defining-custom-attrs">here</a></p>
12,744,337
How to keep android applications always be logged in state?
<p>Right now I am trying to create one Android application, assume it is going to be some "X" concept okay. So I am creating one login screen. What I want to do is at once if I logged in that application on my mobile, it should always be logged in whenever I try to access that application.</p> <p><em>For example our Facebook, g-mail and yahoo etc.. in our mobile phones</em></p> <p>What to do for that?</p>
12,744,408
9
0
null
2012-10-05 10:29:47.633 UTC
31
2022-05-11 08:35:05.55 UTC
2015-08-13 08:41:22.523 UTC
user4935693
null
null
1,371,559
null
1
35
android|autologin
86,494
<p>Use Shared Preference for auto login functionality. When users log in to your application, store the login status into sharedPreference and clear sharedPreference when users log out.</p> <p>Check every time when the user enters into the application if user status from shared Preference is true then no need to log in again otherwise direct to the login page.</p> <p>To achieve this first create a class, in this class you need to write all the function regarding the get and set value in the sharedpreference. Please look at this below Code.</p> <pre><code>public class SaveSharedPreference { static final String PREF_USER_NAME= "username"; static SharedPreferences getSharedPreferences(Context ctx) { return PreferenceManager.getDefaultSharedPreferences(ctx); } public static void setUserName(Context ctx, String userName) { Editor editor = getSharedPreferences(ctx).edit(); editor.putString(PREF_USER_NAME, userName); editor.commit(); } public static String getUserName(Context ctx) { return getSharedPreferences(ctx).getString(PREF_USER_NAME, ""); } } </code></pre> <p>Now in the main activity (The "Activity" where users will be redirected when logged in) first check </p> <pre><code>if(SaveSharedPreference.getUserName(MainActivity.this).length() == 0) { // call Login Activity } else { // Stay at the current activity. } </code></pre> <p>In Login activity if user login successful then set UserName using setUserName() function.</p>
12,908,412
Print "hello world" every X seconds
<p>Lately I've been using loops with large numbers to print out <code>Hello World</code>:</p> <pre><code>int counter = 0; while(true) { //loop for ~5 seconds for(int i = 0; i &lt; 2147483647 ; i++) { //another loop because it's 2012 and PCs have gotten considerably faster :) for(int j = 0; j &lt; 2147483647 ; j++){ ... } } System.out.println(counter + ". Hello World!"); counter++; } </code></pre> <p>I understand that this is a very silly way to do it, but I've never used any timer libraries in Java yet. How would one modify the above to print every say 3 seconds?</p>
12,908,477
14
2
null
2012-10-16 05:59:41.343 UTC
39
2020-09-03 17:37:29.957 UTC
2015-10-30 13:57:11.647 UTC
null
1,864,294
null
665,518
null
1
148
java|timer
304,997
<p>You can also take a look at <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html" rel="noreferrer"><code>Timer</code></a> and <a href="http://docs.oracle.com/javase/7/docs/api/java/util/TimerTask.html" rel="noreferrer"><code>TimerTask</code></a> classes which you can use to schedule your task to run every <code>n</code> seconds.</p> <p>You need a class that extends <code>TimerTask</code> and override the <code>public void run()</code> method, which will be executed everytime you pass an instance of that class to <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html#schedule%28java.util.TimerTask,%20long,%20long%29" rel="noreferrer"><code>timer.schedule()</code></a> method..</p> <p>Here's an example, which prints <code>Hello World</code> every 5 seconds: -</p> <pre><code>class SayHello extends TimerTask { public void run() { System.out.println("Hello World!"); } } // And From your main() method or any other method Timer timer = new Timer(); timer.schedule(new SayHello(), 0, 5000); </code></pre>
11,117,823
Git Push error: refusing to update checked out branch
<p>I have solved some merge conflicts, committed then tried to Push my changes and received the following error:</p> <pre><code>c:\Program Files (x86)\Git\bin\git.exe push --recurse-submodules=check "origin" master:master Done remote: error: refusing to update checked out branch: refs/heads/master remote: error: By default, updating the current branch in a non-bare repository remote: error: is denied, because it will make the index and work tree inconsistent remote: error: with what you pushed, and will require 'git reset --hard' to match remote: error: the work tree to HEAD. remote: error: remote: error: You can set 'receive.denyCurrentBranch' configuration variable to remote: error: 'ignore' or 'warn' in the remote repository to allow pushing into remote: error: its current branch; however, this is not recommended unless you remote: error: arranged to update its work tree to match what you pushed in some remote: error: other way. remote: error: remote: error: To squelch this message and still keep the default behaviour, set remote: error: 'receive.denyCurrentBranch' configuration variable to 'refuse'. To C:/Development/GIT_Repo/Project ! [remote rejected] master -&gt; master (branch is currently checked out) error: failed to push some refs to 'C:/Development/GIT_Repo/Project' </code></pre> <p>Does anyone know what could be causing this error?</p>
11,117,928
14
3
null
2012-06-20 10:40:18.267 UTC
59
2022-09-17 06:03:20.993 UTC
2017-03-26 04:27:31.033 UTC
null
1,033,581
null
545,877
null
1
235
git|git-push
225,397
<p>Reason:You are pushing to a Non-Bare Repository</p> <p>There are two types of repositories: <a href="https://stackoverflow.com/q/5540883/3803682">bare and non-bare</a></p> <p>Bare repositories do not have a working copy and you can push to them. Those are the types of repositories you get in Github! If you want to create a bare repository, you can use</p> <pre><code>git init --bare </code></pre> <p><del>So, in short, <strong>you can't push to a non-bare repository</strong></del> (Edit: Well, you can't push to the currently checked out branch of a repository. With a bare repository, you can push to any branch since none are checked out. Although possible, pushing to non-bare repositories is not common). What you can do, is to fetch and merge from the other repository. This is how the <code>pull request</code> that you can see in Github works. You ask them to pull from you, and you don't force-push into them.</p> <hr> <p><strong>Update</strong>: Thanks to VonC for pointing this out, in the latest git versions (currently 2.3.0), <a href="https://stackoverflow.com/a/28262104/912144">pushing to the checked out branch of a non-bare repository is possible</a>. Nevertheless, you still cannot push to a <em>dirty</em> working tree, which is not a safe operation anyway.</p>
16,869,990
How to convert from boolean array to int array in python
<p>I have a Numpy 2-D array in which one column has Boolean values i.e. <code>True</code>/<code>False</code>. I want to convert it to integer <code>1</code> and <code>0</code> respectively, how can I do it?</p> <p>E.g. my <code>data[0::,2]</code> is boolean, I tried</p> <pre><code>data[0::,2]=int(data[0::,2]) </code></pre> <p>, but it is giving me error:</p> <p><code>TypeError: only length-1 arrays can be converted to Python scalars</code></p> <p>My first 5 rows of array are:</p> <pre><code>[['0', '3', 'True', '22', '1', '0', '7.25', '0'], ['1', '1', 'False', '38', '1', '0', '71.2833', '1'], ['1', '3', 'False', '26', '0', '0', '7.925', '0'], ['1', '1', 'False', '35', '1', '0', '53.1', '0'], ['0', '3', 'True', '35', '0', '0', '8.05', '0']] </code></pre>
16,870,162
5
4
null
2013-06-01 06:55:18.563 UTC
4
2017-08-27 19:50:26.617 UTC
2013-06-01 07:32:04.17 UTC
null
603,094
null
1,643,128
null
1
17
python|numpy
50,772
<p>Ok, the easiest way to change a type of any array to float is doing:</p> <p><code>data.astype(float)</code></p> <p>The issue with your array is that <code>float('True')</code> is an error, because <code>'True'</code> can't be parsed as a float number. So, the best thing to do is fixing your array generation code to produce floats (or, at least, strings with valid float literals) instead of bools.</p> <p>In the meantime you can use this function to fix your array:</p> <pre><code>def boolstr_to_floatstr(v): if v == 'True': return '1' elif v == 'False': return '0' else: return v </code></pre> <p>And finally you convert your array like this:</p> <pre><code>new_data = np.vectorize(boolstr_to_floatstr)(data).astype(float) </code></pre>
16,987,948
Causes of "Error: package '_____' was built before 3.0.0: please re-install it" in R
<p>On one computer running R 2.15.2 I have installed packages from a .zip file (these packages happened to be <em>ggplot2</em> and <em>data.table</em>, but I don't think the specific package is my issue.) Everything works fine. I took these packages to a computer without an internet connection and installed them. This other computer is running R 3.0.1. The packages seemed to install without a problem (using R's "install package(s) from local zip file" option). When I call the packages with the <em>library()</em>, I get the following error:</p> <pre><code>Error: package '&lt;insert name of newly installed package here&gt;' was build before 3.0.0: please-re-install it </code></pre> <p>Can anyone explain potential causes for this error to be thrown? Are there particular directories that the .zip packages must be in for a proper install? If R is installed on a separate partition from where the .zip packages were loaded, could this cause the error? </p> <p>I'm at a loss, any pointers are greatly appreciated. This is a difficult one to reproduce; if you need any other version/system parameters to understand the problem, please don't hesitate to ask.</p>
19,187,680
6
2
null
2013-06-07 15:39:41.37 UTC
9
2019-12-09 08:04:42.407 UTC
2019-12-09 07:58:29.837 UTC
null
680,068
null
1,873,237
null
1
22
r|build|installation|package
25,514
<p>Running <code>install.packages("codetools")</code> can fix this issue for R 3.0.2, if you have the same problem like me:</p> <pre><code>installing to /home/user/R/x86_64-pc-linux-gnu-library/3.0/Rcpp/libs ** R ** inst ** preparing package for lazy loading Error : package ‘**codetools**’ was built before R 3.0.0: please re-install it Error : unable to load R code in package ‘Rcpp’ ERROR: lazy loading failed for package ‘Rcpp’ </code></pre>
16,600,735
What is an internal field count and what is SetInternalFieldCount used for?
<p>I'm having trouble understanding what the <code>SetInternalFieldCount()</code> function actually does. In the <a href="http://izs.me/v8-docs/classv8_1_1ObjectTemplate.html#ab63916ac584a76bca8ba541f86ce9fce">v8 documentation</a> the function is described as setting "the number of internal fields for objects generated from this template." Which is pretty self explanatory and unilluminating. </p> <p>In the <a href="https://developers.google.com/v8/embed#interceptors">v8 embedder's guide</a> they give this example </p> <pre><code>point_templ-&gt;SetInternalFieldCount(1); </code></pre> <p>and say "Here the internal field count is set to 1 which means the object has one internal field, with an index of 0, that points to a C++ object."</p> <p>But what exactly is an internal field and what does setting this value actually tell the program?</p>
18,573,670
1
0
null
2013-05-17 03:02:36.087 UTC
10
2013-09-02 12:45:53.87 UTC
2013-05-17 04:13:22.487 UTC
null
1,470,897
null
1,470,897
null
1
28
c++|v8|embedded-v8
6,549
<p>Function <code>SetInternalFieldCount</code> instructs V8 to allocate internal storage slots for every instance created using template. This allowes you store any kind of information inside those instances.</p> <p>It is useful, for example, to store connection between V8 object and C++ class instance.</p> <pre><code>void* p; // any pointer Local&lt;Object&gt; obj = point_templ-&gt;NewInstance(); obj-&gt;SetInternalField(0, External::New(p)); // 0 means 1-st internal field </code></pre> <p>or for aligned pointer:</p> <pre><code>obj-&gt;SetAlignedPointerInInternalField(0, p); // 0 means 1-st internal field </code></pre> <p>After this in another part of a program you can get your pointer like this:</p> <pre><code>v8::Handle&lt;v8::Object&gt; handle; // some object handle if (handle-&gt;InternalFieldCount() &gt; 0) { void* p = handle-&gt;GetAlignedPointerFromInternalField(0); // from 1-st field // ... do something with p, e.g. cast it to wrapped C++ class instance } </code></pre>
16,647,380
Max-Width vs. Min-Width
<p>Most of the tutorials I'm reading on using Media Queries are demonstrating the use of <code>min-width</code>, but I'm rarely seeing people using <code>max-width</code>.</p> <p>Is this some sort of design trend, or pattern, why people are using <code>min-width</code> over <code>max-width</code>?</p> <p>For example, I'm designing a site starting from mobile, working up to the desktop. I am using Foundation 4, but using media queries to remove various elements on the page and re-position the source order.</p> <p>One thing I am facing is a custom navigation for any device whose width is 360px or less. I want them to have a vertical navigation, rather than an inline horizontal. So my idea was to use <code>max-width</code> to target these devices.</p> <p>Should I be using <code>min-width</code> instead if I am designing mobile first? I.e. all the default styles are for mobile, and thus using <code>min-width</code> to progressively enhance the layout?</p>
16,647,547
7
1
null
2013-05-20 10:20:18.533 UTC
57
2020-08-01 23:54:14.733 UTC
2020-08-01 23:54:14.733 UTC
null
712,558
null
256,409
null
1
88
css|media-queries|zurb-foundation
106,291
<p>It really depends on how your stylesheet works. For example:</p> <pre><code>@media screen and (min-width:100px) { body { font-weight:bold; } } @media screen and (min-width:200px) { body { color:#555; } } </code></pre> <p>The above two media queries would make the <code>body</code> font bold if the screen is greater than or equal to 100px, but <em>also</em> make the color <code>#555</code> if it's greater than or equal to 200px;</p> <p>Another example:</p> <pre><code>@media screen and (max-width:100px) { body { font-weight:bold; } } @media screen and (max-width:200px) { body { color:#555; } } </code></pre> <p>Unlike the first example, this makes the <code>body</code> font bold and color <code>#555</code> only if the screen width is between 0 and 100px. If it's between 0px and 200px it will be color <code>#555</code>.</p> <p>The beauty of media queries is that you can combine these statements:</p> <pre><code>@media screen and (min-width:100px) and (max-width:200px) { body { font-weight:bold; color:#555; } } </code></pre> <p>In this example you are only targeting devices with a width between 100px and 200px - nothing more, nothing less.</p> <p>In short, if you want your styles to <em>leak</em> out of media queries you'd use either <code>min-width</code> <em>or</em> <code>max-width</code>, but if you're wanting to affect a very specific criteria you can just combine the two.</p>
20,534,887
Break on NaN in JavaScript
<p>Is there any modern browser that raises exceptions on NaN propagation (ie multiplying or adding a number to NaN), or that can be configured to do so?</p> <p>Silent NaN propagation is an awful and insidious source of bugs, and I'd love to be able to detect them early, even at a performance penalty.</p> <hr /> <p>Here's an example bug that <code>use strict</code>, <code>jshint</code> et al. wouldn't pick up:</p> <pre><code>object = new MyObject(); object.position.x = 0; object.position.y = 10; // ... lots of code var newPosition = object.position + 1; // &lt;- this is an error, and should // have been object.position.x // however it fails *silently*, // rather than loudly newPosition *= 2; // &lt;- this doesn't raise any errors either. // this code is actually ok if the // previous line had been correct </code></pre> <hr /> <p>Note: The TypeScript compiler is able to detect errors like the above, even in JS code, if type inference succeeds.</p>
20,535,216
5
13
null
2013-12-12 04:10:57.163 UTC
10
2021-02-01 05:34:38.527 UTC
2021-02-01 05:34:38.527 UTC
null
81,804
null
81,804
null
1
54
javascript|nan
6,193
<p>To answer the question as asked:</p> <blockquote> <p>Is there any modern browser that raises exceptions on NaN propagation (ie multiplying or adding a number to NaN), or that can be configured to do so?</p> </blockquote> <p>No. Javascript is a very forgiving language and doesn't care if you want to multiply <code>Math.PI</code> by 'potato' (hint: it's <code>NaN</code>). It's just one of the bad parts (or good parts, depending on your perspective) about the language that us developers have to deal with.</p> <p>Addressing the bug that has you asking this question (presumably), using getters and setters on your Objects is one solid way to enforce this and also keep you from making mistakes like this.</p>
26,883,259
Gmail 5.0 app fails with "Permission denied for the attachment" when it receives ACTION_SEND intent
<p>My app creates mails with attachments, and uses an intent with <code>Intent.ACTION_SEND</code> to launch a mail app.</p> <p>It works with all the mail apps I tested with, except for the new Gmail 5.0 (it works with Gmail 4.9), where the mail opens without attachment, showing the error: "Permission denied for the attachment".</p> <p>There are no useful messages from Gmail on logcat. I only tested Gmail 5.0 on Android KitKat, but on multiple devices.</p> <p>I create the file for the attachment like this:</p> <pre><code>String fileName = "file-name_something_like_this"; FileOutputStream output = context.openFileOutput( fileName, Context.MODE_WORLD_READABLE); // Write data to output... output.close(); File fileToSend = new File(context.getFilesDir(), fileName); </code></pre> <p>I'm aware of the security concerns with <code>MODE_WORLD_READABLE</code>.</p> <p>I send the intent like this:</p> <pre><code>public static void compose( Context context, String address, String subject, String body, File attachment) { Intent emailIntent = new Intent(Intent.ACTION_SEND); emailIntent.setType("message/rfc822"); emailIntent.putExtra( Intent.EXTRA_EMAIL, new String[] { address }); emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject); emailIntent.putExtra(Intent.EXTRA_TEXT, body); emailIntent.putExtra( Intent.EXTRA_STREAM, Uri.fromFile(attachment)); Intent chooser = Intent.createChooser( emailIntent, context.getString(R.string.send_mail_chooser)); context.startActivity(chooser); } </code></pre> <p>Is there anything I do wrong when creating the file or sending the intent? Is there a better way to start a mail app with attachment? Alternatively - has someone encountered this problem and found a workaround for it?</p> <p>Thanks!</p>
27,306,468
9
4
null
2014-11-12 09:19:09.547 UTC
8
2019-04-07 09:38:19.36 UTC
null
null
null
null
2,594,215
null
1
43
android|android-intent
28,148
<p>GMail 5.0 added some security checks to attachments it receives from an Intent. These are unrelated to unix permissions, so the fact that the file is readable doesn't matter.</p> <p>When the attachment Uri is a file://, it'll only accept files from external storage, the private directory of gmail itself, or world-readable files from the private data directory of the calling app.</p> <p>The problem with this security check is that it relies on gmail being able to find the caller app, which is only reliable when the caller has asked for result. In your code above, you do not ask for result and therefore gmail does not know who the caller is, and rejects your file.</p> <p>Since it worked for you in 4.9 but not in 5.0, you know it's not a unix permission problem, so the reason must be the new checks.</p> <p>TL;DR answer: <strong>replace startActivity with startActivityForResult.</strong></p> <p>Or better yet, use a content provider.</p>
9,945,265
Add click event on elements of an embedded SVG in javascript
<p>I got <a href="http://upload.wikimedia.org/wikipedia/commons/e/e8/BlankMap-World6-Equirectangular.svg" rel="noreferrer">this SVG image from Wikipedia</a> and embedded it into a website using this code: </p> <pre><code>&lt;embed src="circle1.svg" type="image/svg+xml"/&gt; </code></pre> <p>If you run this, you can inspect the element and see the source code. All countries in the image are separate elements. If I click on a country, I want to alert the id of that country, since every country has an id of two letters in the SVG. Does anyone know a way to do this? Would it be easier if I place it into a element?</p>
9,989,337
5
0
null
2012-03-30 14:48:01.897 UTC
7
2017-03-04 17:09:35.593 UTC
2017-03-04 17:09:35.593 UTC
null
1,079,075
null
1,066,924
null
1
17
javascript|html|canvas|svg
62,816
<p>Okay using your comments I found an answer to my problem. I added this code in the svg itself.</p> <pre><code>&lt;script type="text/javascript"&gt; &lt;![CDATA[ function addClickEvents() { var countries = document.getElementById('svg1926').childNodes; var i; for (i=0;i&lt;countries.length;i++){ countries[i].addEventListener('click', showCountry); } } function showCountry(e) { var node = e.target; if (node.id != 'ocean') { node = getCorrectNode(node); } alert(node.id); } function getCorrectNode(node) { if (node.id.length == 2 || node.id == 'lakes') { return node; } return getCorrectNode(node.parentNode); } ]]&gt; &lt;/script&gt; </code></pre> <p>The function addClickEvents is triggered when the svg loads. But I still have another problem with this. I have to embed this svg (with the code) into a HTML document using</p> <pre><code>&lt;embed src="circle1.svg" type="image/svg+xml" /&gt; </code></pre> <p>Instead of alerting the id, I have to place it into a div in the HTML document. How do I get this id from the svg?</p>
10,160,708
How do I find an item by value in an combobox in C#?
<p>In C#, I have variable, <code>a</code>, of type <code>string</code>.</p> <p>How do I <code>find item</code> by value of <code>a</code> in <code>combobox</code> (I want find item with value no display text of combobox).</p>
10,160,818
4
2
null
2012-04-15 08:53:51.973 UTC
5
2019-11-07 06:09:48.9 UTC
2015-05-17 16:11:41.627 UTC
null
63,550
null
1,271,330
null
1
25
c#|combobox|find|items
104,194
<p>You can find it by using the following code.</p> <pre><code>int index = comboBox1.Items.IndexOf(a); </code></pre> <p>To get the item itself, write:</p> <pre><code>comboBox1.Items[index]; </code></pre>
9,943,697
What's the reason for letting the semantics of a=a++ be undefined?
<pre><code>a = a++; </code></pre> <p>is undefined behaviour in C. The question I am asking is : <strong>why?</strong></p> <p>I mean, I get that it might be hard to provide a consistent order in which things should be done. But, certain compilers will always do it in one order or the other (at a given optimization level). So why exactly is this left up to the compiler to decide?</p> <p>To be clear, I want to know if this was a design decision and if so, what prompted it? Or maybe there is a hardware limitation of some kind?</p> <p>(Note : If the question title seems unclear or not good enough, then feedback and/or changes are welcome) </p>
9,945,955
8
7
null
2012-03-30 13:12:51.773 UTC
10
2012-08-10 19:05:06.583 UTC
2012-03-30 13:29:58.94 UTC
null
528,617
null
528,617
null
1
32
c|undefined-behavior|language-lawyer
1,907
<p>UPDATE: This question was <a href="http://blogs.msdn.com/b/ericlippert/archive/2012/06/18/implementation-defined-behaviour.aspx" rel="noreferrer">the subject of my blog on June 18th, 2012</a>. Thanks for the great question!</p> <hr> <blockquote> <p>Why? I want to know if this was a design decision and if so, what prompted it? </p> </blockquote> <p>You are essentially asking for the minutes of the meeting of the ANSI C design committee, and I don't have those handy. If your question can only be answered definitively by someone who was in the room that day, then you're going to have to find someone who was in that room.</p> <p>However, I can answer a broader question:</p> <blockquote> <p>What are some of the factors that lead a language design committee to leave the behaviour of a legal program (<code>*</code>) "undefined" or "implementation defined" (<code>**</code>)?</p> </blockquote> <p>The first major factor is: <strong>are there two existing implementations of the language in the marketplace that disagree on the behaviour of a particular program?</strong> If FooCorp's compiler compiles <code>M(A(), B())</code> as "call A, call B, call M", and BarCorp's compiler compiles it as "call B, call A, call M", and neither is the "obviously correct" behaviour then there is strong incentive to the language design committee to say "you're both right", and make it implementation defined behaviour. <em>Particularly this is the case if FooCorp and BarCorp both have representatives on the committee.</em></p> <p>The next major factor is: <strong>does the feature naturally present many different possibilities for implementation?</strong> For example, in C# the compiler's analysis of a "query comprehension" expression is specified as "do a syntactic transformation into an equivalent program that does not have query comprehensions, and then analyze that program normally". There is very little freedom for an implementation to do otherwise. </p> <p>By contrast, the C# specification says that the <code>foreach</code> loop should be treated as the equivalent <code>while</code> loop inside a <code>try</code> block, but allows the implementation some flexibility. A C# compiler is permitted to say, for example "I know how to implement <code>foreach</code> loop semantics more efficiently over an array" and use the array's indexing feature rather than converting the array to a sequence as the specification suggests it should. </p> <p>A third factor is: <strong>is the feature so complex that a detailed breakdown of its exact behaviour would be difficult or expensive to specify?</strong> The C# specification says very little indeed about how anonymous methods, lambda expressions, expression trees, dynamic calls, iterator blocks and async blocks are to be implemented; it merely describes the desired semantics and some restrictions on behaviour, and leaves the rest up to the implementation.</p> <p>A fourth factor is: <strong>does the feature impose a high burden on the compiler to analyze?</strong> For example, in C# if you have:</p> <pre><code>Func&lt;int, int&gt; f1 = (int x)=&gt;x + 1; Func&lt;int, int&gt; f2 = (int x)=&gt;x + 1; bool b = object.ReferenceEquals(f1, f2); </code></pre> <p>Suppose we require b to be true. <em>How are you going to determine when two functions are "the same"</em>? Doing an "intensionality" analysis -- do the function bodies have the same content? -- is hard, and doing an "extensionality" analysis -- do the functions have the same results when given the same inputs? -- is even harder. A language specification committee should seek to minimize the number of open research problems that an implementation team has to solve!</p> <p>In C# this is therefore left to be implementation-defined; a compiler can choose to make them reference equal or not at its discretion.</p> <p>A fifth factor is: <strong>does the feature impose a high burden on the runtime environment?</strong> </p> <p>For example, in C# dereferencing past the end of an array is well-defined; it produces an array-index-was-out-of-bounds exception. This feature can be implemented with a small -- not zero, but small -- cost at runtime. Calling an instance or virtual method with a null receiver is defined as producing a null-was-dereferenced exception; again, this can be implemented with a small, but non-zero cost. The benefit of eliminating the undefined behaviour pays for the small runtime cost.</p> <p>A sixth factor is: <strong>does making the behaviour defined preclude some major optimization</strong>? For example, C# defines the ordering of side effects <em>when observed from the thread that causes the side effects</em>. But the behaviour of a program that observes side effects of one thread from another thread is implementation-defined except for a few "special" side effects. (Like a volatile write, or entering a lock.) If the C# language required that all threads observe the same side effects in the same order then we would have to restrict modern processors from doing their jobs efficiently; modern processors depend on out-of-order execution and sophisticated caching strategies to obtain their high level of performance.</p> <p>Those are just a few factors that come to mind; there are of course many, many other factors that language design committees debate before making a feature "implementation defined" or "undefined".</p> <p>Now let's return to your specific example.</p> <p>The C# language <em>does</em> make that behaviour strictly defined(<code>†</code>); the side effect of the increment is observed to happen before the side effect of the assignment. So there cannot be any "well, it's just impossible" argument there, because it is possible to choose a behaviour and stick to it. Nor does this preclude major opportunities for optimizations. And there are not a multiplicity of possible complex implementation strategies.</p> <p>My <em>guess</em>, therefore, and I emphasize that this is a <em>guess</em>, is that the C language committee made ordering of side effects into implementation defined behaviour because there were multiple compilers in the marketplace that did it differently, none was clearly "more correct", and the committee was unwilling to tell half of them that they were wrong.</p> <hr> <p>(<code>*</code>) Or, sometimes, its compiler! But let's ignore that factor.</p> <p>(<code>**</code>) "Undefined" behaviour means that the code can do <em>anything</em>, including erasing your hard disk. The compiler is not required to generate code that has any particular behaviour, and not required to tell you that it is generating code with undefined behaviour. "Implementation defined" behaviour means that the compiler author is given considerable freedom in choice of implementation strategy, but is required to <em>pick a strategy</em>, <em>use it consistently</em>, and <em>document that choice</em>.</p> <p>(<code>†</code>) When observed from a single thread, of course.</p>
9,714,785
how to set individual session maxAge in express?
<p>I understand that you can set the maxAge when starting up the app as follows: </p> <pre><code>connect.session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}) </code></pre> <p>However, i would like to implement something along the lines of "remember me" setting, how would i go about doing that?</p> <p>Thanks a lot :)</p> <p>Jason</p>
9,718,416
1
0
null
2012-03-15 06:11:02.41 UTC
9
2012-03-15 11:05:11.687 UTC
null
null
null
null
60,893
null
1
36
node.js|express|session-cookies
42,373
<p>You can set either <code>expires</code> or <code>maxAge</code> on the individual cookie belonging to the current user:</p> <pre><code>// This user should log in again after restarting the browser req.session.cookie.expires = false; // This user won't have to log in for a year req.session.cookie.maxAge = 365 * 24 * 60 * 60 * 1000; </code></pre> <p>See <a href="http://www.senchalabs.org/connect/session.html">connect session documentation</a>.</p>
9,671,659
PHP is_null() and ==null
<p>In PHP, what is the difference between <code>is_null</code> and <code>==null</code> in PHP? What are the qualifications for both to return true?</p>
9,671,718
6
1
null
2012-03-12 17:16:20.363 UTC
6
2019-05-15 14:47:29.387 UTC
2012-03-13 16:28:38.727 UTC
null
1,033,808
null
1,259,336
null
1
55
php|null
81,860
<p><code>is_null</code> is the same as <code>=== null</code>. Both return true when a variable is <code>null</code> (or unset).</p> <p>Note that I'm using <code>===</code> and not <code>==</code>. <code>===</code> compares type as well as value.</p>
28,005,134
How do I implement the Add trait for a reference to a struct?
<p>I made a two element <code>Vector</code> struct and I want to overload the <code>+</code> operator.</p> <p>I made all my functions and methods take references, rather than values, and I want the <code>+</code> operator to work the same way.</p> <pre><code>impl Add for Vector { fn add(&amp;self, other: &amp;Vector) -&gt; Vector { Vector { x: self.x + other.x, y: self.y + other.y, } } } </code></pre> <p>Depending on which variation I try, I either get lifetime problems or type mismatches. Specifically, the <code>&amp;self</code> argument seems to not get treated as the right type.</p> <p>I have seen examples with template arguments on <code>impl</code> as well as <code>Add</code>, but they just result in different errors.</p> <p>I found <a href="https://stackoverflow.com/questions/24594374/overload-operators-with-different-rhs-type">How can an operator be overloaded for different RHS types and return values?</a> but the code in the answer doesn't work even if I put a <code>use std::ops::Mul;</code> at the top.</p> <p>I am using rustc 1.0.0-nightly (ed530d7a3 2015-01-16 22:41:16 +0000)</p> <p>I won't accept "you only have two fields, why use a reference" as an answer; what if I wanted a 100 element struct? I will accept an answer that demonstrates that even with a large struct I should be passing by value, if that is the case (I don't think it is, though.) I am interested in knowing a good rule of thumb for struct size and passing by value vs struct, but that is not the current question.</p>
28,005,283
2
5
null
2015-01-17 22:40:51.02 UTC
15
2021-08-11 19:38:24.05 UTC
2017-05-23 12:09:48.173 UTC
null
-1
null
2,325,220
null
1
78
reference|rust|traits|lifetime
23,706
<p>You need to implement <code>Add</code> on <code>&amp;Vector</code> rather than on <code>Vector</code>.</p> <pre><code>impl&lt;'a, 'b&gt; Add&lt;&amp;'b Vector&gt; for &amp;'a Vector { type Output = Vector; fn add(self, other: &amp;'b Vector) -&gt; Vector { Vector { x: self.x + other.x, y: self.y + other.y, } } } </code></pre> <p>In its definition, <code>Add::add</code> always takes <code>self</code> by value. But references are types like any other<sup>1</sup>, so they can implement traits too. When a trait is implemented on a reference type, the type of <code>self</code> is a reference; the reference is passed by value. Normally, passing by value in Rust implies transferring ownership, but when references are passed by value, they're simply copied (or reborrowed/moved if it's a mutable reference), and that doesn't transfer ownership of the referent (because a reference doesn't own its referent in the first place). Considering all this, it makes sense for <code>Add::add</code> (and many other operators) to take <code>self</code> by value: if you need to take ownership of the operands, you can implement <code>Add</code> on structs/enums directly, and if you don't, you can implement <code>Add</code> on references.</p> <p>Here, <code>self</code> is of type <code>&amp;'a Vector</code>, because that's the type we're implementing <code>Add</code> on.</p> <p>Note that I also specified the <code>RHS</code> type parameter with a different lifetime to emphasize the fact that the lifetimes of the two input parameters are unrelated.</p> <hr> <p><sup>1</sup> Actually, reference types are special in that you can implement traits for references to types defined in your crate (i.e. if you're allowed to implement a trait for <code>T</code>, then you're also allowed to implement it for <code>&amp;T</code>). <code>&amp;mut T</code> and <code>Box&lt;T&gt;</code> have the same behavior, but that's not true in general for <code>U&lt;T&gt;</code> where <code>U</code> is not defined in the same crate.</p>
9,901,976
What is JSR and what's its use?
<p>What is the relevance of JSR and how does one optimize it for one's use?</p> <p>I read something like jsr82 for Bluetooth and some other for other technical apps.</p> <p>What's its relevance?</p>
9,902,046
5
0
null
2012-03-28 06:06:42.313 UTC
30
2021-09-12 05:32:09.423 UTC
2019-07-18 07:17:24.817 UTC
null
1,483,676
null
1,172,914
null
1
97
java|jsr
38,668
<p>JSRs are <em>Java Specification Requests</em>, basically change requests for the Java language, libraries and other components.</p> <p>It's all part of the <a href="https://en.wikipedia.org/wiki/Java_Community_Process" rel="noreferrer"><em>Java Community Process</em></a>, whereby interested parties can put forward their ideas for enhancements and (hopefully) have them taken up and acted upon. The process is detailed <a href="http://jcp.org/en/procedures/overview" rel="noreferrer">here</a>.</p> <p>For example, the <a href="https://en.wikipedia.org/wiki/Bluetooth" rel="noreferrer">Bluetooth</a> one you mention is tracked <a href="http://jcp.org/en/jsr/detail?id=82" rel="noreferrer">here</a> and the definitive list is maintained <a href="http://jcp.org/en/jsr/all" rel="noreferrer">here</a>.</p>
9,655,164
Regex: ignore case sensitivity
<p>How can I make the following regex ignore case sensitivity? It should match all the correct characters but ignore whether they are lower or uppercase.</p> <pre><code>G[a-b].* </code></pre>
9,655,186
15
6
null
2012-03-11 13:04:06.017 UTC
75
2022-02-06 14:13:34.963 UTC
2017-08-03 16:07:33.583 UTC
null
1,678,392
null
671,809
null
1
486
regex
1,143,471
<p>Assuming you want the <strong>whole</strong> regex to ignore case, you should look for the <a href="http://www.regular-expressions.info/modifiers.html"><code>i</code> flag</a>. Nearly all regex engines support it:</p> <pre><code>/G[a-b].*/i string.match("G[a-b].*", "i") </code></pre> <p>Check the documentation for your language/platform/tool to find how the matching modes are specified.</p> <p>If you want only <strong>part</strong> of the regex to be case insensitive (as my original answer presumed), then you have two options:</p> <ol> <li><p>Use the <code>(?i)</code> and [optionally] <code>(?-i)</code> mode modifiers:</p> <pre><code>(?i)G[a-b](?-i).* </code></pre></li> <li><p>Put all the variations (i.e. lowercase and uppercase) in the regex - useful if mode modifiers are not supported:</p> <pre><code>[gG][a-bA-B].* </code></pre></li> </ol> <p>One last note: if you're dealing with Unicode characters besides ASCII, check whether or not your regex engine properly supports them.</p>
8,178,623
Not applying the CSS while generating PDF using iTextsharp.dll
<p>I am generating PDF using iTextSharp.dll, but the problem is that I am not able to apply that CSS. I have one div:</p> <pre><code> &lt;div id="personal" class="headerdiv"&gt; Personal Data &lt;/div&gt; </code></pre> <p>now my .aspx.cs code is like this:</p> <pre><code> iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet(); styles.LoadTagStyle("#headerdiv", "height", "30px"); styles.LoadTagStyle("#headerdiv", "font-weight", "bold"); styles.LoadTagStyle("#headerdiv", "font-family", "Cambria"); styles.LoadTagStyle("#headerdiv", "font-size", "20px"); styles.LoadTagStyle("#headerdiv", "background-color", "Blue"); styles.LoadTagStyle("#headerdiv", "color", "White"); styles.LoadTagStyle("#headerdiv", "padding-left", "5px"); HTMLWorker worker = new HTMLWorker(document); worker.SetStyleSheet(styles); // step 4: we open document and start the worker on the document document.Open(); worker.StartDocument(); // step 5: parse the html into the document worker.Parse(reader); // step 6: close the document and the worker worker.EndDocument(); worker.Close(); document.Close(); </code></pre>
8,184,565
3
0
null
2011-11-18 06:31:11.71 UTC
6
2014-07-16 17:30:04.1 UTC
2011-11-18 07:29:06.547 UTC
null
540,162
null
1,005,378
null
1
7
c#|.net|pdf|itextsharp
51,895
<p>There's a couple of things going on here. First and foremost, the HTML/CSS parser in iText and iTextSharp are far from complete. They're definitely very powerful but still have a ways to go. Each version gets better so always make sure that you're using the latest version.</p> <p>Second, I've seen more HTML/CSS activity in an add-on for iText/iTextSharp called XMLWorker that you might want to look at. You don't "load styles" anymore, you just pass raw HTML/CSS in and it figures out a lot of things. You can see some <a href="http://demo.itextsupport.com/xmlworker/itextdoc/index.html">examples here</a>, see a list of <a href="http://demo.itextsupport.com/xmlworker/itextdoc/index.html">supported CSS attributes here</a>, <a href="http://sourceforge.net/projects/itextsharp/files/xmlworker/xmlworker-1.1.0/">download it here</a> (and get the two missing files <a href="http://itextsharp.svn.sourceforge.net/viewvc/itextsharp/trunk/src/extras/itextsharp.xmlworker/iTextSharp/errors/errors.properties?revision=286&amp;content-type=text/plain">here</a> and <a href="http://itextsharp.svn.sourceforge.net/viewvc/itextsharp/trunk/src/extras/itextsharp.xmlworker/iTextSharp/errors/errors_nl.properties?revision=286&amp;content-type=text/plain">here</a>).</p> <p>Third, <code>LoadTagStyle</code> is for loading style attributes for HTML tags, not CSS IDs or Classes. You want to use <code>LoadStyle</code> to load by class:</p> <pre><code>styles.LoadStyle("&lt;classname&gt;", "&lt;attribute&gt;", "&lt;value&gt;"); </code></pre> <p>Unfortunately this method still doesn't do what you want it to do always. For instance, to change the font size you'd think you'd say:</p> <pre><code>styles.LoadStyle("headerdiv", "font-size", "60ptx); </code></pre> <p>But to get it to work you can only use relative HTML font sizes (1,2,-1, etc) or PT sizes and you must use the <code>size</code> property:</p> <pre><code>styles.LoadStyle("headerdiv", "size", "60pt"); //or styles.LoadStyle("headerdiv", "size", "2"); </code></pre> <p>The <code>LoadStyle</code> honestly feels like an afterthought that was only partially completed and I recommend not using it actually. Instead I recommend writing the style attributes directly inline if you can:</p> <pre><code>string html = "&lt;div id=\"personal\" class=\"headerdiv\" style=\"padding-left:50px;font-size:60pt;font-family:Cambria;font-weight:700;\"&gt;Personal Data&lt;/div&gt;"; </code></pre> <p>Obviously this defeats the points of CSS and once again, that's why they're working on the new XMLWorker above.</p> <p>Lastly, to use fonts by name you have to register them with iTextSharp first, it won't go looking for them:</p> <pre><code>iTextSharp.text.FontFactory.Register(@"c:\windows\fonts\cambria.ttc", "Cambria"); </code></pre>
11,881,027
chrome cache removal for single files
<p>recently I had to remove my entire cache to be able to view a webpage I was working on. This is fine I guess but it could be improved by removing specific pages from the cache. the chrome.browsingData.remove, seemingly has no option for indicating individual pages for removal. I was wondering if this could be done externally, but I am not familiar with the chromium code. I was also wondering if there are any planned changes to the chrome.browsingData.remove implementation. Many thanks</p>
11,881,130
6
1
null
2012-08-09 10:06:25.587 UTC
2
2022-07-28 10:10:13.807 UTC
null
null
null
null
1,587,138
null
1
31
google-chrome-devtools
13,165
<p>If you are working on a webpage and wish to avoid caching (btw, it's recommended! :) You can do it today in Chrome DevTools. Go to Settings (the icon in the bottom-right corner) and click on it. Then, you will have an option 'disable cache' - mark it and you done.</p> <p>Just don't forget to return this state when you done working as chrome will be faster with its caching schema.</p>
11,918,797
How to check if a MySQL query using the legacy API was successful?
<p>How do I check if a MySQL query is successful other than using <code>die()</code></p> <p>I'm trying to achieve...</p> <pre><code>mysql_query($query); if(success){ //move file } else if(fail){ //display error } </code></pre>
11,918,808
6
0
null
2012-08-12 00:27:47.247 UTC
5
2016-06-13 09:44:23.833 UTC
2016-06-13 08:52:08.783 UTC
null
13,508
null
963,622
null
1
34
php|mysql
112,533
<p>This is the first example in the manual page for <a href="http://php.net/manual/en/function.mysql-query.php" rel="noreferrer"><code>mysql_query</code></a>:</p> <pre><code>$result = mysql_query('SELECT * WHERE 1=1'); if (!$result) { die('Invalid query: ' . mysql_error()); } </code></pre> <p>If you wish to use something other than <code>die</code>, then I'd suggest <a href="http://php.net/manual/en/function.trigger-error.php" rel="noreferrer"><code>trigger_error</code></a>.</p>
12,008,908
AngularJS: How can I pass variables between controllers?
<p>I have two Angular controllers:</p> <pre><code>function Ctrl1($scope) { $scope.prop1 = "First"; } function Ctrl2($scope) { $scope.prop2 = "Second"; $scope.both = Ctrl1.prop1 + $scope.prop2; //This is what I would like to do ideally } </code></pre> <p>I can't use <code>Ctrl1</code> inside <code>Ctrl2</code> because it is undefined. However if I try to pass it in like so…</p> <pre><code>function Ctrl2($scope, Ctrl1) { $scope.prop2 = "Second"; $scope.both = Ctrl1.prop1 + $scope.prop2; //This is what I would like to do ideally } </code></pre> <p>I get an error. Does anyone know how to do this?</p> <p>Doing </p> <pre><code>Ctrl2.prototype = new Ctrl1(); </code></pre> <p>Also fails.</p> <p><strong>NOTE:</strong> These controllers are not nested inside each other.</p>
12,009,408
16
2
null
2012-08-17 15:42:45 UTC
163
2020-09-04 23:15:43.287 UTC
2016-03-24 02:12:00.247 UTC
null
1,476,885
null
858,962
null
1
332
javascript|angularjs|angularjs-controller
332,742
<p>One way to share variables across multiple controllers is to <a href="https://code.angularjs.org/1.2.21/docs/guide/services" rel="noreferrer">create a service</a> and inject it in any controller where you want to use it.</p> <p><strong>Simple service example:</strong></p> <pre><code>angular.module('myApp', []) .service('sharedProperties', function () { var property = 'First'; return { getProperty: function () { return property; }, setProperty: function(value) { property = value; } }; }); </code></pre> <p><strong>Using the service in a controller:</strong></p> <pre><code>function Ctrl2($scope, sharedProperties) { $scope.prop2 = "Second"; $scope.both = sharedProperties.getProperty() + $scope.prop2; } </code></pre> <p>This is described very nicely in <a href="http://onehungrymind.com/angularjs-sticky-notes-pt-1-architecture/" rel="noreferrer">this blog</a> (Lesson 2 and on in particular).</p> <p>I've found that if you want to bind to these properties across multiple controllers it works better if you bind to an object's property instead of a primitive type (boolean, string, number) to retain the bound reference. </p> <p>Example: <code>var property = { Property1: 'First' };</code> instead of <code>var property = 'First';</code>.</p> <hr> <p><strong>UPDATE:</strong> To (hopefully) make things more clear <a href="http://jsfiddle.net/b2fCE/1/" rel="noreferrer">here is a fiddle</a> that shows an example of:</p> <ul> <li><strong>Binding to static copies of the shared value (in myController1)</strong> <ul> <li>Binding to a primitive (string)</li> <li>Binding to an object's property (saved to a scope variable)</li> </ul></li> <li><strong>Binding to shared values that update the UI as the values are updated (in myController2)</strong> <ul> <li>Binding to a function that returns a primitive (string)</li> <li>Binding to the object's property</li> <li>Two way binding to an object's property</li> </ul></li> </ul>
4,026,213
PHP Regex Any Character
<p>The <code>.</code> character in a php regex accepts all characters, except a newline. What can I use to accept ALL characters, including newlines?</p>
4,026,233
5
0
null
2010-10-26 17:26:11.12 UTC
3
2017-05-14 08:20:00.413 UTC
2010-11-05 02:02:19.497 UTC
null
322,819
null
481,702
null
1
27
php|regex
49,739
<p>This is commonly used to capture all characters:</p> <pre><code>[\s\S] </code></pre> <p>You could use any other combination of "Type-X + Non-Type-X" in the same way:</p> <pre><code>[\d\D] [\w\W] </code></pre> <p>but <code>[\s\S]</code> is recognized by convention as a shorthand for "really anything".</p> <p>You can also use the <code>.</code> if you switch the regex into "dotall" (a.k.a. "single-line") mode via the <code>"s"</code> modifier. Sometimes that's not a viable solution (dynamic regex in a black box, for example, or if you don't want to modify the <em>entire</em> regex). In such cases the other alternatives do the same, no matter how the regex is configured.</p>
3,581,981
Overloading the C++ indexing subscript operator [] in a manner that allows for responses to updates
<p>Consider the task of writing an indexable class which automatically synchronizes its state with some external data-store (e.g. a file). In order to do this the class would need to be made aware of changes to the indexed value which might occur. Unfortunately the usual approach to overloading operator[] does not allow for this, for example...</p> <pre><code>Type&amp; operator[](int index) { assert(index &gt;=0 &amp;&amp; index &lt; size); return state[index]; } </code></pre> <p>I there any way to distinguish between a value being accessed and a value being modified?</p> <pre><code>Type a = myIndexable[2]; //Access myIndexable[3] = a; //Modification </code></pre> <p>Both of these cases occur after the function has returned. Is there some other approach to overloading operator[] which would perhaps make more sense? </p>
3,582,101
6
0
null
2010-08-27 06:56:02.72 UTC
11
2016-12-14 01:12:28.793 UTC
2010-08-27 08:21:52.453 UTC
null
141,997
null
141,997
null
1
29
c++|indexing|operator-overloading
47,096
<p>From the operator[] you can only really tell access.<br> Even if the external entity uses the non cost version this does not mean that a write will take place rather that it could take place. </p> <p>As such What you need to do is return an object that can detect modification.<br> The best way to do this is to wrap the object with a class that overrides the <code>operator=</code>. This wrapper can then inform the store when the object has been updated. You would also want to override the <code>operator Type</code> (cast) so that a const version of the object can be retrieved for read accesses.</p> <p>Then we could do something like this:</p> <pre><code>class WriteCheck; class Store { public: Type const&amp; operator[](int index) const { return state[index]; } WriteCheck operator[](int index); void stateUpdate(int index) { // Called when a particular index has been updated. } // Stuff }; class WriteCheck { Store&amp; store; Type&amp; object; int index; public: WriteCheck(Store&amp; s, Type&amp; o, int i): store(s), object(o), index(i) {} // When assignment is done assign // Then inform the store. WriteCheck&amp; operator=(Type const&amp; rhs) { object = rhs; store.stateUpdate(index); } // Still allow the base object to be read // From within this wrapper. operator Type const&amp;() { return object; } }; WriteCheck Store::operator[](int index) { return WriteCheck(*this, state[index], index); } </code></pre> <p>An simpler alternative is:<br> Rather than provide the operator[] you provide a specific set method on the store object and only provide read access through the operator[]</p>
3,333,102
Is "git push --mirror" sufficient for backing up my repository?
<p>I'm a solo developer, working in a local Git repository. For backups, I want to send an exact copy of that repository off to another server.</p> <p>Is it sufficient to do this?</p> <pre><code>git push --mirror </code></pre> <p>I'm asking because I can sometimes run this command two or three times before Git tells me "Everything up-to-date", so apparently it's not an exact mirror. It seems to be re-pushing tracking branches...?</p> <pre><code>$ git push --mirror Counting objects: 42, done. Delta compression using up to 8 threads. Compressing objects: 100% (30/30), done. Writing objects: 100% (30/30), 5.09 KiB, done. Total 30 (delta 17), reused 0 (delta 0) To ssh://my/repo/url c094a10..0eedc92 mybranch -&gt; mybranch $ git push --mirror Total 0 (delta 0), reused 0 (delta 0) To ssh://my/repo/url c094a10..0eedc92 origin/mybranch -&gt; origin/mybranch $ git push --mirror Everything up-to-date </code></pre> <p>What is happening, and is this a good strategy?</p> <p>Edit: I don't like to use something like <code>git bundle</code> or <code>.tar.bz2</code> archives, because I'd like the backup to be an accessible working copy. Since my backup server is connected to the net and always on, this is a nice way to access the repository when I'm on the road.</p>
3,333,168
7
2
null
2010-07-26 07:56:21.747 UTC
20
2014-05-29 02:45:35.063 UTC
2010-07-27 07:02:59.597 UTC
null
14,637
null
14,637
null
1
71
git|backup
56,819
<p>I would say this is a perfectly acceptable strategy for backing up your repository. It should perform a push to your origin remote for every ref in the repository. Making it a complete 'mirror' of your local repository. </p> <p>EDIT: I've just seen your updated description in the question. It seems git is pushing your remote ref to the remote itself along with everything else. Once the push has finished, the remote ref will be updated to reflect that you have just pushed to it. This will now be out of date with the remote repository so a further push is necessary. If this doesn't satisfy you. You can delete this remote ref with </p> <blockquote> <p>git push :origin/mybranch</p> </blockquote> <p>and then use</p> <blockquote> <p>git push --all</p> </blockquote> <p>remember that this won't push any new branches you create though. </p>
3,663,665
How can I get the current screen orientation?
<p>I just want to set some flags when my orientation is in landscape so that when the activity is recreated in onCreate() i can toggle between what to load in portrait vs. landscape. I already have a layout-land xml that is handling my layout.</p> <pre><code>public void onConfigurationChanged(Configuration _newConfig) { if (_newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { this.loadURLData = false; } if (_newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { this.loadURLData = true; } super.onConfigurationChanged(_newConfig); } </code></pre> <p>Over-riding onConfigurationChanged will prevent my layout-land xml from loading in landscape orientation.</p> <p>I just want to get the current orientation of my device in onCreate(). How can I get this?</p>
3,663,693
9
0
null
2010-09-08 00:15:47.65 UTC
40
2019-02-07 09:59:41.37 UTC
null
null
null
null
19,875
null
1
224
java|android|configuration|orientation
172,971
<pre><code>Activity.getResources().getConfiguration().orientation </code></pre>
3,682,649
How to stretch the width of an element, so that it's 100% - widths of its siblings?
<p>Say, I have the following unordered list. The button has <code>width: auto</code>. How do I style the elements, so <code>#textField</code> would stretch as much as possible, so the width of <code>#textField</code> and the button would add up to 100%? I.e. <code>#textField</code>'s width == (100% of width) - (button's computed width).</p> <pre><code>&lt;ul&gt; &lt;li&gt; &lt;input id="textField" type="text" /&gt;&lt;input type="button" /&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>So, for example, let's say 100% width of <code>li</code> is 100 pixels: if the button's computed width is 30px, <code>#textField</code>'s width would be 70px; if button's computed width is 25px, <code>#textField</code>'s width would become 75px. </p>
8,765,917
11
4
null
2010-09-10 06:30:44.787 UTC
19
2013-03-21 11:57:52.427 UTC
2012-11-19 10:32:35.287 UTC
null
75,500
null
404,033
null
1
27
html|css
42,135
<p>You can quickly achieve this effect using a mixture of <code>float</code> and <code>overflow: hidden</code>:</p> <pre><code>&lt;ul&gt; &lt;li&gt; &lt;input class="btn" type="button" value="Submit"/&gt; &lt;div class="inputbox"&gt;&lt;input id="textField" type="text" /&gt;&lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>CSS:</p> <pre><code>ul { list-style: none; padding: 0; } .btn { float: right; } .inputbox { padding: 0 5px 0 0; overflow: hidden; } .inputbox input { width: 100%; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } </code></pre> <p>Preview (with box-sizing): <a href="http://jsfiddle.net/Wexcode/E8uHf/546/" rel="noreferrer">http://jsfiddle.net/Wexcode/E8uHf/546/</a></p> <p>Here is how it looks without box-sizing: <a href="http://jsfiddle.net/Wexcode/E8uHf/" rel="noreferrer">http://jsfiddle.net/Wexcode/E8uHf/</a></p>
3,227,546
IntelliJ and Git Branch Name
<p>I've recently moved from Eclipse to IntelliJ. A challenge as I'm a keyboard shortcut junkie, but that isn't what I'm here about. </p> <p>I miss having the git branch name shown in the package/project view. </p> <p>Does anyone know of a way to configure IntelliJ to display what git branch the project is in, so I don't have to keep switching back to the terminal and checking.</p> <p>Thanks.</p>
11,671,998
11
0
null
2010-07-12 10:10:43.267 UTC
12
2021-06-11 16:56:50.557 UTC
2012-03-20 14:17:44.413 UTC
null
21,234
null
352,054
null
1
84
git|intellij-idea
53,663
<p>As of IntelliJ 11 the current Git branch is displayed in the bottom right corner of the status bar. Moreover, clicking on the branch name displays a nice popup with all available branches, and you can invoke some actions on them.</p> <hr> <p>To enable <code>status bar</code> follow the below steps : </p> <pre><code> View --&gt; Appearance --&gt; Status Bar [and click to enable/disable] </code></pre>
3,765,998
Add a properties file to IntelliJ's classpath
<p>I'm running a simple Java program from the IntelliJ IDE using the Run->Run menu. It works fine. Now I want to add log4j logging.</p> <p>I added a resources folder under my project root. I added a log4j.properties file in that folder. I changed the code to log something.</p> <p>What is the right way to tell IntelliJ to include the resources folder in the classpath so the properties file is seen?</p> <p>With IntelliJ 8 I could guess like a drunk monkey and eventually get it to work. I have 9 now and I am wholly unsuccessful. I've been trying for an hour. How about an "Add to classpath" option somewhere? /fume /vent /rant</p>
3,766,176
11
2
null
2010-09-22 02:51:15.14 UTC
38
2021-05-10 14:27:50.46 UTC
2014-11-30 19:14:53.25 UTC
null
3,885,376
null
449,693
null
1
133
java|intellij-idea|classpath
203,703
<p>Try this:</p> <ul> <li>Go to Project Structure.</li> <li>Select your module.</li> <li>Find the folder in the tree on the right and select it.</li> <li>Click the Sources button above that tree (with the blue folder) to make that folder a sources folder.</li> </ul>
8,198,253
ProgressBar in an ActionBar, like GMail app with Refresh
<p>I would like to do the same thing than the GMail application on Honeycomb tablets. When you click on the Refresh button, the icon is replaced by a ProgressBar. How can I do this?</p> <p>Thanks</p>
13,038,016
4
0
null
2011-11-19 23:44:04.333 UTC
15
2013-08-20 09:39:42.147 UTC
2012-11-04 13:33:41.56 UTC
null
1,333,975
null
326,173
null
1
23
android|gmail|progress-bar|android-3.0-honeycomb|tablet
15,750
<p>Ok, I tried what Cailean suggested but it didn't work for me. Every time I want to revert indeterminate progress to the original button it becomes unclickable, I used this layout for the progress</p> <p>(actionbar_refresh_progress.xml)</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;ProgressBar xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="32dp" android:layout_height="32dp" android:layout_gravity="center"/&gt; </code></pre> <p>and this one to revert to the button</p> <p>(actionbar_refresh_button.xml)</p> <pre><code>&lt;ImageView xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/ic_menu_refresh_holo_light" android:layout_height="wrap_content" android:layout_width="wrap_content"/&gt; </code></pre> <p>my code was:</p> <pre><code>private void setRefreshing(boolean refreshing) { this.refreshing = refreshing; if(refreshMenuItem == null) return; View refreshView; LayoutInflater inflater = (LayoutInflater)getActionBar().getThemedContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); if(refreshing) refreshView = inflater.inflate(R.layout.actionbar_refresh_progress, null); else refreshView = inflater.inflate(R.layout.actionbar_refresh_button, null); refreshMenuItem.setActionView(refreshView); } </code></pre> <p>After browsing the source of the Google IO app, especially this file: <a href="http://code.google.com/p/iosched/source/browse/android/src/com/google/android/apps/iosched/ui/HomeActivity.java" rel="noreferrer">http://code.google.com/p/iosched/source/browse/android/src/com/google/android/apps/iosched/ui/HomeActivity.java</a> i found another easier way.</p> <p>Now I need only the first layout with progress and the working method looks like this:</p> <pre><code>private void setRefreshing(boolean refreshing) { this.refreshing = refreshing; if(refreshMenuItem == null) return; if(refreshing) refreshMenuItem.setActionView(R.layout.actionbar_refresh_progress); else refreshMenuItem.setActionView(null); } </code></pre> <p>Menu item definition:</p> <pre><code>&lt;item android:id="@+id/mail_refresh" android:title="Refresh" android:icon="@drawable/ic_menu_refresh_holo_light" android:showAsAction="always"/&gt; </code></pre> <p>I hope someone finds this useful.</p>
7,777,985
Validate DateTime with FluentValidator
<p>This is my <strong>ViewModel</strong> class:</p> <pre><code>public class CreatePersonModel { public string Name { get; set; } public DateTime DateBirth { get; set; } public string Email { get; set; } } </code></pre> <p><strong>CreatePerson.cshtml</strong></p> <pre><code>@model ViewModels.CreatePersonModel @{ ViewBag.Title = "Create Person"; } &lt;h2&gt;@ViewBag.Title&lt;/h2&gt; @using (Html.BeginForm()) { &lt;fieldset&gt; &lt;legend&gt;RegisterModel&lt;/legend&gt; @Html.EditorForModel() &lt;p&gt; &lt;input type="submit" value="Create" /&gt; &lt;/p&gt; &lt;/fieldset&gt; } </code></pre> <p><strong>CreatePersonValidator.cs</strong></p> <pre><code>public class CreatePersonValidator : AbstractValidator&lt;CreatePersonModel&gt; { public CreatePersonValidator() { RuleFor(p =&gt; p.Name) .NotEmpty().WithMessage("campo obrigatório") .Length(5, 30).WithMessage("mínimo de {0} e máximo de {1} caractéres", 5, 30) .Must((p, n) =&gt; n.Any(c =&gt; c == ' ')).WithMessage("deve conter nome e sobrenome"); RuleFor(p =&gt; p.DateBirth) .NotEmpty().WithMessage("campo obrigatório") .LessThan(p =&gt; DateTime.Now).WithMessage("a data deve estar no passado"); RuleFor(p =&gt; p.Email) .NotEmpty().WithMessage("campo obrigatório") .EmailAddress().WithMessage("email inválido") .OnAnyFailure(p =&gt; p.Email = ""); } } </code></pre> <p><strong>When trying to create a person with an invalid date format:</strong></p> <p><img src="https://i.stack.imgur.com/pKtur.png" alt="Error trying to save the person"></p> <h2>Observations</h2> <p>As in my CreatePersonModel class the <code>DateBirth</code> property is a <code>DateTime</code> type, the asp.net MVC validation has done for me.</p> <p>But I want to customize the error message <strong>using the FluentValidation</strong>.</p> <p><strong>I do not want to change the type of property</strong> for various reasons such as:</p> <p>In a <code>CreatePersonValidator.cs</code> class, validation is to check if the date is in the past:</p> <pre><code>.LessThan (p =&gt; DateTime.Now) </code></pre> <h2>Question</h2> <p>How to customize the error message <strong>without using DataAnnotations</strong> (using FluentValidator).</p>
12,213,220
5
0
null
2011-10-15 13:07:05.35 UTC
5
2021-10-21 12:13:48.92 UTC
null
null
null
null
491,181
null
1
27
asp.net-mvc-3|datetime|fluentvalidation
44,812
<pre><code>public CreatePersonValidator() { RuleFor(courseOffering =&gt; courseOffering.StartDate) .Must(BeAValidDate).WithMessage("Start date is required"); //.... } private bool BeAValidDate(DateTime date) { return !date.Equals(default(DateTime)); } </code></pre>
7,728,878
Project dependency in Eclipse CDT
<p>I'm using eclipse for the first time. I'm a seasoned VisualStudio user, so I'm trying to find similar functionality in eclipse. I have two projects, A and B. Project A spits out libA.a when it's done compiling. Project B links against libA.a. Here is my problem.</p> <ol> <li>I compile project A then project B, everything is fine. </li> <li>I make a code change to project A that requires a build of project A. </li> <li>I try to build project B, but it states that no changes have been detected.</li> </ol> <p>How do I make project B aware of the output of project A?? Currently I'm having to do a clean build of project B for it to re-link against libA.a.</p> <p>Thanks.</p> <p>EDIT: In my ProjectB->Path and Symbols->References tab, I have project A checked. This doesn't relink after project A is rebuilt.</p>
9,070,500
6
1
null
2011-10-11 15:50:42.183 UTC
6
2022-05-19 07:32:24.357 UTC
null
null
null
null
318,811
null
1
30
c++|eclipse
17,134
<p>One can work around this problem by using the <code>touch</code> command.</p> <p>In Eclipse, as part of C/C++ Build/Settings is the tab 'Build Steps'. In the pre-build steps command line, enter <code>touch filename</code>.</p> <p><code>filename</code> is any file in your application. This could be the file with <code>main()</code>. This could be a special file just for this workaround, <code>touchdummy.c</code>, which can be a tiny file, which compiles quickly.</p> <p>When the application builds, even if you didn't change any sources, the <code>touch</code> command causes make to rebuild the application. If the library was rebuilt, then the application gets rebuilt with the new library.</p> <p>One can read about how <code>touch</code> affects the date/time of the file here. <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/touch.html" rel="nofollow noreferrer">http://pubs.opengroup.org/onlinepubs/9699919799/utilities/touch.html</a></p> <p>Edit: The exact command in Eclipse would be touch <code>${ProjDirPath}/src/main.c</code></p> <p>Edit: This command should work, but it appears that if the 'main' project did not change, the pre-build step is not executed. Also the <code>touch</code> command causes eclipse to prompt to reload the file it touched. A large annoyance.</p>
7,931,650
Adding elements to an xml file in C#
<p>I have an XML file formatted like this:</p> <pre><code>&lt;Snippets&gt; &lt;Snippet name="abc"&gt; &lt;SnippetCode&gt; testcode1 &lt;/SnippetCode&gt; &lt;/Snippet&gt; &lt;Snippet name="xyz"&gt; &lt;SnippetCode&gt; testcode2 &lt;/SnippetCode&gt; &lt;/Snippet&gt; ... &lt;/Snippets&gt; </code></pre> <p>I can successfully load the elements using XDocument, but I have trouble adding new elements (there are many functions and most of which I tried didn't work well for me). How would this be done? The new element would contain the snippet name tag and the snippet code tag. My previous approach was to open the file, and manually create the element using a string which although works, is a very bad idea.</p> <p>What I have tried:</p> <pre><code>XDocument doc = XDocument.Load(spath); XElement root = new XElement("Snippet"); root.Add(new XElement("name", "name goes here")); root.Add(new XElement("SnippetCode", "SnippetCode")); doc.Element("Snippets").Add(root); doc.Save(spath); </code></pre> <p>And the result is this:</p> <pre><code>&lt;Snippet&gt; &lt;name&gt;name goes here&lt;/name&gt; &lt;SnippetCode&gt; code goes here &lt;/SnippetCode&gt; &lt;/Snippet&gt; </code></pre> <p>It works fine except that the name tag is generated incorrectly. It should be </p> <pre><code>&lt;Snippet name="abc"&gt; </code></pre> <p>but I can't generate that properly.</p>
7,932,047
7
3
null
2011-10-28 15:50:19.453 UTC
8
2021-07-01 06:12:03.613 UTC
2018-02-10 14:03:01.473 UTC
null
181,087
null
509,060
null
1
40
c#|xml|file
123,044
<p>You're close, but you want name to be an <a href="https://docs.microsoft.com/en-us/dotnet/api/system.xml.linq.xattribute" rel="noreferrer"><code>XAttribute</code></a> rather than <a href="https://docs.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement" rel="noreferrer"><code>XElement</code></a>:</p> <pre><code> XDocument doc = XDocument.Load(spath); XElement root = new XElement("Snippet"); root.Add(new XAttribute("name", "name goes here")); root.Add(new XElement("SnippetCode", "SnippetCode")); doc.Element("Snippets").Add(root); doc.Save(spath); </code></pre>
7,719,412
How to ignore touch events and pass them to another subview's UIControl objects?
<p>I have a custom UIViewController whose UIView takes up a corner of the screen, but most of it is transparent except for the parts of it that have some buttons and stuff on it. Due to the layout of the objects on that view, the view's frame can cover up some buttons beneath it. I want to be able to ignore any touches on that view if they aren't touching anything important on it, but I seem to only be able to pass along actual touch events (touchesEnded/nextResponder stuff). If I have a UIButton or something like that which doesnt use touchesEnded, how do I pass the touch event along to that? </p> <p>I can't just manually figure out button selector to call, because this custom ViewController can be used on many different views. I basically need a way to call this:</p> <p><code>[self.nextResponder touchesEnded:touches withEvent:event];</code> </p> <p>on UIControl types as well. </p>
7,719,901
7
0
null
2011-10-10 22:30:25.08 UTC
29
2019-11-26 13:58:39.35 UTC
2011-10-11 00:16:24.427 UTC
null
30,461
null
830,698
null
1
74
ios|cocoa-touch|uikit|uiresponder
72,150
<p>Probably the best way to do this is to override <code>hitTest:withEvent:</code> in the view that you want to be ignoring touches. Depending on the complexity of your view hierarchy, there are a couple of easy ways to do this.</p> <p>If you have a reference to the view underneath the view to ignore:</p> <pre><code>- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { UIView *hitView = [super hitTest:point withEvent:event]; // If the hitView is THIS view, return the view that you want to receive the touch instead: if (hitView == self) { return otherView; } // Else return the hitView (as it could be one of this view's buttons): return hitView; } </code></pre> <p>If you don't have a reference to the view:</p> <pre><code>- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { UIView *hitView = [super hitTest:point withEvent:event]; // If the hitView is THIS view, return nil and allow hitTest:withEvent: to // continue traversing the hierarchy to find the underlying view. if (hitView == self) { return nil; } // Else return the hitView (as it could be one of this view's buttons): return hitView; } </code></pre> <p>I would recommend the first approach as being the most robust (if it's possible to obtain a reference to the underlying view).</p>
4,098,343
Entity Framework .Where method chaining
<p>Is there any difference between these two ways of querying the context?</p> <pre><code>Firm firm = base.context.Firms .Where(f =&gt; f.SomeId == someId) .Where(f =&gt; f.AnotherId == anotherId) .FirstOrDefault(); Firm firm = base.context.Firms .Where(f =&gt; f.SomeId == someId &amp;&amp; f.AnotherId == anotherId) .FirstOrDefault(); </code></pre> <p>It seems that chaining is perfectly fine to accomplish the AND condition. I don't believe you can chain OR statements. Is there a reason to prefer one over another, or scenarios when one is better/more efficient?</p>
4,098,366
3
0
null
2010-11-04 15:35:47.323 UTC
5
2010-11-04 16:57:09.083 UTC
2010-11-04 16:57:09.083 UTC
null
25,300
null
174,685
null
1
34
c#|entity-framework|entity-framework-4
61,636
<p>They should both produce the same end result (if I'm not mistaken) but I find the the second is more readable and better shows the original intent.</p> <hr /> <p><strong>Update</strong></p> <p>I just verified the above statement using LINQPad. Both queries will, in fact, product the same SQL.</p> <p>For example:</p> <pre><code>context.SomeTable.Where(c =&gt; c.ParentId == null) .Where(c =&gt; c.Name.Contains("F")) .Select(c =&gt; c.Name); </code></pre> <p>Produces:</p> <pre><code>SELECT [t0].[Name] FROM [SomeTable] AS [t0] WHERE ([t0].[Name] LIKE @p0) AND ([t0].[ParentId] IS NULL) </code></pre> <p>Which is the same SQL that is produced by:</p> <pre><code>context.SomeTable.Where(c =&gt; c.ParentId == null &amp;&amp; c.Name.Contains("F")) .Select(c =&gt; c.Name); </code></pre> <p><br /></p> <hr /> <p>You could also compact things a little more (which I find preferable for the same reasons as above):</p> <pre><code>var firm = base.context.Firms.FirstOrDefault(f =&gt; f.SomeId == someId &amp;&amp; f.AnotherId == anotherId); </code></pre>
4,410,873
How to control the margin size around subplots?
<p>I'm plotting 5 x 3 plots using subplot command, but there are massive margins around each subplot. </p> <p>How do I control the margin size around them?</p> <pre><code>figure; for c=1:15 subplot(5,3,c); imagesc(reshape(image(:,c), 360,480)); colormap gray; axis image; end </code></pre> <p><img src="https://i.stack.imgur.com/mUmxR.png" alt="alt text"></p>
4,410,983
5
1
null
2010-12-10 16:15:15.827 UTC
8
2021-02-01 22:24:18.66 UTC
2020-07-03 12:09:11.677 UTC
null
1,536,976
null
445,762
null
1
29
matlab|plot|subplot
19,434
<p>The problem is that Matlab assigns the <code>position</code> property of each axis such that there is space around each plot. You can either adjust the <code>position</code> property, or you can get <a href="http://www.mathworks.com/matlabcentral/fileexchange/3696-subaxis-subplot">subaxis</a> from the File Exchange and set up the subplots the way you like.</p>
4,453,764
How do I modify the session in the Django test framework
<p>My site allows individuals to contribute content in the absence of being logged in by creating a User based on the current session_key</p> <p>I would like to setup a test for my view, but it seems that it is not possible to modify the request.session:</p> <p>I'd like to do this:</p> <pre><code>from django.contrib.sessions.models import Session s = Session() s.expire_date = '2010-12-05' s.session_key = 'my_session_key' s.save() self.client.session = s response = self.client.get('/myview/') </code></pre> <p>But I get the error:</p> <pre><code>AttributeError: can't set attribute </code></pre> <p>Thoughts on how to modify the client session before making get requests? I have seen <a href="https://stackoverflow.com/questions/4252133/using-session-objects-in-django-while-testing">this</a> and it doesn't seem to work</p>
7,722,483
5
1
null
2010-12-15 19:01:59.433 UTC
8
2018-02-28 12:14:04.98 UTC
2017-05-23 12:26:09.273 UTC
null
-1
null
542,287
null
1
37
python|django|django-testing|django-sessions
17,187
<p>This is how I did it (inspired by a solution in <a href="http://blog.mediaonfire.com/?p=36" rel="noreferrer">http://blog.mediaonfire.com/?p=36</a>).</p> <pre><code>from django.test import TestCase from django.conf import settings from django.utils.importlib import import_module class SessionTestCase(TestCase): def setUp(self): # http://code.djangoproject.com/ticket/10899 settings.SESSION_ENGINE = 'django.contrib.sessions.backends.file' engine = import_module(settings.SESSION_ENGINE) store = engine.SessionStore() store.save() self.session = store self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key </code></pre> <p>After that, you may create your tests as:</p> <pre><code>class BlahTestCase(SessionTestCase): def test_blah_with_session(self): session = self.session session['operator'] = 'Jimmy' session.save() </code></pre> <p>etc...</p>
4,640,404
parseFloat rounding
<p>I have javascript function that automatically adds input fields together, but adding numbers like 1.35 + 1.35 + 1.35 gives me an output of 4.050000000000001, just as an example. How can I round the total to the second decimal instead of that long string? </p> <p>The input fields will have more than just the 1.35 example so I need the total to never have more than 2 points after the decimal. Here is the full working code:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; function Calc(className){ var elements = document.getElementsByClassName(className); var total = 0; for(var i = 0; i &lt; elements.length; ++i){ total += parseFloat(elements[i].value); } document.form0.total.value = total; } function addone(field) { field.value = Number(field.value) + 1; Calc('add'); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form name="form0" id="form0"&gt; 1: &lt;input type="text" name="box1" id="box1" class="add" value="0" onKeyUp="Calc('add')" onChange="updatesum()" onClick="this.focus();this.select();" /&gt; &lt;input type="button" value=" + " onclick="addone(box1);"&gt; &lt;br /&gt; 2: &lt;input type="text" name="box2" id="box2" class="add" value="0" onKeyUp="Calc('add')" onClick="this.focus();this.select();" /&gt; &lt;input type="button" value=" + " onclick="addone(box2);"&gt; &lt;br /&gt; &lt;br /&gt; Total: &lt;input readonly style="border:0px; font-size:14; color:red;" id="total" name="total"&gt; &lt;br /&gt; &lt;/form&gt; &lt;/body&gt;&lt;/html&gt; </code></pre> <p>Some things I have tried, which should work but I am clearly implementing them incorrectly:</p> <pre><code>for(var i = 0; i &lt; elements.length; ++i){ total += parseFloat(elements[i].value.toString().match(/^\d+(?:\.\d{0,2})?/)); var str = total.toFixed(2); </code></pre> <p>or</p> <pre><code>for(var i = 0; i &lt; elements.length; ++i){ total += parseFloat(elements[i].value * 100) / 100).toFixed(2) </code></pre> <p>Have also had no luck with <code>Math.floor</code></p>
4,640,423
5
5
null
2011-01-09 16:56:48.357 UTC
6
2016-01-20 07:42:47.637 UTC
2011-01-09 17:14:50.24 UTC
null
418,569
null
418,569
null
1
49
javascript|math|parsefloat
79,145
<p>Use <code>toFixed()</code> to round <code>num</code> to 2 decimal digits using the traditional rounding method. It will round 4.050000000000001 to 4.05.</p> <pre><code>num.toFixed(2); </code></pre> <p>You might prefer using <code>toPrecision()</code>, which will strip any resulting trailing zeros.</p> <p><a href="http://ideone.com/i8cjG" rel="noreferrer">Example</a>:</p> <pre><code>1.35+1.35+1.35 =&gt; 4.050000000000001 (1.35+1.35+1.35).toFixed(2) =&gt; 4.05 (1.35+1.35+1.35).toPrecision(3) =&gt; 4.05 // or... (1.35+1.35+1.35).toFixed(4) =&gt; 4.0500 (1.35+1.35+1.35).toPrecision(4) =&gt; 4.05 </code></pre> <p>Reference: <a href="http://www.mredkj.com/javascript/nfbasic2.html" rel="noreferrer">JavaScript Number Format - Decimal Precision</a></p>
4,371,178
Session-only cookie for Express.js
<p><a href="http://www.javascriptkit.com/javatutors/cookie.shtml" rel="noreferrer">http://www.javascriptkit.com/javatutors/cookie.shtml</a></p> <blockquote> <p>Session-only cookies, on the other hand, stores information in the browser memory, and is available for the duration of the browser session. In other words, the data stored inside a session cookie is available from the time of storage until the browser is closed. Moving from page to page during this time does not erase the data.</p> </blockquote> <p>How can I achieve this using <a href="https://en.wikipedia.org/wiki/Express.js" rel="noreferrer">Express.js</a>?</p>
4,371,696
6
2
null
2010-12-06 21:33:49.867 UTC
31
2021-10-15 01:03:26.99 UTC
2015-05-04 10:45:29.523 UTC
null
63,550
null
11,926
null
1
24
node.js|session-cookies|express
49,633
<p>The following is what I wanted (sort of). When I close browser the information is gone.</p> <pre><code>var express = require('express'); var app = express.createServer(); var MemoryStore = require('connect/middleware/session/memory'); app.use(express.bodyDecoder()); app.use(express.cookieDecoder()); app.get('/remember', function(req, res) { res.cookie('rememberme', 'yes', { expires: new Date() - 1, httpOnly: true }); }); app.get('/', function(req, res){ res.send('remember: ' + req.cookies.rememberme); }); app.listen(4000, '127.0.0.1'); </code></pre>
4,219,054
Xcode : Adding a project as a build dependency
<p>Im playing around with the <a href="https://github.com/soundcloud/cocoa-api-wrapper/tree/oauth2" rel="noreferrer">soundcloud api</a>, in its instructions it says to</p> <ul> <li>drag SoundCloudAPI.xcodeproj into your project</li> <li>add it as a build dependency</li> </ul> <p>I can drag the project in pretty easily, but how does one accomplish the next step?</p>
4,219,171
7
7
null
2010-11-18 20:07:45.87 UTC
12
2022-09-15 16:16:56.033 UTC
2019-05-28 16:44:45.723 UTC
null
2,415,822
null
100,652
null
1
55
xcode|xcodebuild|build-dependencies
113,899
<p>To add it as a dependency do the following:</p> <ul> <li>Highlight the added project in your file explorer within xcode. In the directory browser window to the right it should show a file with a .a extension. There is a checkbox under the target column (target icon), check it.</li> <li>Right-Click on your Target (under the targets item in the file explorer) and choose Get Info</li> <li>On the general tab is a Direct Dependencies section. Hit the plus button</li> <li>Choose the project and click Add Target</li> </ul>
4,084,669
How to generate a graph of the dependency between all modules of a Maven project?
<p>How to generate a graph of the dependency between all modules of a Maven project (excluding third party libraries like JUnit, SLF4J, etc.)? I couldn't find a way to include all modules into one graph using m2eclipse. Thanks.</p>
4,084,854
8
2
null
2010-11-03 06:26:46.967 UTC
16
2020-10-18 20:49:30.69 UTC
2013-02-04 15:00:53.673 UTC
null
521,799
user168237
null
null
1
55
java|maven-2
55,438
<p>If the <strong>Dependency Graph</strong> feature of m2eclipse doesn't cover your needs, maybe have a look at the <a href="http://mvnplugins.fusesource.org/maven/1.4/maven-graph-plugin/index.html" rel="noreferrer">Maven Graph Plugin</a> and in particular its <a href="http://mvnplugins.fusesource.org/maven/1.4/maven-graph-plugin/reactor-mojo.html" rel="noreferrer"><code>graph:reactor</code></a> goal.</p> <p><strong>UPDATE</strong>: the <strong>Dependency Graph</strong> feature was <em>removed in m2eclipse 1.0</em>. For more info see: <a href="https://stackoverflow.com/questions/6475927/maven-pom-editor-dependency-graph-missing">Maven POM-Editor: Dependency Graph missing</a></p>
4,598,702
Dynamically Changing log4j log level
<p>What are the different approaches for changing the log4j log level dynamically, so that I will not have to redeploy the application. Will the changes be permanent in those cases? </p>
4,598,829
9
4
null
2011-01-04 21:38:43.703 UTC
42
2022-08-02 10:22:12.86 UTC
2015-12-28 09:06:47.413 UTC
null
416,300
null
177,971
null
1
138
java|logging|log4j|runtime
183,045
<p>Changing the log level is simple; modifying other portions of the configuration will pose a more in depth approach.</p> <pre><code>LogManager.getRootLogger().setLevel(Level.DEBUG); </code></pre> <p>The changes are permanent through the life cyle of the <code>Logger</code>. On reinitialization the configuration will be read and used as setting the level at runtime does not persist the level change.</p> <p><strong>UPDATE:</strong> If you are using Log4j 2 you should remove the calls to <code>setLevel</code> per the <a href="http://logging.apache.org/log4j/2.x/manual/migration.html">documentation</a> as this can be achieved via implementation classes.</p> <blockquote> <p>Calls to logger.setLevel() or similar methods are not supported in the API. Applications should remove these. Equivalent functionality is provided in the Log4j 2 implementation classes but may leave the application susceptible to changes in Log4j 2 internals.</p> </blockquote>
4,279,420
Does use of final keyword in Java improve the performance?
<p>In Java we see lots of places where the <code>final</code> keyword can be used but its use is uncommon. </p> <p>For example:</p> <pre><code>String str = "abc"; System.out.println(str); </code></pre> <p>In the above case, <code>str</code> can be <code>final</code> but this is commonly left off. </p> <p>When a method is never going to be overridden we can use final keyword. Similarly in case of a class which is not going to be inherited.</p> <p>Does the use of final keyword in any or all of these cases really improve performance? If so, then how? Please explain. If the proper use of <code>final</code> really matters for performance, what habits should a Java programmer develop to make best use of the keyword?</p>
4,279,442
14
8
null
2010-11-25 17:08:50.96 UTC
91
2022-08-30 15:55:00.533 UTC
2020-09-25 05:51:21.853 UTC
null
1,746,118
null
300,829
null
1
398
java|performance|final
109,802
<p>Usually not. For virtual methods, HotSpot keeps track of whether the method has <em>actually</em> been overridden, and is able to perform optimizations such as inlining on the <em>assumption</em> that a method hasn't been overridden - until it loads a class which overrides the method, at which point it can undo (or partially undo) those optimizations.</p> <p>(Of course, this is assuming you're using HotSpot - but it's by far the most common JVM, so...)</p> <p>To my mind you should use <code>final</code> based on clear design and readability rather than for performance reasons. If you want to change anything for performance reasons, you should perform appropriate measurements before bending the clearest code out of shape - that way you can decide whether any extra performance achieved is worth the poorer readability/design. (In my experience it's almost never worth it; YMMV.)</p> <p>EDIT: As final fields have been mentioned, it's worth bringing up that they are often a good idea anyway, in terms of clear design. They also change the guaranteed behaviour in terms of cross-thread visibility: after a constructor has completed, any final fields are guaranteed to be visible in other threads immediately. This is probably the most common use of <code>final</code> in my experience, although as a supporter of Josh Bloch's "design for inheritance or prohibit it" rule of thumb, I should probably use <code>final</code> more often for classes...</p>
14,560,223
Unicode Conversion in c#
<p>i am trying to assign Unicode on string but it return "Привет" string as "Привет" But i need "Привет", i am converting by following function .</p> <pre><code>public string Convert(string str) { byte[] utf8Bytes = Encoding.UTF8.GetBytes(str); str = Encoding.UTF8.GetString(utf8Bytes); return str; } </code></pre> <p>what can i do for solve this problem to return "Привет".</p>
14,560,762
2
6
null
2013-01-28 10:42:25.393 UTC
null
2013-10-12 19:54:07.637 UTC
null
null
null
null
1,756,068
null
1
8
c#|unicode-string
55,565
<p><code>П</code> is Unicode character <a href="http://www.fileformat.info/info/unicode/char/41f/index.htm">0x041F</a>, and its UTF-8 encoding is <code>0xD0 0x9F</code> resulting in <a href="http://forumtreff.pytalhost.de/viewtopic.php?f=47&amp;t=66&amp;start=2"><code>П</code></a>.</p> <p>Since the function only returns the input parameter, as commenters already discussed, I conclude that your original input string is actually in UTF-8, and you want to convert it into native .Net string.</p> <p>Where does the original string come from? </p> <p>Instead of reading the input into a C# <code>string</code>, change your code to read a <code>byte[]</code>, and then call <code>Encoding.UTF8.GetString(inputUtf8ByteArray)</code>.</p>
14,907,809
Drag and drop table row from one tabs table to another tabs table - Jquery
<p>I have two tabs(built using boostrap) and each tab has its own table. </p> <p>I need to drag table row from one tab and drop into another tabs table. While dragging i want to open the tab under cursor before dropping into table. Any help appreciated.</p> <p>This is my HTML code </p> <pre><code>&lt;div class="tabbable" &gt; &lt;ul class="nav nav-tabs" id="my-tabs"&gt; &lt;li class="active"&gt;&lt;a href="#tab1" data-toggle="tab"&gt; Tab1 &lt;/a&gt;&lt;/li&gt; &lt;li class=""&gt;&lt;a href="#tab2" data-toggle="tab"&gt; Tab2 &lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="tab-content"&gt; &lt;div class="tab-pane active" id="tab1"&gt; &lt;table id='table-draggable1'&gt; &lt;thead&gt; &lt;th&gt;col1&lt;/th&gt; &lt;th&gt;col2&lt;/th&gt; &lt;th&gt;col3&lt;/th&gt; &lt;th&gt;col4&lt;/th&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;256&lt;/td&gt; &lt;td&gt;668&lt;/td&gt; &lt;td&gt;100.95&lt;/td&gt; &lt;td&gt;1.82&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;256&lt;/td&gt; &lt;td&gt;668&lt;/td&gt; &lt;td&gt;100.95&lt;/td&gt; &lt;td&gt;1.82&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;div class="tab-pane" id="tab2"&gt; &lt;table id='table-draggable2'&gt; &lt;thead&gt; &lt;th&gt;col1&lt;/th&gt; &lt;th&gt;col2&lt;/th&gt; &lt;th&gt;col3&lt;/th&gt; &lt;th&gt;col4&lt;/th&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;256&lt;/td&gt; &lt;td&gt;668&lt;/td&gt; &lt;td&gt;100.95&lt;/td&gt; &lt;td&gt;1.82&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;256&lt;/td&gt; &lt;td&gt;668&lt;/td&gt; &lt;td&gt;100.95&lt;/td&gt; &lt;td&gt;1.82&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; </code></pre> <p>This is my JS code</p> <pre><code>$('.table-draggable1 tbody').draggable(); $('#my-tabs &gt; li').droppable({ over:function(event, ui){ console.log(event.target); }, drop:function(event,ui){ } }); </code></pre>
14,983,173
2
4
null
2013-02-16 06:52:26.983 UTC
9
2020-02-13 18:48:47.637 UTC
2013-02-27 00:02:03.647 UTC
null
244,811
null
107,748
null
1
9
jquery|jquery-ui|twitter-bootstrap|drag-and-drop
26,422
<p>Here is a solution that combines jqueryUI droppable with sortable to satisfy your requirement:</p> <pre><code>$(document).ready(function() { $tabs = $(".tabbable"); $('.nav-tabs a').click(function(e) { e.preventDefault(); $(this).tab('show'); }) $( "tbody.connectedSortable" ).sortable({ connectWith: ".connectedSortable", items: "&gt; tr:not(:first)", appendTo: $tabs, helper:"clone", zIndex: 99999, start: function(){ $tabs.addClass("dragging") }, stop: function(){ $tabs.removeClass("dragging") } }); var $tab_items = $( "ul:first &gt; li", $tabs ).droppable({ accept: ".connectedSortable tr", hoverClass: "ui-state-hover", over: function( event, ui ) { var $item = $( this ); $item.find("a").tab("show"); } }); }); </code></pre> <p><strong>EDIT:</strong> <a href="http://jsfiddle.net/martyk/Kzf62/85/"><strong>Link to jsfiddle</strong></a></p>
14,501,094
Hibernate could not locate named parameter even if it exist
<p>Hibernate Keeps detecting </p> <pre><code>org.hibernate.QueryParameterException: could not locate named parameter [name] </code></pre> <p>even though it exist. here's my hql</p> <pre><code>Query query = sess().createQuery("from UserProfile where firstName LIKE '%:name%'").setParameter("name", name); </code></pre> <p>Why does hibernate keeps throwing that exception? even though the parameter exist?</p>
14,501,143
2
1
null
2013-01-24 12:12:27.787 UTC
3
2018-05-24 16:02:00.303 UTC
null
null
null
null
962,206
null
1
22
java|hibernate|hql|named-parameters
50,560
<p>Should be like this:</p> <pre><code>Query query = sess().createQuery("from UserProfile where firstName LIKE :name") .setParameter("name", "%"+name+"%"); </code></pre> <p>In your case <code>':name'</code> is actual string Hibernate will search for. If you need to have a real named parameter, you need to have just <code>:name</code>. </p> <p>Thus <code>%</code> should be passed as a value of <code>:name</code> and Hibernate will substitute <code>:name</code> with actual value. </p> <p>Note, that if your value contains <code>%</code> and you want it to be an actual letter instead of wildcard, you'll have to escape it, <a href="http://fisheye.jtalks.org/browse/~br=master/Poulpe/poulpe-model/src/main/java/org/jtalks/poulpe/model/dao/utils/SqlLikeEscaper.java?r=4e390d7d4e1ed18701d2e2463fc693b7ed367819" rel="noreferrer">here is</a> an example of escaper-class.</p>
14,601,676
The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties
<p>Using this code in <strong>Entity Framework</strong> I receive the following error. I need to get all the rows for a specific date, <code>DateTimeStart</code> is of type DataType in this format <code>2013-01-30 12:00:00.000</code></p> <p>Code:</p> <pre><code> var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference) .Where(x =&gt; x.DateTimeStart.Date == currentDateTime.Date); </code></pre> <hr> <p>Error:</p> <blockquote> <p>base {System.SystemException} = {"The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported."}</p> </blockquote> <p>Any ideas how to fix it?</p>
14,601,775
11
1
null
2013-01-30 10:25:03.797 UTC
31
2022-07-13 12:09:24.377 UTC
2020-02-15 00:12:02.753 UTC
null
5,519,709
null
379,008
null
1
162
linq|entity-framework-4|linq-to-entities
120,004
<p><code>DateTime.Date</code> cannot be converted to SQL. Use <a href="http://msdn.microsoft.com/en-us/library/dd395596.aspx" rel="noreferrer">EntityFunctions.TruncateTime</a> method to get date part.</p> <pre><code>var eventsCustom = eventCustomRepository .FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference) .Where(x =&gt; EntityFunctions.TruncateTime(x.DateTimeStart) == currentDate.Date); </code></pre> <p>UPDATE: As @shankbond mentioned in comments, in Entity Framework 6 <a href="http://msdn.microsoft.com/en-us/library/system.data.objects.entityfunctions%28v=vs.110%29.aspx" rel="noreferrer"><code>EntityFunctions</code></a> is obsolete, and you should use <a href="http://msdn.microsoft.com/en-us/library/system.data.entity.dbfunctions%28v=vs.113%29.aspx" rel="noreferrer"><code>DbFunctions</code></a> class, which is shipped with Entity Framework.</p>
14,876,677
Enable and disable TextBox with a checkbox in visual basic
<p>I've 6 TextBox and 6 CheckBox. Now I want to disable the TextBox1 with a CheckBox1 and reactivate it with the Same CheckBox. How a can do it? </p> <p>Edit1 15.55 14/02/2013</p> <p>I have done so to solve my problem!</p> <blockquote> <p><code> Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged <br>If CheckBox1.Checked = True Then <br>TextBox1.Enabled = False <br>ElseIf CheckBox1.Checked = False Then <br>TextBox1.Enabled = True End If End Sub </code>`</p> </blockquote>
14,878,915
5
6
null
2013-02-14 14:08:43.253 UTC
null
2021-03-19 15:25:57.55 UTC
2013-02-14 14:56:04.647 UTC
null
2,066,084
null
2,066,084
null
1
-2
vb.net|checkbox|textbox
74,847
<p>This will work, just add more for the other check boxes</p> <pre><code>Private Sub CheckBox1_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBox1.CheckedChanged If CheckBox1.Checked = True Then TextBox1.Enabled = True Else TextBox1.Enabled = False End If End Sub </code></pre> <p>What this does: if checkbox1 is check, the checked_changed event fires and the code inside is ran. The if statement looks to see if the checkbox is checked or not. If it is checked, then it sets the textbox1 to enabled, if not it sets it to disabled. Be sure to set the enabled property to either enabled or disabled when you create your program. If you want it to be enabled from the start, that is the default....otherwise set it to disabled in its properties view.</p>
2,538,486
How do you calculate the number of weeks between two dates?
<p>How do you calculate the number of weeks between two dates?</p> <p>for example as follows</p> <pre><code>Declare @StartDate as DateTime = "01 Jan 2009"; Declare @EndDate as DateTime = "01 June 2009"; @StartDate and @EndDate </code></pre>
2,538,524
2
1
2010-03-29 14:10:51.163 UTC
2010-03-29 14:10:51.163 UTC
1
2014-09-04 01:18:27.313 UTC
2014-03-28 10:31:01.77 UTC
null
2,240,243
null
296,653
null
1
9
tsql
46,217
<p>Use the Datediff function. <code>datediff(ww,@startdate,@enddate)</code></p> <p>the ww tells the function what units you require the difference to be counted in.</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms189794.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms189794.aspx</a></p>
44,500,176
Setting up Gradle for api 26 (Android)
<p>Since I have upgraded my Nexus 5x to Android O DP3 I am not able to test my applications. I get the error for not having configured my Gradle-file to work with the new API-level (26).</p> <p>So I changed this and the dependencies, but I keep getting errors on ALL my support libraries like</p> <pre><code>Failed to resolve: com.android.support:design:26.0.0-beta2 </code></pre> <p>Clicking on</p> <pre><code>Install repository and sync project </code></pre> <p>Pops up a progressdialog for downloading the right dependency but does not remove the error. Cleaning up project, installing repositories and then rebuilding the project won't work either.</p> <h3>appcompat-v7</h3> <p>On appcompat-v7:26.0.0-beta2 I get (before even a Gradle sync) squickly lines with the error:</p> <pre><code>When using a compileSdkVersion older than android-O revision 2, the support library version must be 26.0.0-alpha1 or lower (was 26.0.0-beta2) </code></pre> <p>Can someone help me get the gradle file to be configured correctly for Android API 26? Any help would be appreciated.</p> <p>PS: I'm using Gradle 3.0.0-alpha3 at the moment but get the same error on Gradle 2.3.2</p> <p>My Gradle file:</p> <pre><code>apply plugin: 'com.android.application' android { compileSdkVersion 26 buildToolsVersion '26.0.0' defaultConfig { applicationId &quot;********&quot; minSdkVersion 21 targetSdkVersion 26 versionCode 3 versionName &quot;2.0&quot; } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:26.0.0-beta2' compile 'com.android.support:design:26.0.0-beta2' compile 'com.github.bumptech.glide:glide:3.7.0' compile 'com.squareup.picasso:picasso:2.5.2' compile 'com.android.support:cardview-v7:26.0.0-beta2' compile 'com.android.support:recyclerview-v7:26.0.0-beta2' compile 'com.redbooth:WelcomeCoordinator:1.0.1' compile 'com.github.kittinunf.fuel:fuel-android:1.4.0' compile 'com.pkmmte.view:circularimageview:1.1' compile 'com.ramotion.foldingcell:folding-cell:1.1.0' } </code></pre>
44,503,639
6
1
null
2017-06-12 13:02:09.5 UTC
16
2019-07-14 20:05:58.937 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
8,148,900
null
1
59
android|gradle|build.gradle|android-support-library|android-8.0-oreo
109,631
<p>Have you added the <a href="https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-0-beta1" rel="noreferrer">google maven endpoint</a>?</p> <blockquote> <p><strong>Important:</strong> The support libraries are now available through Google's Maven repository. You do not need to download the support repository from the SDK Manager. For more information, see <a href="https://developer.android.com/topic/libraries/support-library/setup.html#add-library" rel="noreferrer">Support Library Setup</a>. </p> </blockquote> <p>Add the endpoint to your <em>build.gradle</em> file:</p> <pre><code>allprojects { repositories { jcenter() maven { url 'https://maven.google.com' } } } </code></pre> <p>Which can be replaced by the shortcut <code>google()</code> since Android Gradle v3:</p> <pre><code>allprojects { repositories { jcenter() google() } } </code></pre> <p>If you already have any maven url inside <code>repositories</code>, you can add the reference after them, i.e.:</p> <pre><code>allprojects { repositories { jcenter() maven { url 'https://jitpack.io' } maven { url 'https://maven.google.com' } } } </code></pre>
41,746,028
PropTypes in a TypeScript React Application
<p>Does using <code>React.PropTypes</code> make sense in a TypeScript React Application or is this just a case of "belt and suspenders"?</p> <p>Since the component class is declared with a <code>Props</code> type parameter:</p> <pre><code>interface Props { // ... } export class MyComponent extends React.Component&lt;Props, any&gt; { ... } </code></pre> <p>is there any real benefit to adding</p> <pre><code>static propTypes { myProp: React.PropTypes.string } </code></pre> <p>to the class definition?</p>
43,187,969
6
0
null
2017-01-19 15:45:55.153 UTC
48
2022-06-28 20:20:44.983 UTC
null
null
null
null
96,233
null
1
218
reactjs|typescript|react-proptypes
113,084
<p>There's usually not much value to maintaining both your component props as TypeScript types and <code>React.PropTypes</code> at the same time.</p> <p>Here are some cases where it is useful to do so:</p> <ul> <li>Publishing a package such as a component library that will be used by plain JavaScript.</li> <li>Accepting and passing along external input such as results from an API call.</li> <li>Using data from a library that may not have adequate or accurate typings, if any.</li> </ul> <p>So, usually it's a question of how much you can trust your compile time validation.</p> <p>Newer versions of TypeScript can now infer types based on your <code>React.PropTypes</code> (<code>PropTypes.InferProps</code>), but the resulting types can be difficult to use or refer to elsewhere in your code.</p>
24,795,198
Get all child elements
<p>In Selenium with Python is it possible to get all the children of a WebElement as a list?</p>
24,795,416
4
0
null
2014-07-17 05:00:43.343 UTC
29
2022-04-02 23:05:26.547 UTC
2018-05-03 14:03:31.537 UTC
null
2,154,065
null
1,672,428
null
1
105
python|selenium|selenium-webdriver
225,007
<p>Yes, you can achieve it by <code>find_elements_by_css_selector("*")</code> or <code>find_elements_by_xpath(".//*")</code>.</p> <p>However, this doesn't sound like a valid use case to find <strong>all children</strong> of an element. It is an expensive operation to get all direct/indirect children. Please further explain what you are trying to do. There should be a better way.</p> <pre><code>from selenium import webdriver driver = webdriver.Firefox() driver.get("http://www.stackoverflow.com") header = driver.find_element_by_id("header") # start from your target element, here for example, "header" all_children_by_css = header.find_elements_by_css_selector("*") all_children_by_xpath = header.find_elements_by_xpath(".//*") print 'len(all_children_by_css): ' + str(len(all_children_by_css)) print 'len(all_children_by_xpath): ' + str(len(all_children_by_xpath)) </code></pre>
38,572,888
How to use orderby() with descending order in Spark window functions?
<p>I need a window function that partitions by some keys (=column names), orders by another column name and returns the rows with top x ranks. </p> <p>This works fine for ascending order:</p> <pre><code>def getTopX(df: DataFrame, top_x: String, top_key: String, top_value:String): DataFrame ={ val top_keys: List[String] = top_key.split(", ").map(_.trim).toList val w = Window.partitionBy(top_keys(1),top_keys.drop(1):_*) .orderBy(top_value) val rankCondition = "rn &lt; "+top_x.toString val dfTop = df.withColumn("rn",row_number().over(w)) .where(rankCondition).drop("rn") return dfTop } </code></pre> <p>But when I try to change it to <code>orderBy(desc(top_value))</code> or <code>orderBy(top_value.desc)</code> in line 4, I get a syntax error. What's the correct syntax here? </p>
38,575,271
3
0
null
2016-07-25 16:21:43.73 UTC
5
2022-09-15 10:10:52.873 UTC
2022-09-15 10:10:52.873 UTC
null
2,753,501
null
1,325,071
null
1
30
scala|apache-spark|apache-spark-sql
88,120
<p>There are two versions of <code>orderBy</code>, one that works with strings and one that works with <code>Column</code> objects (<a href="https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.expressions.WindowSpec">API</a>). Your code is using the first version, which does not allow for changing the sort order. You need to switch to the column version and then call the <code>desc</code> method, e.g., <code>myCol.desc</code>.</p> <p>Now, we get into API design territory. The advantage of passing <code>Column</code> parameters is that you have a lot more flexibility, e.g., you can use expressions, etc. If you want to maintain an API that takes in a string as opposed to a <code>Column</code>, you need to convert the string to a column. There are a number of ways to do this and the easiest is to use <code>org.apache.spark.sql.functions.col(myColName)</code>.</p> <p>Putting it all together, we get</p> <pre><code>.orderBy(org.apache.spark.sql.functions.col(top_value).desc) </code></pre>
31,370,456
Check if string contains space
<p>I am trying to check if a sting has a space in it. The following is not working for me.</p> <pre><code>if (skpwords.contains(lcase(query)) And Mid(query, InStrRev(query, " "))) then end if </code></pre>
31,371,140
3
0
null
2015-07-12 17:17:44.42 UTC
4
2015-07-13 05:09:31.477 UTC
null
null
null
user2867494
null
null
1
8
vbscript
39,979
<p>The proper way to check if a string contains a character (or substring) is to use the <code>InStr()</code> function. It will return the one-based index of the position within the string where the text was found. So, a return value > 0 indicates a successful find. For example:</p> <pre><code>If InStr(query, " ") &gt; 0 Then ' query contains a space End If </code></pre> <p>The <code>InStr()</code> function can optionally take three or four arguments as well. If you want to specify a starting index, use the three-argument version:</p> <pre><code>If InStr(3, query, " ") &gt; 0 Then ' query contains a space at or after the 3rd character End If </code></pre> <p>If you want to perform a case-insensitive search (the default is case-sensitive), then use the four-argument version. Note that there is no three-argument version of this function that allows you to specify case sensitivity. If you want to perform a case-insensitive search, you must always supply the starting index, even if you want to start your search at the beginning (<code>1</code>):</p> <pre><code>If InStr(1, query, "A", vbTextCompare) &gt; 0 Then ' query contains "a" or "A" End If </code></pre>
50,185,681
Explanation needed about Parallel Full GC for G1
<p>As part of the java JDK10 JEP307 was <a href="http://openjdk.java.net/jeps/307" rel="noreferrer">Parallel Full GC for G1</a> realsed.</p> <p>I've tried to grasp its description, but I am still not confident that I got the idea properly.</p> <p>my doubt was is it related to <strong>Concurrent Garbage</strong></p>
50,188,760
6
0
null
2018-05-05 04:22:49.493 UTC
9
2018-08-13 06:47:47.733 UTC
null
null
null
null
6,750,645
null
1
15
java|garbage-collection
3,366
<p>As a simplified explanation - garbage collectors have two possible collection types, "incremental" and "full". Incremental collection is the better of the two for staying out the way, as it'll do a little bit of work every so often. Full collection is often more disruptive, as it takes longer and often has to halt the entire program execution while it's running.</p> <p>Because of this, most modern GCs (including G1) will generally try to ensure that in normal circumstances, the incremental collection will be enough and a full collection will never be required. However, if lots of objects across different generations are being made eligible for garbage collection in unpredictable ways, then occasionally a full GC may be inevitable.</p> <p>At present, the G1 full collection implementation is only single threaded. And that's where that JEP comes in - it aims to parallelize it, so that when a full GC does occur it's faster on systems that can support parallel execution.</p>
30,249,324
How to get Java to wait for user Input
<p>I am trying to make an IRC bot for my channel. I would like the bot to be able to take commands from the console. In an attempt to make the main loop wait for the user to input something I added the loop:</p> <pre><code>while(!userInput.hasNext()); </code></pre> <p>this did not seem to work. I have heard of BufferedReader but I have never used it and am not sure if this would be able to solve my problem. </p> <pre><code>while(true) { System.out.println("Ready for a new command sir."); Scanner userInput = new Scanner(System.in); while(!userInput.hasNext()); String input = ""; if (userInput.hasNext()) input = userInput.nextLine(); System.out.println("input is '" + input + "'"); if (!input.equals("")) { //main code } userInput.close(); Thread.sleep(1000); } </code></pre>
30,249,614
1
0
null
2015-05-14 23:50:11.3 UTC
2
2015-05-15 00:33:39.277 UTC
2015-05-15 00:33:39.277 UTC
null
2,350,771
null
2,350,771
null
1
12
java
59,214
<p>There is no need for you to check for available input waiting and sleeping until there is since <code>Scanner.nextLine()</code> will block until a line is available.</p> <p>Have a look at this example I wrote to demonstrate it:</p> <pre><code>public class ScannerTest { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); try { while (true) { System.out.println("Please input a line"); long then = System.currentTimeMillis(); String line = scanner.nextLine(); long now = System.currentTimeMillis(); System.out.printf("Waited %.3fs for user input%n", (now - then) / 1000d); System.out.printf("User input was: %s%n", line); } } catch(IllegalStateException | NoSuchElementException e) { // System.in has been closed System.out.println("System.in was closed; exiting"); } } } </code></pre> <blockquote> <p>Please input a line<br> <em>hello</em><br> Waited 1.892s for user input<br> User input was: hello<br> Please input a line<br> <em>^D</em><br> System.in was closed; exiting </p> </blockquote> <p>So all you have to do is to use <code>Scanner.nextLine()</code> and your app will wait until the user has entered a newline. You also don't want to define your Scanner inside the loop and close it since you're going to use it again in the next iteration:</p> <pre><code>Scanner userInput = new Scanner(System.in); while(true) { System.out.println("Ready for a new command sir."); String input = userInput.nextLine(); System.out.println("input is '" + input + "'"); if (!input.isEmpty()) { // Handle input } } } </code></pre>
35,177,797
What exactly is Fragmented mp4(fMP4)? How is it different from normal mp4?
<p>Media Source Extension (<strong>MSE</strong>) needs fragmented mp4 for playback in the browser.</p>
35,180,327
2
0
null
2016-02-03 12:59:34.393 UTC
47
2022-08-30 09:31:08.547 UTC
2021-04-24 14:00:21.74 UTC
null
205,608
null
5,160,432
null
1
78
media|mp4|media-source|fmp4
70,761
<p>A fragmented MP4 contains a series of segments which can be requested individually if your server supports byte-range requests.</p> <h2>Boxes aka Atoms</h2> <p>All MP4 files use an object oriented format that contains <a href="http://atomicparsley.sourceforge.net/mpeg-4files.html" rel="noreferrer">boxes aka atoms</a>.</p> <p>You can view a representation of the boxes in your MP4 using an online tool such as <a href="http://mp4parser.com/" rel="noreferrer">MP4 Parser</a> or if you're using Windows, <a href="https://mp4explorer.codeplex.com/" rel="noreferrer">MP4 Explorer</a>. Let's compare a normal MP4 with one that is fragmented:</p> <h2>Non-Fragmented MP4</h2> <p>This screenshot (from <a href="http://mp4parser.com/" rel="noreferrer">MP4 Parser</a>) shows an MP4 that hasn't been fragmented and quite simply has one massive <code>mdat</code> (Movie Data) box.</p> <p><a href="https://i.stack.imgur.com/WGdG4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WGdG4.png" alt="Representation of boxes within a normal, non fragmented MP4, generated using MP4 Parser"></a></p> <p>If we were building a video player that supports adaptive bitrate, we might need to know the byte position of the 10 sec mark in a 0.5Mbps and a 1Mbps file in order to switch the video source between the two files at that moment. Determining this exact byte position within one massive <code>mdat</code> in each respective file is not trivial.</p> <h2>Fragmented MP4</h2> <p>This screenshot shows a fragmented MP4 which has been segmented using <a href="https://gpac.wp.mines-telecom.fr/mp4box/dash/" rel="noreferrer">MP4Box</a> with the <code>onDemand</code> profile.</p> <p><a href="https://i.stack.imgur.com/K76lh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/K76lh.png" alt="Representation of boxes within a fragmented MP4, generated using MP4 Parser"></a></p> <p>You'll notice the <code>sidx</code> and series of <a href="https://stackoverflow.com/a/14558271/619602"><code>moof</code>+<code>mdat</code></a> boxes. The <code>sidx</code> is the Segment Index and stores meta data of the precise byte range locations of the <code>moof</code>+<code>mdat</code> segments.</p> <p>Essentially, you can independently load the <code>sidx</code> (its byte-range will be defined in the accompanying <code>.mpd</code> Media Presentation Descriptor file) and then choose which segments you'd like to subsequently load and add to the MSE <a href="https://msdn.microsoft.com/en-us/library/windows/apps/dn298840.aspx" rel="noreferrer">SourceBuffer</a>.</p> <p>Importantly, each segment is created at a regular interval of your choosing (ie. every 5 seconds), so the segments can have temporal alignment across files of different bitrates, making it easy to adapt the bitrate during playback. </p>
29,468,404
gyp WARN EACCES user "root" does not have permission to access the dev dir
<p>Trying to </p> <pre><code>sudo npm install protractor -g </code></pre> <p>and the same notorious error/warning again (googled to no avail):</p> <pre><code>gyp WARN EACCES user "root" does not have permission to access the dev dir "/Users/dmitrizaitsev/.node-gyp/0.12.0" </code></pre> <p>What seems to happen is that <code>node version 0.12.0</code> is downloaded and rebuilt, again and again during the same installation, despite of being the current node version on my machine:</p> <pre><code>node -v v0.12.0 </code></pre> <p>Questions:</p> <ul> <li><p>The directory "/Users/dmitrizaitsev/.node-gyp/0.12.0" is actually missing! Why such a misleading message?</p></li> <li><p>Why was this directory not created neither during the <code>node v0.12.0</code> nor during the previous successful rebuild with <code>node-gyp</code>?</p></li> <li><p>(Obviously) How can I prevent this from happening?</p></li> </ul> <p>I run Mac OSX 10.8.5 if that is of any importance.</p>
29,787,502
3
0
null
2015-04-06 09:17:10.997 UTC
20
2021-12-31 08:13:28.163 UTC
null
null
null
null
1,614,973
null
1
51
node.js|permissions|npm|root
39,984
<p>UPDATE. There is a better way - changing <code>npm</code>'s default global directory to user sub-directory to which you already have correct permissions, so no need to mess with system file's permissions or ownership in first place.</p> <p>As recommended in <a href="https://docs.npmjs.com/getting-started/fixing-npm-permissions" rel="noreferrer">https://docs.npmjs.com/getting-started/fixing-npm-permissions</a>:</p> <blockquote> <ol> <li>Make a directory for global installations:</li> </ol> </blockquote> <pre><code>mkdir ~/.npm-global </code></pre> <blockquote> <ol start="2"> <li>Configure npm to use the new directory path:</li> </ol> </blockquote> <pre><code>npm config set prefix '~/.npm-global' </code></pre> <blockquote> <ol start="3"> <li>Open or create a <code>~/.profile</code> (or <code>~/.bash_profile</code> etc) file and add this line (at the end of the file):</li> </ol> </blockquote> <pre><code>export PATH=~/.npm-global/bin:$PATH </code></pre> <blockquote> <ol start="4"> <li>On the command line, update your system variables:</li> </ol> </blockquote> <pre><code>source ~/.profile </code></pre> <p><strong>or</strong> <code>source ~/.bash_profile</code></p> <p>See also Sindre Sorhus's guide on the topic: <a href="https://github.com/sindresorhus/guides/blob/master/npm-global-without-sudo.md" rel="noreferrer">https://github.com/sindresorhus/guides/blob/master/npm-global-without-sudo.md</a></p> <hr> <p>Have now figured what was wrong:</p> <p>The directory had wrong permissions - it was not <strong>writable</strong> (which would have been a better error message than "accessible").</p> <p>And because it was not writable, a temporary directory was used and deleted after every use, which is why the whole download had to run again and again.</p> <p>The solution is to set user permissions with </p> <pre><code>sudo chown -R $USER &lt;directory&gt; </code></pre> <p>and never <code>sudo npm</code> again. It seems whenever you run <code>sudo npm</code>, all subdirectories created get wrong permissions, which will lead to problems later on.</p> <p><a href="https://stackoverflow.com/a/29787215/1614973">See here for more details</a>.</p>
26,399,989
MongoDb aggregation $match error : "Arguments must be aggregate pipeline operators"
<p>I can get all stats of the site with <code>aggregation</code> but I want to it for a certain user, like <code>$where</code>.</p> <p>All stats:</p> <pre><code>games.aggregate([{ $group: { _id: '$id', game_total: { $sum: '$game_amount'}, game_total_profit: { $sum: '$game_profit'}} }]).exec(function ( e, d ) { console.log( d ) }) </code></pre> <p>When I try to use <code>$match</code> operator, I'm getting error :</p> <pre><code>games.aggregate([{ $match: { '$game_user_id' : '12345789' }, $group: { _id: '$id', game_total: { $sum: '$game_amount'}, game_total_profit: { $sum: '$game_profit'}} }]).exec(function ( e, d ) { console.log( d ) }) Arguments must be aggregate pipeline operators </code></pre> <p>What am I missing?</p>
26,400,101
4
0
null
2014-10-16 08:47:23.083 UTC
6
2021-11-30 17:45:27.563 UTC
2017-06-28 03:21:19.36 UTC
null
2,313,887
null
3,681,056
null
1
23
javascript|node.js|mongodb|mongodb-query|aggregation-framework
44,146
<p>Pipeline stages are separate BSON documents in the array:</p> <pre><code>games.aggregate([ { $match: { 'game_user_id' : '12345789' } }, { $group: { _id: '$id', game_total: { $sum: '$game_amount'}, game_total_profit: { $sum: '$game_profit'}} }} ]).exec(function ( e, d ) { console.log( d ) }); </code></pre> <p>So the Array or <code>[]</code> bracket notation in JavaScript means it expects a "list" to be provided. This means a list of "documents" which are generally specified in JSON notation with <code>{}</code> braces.</p>
33,997,361
How to convert degree minute second to degree decimal
<p>I receive the latitude and longitude from GPS with this format:</p> <p>Latitude : 78°55'44.29458&quot;N</p> <p>I need convert this data to:</p> <p>latitude: 78.9288888889</p> <p>I found this code here: <a href="http://en.proft.me/2015/09/20/converting-latitude-and-longitude-decimal-values-p/" rel="nofollow noreferrer">link</a></p> <pre><code>import re def dms2dd(degrees, minutes, seconds, direction): dd = float(degrees) + float(minutes)/60 + float(seconds)/(60*60); if direction == 'E' or direction == 'S': dd *= -1 return dd; def dd2dms(deg): d = int(deg) md = abs(deg - d) * 60 m = int(md) sd = (md - m) * 60 return [d, m, sd] def parse_dms(dms): parts = re.split('[^\d\w]+', dms) lat = dms2dd(parts[0], parts[1], parts[2], parts[3]) return (lat) dd = parse_dms(&quot;78°55'44.33324&quot;N ) print(dd) </code></pre> <p>It is working for for this format</p> <pre><code>dd = parse_dms(&quot;78°55'44.33324'N&quot; ) </code></pre> <p>but it is not working for my datafromat. Can anyone help me to solve this problem?</p>
33,997,602
8
0
null
2015-11-30 11:18:20.41 UTC
6
2021-05-29 13:51:03.913 UTC
2021-05-28 16:39:58.633 UTC
null
1,352,749
null
5,111,380
null
1
16
python|parsing|gis
44,638
<p>The problem is that the seconds 44.29458 are split at <code>.</code>.</p> <p>You could either define the split characters directly (instead of where <em>not</em> to split):</p> <pre><code>&gt;&gt;&gt; re.split('[°\'"]+', """78°55'44.29458"N""") ['78', '55', '44.29458', 'N'] </code></pre> <p>or leave the regular expression as it is and merge parts 2 and 3:</p> <pre><code>dms2dd(parts[0], parts[1], parts[2] + "." + parts[3], parts[4]) </code></pre> <hr> <p><strong>Update:</strong></p> <p>Your method call <code>dd = parse_dms("78°55'44.33324"N )</code> is a syntax error. Add the closing <code>"</code> and escape the other one. Or use tripple quotes for the string definition:</p> <pre><code>parse_dms("""78°55'44.29458"N""") </code></pre>
47,640,550
What is &'a in Rust Language
<p>I read <a href="https://doc.rust-lang.org/reference/types.html" rel="noreferrer">here</a> that </p> <blockquote> <p>A shared reference type is written <code>&amp;type</code>, or <code>&amp;'a type</code> when you need to specify an explicit lifetime. </p> </blockquote> <p>Understood <code>&amp;</code> is for <code>shared reference</code> but did not understand what is the difference between <code>type</code> and <code>'a</code> in Rust language</p> <p>In <a href="https://rustbyexample.com/hello/print/print_debug.html" rel="noreferrer">another location</a> I read this code:</p> <pre><code>#[derive(Debug)] struct Person&lt;'a&gt; { name: &amp;'a str, age: u8 } fn main() { let name = "Peter"; let age = 27; let peter = Person { name, age }; // Pretty print println!("{:#?}", peter); } </code></pre> <p>What does <code>'a</code> in the <code>struct Person&lt;'a&gt; { }</code> means? and can I build the same <code>struct</code> using <code>struct Person&lt;'type&gt; { }</code> or <code>struct Person&lt;T&gt; { }</code>?</p> <p>And what is the meaning of <code>name: &amp;'a str</code>?</p> <p>And how can I re-code it, if want to avoid using the <code>&lt;'a&gt;</code></p>
47,641,166
1
0
null
2017-12-04 19:26:37.713 UTC
10
2021-01-23 13:54:56.797 UTC
2017-12-04 20:29:39.833 UTC
null
2,441,637
null
2,441,637
null
1
35
rust
21,861
<p>I found <a href="https://doc.rust-lang.org/book/second-edition/ch10-03-lifetime-syntax.html#lifetime-annotation-syntax" rel="noreferrer">this</a> and <a href="https://doc.rust-lang.org/book/second-edition/ch19-02-advanced-lifetimes.html" rel="noreferrer">this</a> and <a href="https://doc.rust-lang.org/1.6.0/book/lifetimes.html" rel="noreferrer">this</a> and <a href="https://doc.rust-lang.org/1.6.0/book/strings.html" rel="noreferrer">this</a> that explains my question.</p> <p>The <code>'a</code> reads ‘the lifetime a’. Technically, every reference has some lifetime associated with it, but the compiler lets you elide (i.e. omit, see &quot;<a href="https://doc.rust-lang.org/1.6.0/book/lifetimes.html#lifetime-elision" rel="noreferrer">Lifetime Elision</a>&quot;) them in common cases.</p> <pre><code>fn bar&lt;'a&gt;(...) </code></pre> <p>A function can have ‘generic parameters’ between the <code>&lt;&gt;</code>s, of which lifetimes are one kind. The <code>&lt;&gt;</code> is used to declare lifetimes. This says that bar has one lifetime, 'a.</p> <p>Rust has two main types of strings: <code>&amp;str</code> and <code>String</code>. The <code>&amp;str</code> are called <code>‘string slices’</code>. A string slice has a fixed size, and cannot be mutated. It is a reference to a sequence of UTF-8 bytes.</p> <pre><code>let greeting = &quot;Hello there.&quot;; // greeting: &amp;'static str </code></pre> <p>&quot;Hello there.&quot; is a <code>string literal</code> and its type is <code>&amp;'static str</code>. A string literal is a string slice that is statically allocated, meaning that it’s saved inside our compiled program, and exists for the entire duration it runs. The greeting binding is a reference to this statically allocated string. Any function expecting a string slice will also accept a string literal.</p> <p>In the above example</p> <pre><code>struct Person&lt;'a&gt; { } </code></pre> <p>requires to contain <code>&lt;'a&gt;</code> as the <code>name</code> is defined using:</p> <pre><code>name: &amp;'a str, </code></pre> <p>which is called by:</p> <pre><code>let name = &quot;Peter&quot;; </code></pre> <p>If interested to avoid the usage of <code>'a</code> then the above code can be re-written as:</p> <pre><code>#[derive(Debug)] struct Person { // instead of: struct Person&lt;'a&gt; { name: String, // instead of: name: &amp;'a str age: u8 } fn main() { let name = String::from(&quot;Peter&quot;); // instead of: let name = &quot;Peter&quot;; which is &amp;'static str let age = 27; let peter = Person { name, age }; // Pretty print println!(&quot;{:#?}&quot;, peter); } </code></pre> <p>As mentioned by @DimitrisSfounis in the comments, in short, &quot;Why is 'a there?&quot; ---- Because the struct definition ties it to a referenced object (in this case, every struct Person instance is referencing a &amp;str) you want to specificly declare an arbitary lifetime and tie these two things together: You want a struct Person instance to only live as long as its referenced object (hence Person&lt;'a&gt; and name: &amp;'a str) so dangling references after each other's death is avoided.</p>
46,930,242
Angular io (4) *ngFor first and last
<p>I am trying to tell whether an item in an <code>*ngFor</code> is the first or last element to style a container. Is there a way to do something like this?</p> <pre><code>&lt;md-expansion-panel *ngFor="let item of items" *ngClass="{ 'first' : item.isFirst }"&gt; &lt;content&gt;&lt;/content&gt; &lt;/md-expansion-panel&gt; </code></pre> <p>Thanks for any help offered!</p>
46,930,341
2
0
null
2017-10-25 10:40:08.303 UTC
12
2021-12-01 23:34:29.56 UTC
2020-12-28 09:04:10.323 UTC
null
3,980,621
null
7,574,618
null
1
44
angular|typescript|ngfor|angular-template
51,994
<p>Inside the <code>ngFor</code> you have access to several variables:</p> <ul> <li>index: number: The index of the current item in the iterable.</li> <li>first: boolean: True when the item is the first item in the iterable.</li> <li>last: boolean: True when the item is the last item in the iterable.</li> <li>even: boolean: True when the item has an even index in the iterable.</li> <li>odd: boolean: True when the item has an odd index in the iterable.</li> </ul> <p>So:</p> <pre><code>&lt;md-expansion-panel *ngFor="let item of items; first as isFirst" *ngClass="{ 'first' : isFirst }"&gt; &lt;content&gt;&lt;/content&gt; &lt;/md-expansion-panel&gt; </code></pre> <p>Documentation at <a href="https://angular.io/api/common/NgForOf" rel="noreferrer">https://angular.io/api/common/NgForOf</a> gives this example:</p> <pre><code>&lt;li *ngFor="let user of userObservable | async as users; index as i; first as isFirst"&gt; {{i}}/{{users.length}}. {{user}} &lt;span *ngIf="isFirst"&gt;default&lt;/span&gt; &lt;/li&gt; </code></pre>
6,165,813
Using my own prebuilt shared library in an Android NDK project
<p>I came across this post that is almost what I need:</p> <p><a href="https://stackoverflow.com/questions/2943828/how-to-compile-a-static-library-using-the-android-ndk">How to compile a static library using the Android NDK?</a></p> <blockquote> <p>Basically, there are certain parts in my project that are never updated, so I am trying to avoid having them built every single time I update the Android.mk file to add something.</p> </blockquote> <p>The above answer shows how to get some of the code built into a separate static lib, but when I try to pre-build the above code in a separate Android.mk file, It won't build by itself. This seems a little redundant... If I have to build them both at the same time, then what's the point of making a separate static lib anyways?</p> <p>And if I change Android.mk in the separate project to read:</p> <blockquote> <p>include $(BUILD_SHARED_LIBRARY)</p> </blockquote> <p>and include it like this in the main project:</p> <blockquote> <p>LOCAL_SHARED_LIBRARIES := libMyaccessories.so</p> </blockquote> <p>then I get unresolved reference to(function name), probably because it can't find the shared lib(which is in the calling path)</p> <blockquote> <p>Can anyone help me out with this?</p> </blockquote>
6,166,046
1
0
null
2011-05-29 03:40:05.413 UTC
9
2011-05-29 05:00:27.62 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
402,041
null
1
14
c++|android|build|android-ndk
20,183
<p>In the documentation of Android.mk, check the <code>PREBUILT_SHARED_LIBRARY</code> script description. Put the .so file in <code>lib</code> (not <code>libs</code>) directory and write an Android.mk file next to it that looks something like:</p> <pre><code>LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := Myaccessories LOCAL_SRC_FILES := libMyaccessories.so LOCAL_C_INCLUDES := $(LOCAL_PATH)/../jni/include include $(PREBUILT_SHARED_LIBRARY) </code></pre>
24,884,985
Context initialization failed Spring
<p>I am making a sample project following the steps of a website and is giving me a weird bug and I can not fix it, and I'm desperate :(.</p> <p><img src="https://i.stack.imgur.com/rvVRa.png" alt="enter image description here"></p> <p>HelloController.java:</p> <pre><code>package com.companyname.springapp.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class HelloController { protected final Log logger = LogFactory.getLog(getClass()); @RequestMapping(value="/hello.htm") public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.info("Returning hello view"); return new ModelAndView("hello.jsp"); } } </code></pre> <p>HelloControllerTest.java</p> <pre><code>package com.companyname.springapp.web; import static org.junit.Assert.*; import org.junit.Test; import org.springframework.web.servlet.ModelAndView; public class HelloControllerTest { @Test public void testHandleRequestView() throws Exception{ HelloController controller = new HelloController(); ModelAndView modelAndView = controller.handleRequest(null, null); assertEquals("hello.jsp", modelAndView.getViewName()); } } </code></pre> <p>app-config.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"&gt; &lt;!-- Scans the classpath of this application for @Components to deploy as beans --&gt; &lt;context:component-scan base-package="com.companyname.springapp.web" /&gt; &lt;!-- Configures the @Controller programming model --&gt; &lt;mvc:annotation-driven /&gt; &lt;/beans&gt; </code></pre> <p>web.xml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"&gt; &lt;display-name&gt;Springapp&lt;/display-name&gt; &lt;servlet&gt; &lt;servlet-name&gt;springapp&lt;/servlet-name&gt; &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/spring/app-config.xml&lt;/param-value&gt; &lt;/init-param&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;springapp&lt;/servlet-name&gt; &lt;url-pattern&gt;*.htm&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;/web-app&gt; </code></pre> <p>hello.jsp</p> <pre><code>&lt;html&gt; &lt;head&gt;&lt;title&gt;Hello :: Spring Application&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;h1&gt;Hello - Spring Application&lt;/h1&gt; &lt;p&gt;Greetings.&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>pom.xml</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.companyname&lt;/groupId&gt; &lt;artifactId&gt;springapp&lt;/artifactId&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;name&gt;springapp Maven Webapp&lt;/name&gt; &lt;url&gt;http://maven.apache.org&lt;/url&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;4.11&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-core&lt;/artifactId&gt; &lt;version&gt;${org.springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt; &lt;version&gt;${org.springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;servlet-api&lt;/artifactId&gt; &lt;version&gt;2.5&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;finalName&gt;springapp&lt;/finalName&gt; &lt;/build&gt; &lt;properties&gt; &lt;org.springframework.version&gt;3.2.0.RELEASE&lt;/org.springframework.version&gt; &lt;/properties&gt; &lt;/project&gt; </code></pre> <p>Error:</p> <pre><code>SEVERE: Context initialization failed java.lang.IllegalArgumentException at org.springframework.asm.ClassReader.&lt;init&gt;(Unknown Source) at org.springframework.asm.ClassReader.&lt;init&gt;(Unknown Source) at org.springframework.asm.ClassReader.&lt;init&gt;(Unknown Source) at org.springframework.core.type.classreading.SimpleMetadataReader.&lt;init&gt;(SimpleMetadataReader.java:52) at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80) at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:101) at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:76) at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:298) at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300) at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300) at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:230) at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:153) at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:130) at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:285) at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:223) at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:630) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461) at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:647) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:598) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:661) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:517) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:458) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5210) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5493) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) jul 22, 2014 12:06:12 PM org.apache.catalina.core.ApplicationContext log SEVERE: StandardWrapper.Throwable java.lang.IllegalArgumentException at org.springframework.asm.ClassReader.&lt;init&gt;(Unknown Source) at org.springframework.asm.ClassReader.&lt;init&gt;(Unknown Source) at org.springframework.asm.ClassReader.&lt;init&gt;(Unknown Source) at org.springframework.core.type.classreading.SimpleMetadataReader.&lt;init&gt;(SimpleMetadataReader.java:52) at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80) at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:101) at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:76) at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:298) at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300) at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300) at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:230) at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:153) at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:130) at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:285) at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:223) at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:630) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461) at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:647) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:598) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:661) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:517) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:458) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5210) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5493) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) jul 22, 2014 12:06:12 PM org.apache.catalina.core.StandardContext loadOnStartup SEVERE: Servlet /springapp threw load() exception java.lang.IllegalArgumentException at org.springframework.asm.ClassReader.&lt;init&gt;(Unknown Source) at org.springframework.asm.ClassReader.&lt;init&gt;(Unknown Source) at org.springframework.asm.ClassReader.&lt;init&gt;(Unknown Source) at org.springframework.core.type.classreading.SimpleMetadataReader.&lt;init&gt;(SimpleMetadataReader.java:52) at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80) at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:101) at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:76) at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:298) at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300) at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300) at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:230) at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:153) at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:130) at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:285) at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:223) at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:630) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461) at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:647) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:598) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:661) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:517) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:458) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5210) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5493) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) </code></pre> <p>And the web where I am following the steps is: </p> <p><a href="http://www.uv.es/grimo/teaching/SpringMVCv3PasoAPaso/part1.html" rel="noreferrer">http://www.uv.es/grimo/teaching/SpringMVCv3PasoAPaso/part1.html</a></p> <p>thank you very much.</p>
24,885,065
2
0
null
2014-07-22 10:32:06.397 UTC
1
2021-03-27 20:06:16.497 UTC
null
null
null
null
2,699,302
null
1
8
java|xml|spring|maven
51,509
<p>It looks like you may be trying to use Java 8 with Spring 3.2.0, which doesn't support it. You will need to use Spring 4 instead, or downgrade to Java 7.</p>
28,503,808
Allocating memory in Flash for user data (STM32F4 HAL)
<p>I'm trying to use the internal flash of an STM32F405 to store a bunch of user settable bytes that remain after rebooting.</p> <p>I'm using:</p> <pre><code>uint8_t userConfig[64] __attribute__((at(0x0800C000))); </code></pre> <p>to allocate memory for the data I want to store.</p> <p>When the program starts, I check to see if the first byte is set to <code>0x42</code>, if not, i set it using:</p> <pre><code>HAL_FLASH_Unlock(); HAL_FLASH_Program(TYPEPROGRAM_BYTE, &amp;userConfig[0], 0x42); HAL_FLASH_Lock(); </code></pre> <p>After that I check the value in <code>userConfig[0]</code> and I see <code>0x42</code>... Great!</p> <p>When I hit reset, however, and look at the location again, it's not <code>0x42</code> anymore...</p> <p>Any idea where I'm going wrong? I've also tried:</p> <pre><code>#pragma location = 0x0800C00 volatile const uint8_t userConfig[64] </code></pre> <p>but I get the same result..</p>
28,505,272
1
0
null
2015-02-13 16:09:37.893 UTC
13
2018-07-18 10:03:49.513 UTC
2018-07-18 10:03:49.513 UTC
null
7,640,269
null
3,794,508
null
1
14
microcontroller|stm32|stm32f4discovery|flash-memory
20,504
<p>Okay I found an answer on <a href="https://my.st.com/public/STe2ecommunities/mcu/Lists/cortex_mx_stm32/Flat.aspx?RootFolder=%2Fpublic%2FSTe2ecommunities%2Fmcu%2FLists%2Fcortex_mx_stm32%2FHow%20to%20allocate%20variable%20in%20Flash%20to%20desired%20address&amp;FolderCTID=0x01200200770978C69A1141439FE559EB459D7580009C4E14902C3CDE46A77F0FFD06506F5B&amp;currentviews=7799">the ST forums</a> thanks to <code>clive1</code>. This example works for an STM32F405xG.</p> <p>First we need to modify the memory layout in the linker script file (.ld file)</p> <p>Modify the existing FLASH and add a new line for DATA. Here I've allocated all of <code>section 11</code>.</p> <pre><code>MEMORY { FLASH (RX) : ORIGIN = 0x08000000, LENGTH = 1M-128K DATA (RWX) : ORIGIN = 0x080E0000, LENGTH = 128k ... ... } </code></pre> <p><a href="https://sourceware.org/binutils/docs/ld/MEMORY.html#MEMORY">Manual for editing linker files on the sourceware website</a></p> <p>In the same file, we need to add:</p> <pre><code>.user_data : { . = ALIGN(4); *(.user_data) . = ALIGN(4); } &gt; DATA </code></pre> <p>This creates a <code>section</code> called <code>.user_data</code> that we can address in the program code.</p> <p>Finally, in your .c file add:</p> <pre><code>__attribute__((__section__(".user_data"))) const uint8_t userConfig[64] </code></pre> <p>This specifies that we wish to store the <code>userConfig</code> variable in the <code>.user_data</code> section and <code>const</code> makes sure the address of <code>userConfig</code> is kept static.</p> <p>Now, to write to this area of flash during runtime, you can use the stm32f4 stdlib or HAL flash driver.</p> <p>Before you can write to the flash, it has to be erased (all bytes set to 0xFF) The instructions for the HAL library say nothing about doing this for some reason...</p> <pre><code>HAL_FLASH_Unlock(); __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGSERR ); FLASH_Erase_Sector(FLASH_SECTOR_11, VOLTAGE_RANGE_3); HAL_FLASH_Program(TYPEPROGRAM_WORD, &amp;userConfig[index], someData); HAL_FLASH_Lock(); </code></pre>
25,390,446
How to replicate the blurred text in Notification Center (iOS 8)
<p>I am playing with TodayExtension in iOS 8 and I wondered how to apply that blur effect to the Text or to buttons. I already figured out that it has something to do with UIVisualEffectView. But I don't know how to use it.</p> <p>I am using Objective-C</p> <p>Can anyone explain it to me how to achieve this?</p> <p>Thanks, David</p> <p><img src="https://i.stack.imgur.com/Mgxw9.jpg" alt="enter image description here"></p>
25,398,791
5
0
null
2014-08-19 18:25:52.533 UTC
14
2016-09-16 07:39:12.287 UTC
2014-09-10 21:58:37.037 UTC
null
111,783
null
1,766,321
null
1
21
uilabel|ios8|blur
9,547
<p><strong>Updated Answer for iOS 10</strong></p> <p>In iOS 10, you can use <code>widgetPrimaryVibrancyEffect</code> and <code>widgetSecondaryVibrancyEffect</code> to automatically return a <code>UIVibrancyEffect</code> object.</p> <p>Check out the documentation <a href="https://developer.apple.com/reference/uikit/uivibrancyeffect/1771278-widgetprimaryvibrancyeffect" rel="nofollow">here</a> and <a href="https://developer.apple.com/reference/uikit/uivibrancyeffect/1771277-widgetsecondary" rel="nofollow">here</a>.</p> <p><strong>Answer for iOS 9</strong></p> <p>Use this code to apply a vibrancy effect to your whole widget:</p> <pre><code>UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:[UIVibrancyEffect notificationCenterVibrancyEffect]]; effectView.frame = self.view.bounds effectView.autoresizingMask = self.view.autoresizingMask; __strong UIView *oldView = self.view; self.view = effectView; [effectView.contentView addSubview:oldView]; self.view.tintColor = [UIColor clearColor]; </code></pre>
25,097,779
Getting stock's historical data
<p>We would like to check on stock's historical data, using HTTP request, and get JSON. </p> <p>Using the yahoo API ,I found it hard to not only clearly understand the HTTP request fields, but also <strong>to get the data of a certain day</strong> (not average for each day, but the values during a certain day), with this :</p> <p><code>http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22AAPL%22%20and%20startDate%20%3D%20%222012-09-11%22%20and%20endDate%20%3D%20%222014-02-11%22&amp;format=json&amp;diagnostics=true&amp;env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&amp;callback=</code></p> <p><strong>1.</strong> There is no explanation anywhere of how to set each field (also not at Yahoo console).</p> <p><strong>2.</strong> You can't set a certain day, and get its values .</p> <p>Is there a stable solution other than Yahoo which is now free? Or, can someone help me understand what all these junk signs in the request?</p>
25,318,216
1
0
null
2014-08-02 17:45:14.32 UTC
10
2017-05-29 17:03:04.847 UTC
2014-08-14 22:18:00.943 UTC
null
25,704
null
721,925
null
1
12
yahoo-finance|algorithmic-trading
19,800
<h2>Ad-hypothesis in 2.: "<em>You <strong>can't</strong> set a certain day, and get his values</em>" ... well, YOU CAN:</h2> <p>The &lt;<em>URL</em>> per-se contains data selection tags included:</p> <pre><code>http://query.yahooapis.com/v1/public/yql?q= select * from yahoo.finance.historicaldata where symbol = "AAPL" and startDate = "2012-09-11" and endDate = "2014-02-11" &amp;format=json &amp;diagnostics=true &amp;env=store://datatables.org/alltableswithkeys &amp;callback= </code></pre> <p>so to get just the last few ( a pair of, notice the interpretation of endDate in results ) days between 2014-08-10 .. 2014-08-12 on "AAPL":</p> <hr> <pre><code> "results":{ "quote":[ { "Symbol":"AAPL", "Date":"2014-08-12", "Open":"96.04", "High":"96.88", "Low":"95.61", "Close":"95.97", "Volume":"33795000", "Adj_Close":"95.97" }, { "Symbol":"AAPL", "Date":"2014-08-11", "Open":"95.27", "High":"96.08", "Low":"94.84", "Close":"95.99", "Volume":"36585000", "Adj_Close":"95.99" } ] } </code></pre> <p><em>( a full Y! response transcript )</em></p> <pre><code>{ "query":{ "count":2, "created":"2014-08-14T21:32:41Z", "lang":"en-EN", "diagnostics":{ "url":[ { "execution-start-time":"0", "execution-stop-time":"1", "execution-time":"1", "content":"http://www.datatables.org/yahoo/finance/yahoo.finance.historicaldata.xml" }, { "execution-start-time":"5", "execution-stop-time":"16", "execution-time":"11", "content":"http://ichart.finance.yahoo.com/table.csv?g=d&amp;f=2014&amp;e=12&amp;c=2014&amp;b=10&amp;a=7&amp;d=7&amp;s=AAPL" }, { "execution-start-time":"18", "execution-stop-time":"28", "execution-time":"10", "content":"http://ichart.finance.yahoo.com/table.csv?g=d&amp;f=2014&amp;e=12&amp;c=2014&amp;b=10&amp;a=7&amp;d=7&amp;s=AAPL" } ], "publiclyCallable":"true", "cache":[ { "execution-start-time":"4", "execution-stop-time":"4", "execution-time":"0", "method":"GET", "type":"MEMCACHED", "content":"91a0664b4e7cf29d40cce123239fec85" }, { "execution-start-time":"17", "execution-stop-time":"18", "execution-time":"1", "method":"GET", "type":"MEMCACHED", "content":"31dd9633be8581af77baa442f314c921" } ], "query":[ { "execution-start-time":"5", "execution-stop-time":"17", "execution-time":"12", "params":"{url=[http://ichart.finance.yahoo.com/table.csv?g=d&amp;f=2014&amp;e=12&amp;c=2014&amp;b=10&amp;a=7&amp;d=7&amp;s=AAPL]}", "content":"select * from csv(0,1) where url=@url" }, { "execution-start-time":"18", "execution-stop-time":"28", "execution-time":"10", "params":"{columnsNames=[Date,Open,High,Low,Close,Volume,Adj_Close], url=[http://ichart.finance.yahoo.com/table.csv?g=d&amp;f=2014&amp;e=12&amp;c=2014&amp;b=10&amp;a=7&amp;d=7&amp;s=AAPL]}", "content":"select * from csv(2,0) where url=@url and columns=@columnsNames" } ], "javascript":{ "execution-start-time":"3", "execution-stop-time":"29", "execution-time":"25", "instructions-used":"34359", "table-name":"yahoo.finance.historicaldata" }, "user-time":"31", "service-time":"23", "build-version":"0.2.2666" }, "results":{ "quote":[ { "Symbol":"AAPL", "Date":"2014-08-12", "Open":"96.04", "High":"96.88", "Low":"95.61", "Close":"95.97", "Volume":"33795000", "Adj_Close":"95.97" }, { "Symbol":"AAPL", "Date":"2014-08-11", "Open":"95.27", "High":"96.08", "Low":"94.84", "Close":"95.99", "Volume":"36585000", "Adj_Close":"95.99" } ] } } } </code></pre> <h2>Nota Bene:</h2> <p>One may detect, that the fully-fledged query processing re-wraps data-source request sourced and post-processed from just:</p> <p><strong><code>http://ichart.finance.yahoo.com/table.csv?g=d&amp;f=2014&amp;e=12&amp;c=2014&amp;b=10&amp;a=7&amp;d=7&amp;s=AAPL</code></strong></p> <p>yielding:</p> <pre><code>Date,Open,High,Low,Close,Volume,Adj Close 2014-08-12,96.04,96.88,95.61,95.97,33795000,95.97 2014-08-11,95.27,96.08,94.84,95.99,36585000,95.99 </code></pre> <hr> <p><strong><em>Per aspera Ad Astra ...</em></strong> ( ... more GHz, more TB, more Gbps, more ..., more ..., Moore! )</p>
18,496,341
How can I center a UIView programmatically on top of an existing UIView using Autolayout?
<p>In case of a successful Foursquare checkin, my iPhone app shows adds a view on top of the view which is shown.</p> <p>I want the view to be centered on the X and Y and for it to have a definite width and height using autolayout, but I'm not sure which constraints to add programmatically. I know how to do it in Storyboard, but I'm not sure what exactly to type in code to do the same as this view is added later in response to a successful action in the app.</p> <p>I can't get it working properly and the UIView has a nib which it loads with loadNibNamed:.</p> <pre><code>SuccessView *successfulCheckInView = [[SuccessView alloc] initWithFrame:CGRectZero]; successfulCheckInView.placeNameLabel.text = properVenue.name; successfulCheckInView.placeAddressLabel.text = properVenue.address; successfulCheckInView.delegate = self; [self.ownerVC.view addSubview:successfulCheckInView]; </code></pre>
18,496,683
1
1
null
2013-08-28 19:13:00.797 UTC
1
2016-11-28 15:53:41.003 UTC
null
null
null
null
75,350
null
1
31
iphone|ios|uiview|autolayout
33,283
<p>Try this:</p> <pre><code>NSLayoutConstraint *xCenterConstraint = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:view2 attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]; [superview addConstraint:xCenterConstraint]; NSLayoutConstraint *yCenterConstraint = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:view2 attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]; [superview addConstraint:yCenterConstraint]; </code></pre> <p>Updated for Swift:</p> <pre><code>NSLayoutConstraint(item: view1, attribute: .centerX, relatedBy: .equal, toItem: view2, attribute: .centerX, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: view1, attribute: .centerY, relatedBy: .equal, toItem: view2, attribute: .centerY, multiplier: 1, constant: 0).isActive = true </code></pre>
51,621,400
What is difference between release notes and changelog?
<p>Software packages are often shipped with <strong>changelog</strong> and/or <strong>release notes</strong>. What's the difference between them? Should they be both included with release of a new version?</p>
53,069,727
2
0
null
2018-07-31 20:16:43.657 UTC
5
2018-10-30 17:22:49.907 UTC
null
null
null
null
2,079,061
null
1
29
version-control|release|release-management|software-distribution
12,925
<p>To directly answer your question, you can include both in your software release.</p> <p><a href="https://en.wikipedia.org/wiki/Release_notes" rel="noreferrer">Release notes</a> are a set of documents delivered to customers with the intent to provide a verbose description of the release of a new version of a product or service. These artifacts are generally created by a marketing team or product owner and contain feature summaries, bug fixes, use cases, and other support material. The release notes are used as a quick guide to what changed outside of the user documentation.</p> <p>Conversely, <a href="https://en.wikipedia.org/wiki/Changelog" rel="noreferrer">changelogs</a> are comprehensive lists of the new features, enhancements, bugs, and other changes in reverse chronological order. Changelogs usually link to specific issues or feature requests within a change management system and also may include links to the developer who supplied the change.</p>
2,946,338
How do I programmatically compile and instantiate a Java class?
<p>I have the class name stored in a property file. I know that the classes store will implement IDynamicLoad. How do I instantiate the class dynamically?</p> <p>Right now I have</p> <pre><code> Properties foo = new Properties(); foo.load(new FileInputStream(new File("ClassName.properties"))); String class_name = foo.getProperty("class","DefaultClass"); //IDynamicLoad newClass = Class.forName(class_name).newInstance(); </code></pre> <p>Does the newInstance only load compiled .class files? How do I load a Java Class that is not compiled?</p>
2,946,402
3
1
null
2010-05-31 22:53:11.753 UTC
62
2020-10-17 04:22:31.33 UTC
2011-02-23 12:04:55.807 UTC
null
157,882
null
82,368
null
1
74
java|reflection|dynamic-loading
63,631
<blockquote> <p><em>How do I load a Java Class that is not compiled?</em></p> </blockquote> <p>You need to compile it first. This can be done programmatically with the <a href="http://docs.oracle.com/javase/8/docs/api/javax/tools/package-summary.html" rel="noreferrer"><code>javax.tools</code> API</a>. This only requires the <a href="http://www.oracle.com/technetwork/java/javase/downloads/index.html" rel="noreferrer">JDK</a> being installed at the local machine on top of JRE. </p> <p>Here's a basic kickoff example (leaving obvious exception handling aside):</p> <pre><code>// Prepare source somehow. String source = "package test; public class Test { static { System.out.println(\"hello\"); } public Test() { System.out.println(\"world\"); } }"; // Save source in .java file. File root = new File("/java"); // On Windows running on C:\, this is C:\java. File sourceFile = new File(root, "test/Test.java"); sourceFile.getParentFile().mkdirs(); Files.write(sourceFile.toPath(), source.getBytes(StandardCharsets.UTF_8)); // Compile source file. JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); compiler.run(null, null, null, sourceFile.getPath()); // Load and instantiate compiled class. URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() }); Class&lt;?&gt; cls = Class.forName("test.Test", true, classLoader); // Should print "hello". Object instance = cls.newInstance(); // Should print "world". System.out.println(instance); // Should print "test.Test@hashcode". </code></pre> <p>Which yields like</p> <pre><code>hello world test.Test@ab853b </code></pre> <p>Further use would be more easy if those classes <code>implements</code> a certain interface which is already in the classpath. </p> <pre><code>SomeInterface instance = (SomeInterface) cls.newInstance(); </code></pre> <p>Otherwise you need to involve the <a href="http://docs.oracle.com/javase/tutorial/reflect/" rel="noreferrer">Reflection API</a> to access and invoke the (unknown) methods/fields.</p> <hr> <p>That said and unrelated to the actual problem:</p> <pre><code>properties.load(new FileInputStream(new File("ClassName.properties"))); </code></pre> <p>Letting <code>java.io.File</code> rely on current working directory is recipe for portability trouble. Don't do that. Put that file in classpath and use <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/ClassLoader.html#getResourceAsStream-java.lang.String-" rel="noreferrer"><code>ClassLoader#getResourceAsStream()</code></a> with a classpath-relative path. </p> <pre><code>properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("ClassName.properties")); </code></pre>
2,431,025
USE case to Class Diagram - How do I?
<p>I would like your guidance on how to create classes and their relationships (generalization, association, aggregation and composition) accurately from my USE case diagram (please see below). </p> <p>I am trying to create this class diagram so I can use it to create a simple online PHP application that allows the user to register an account, login and logout, and store, search and retrieve data from a MySQL database.</p> <p>Are my classes correct? Or should I create more classes? And if so, what classes are missing? What relationships should I use when connecting the register, login, logout, search_database and add_to_database to the users? </p> <p>I'm new to design patterns and UML class diagrams but from my understanding, the association relationship relates one object with another object; the aggregation relationship is a special kind of association that allows "a part" to belong to more than one "whole" (e.g. a credit card and its PIN - the PIN class can also be used in a debit card class); and a composition relationship is a special form of aggregation that allows each part to belong to only one whole at a time. </p> <p>I feel like I have left out some classes or something because I just can't seem to find the relationships from my understanding of relationships.</p> <p>Any assistance will be really appreciated. Thanks in advance.</p> <p>USE CASE DIAGRAM</p> <p><a href="https://i.stack.imgur.com/lyunq.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/lyunq.gif" alt="alt text"></a></p> <p>USE case explanation:</p> <p><strong>Register</strong> Any users can create an account by registering. The system will validate the user name and password and will reject them if either they are missing or if the user name is already taken.</p> <p><strong>Login</strong> Any users can login only if they have already registered. Their user name and password will be validated in the same manner as when registering an account.</p> <p><strong>Search Database</strong> Any users will beable to input a searchkey of datatype string and the system will open the database, search for the searchkey, and return true or false depending on whether or not the searchkey was found, and close the database.</p> <p><strong>Add data to database</strong> All users will be able to input some data, the system will open the database, store the data, return true or false depending on whether or not the data was stored, and close the database.</p> <p><strong>Logout</strong> The user will press the logout button, and the system will logout the user</p> <p><strong>Delete from database</strong> Only the administrator can delete data from the database.</p> <p><strong>Delete regular users</strong> Only the administrator can delete a regular user</p> <p>CLASS DIAGRAM</p> <p><a href="https://i.stack.imgur.com/0R197.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/0R197.gif" alt="alt text"></a></p>
2,431,186
4
0
null
2010-03-12 07:01:03.383 UTC
17
2015-12-14 11:37:53.77 UTC
2015-08-17 16:28:05.503 UTC
null
4,374,739
null
225,998
null
1
17
design-patterns|oop|class-design|uml
77,727
<p>First, if you're determined to go down a modeling path, then I'd recommend a book by Rosenberg and Stephens, <a href="https://rads.stackoverflow.com/amzn/click/com/1590597745" rel="noreferrer" rel="nofollow noreferrer">Use Case Driven Object Modeling with UML</a>. This goes through a process exactly what you're describing: how to write good use cases, build class diagrams from them, build sequence diagrams from that, and (ta-da!) code it up into working software. You might be able to Google for the ICONIX process and find details online.</p> <p>Some casual comments:</p> <ul> <li>The 'diagram' of any Use Case Diagram is the <em>least</em> useful aspect of use cases. Every oval on the diagram represents a paragraph or two of text telling the story of what's going on. It's that text that's really helpful.</li> <li>Usually you have classes for the nouns in your use cases, and methods for the verbs. Some of your verbs (<code>Add_data_to_database</code>, <code>Logout</code>, ...) are classes instead of methods. <ul> <li>Sometimes you get this sort of thing if you use a framework that encourages a command pattern. Even then, the command objects can/should just invoke methods on your real classes. </li> <li>I would say you're missing some nouns (what type of data are your storing in the database?). If you had that, then you would find relationships between <code>User</code>'s and those data classes.</li> </ul></li> </ul>
2,428,076
What is the difference between a stream and a reader in Java?
<p>Today I got this question for which I think I answered very bad. I said stream is a data that flows and reader is a technique where we read from that is a static data. I know this is an awful answer, so please provide me the crisp difference and definitions between these two with example in Java.</p> <p>Thanks.</p>
2,428,156
4
0
null
2010-03-11 19:38:33.117 UTC
9
2016-01-29 19:31:35.76 UTC
null
null
null
null
1,977,903
null
1
20
java|stream
16,183
<p>As others have said, the use cases for each are slightly different (even though they often can be used interchangeably)</p> <p>Since readers are for reading characters, they are better when you are dealing with input that is of a textual nature (or data represented as characters). I say better because Readers (in the context of typical usage) are essentially streams with methods that easily facilitate reading character input.</p>
38,060,002
How to show/hide TextView in android xml file and java file?
<p>I have TextView in one of my layout. I want keep it hide and only want to make it visible when button is clicked, how can I do it ? My view is like below. Thanks.</p> <pre><code> &lt;TextView android:layout_marginBottom=&quot;16dp&quot; android:layout_marginRight=&quot;8dp&quot; android:id=&quot;@+id/textAuthorSign&quot; android:layout_gravity=&quot;right&quot; android:text=&quot;- ABJ Abdul Kalam&quot; android:textStyle=&quot;italic&quot; android:textSize=&quot;16sp&quot; android:typeface=&quot;serif&quot; android:visibility=&quot;invisible&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; /&gt; </code></pre> <p>Thanks</p>
38,060,137
3
1
null
2016-06-27 17:38:21.877 UTC
6
2022-01-20 12:48:30.02 UTC
2020-09-03 14:51:57.697 UTC
null
2,315,166
null
6,293,770
null
1
17
java|android|xml
48,913
<p>I think you want a toggle (As stated by the question title)</p> <p>XML File:</p> <pre><code> &lt;Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/self_destruct" android:onClick="hide" /&gt; &lt;TextView android:layout_marginBottom="16dp" android:layout_marginRight="8dp" android:id="@+id/textAuthorSign" android:layout_gravity="right" android:text="- ABJ Abdul Kalam" android:textStyle="italic" android:textSize="16sp" android:visibility="invisible" android:typeface="serif" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; </code></pre> <p>Java:</p> <pre><code> public void hide(View view) { TextView txtView = (TextView)findViewById(R.id.textAuthorSign); //Toggle if (txtView.getVisibility() == View.VISIBLE) txtView.setVisibility(View.INVISIBLE); else txtView.setVisibility(View.VISIBLE); //If you want it only one time //txtView.setVisibility(View.VISIBLE); } </code></pre>
809,898
Loading a view controller & view hierarchy programmatically in Cocoa Touch without xib
<p>It seems like all of the Cocoa Touch templates are set up to load a nib. </p> <p>If I want to start a new project that's going to use a view controller, and load its view(hierarchy) programatically, not from a nib/xib, what are the steps to setting that up or adjusting a template.</p> <p>I though all I had to do was implement -loadView, but I have trouble every time I try to do this.</p>
812,094
2
2
null
2009-05-01 01:50:50.517 UTC
9
2019-04-07 12:00:42.377 UTC
2019-04-07 12:00:42.377 UTC
null
1,033,581
null
48,571
null
1
7
iphone|cocoa-touch|uikit|uiviewcontroller
12,324
<p>It's reasonably simple to do completely programmatic user interface generation. First, you need to edit main.m to look something like the following:</p> <pre><code>int main(int argc, char *argv[]) { NSAutoreleasePool *pool = [NSAutoreleasePool new]; UIApplicationMain(argc, argv, nil, @"MyAppDelegate"); [pool release]; return 0; } </code></pre> <p>where MyAppDelegate is the name of your application delegate class. This means that an instance of MyAppDelegate will be created on launch, something that is normally handled by the main Nib file for the application.</p> <p>Within MyAppDelegate, implement your applicationDidFinishLaunching: method similar to the following:</p> <pre><code>- (void)applicationDidFinishLaunching:(UIApplication *)application { window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; if (!window) { [self release]; return; } window.backgroundColor = [UIColor whiteColor]; rootController = [[MyRootViewController alloc] init]; [window addSubview:rootController.view]; [window makeKeyAndVisible]; [window layoutSubviews]; } </code></pre> <p>where MyRootViewController is the view controller for the primary view in your window. This should initialize the main window, and add the view managed by MyRootViewController to it. rootController is kept as an instance variable within the delegate, for later reference.</p> <p>This should let you programmatically generate your user interface through MyRootViewController.</p>
56,402
Aligning text in SVG
<p>I am trying to make SVG XML documents with a mixture of lines and brief text snippets (two or three words typically). The major problem I'm having is getting the text aligning with line segments.</p> <p>For horizontal alignment I can use <code>text-anchor</code> with <code>left</code>, <code>middle</code> or <code>right</code>. I can't find a equivalent for vertical alignment; <code>alignment-baseline</code> doesn't seem to do it, so at present I'm using <code>dy="0.5ex"</code> as a kludge for centre alignment.</p> <p>Is there a proper manner for aligning with the vertical centre or top of the text?</p>
73,257
2
1
null
2008-09-11 12:24:24.157 UTC
9
2015-10-12 15:08:13.56 UTC
2015-10-12 13:57:56.013 UTC
null
63,550
Ian G
5,764
null
1
70
xml|svg
61,160
<p>It turns out that you don't need explicit text paths. Firefox 3 has only partial support of the vertical alignment tags (<a href="http://groups.google.com/group/mozilla.dev.tech.svg/browse_thread/thread/1be0c56cfbfb3053?fwc=1" rel="noreferrer">see this thread</a>). It also seems that dominant-baseline only works when applied as a style whereas text-anchor can be part of the style or a tag attribute.</p> <pre><code>&lt;path d="M10, 20 L17, 20" style="fill:none; color:black; stroke:black; stroke-width:1.00"/&gt; &lt;text fill="black" font-family="sans-serif" font-size="16" x="27" y="20" style="dominant-baseline: central;"&gt; Vertical &lt;/text&gt; &lt;path d="M60, 40 L60, 47" style="fill:none; color:red; stroke:red; stroke-width:1.00"/&gt; &lt;text fill="red" font-family="sans-serif" font-size="16" x="60" y="70" style="text-anchor: middle;"&gt; Horizontal &lt;/text&gt; &lt;path d="M60, 90 L60, 97" style="fill:none; color:blue; stroke:blue; stroke-width:1.00"/&gt; &lt;text fill="blue" font-family="sans-serif" font-size="16" x="60" y="97" style="text-anchor: middle; dominant-baseline: hanging;"&gt; Bit of Both &lt;/text&gt; </code></pre> <p>This works in Firefox. Unfortunately Inkscape doesn't seem to handle dominant-baseline (or at least not in the same way).</p>
341,175
datetime.parse and making it work with a specific format
<p>I have a datetime coming back from an XML file in the format:</p> <blockquote> <p>20080916 11:02</p> </blockquote> <p>as in </p> <blockquote> <p>yyyymm hh:ss</p> </blockquote> <p>How can i get the datetime.parse function to pick up on this? Ie parse it without erroring? Cheers</p>
341,200
2
0
null
2008-12-04 16:15:40.863 UTC
12
2018-05-16 12:41:38.233 UTC
2013-07-04 10:05:24.33 UTC
null
1,545,777
anonym0use
35,441
null
1
159
c#|asp.net|.net-2.0
168,438
<pre><code>DateTime.ParseExact(input,"yyyyMMdd HH:mm",null); </code></pre> <p>assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing. </p> <p>The <a href="http://msdn.microsoft.com/en-us/library/system.datetime.parseexact(VS.80).aspx" rel="noreferrer">ParseExact documentation</a> details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.</p> <p>As @<a href="https://stackoverflow.com/users/3043/joel-coehoorn">Joel Coehoorn</a> mentions, there's also the option of using <a href="http://msdn.microsoft.com/en-us/library/system.datetime.tryparseexact(VS.80).aspx" rel="noreferrer">TryParseExact</a>, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.</p> <p>If you need to parse other formats, you can check out the <a href="https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings" rel="noreferrer">Standard DateTime Format Strings</a>.</p>
2,952,202
How do I get the name of the test method that was run in a testng tear down method?
<p>Basically, I have a teardown method that I want to log to the console which test was just run. How would I go about getting that string?</p> <p>I can get the class name, but I want the actual method that was just executed.</p> <pre><code>public class TestSomething { @AfterMethod public void tearDown() { System.out.println("The test that just ran was: " + getTestThatJustRanMethodName()); } @Test public void testCase() { assertTrue(1 == 1); } } </code></pre> <p>...should output to the screen: "The test that just ran was: testCase"</p> <p>However, I don't know the magic that <code>getTestThatJustRanMethodName</code> should actually be.</p>
2,954,047
5
0
null
2010-06-01 18:20:18.357 UTC
9
2020-04-12 20:06:28.33 UTC
2018-10-25 06:33:12.293 UTC
null
452,775
null
91,163
null
1
35
java|unit-testing|testng
53,506
<p>Declare a parameter of type ITestResult in your @AfterMethod and TestNG will inject it:</p> <pre><code>@AfterMethod public void afterMethod(ITestResult result) { System.out.println("method name:" + result.getMethod().getMethodName()); } </code></pre>
2,918,106
Algorithm to calculate a page importance based on its views / comments
<p>I need an algorithm that allows me to determine an appropriate <code>&lt;priority&gt;</code> field for my website's <a href="http://www.sitemaps.org/protocol.php" rel="noreferrer">sitemap</a> based on the page's views and comments count.</p> <p>For those of you unfamiliar with sitemaps, the priority field is used to signal the importance of a page relative to the others on the same website. It must be a decimal number between 0 and 1.</p> <p>The algorithm will accept two parameters, <code>viewCount</code> and <code>commentCount</code>, and will return the priority value. For example:</p> <pre><code>GetPriority(100000, 100000); // Damn, a lot of views/comments! The returned value will be very close to 1, for example 0.995 GetPriority(3, 2); // Ok not many users are interested in this page, so for example it will return 0.082 </code></pre>
2,953,976
6
7
null
2010-05-27 02:26:30.6 UTC
11
2011-01-20 21:25:10.293 UTC
2010-06-02 21:52:57.443 UTC
null
332,624
null
332,624
null
1
11
algorithm|language-agnostic|math|ranking|sitemap.xml
2,395
<p>You mentioned doing this in an SQL query, so I'll give samples in that.</p> <p>If you have a table/view <code>Pages</code>, something like this</p> <pre><code>Pages ----- page_id:int views:int - indexed comments:int - indexed </code></pre> <p>Then you can order them by writing</p> <pre><code>SELECT * FROM Pages ORDER BY (0.3+LOG10(10+views)/LOG10(10+(SELECT MAX(views) FROM Pages))) + (0.7+LOG10(10+comments)/LOG10(10+(SELECT MAX(comments) FROM Pages))) </code></pre> <p>I've deliberately chosen unequal weighting between views and comments. A problem that can arise with keeping an equal weighting with views/comments is that the ranking becomes a self-fulfilling prophecy - a page is returned at the top of the list, so it's visited more often, and thus gets more points, so it's shown at the stop of the list, and it's visited more often, and it gets more points.... Putting more weight on on the comments reflects that these take real effort and show real interest.</p> <p>The above formula will give you ranking based on all-time statistics. So an article that amassed the same number of views/comments in the last week as another article amassed in the last year will be given the same priority. It may make sense to repeat the formula, each time specifying a range of dates, and favoring pages with higher activity, e.g.</p> <pre><code> 0.3*(score for views/comments today) - live data 0.3*(score for views/comments in the last week) 0.25*(score for views/comments in the last month) 0.15*(score for all views/comments, all time) </code></pre> <p>This will ensure that "hot" pages are given higher priority than similarly scored pages that haven't seen much action lately. All values apart from today's scores can be persisted in tables by scheduled stored procedures so that the database isn't having to aggregate many many comments/view stats. Only today's stats are computed "live". Taking it one step further, the ranking formula itself can be computed and stored for historical data by a stored procedure run daily.</p> <p>EDIT: To get a strict range from 0.1 to 1.0, you would motify the formula like this. But I stress - this will only add overhead and is unecessary - the absolute values of priority are not important - only their relative values to other urls. The search engine uses these to answer the question, is URL A more important/relevant than URL B? It does this by comparing their priorities - which one is greatest - not their absolute values.</p> <p>// unnormalized - x is some page id un(x) = 0.3*log(views(x)+10)/log(10+maxViews()) + 0.7*log(comments(x)+10)/log(10+maxComments()) // the original formula (now in pseudo code)</p> <p>The maximum will be 1.0, the minimum will start at 1.0 and move downwards as more views/comments are made.</p> <p>we define un(0) as the minimum value, i.e. (where views(x) and comments(x) are both 0 in the above formula)</p> <p>To get a normalized formula from 0.1 to 1.0, you then compute n(x), the normalized priority for page <code>x</code></p> <pre><code> (1.0-un(x)) * (un(0)-0.1) n(x) = un(x) - ------------------------- when un(0) != 1.0 1.0-un(0) = 0.1 otherwise. </code></pre>
2,775,261
How to enable gzip HTTP compression on Windows Azure dynamic content
<p>I've been trying unsuccessfully to enable gzip HTTP compression on my Windows Azure hosted WCF Restful service which returns JSON only from GET and POST requests. </p> <p>I have tried so many things that I would have a hard time listing all of them, and I now realise I have been working with conflicting information (regarding old version of azure etc) so think it best to start with a clean slate!</p> <p>I am working with Visual Studio 2008, using the February 2010 tools for Visual Studio.</p> <p>So, according to the following <a href="http://msdn.microsoft.com/en-us/library/ff436045.aspx" rel="noreferrer">link</a>..</p> <p>.. HTTP compression has now been enabled. I've used the advice at the following page (the URL compression advice only).. </p> <p><a href="http://blog.smarx.com/posts/iis-compression-in-windows-azure" rel="noreferrer">http://blog.smarx.com/posts/iis-compression-in-windows-azure</a></p> <pre><code>&lt;urlCompression doStaticCompression="true" doDynamicCompression="true" dynamicCompressionBeforeCache="true" /&gt; </code></pre> <p>.. but I get no compression. It doesn't help that I don't know what the difference is between <strong>urlCompression</strong> and <strong>httpCompression</strong>. I've tried to find out but to no avail!</p> <p>Could, the fact that the tools for Visual Studio were released before the version of Azure which supports compression, be a problem? I have read somewhere that, with the latest tools, you can choose which version of Azure OS you want to use when you publish ... but I don't know if that's true, and if it is, I can't find where to choose. Could I be using a pre-http enabled version?</p> <p>I've also tried blowery http compression module, but no results. </p> <p>Does any one have any up-to-date advice on how to achieve this? i.e. advice that relates to the current version of the Azure OS.</p> <p>Cheers!</p> <p>Steven</p> <p><b>Update:</b> I edited the above code to fix a type in the web.config snippet.</p> <p><b>Update 2:</b> Testing the responses using the whatsmyip URL shown in the answer below is showing that my JSON responses from my service.svc are being returned without any compression, but static HTML pages <b>ARE</b> being returned with gzip compression. Any advice on how to get the JSON responses to compress will be gratefully received!</p> <p><b>Update 3:</b> Tried a JSON response larger than 256KB to see if the problem was due to the JSON response being smaller than this as mentioned in comments below. Unfortunately the response is still un-compressed.</p>
7,375,645
6
1
null
2010-05-05 17:02:58.223 UTC
33
2016-07-14 07:37:36.693 UTC
2016-07-14 07:37:36.693 UTC
null
1,745,409
null
629,438
null
1
58
json|gzip|azure|http-compression
20,519
<p>Well it took a <strong>very</strong> long time ... but I have finally solved this, and I want to post the answer for anyone else who is struggling. The solution is very simple and I've verified that it does definitely work!!</p> <p>Edit your ServiceDefinition.csdef file to contain this in the WebRole tag:</p> <pre><code> &lt;Startup&gt; &lt;Task commandLine="EnableCompression.cmd" executionContext="elevated" taskType="simple"&gt;&lt;/Task&gt; &lt;/Startup&gt; </code></pre> <p>In your web-role, create a text file and save it as "EnableCompression.cmd"</p> <p>EnableCompression.cmd should contain this:</p> <pre><code>%windir%\system32\inetsrv\appcmd set config /section:urlCompression /doDynamicCompression:True /commit:apphost %windir%\system32\inetsrv\appcmd set config -section:system.webServer/httpCompression /+"dynamicTypes.[mimeType='application/json; charset=utf-8',enabled='True']" /commit:apphost </code></pre> <p>.. and that's it! Done! This enables dynamic compression for the json returned by the web-role, which I think I read somewhere has a rather odd mime type, so make sure you copy the code exactly.</p>
2,355,148
Run a string as a command within a Bash script
<p>I have a Bash script that builds a string to run as a command</p> <p><strong>Script:</strong></p> <pre><code>#! /bin/bash matchdir="/home/joao/robocup/runner_workdir/matches/testmatch/" teamAComm="`pwd`/a.sh" teamBComm="`pwd`/b.sh" include="`pwd`/server_official.conf" serverbin='/usr/local/bin/rcssserver' cd $matchdir illcommando="$serverbin include='$include' server::team_l_start = '${teamAComm}' server::team_r_start = '${teamBComm}' CSVSaver::save='true' CSVSaver::filename = 'out.csv'" echo "running: $illcommando" # $illcommando &gt; server-output.log 2&gt; server-error.log $illcommando </code></pre> <p>which does not seem to supply the arguments correctly to the <code>$serverbin</code>.</p> <p><strong>Script output:</strong></p> <pre><code>running: /usr/local/bin/rcssserver include='/home/joao/robocup/runner_workdir/server_official.conf' server::team_l_start = '/home/joao/robocup/runner_workdir/a.sh' server::team_r_start = '/home/joao/robocup/runner_workdir/b.sh' CSVSaver::save='true' CSVSaver::filename = 'out.csv' rcssserver-14.0.1 Copyright (C) 1995, 1996, 1997, 1998, 1999 Electrotechnical Laboratory. 2000 - 2009 RoboCup Soccer Simulator Maintenance Group. Usage: /usr/local/bin/rcssserver [[-[-]]namespace::option=value] [[-[-]][namespace::]help] [[-[-]]include=file] Options: help display generic help include=file parse the specified configuration file. Configuration files have the same format as the command line options. The configuration file specified will be parsed before all subsequent options. server::help display detailed help for the "server" module player::help display detailed help for the "player" module CSVSaver::help display detailed help for the "CSVSaver" module CSVSaver Options: CSVSaver::save=&lt;on|off|true|false|1|0|&gt; If save is on/true, then the saver will attempt to save the results to the database. Otherwise it will do nothing. current value: false CSVSaver::filename='&lt;STRING&gt;' The file to save the results to. If this file does not exist it will be created. If the file does exist, the results will be appended to the end. current value: 'out.csv' </code></pre> <p>if I just paste the command <code>/usr/local/bin/rcssserver include='/home/joao/robocup/runner_workdir/server_official.conf' server::team_l_start = '/home/joao/robocup/runner_workdir/a.sh' server::team_r_start = '/home/joao/robocup/runner_workdir/b.sh' CSVSaver::save='true' CSVSaver::filename = 'out.csv'</code> (in the output after "runnning: ") it works fine.</p>
2,355,242
8
2
null
2010-03-01 10:36:22.59 UTC
39
2020-08-25 13:57:23.42 UTC
2014-09-16 11:37:03.603 UTC
null
2,777,965
null
86,845
null
1
190
bash|shell|command-line-arguments
504,207
<p>You can use <code>eval</code> to execute a string:</p> <pre><code>eval $illcommando </code></pre>
2,954,359
How to get and display yesterday date?
<p>I am using the date command for a batch script.<br> I am wondering how to use command <strong>date</strong> to get yesterday date.</p>
2,954,418
9
1
null
2010-06-02 00:58:30.19 UTC
5
2018-05-02 08:02:04.613 UTC
2016-04-10 11:50:28.627 UTC
null
3,074,564
null
355,974
null
1
7
batch-file
95,804
<p>Looking at @JRL's <a href="https://stackoverflow.com/questions/2954359/dos-batch-programming-howto-get-and-display-yesterday-date/2954377#2954377">answer</a>... If it's truly that hard, perhaps use PowerShell and then do similar to <a href="https://stackoverflow.com/questions/2433941/powershells-get-date-how-to-get-yesterday-at-2200-in-a-variable">Powershell&#39;s Get-date: How to get Yesterday at 22:00 in a variable?</a></p> <p>You can call to PowerShell in a bat file like so: <a href="https://stackoverflow.com/questions/1804751/use-bat-to-start-powershell-script">Use bat to start Powershell script</a></p> <p>You'll end up with a three or four liner solution rather than the 100 or so written (immaculately I'll add) by Rob Van der Woude.</p> <p>Good luck...</p>
2,427,381
How to detect that C# Windows Forms code is executed within Visual Studio?
<p>Is there a variable or a preprocessor constant that allows to know that the code is executed within the context of Visual Studio?</p>
2,427,420
9
2
null
2010-03-11 17:55:41.947 UTC
16
2022-01-21 18:08:53.507 UTC
2014-02-20 23:02:22.1 UTC
null
63,550
null
310,291
null
1
48
c#|winforms
21,126
<p>Try <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.isattached.aspx" rel="noreferrer"><strong>Debugger.IsAttached</strong></a> or <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.component.designmode.aspx" rel="noreferrer"><strong>DesignMode</strong></a> property or get <a href="http://vidmar.net/weblog/archive/2005/04/11/1246.aspx" rel="noreferrer"><strong>ProcessName</strong></a> or a combination, as appropriate</p> <pre><code>Debugger.IsAttached // or LicenseUsageMode.Designtime // or System.Diagnostics.Process.GetCurrentProcess().ProcessName </code></pre> <p>Here is a <a href="http://voidnish.wordpress.com/2009/06/21/checking-for-design-mode/" rel="noreferrer"><strong>sample</strong></a></p> <pre><code>public static class DesignTimeHelper { public static bool IsInDesignMode { get { bool isInDesignMode = LicenseManager.UsageMode == LicenseUsageMode.Designtime || Debugger.IsAttached == true; if (!isInDesignMode) { using (var process = Process.GetCurrentProcess()) { return process.ProcessName.ToLowerInvariant().Contains("devenv"); } } return isInDesignMode; } } } </code></pre>
3,205,132
>!= PHP operator, how to write not equal to or greater than?
<p>How can I write not greater-than-or-equal-to in PHP?</p> <p>Is it <code>&gt;!=</code> ?</p>
3,205,151
13
2
null
2010-07-08 15:18:13.893 UTC
10
2022-01-06 07:44:13.817 UTC
2018-04-25 16:12:11.827 UTC
null
4,939,819
null
353,542
null
1
20
php|operator-keyword
60,533
<p>Isn't <code>not greater than or equal to x</code> the same as <code>less than x</code> ?</p>
2,663,115
How to detect a loop in a linked list?
<p>Say you have a linked list structure in Java. It's made up of Nodes:</p> <pre><code>class Node { Node next; // some user data } </code></pre> <p>and each Node points to the next node, except for the last Node, which has null for next. Say there is a possibility that the list can contain a loop - i.e. the final Node, instead of having a null, has a reference to one of the nodes in the list which came before it.</p> <p>What's the best way of writing</p> <pre><code>boolean hasLoop(Node first) </code></pre> <p>which would return <code>true</code> if the given Node is the first of a list with a loop, and <code>false</code> otherwise? How could you write so that it takes a constant amount of space and a reasonable amount of time?</p> <p>Here's a picture of what a list with a loop looks like:</p> <p><img src="https://i.stack.imgur.com/irw1S.jpg" alt="alt text"></p>
2,663,147
28
20
null
2010-04-18 17:08:53.63 UTC
288
2022-08-08 11:45:43.837 UTC
2013-05-05 16:35:27.05 UTC
null
1,824,094
null
75,863
null
1
468
java|algorithm|data-structures|linked-list
208,537
<p>You can make use of <a href="http://en.wikipedia.org/wiki/Cycle_detection#Tortoise_and_hare" rel="noreferrer"><strong>Floyd's cycle-finding algorithm</strong></a>, also known as <em>tortoise and hare algorithm</em>.<br><br> The idea is to have two references to the list and move them at <strong>different speeds</strong>. Move one forward by <code>1</code> node and the other by <code>2</code> nodes. </p> <ul> <li>If the linked list has a loop they will <em>definitely</em> meet.</li> <li>Else either of the two references(or their <code>next</code>) will become <code>null</code>.</li> </ul> <p>Java function implementing the algorithm:</p> <pre><code>boolean hasLoop(Node first) { if(first == null) // list does not exist..so no loop either return false; Node slow, fast; // create two references. slow = fast = first; // make both refer to the start of the list while(true) { slow = slow.next; // 1 hop if(fast.next != null) fast = fast.next.next; // 2 hops else return false; // next node null =&gt; no loop if(slow == null || fast == null) // if either hits null..no loop return false; if(slow == fast) // if the two ever meet...we must have a loop return true; } } </code></pre>
2,634,427
Code Golf: Numeric equivalent of an Excel column name
<h2>The challenge</h2> <p>The shortest code by character count that will output the numeric equivalent of an Excel column string.</p> <p>For example, the <code>A</code> column is 1, <code>B</code> is 2, so on and so forth. Once you hit <code>Z</code>, the next column becomes <code>AA</code>, then <code>AB</code> and so on.</p> <h2>Test cases:</h2> <pre><code>A: 1 B: 2 AD: 30 ABC: 731 WTF: 16074 ROFL: 326676 </code></pre> <p>Code count includes input/output (i.e full program).</p>
2,634,694
67
7
2010-04-14 02:14:22.577 UTC
2010-04-14 02:06:45.537 UTC
23
2015-04-03 16:34:49.57 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
263,004
null
1
76
excel|code-golf
53,775
<h2>Perl, <s>36</s> <s>34</s> <s>33</s> <s>31</s> <s>30</s> <s>17</s> <s>15</s> 11 characters</h2> <pre><code>$_=()=A..$_ </code></pre> <p>Usage:</p> <pre><code>$ echo -n WTF | perl -ple '$_=()=A..$_' 16074 </code></pre> <p>Reduced to 17 by using echo -n to avoid a <code>chop</code> call.</p> <p>Reduced to 15 by using say instead of print.</p> <p>Reduced to 11 by using -p instead of say.</p> <p>Explanation: <code>A</code> is evaluated in string context and <code>A..$_</code> builds a list starting at "A" and string-incrementing up to the input string. Perl interprets the <code>++</code> operator (and thus <code>..</code>) on strings in an alphabetic context, so for example <code>$_="AZ";$_++;print</code> outputs <code>BA</code>.</p> <p><code>=()=</code> (aka <a href="http://www.perlmonks.org/?node_id=527973" rel="noreferrer">"goatse" operator</a>) forces an expression to be evaluated in list context, and returns the number of elements returned by that expression i.e., <code>$scalar = () = &lt;expr&gt;</code> corresponds to <code>@list = &lt;expr&gt;; $scalar = @list</code>.</p>
25,234,941
Python regularise irregular time series with linear interpolation
<p>I have a time series in pandas that looks like this:</p> <pre><code> Values 1992-08-27 07:46:48 28.0 1992-08-27 08:00:48 28.2 1992-08-27 08:33:48 28.4 1992-08-27 08:43:48 28.8 1992-08-27 08:48:48 29.0 1992-08-27 08:51:48 29.2 1992-08-27 08:53:48 29.6 1992-08-27 08:56:48 29.8 1992-08-27 09:03:48 30.0 </code></pre> <p>I would like to resample it to a regular time series with 15 min times steps where the values are linearly interpolated. Basically I would like to get:</p> <pre><code> Values 1992-08-27 08:00:00 28.2 1992-08-27 08:15:00 28.3 1992-08-27 08:30:00 28.4 1992-08-27 08:45:00 28.8 1992-08-27 09:00:00 29.9 </code></pre> <p>However using the resample method (df.resample('15Min')) from Pandas I get:</p> <pre><code> Values 1992-08-27 08:00:00 28.20 1992-08-27 08:15:00 NaN 1992-08-27 08:30:00 28.60 1992-08-27 08:45:00 29.40 1992-08-27 09:00:00 30.00 </code></pre> <p>I have tried the resample method with different 'how' and 'fill_method' parameters but never got exactly the results I wanted. Am I using the wrong method?</p> <p>I figure this is a fairly simple query, but I have searched the web for a while and couldn't find an answer.</p> <p>Thanks in advance for any help I can get.</p>
25,253,780
4
0
null
2014-08-11 02:04:51.033 UTC
17
2018-08-19 17:34:37.147 UTC
null
null
null
null
3,928,036
null
1
25
python|pandas|time-series|linear-interpolation
19,966
<p>It takes a bit of work, but try this out. Basic idea is find the closest two timestamps to each resample point and interpolate. <code>np.searchsorted</code> is used to find dates closest to the resample point.</p> <pre><code># empty frame with desired index rs = pd.DataFrame(index=df.resample('15min').iloc[1:].index) # array of indexes corresponding with closest timestamp after resample idx_after = np.searchsorted(df.index.values, rs.index.values) # values and timestamp before/after resample rs['after'] = df.loc[df.index[idx_after], 'Values'].values rs['before'] = df.loc[df.index[idx_after - 1], 'Values'].values rs['after_time'] = df.index[idx_after] rs['before_time'] = df.index[idx_after - 1] #calculate new weighted value rs['span'] = (rs['after_time'] - rs['before_time']) rs['after_weight'] = (rs['after_time'] - rs.index) / rs['span'] # I got errors here unless I turn the index to a series rs['before_weight'] = (pd.Series(data=rs.index, index=rs.index) - rs['before_time']) / rs['span'] rs['Values'] = rs.eval('before * before_weight + after * after_weight') </code></pre> <p>After all that, hopefully the right answer:</p> <pre><code>In [161]: rs['Values'] Out[161]: 1992-08-27 08:00:00 28.011429 1992-08-27 08:15:00 28.313939 1992-08-27 08:30:00 28.223030 1992-08-27 08:45:00 28.952000 1992-08-27 09:00:00 29.908571 Freq: 15T, Name: Values, dtype: float64 </code></pre>
33,538,420
MYSQL search if a string contains special characters?
<p>I need to search table field contains special characters. I found a solution given <a href="https://stackoverflow.com/questions/2558755/how-to-detect-if-a-string-contains-special-characters">here</a> something like:</p> <pre><code>SELECT * FROM `tableName` WHERE `columnName` LIKE "%#%" OR `columnName` LIKE "%$%" OR (etc.) </code></pre> <p>But this solution is too broad. I need to mention all the special characters. But I want something which search something like:</p> <pre><code>SELECT * FROM `tableName` WHERE `columnName` LIKE '%[^a-zA-Z0-9]%' </code></pre> <p>That is search column which contains not only a-z, A-Z and 0-9 but some other characters also. Is it possible with <code>MYSQL</code></p>
33,538,438
1
1
null
2015-11-05 07:00:52.057 UTC
5
2015-11-05 07:02:02.003 UTC
2017-05-23 11:47:17.113 UTC
null
-1
null
3,113,693
null
1
16
mysql|sql|regex|select
51,325
<p>Use <code>regexp</code></p> <pre><code>SELECT * FROM `tableName` WHERE `columnName` REGEXP '[^a-zA-Z0-9]' </code></pre> <p>This would select all the rows where the particular column contain atleast one non-alphanumeric character. </p> <p>or</p> <pre><code>REGEXP '[^[:alnum:]]' </code></pre>
45,399,894
Is it impossible to checkout a different branch in Jenkinsfile?
<p>I have two branches on BitBucket: <code>master</code> and <code>develop</code>. I've also got a BitBucket Team Folder job configured on my Jenkins server to build that repository. On the <code>develop</code> branch there's the following Jenkinsfile:</p> <pre><code>node { stage('Checkout') { checkout scm } stage('Try different branch') { sh "git branch -r" sh "git checkout master" } } </code></pre> <p>When Jenkins runs it, the build fails when it attempts to checkout <code>master</code>:</p> <pre><code>[Pipeline] stage [Pipeline] { (Try different branch) [Pipeline] sh [e_jenkinsfile-tests_develop-4R65E2H6B73J3LB52BLACQOZLBJGN2QG22IPONX3CV46B764LAXA] Running shell script + git branch -r origin/develop [Pipeline] sh [e_jenkinsfile-tests_develop-4R65E2H6B73J3LB52BLACQOZLBJGN2QG22IPONX3CV46B764LAXA] Running shell script + git checkout master error: pathspec 'master' did not match any file(s) known to git. [Pipeline] } </code></pre> <p>I had expected the <code>git branch -r</code> command to print out both <code>origin/master</code> and <code>origin/develop</code>, but for some reason it only prints the latter.</p> <p>I've read around and tried to come up with any ways to do this: For example, I tried installing the SSH Agent Plugin for Jenkins and changed the Jenkinsfile to:</p> <pre><code>node { stage('Checkout') { checkout scm } stage('Try different branch') { sshagent(['Bitbucket']) { sh "git branch -r" sh "git checkout master" } } } </code></pre> <p>But it still doesn't appear to find <code>origin/master</code>. What's worse, the SSH agent seems to be killed before it attempts to checkout <code>master</code>:</p> <pre><code>[Pipeline] { (Try different branch) [Pipeline] sshagent [ssh-agent] Using credentials ThomasKasene (Used to communicate with Bitbucket) [ssh-agent] Looking for ssh-agent implementation... [ssh-agent] Exec ssh-agent (binary ssh-agent on a remote machine) $ ssh-agent SSH_AUTH_SOCK=/tmp/ssh-M6pIguCUpAV4/agent.11899 SSH_AGENT_PID=11902 $ ssh-add /var/jenkins_home/workspace/e_jenkinsfile-tests_develop-4R65E2H6B73J3LB52BLACQOZLBJGN2QG22IPONX3CV46B764LAXA@tmp/private_key_2394129657382526146.key Identity added: /var/jenkins_home/workspace/e_jenkinsfile-tests_develop-4R65E2H6B73J3LB52BLACQOZLBJGN2QG22IPONX3CV46B764LAXA@tmp/private_key_2394129657382526146.key (/var/jenkins_home/workspace/e_jenkinsfile-tests_develop-4R65E2H6B73J3LB52BLACQOZLBJGN2QG22IPONX3CV46B764LAXA@tmp/private_key_2394129657382526146.key) [ssh-agent] Started. [Pipeline] { [Pipeline] sh [e_jenkinsfile-tests_develop-4R65E2H6B73J3LB52BLACQOZLBJGN2QG22IPONX3CV46B764LAXA] Running shell script + git branch -r origin/develop [Pipeline] sh $ ssh-agent -k unset SSH_AUTH_SOCK; unset SSH_AGENT_PID; echo Agent pid 11902 killed; [ssh-agent] Stopped. [e_jenkinsfile-tests_develop-4R65E2H6B73J3LB52BLACQOZLBJGN2QG22IPONX3CV46B764LAXA] Running shell script + git checkout master error: pathspec 'master' did not match any file(s) known to git. [Pipeline] } </code></pre> <p>My eventual plan is to commit something to <code>develop</code> and then merge it into <code>master</code>, but so far I have had very little luck. Has anybody got a possible solution or workaround?</p> <p>PS: This only seems to be a problem in Jenkinsfile; I have a freestyle job that does something similar to what I want, and it works fine.</p>
45,405,121
5
0
null
2017-07-30 12:36:50.353 UTC
5
2020-03-17 19:42:40.37 UTC
2017-08-09 12:59:35.067 UTC
null
1,000,551
null
6,737,860
null
1
25
git|jenkins|bitbucket|jenkins-pipeline
72,657
<p>After some hours of trial and error, I came up with a possible solution. It builds partly on Matt's answer, but I had to alter it to make it work.</p> <p>Matt was correct in the essentials: <code>checkout scm</code> simply wasn't flexible enough to allow me to do what I needed, so I had to use <code>GitSCM</code> to customize it. The major points of interest are:</p> <ul> <li>Added extension <code>LocalBranch</code> to make sure I check out to an actual branch, and not just a detached <code>HEAD</code>.</li> <li>Added extension <code>WipeWorkspace</code> to delete everything in the workspace and force a complete clone. I don't think this was a part of the solution to my question, but it was still handy to have.</li> <li>Specified the SSH credentials using the <code>credentialsId</code> property since the repository is private.</li> </ul> <p>For whatever reason, when the <code>checkout</code> step is executed, it only checks out the branch, but does not set it to track the remote branch. Until I find a more elegant solution, I had to do this manually.</p> <p>After all that was done, I could use regular <code>sh "git checkout master"</code> and even <code>sh "git push"</code>, as long as I enclosed them in an <code>sshagent</code> step.</p> <p>I added a working example of the resulting Jenkinsfile below, but please keep in mind that it shouldn't be used for anything close to production as it's still very much in its infancy; hardcoded version numbers and no checks for which branch you're in, for example.</p> <pre><code>node { mvnHome = tool 'Maven' mvn = "${mvnHome}/bin/mvn" stage('Checkout') { checkout([ $class: 'GitSCM', branches: scm.branches, extensions: scm.extensions + [[$class: 'LocalBranch'], [$class: 'WipeWorkspace']], userRemoteConfigs: [[credentialsId: 'Bitbucket', url: '[email protected]:NAVFREG/jenkinsfile-tests.git']], doGenerateSubmoduleConfigurations: false ]) } stage('Release') { // Preparing Git sh "git branch -u origin/develop develop" sh "git config user.email \"[email protected]\"" sh "git config user.name \"Jenkins\"" // Making and committing new verison sh "${mvn} versions:set -DnewVersion=2.0.0 -DgenerateBackupPoms=false" sh "git commit -am \"Released version 2.0.0\"" // Merging new version into master sh "git checkout master" sh "git merge develop" sh "git checkout develop" // Making and committing new snapshot version sh "${mvn} versions:set -DnewVersion=3.0.0-SNAPSHOT -DgenerateBackupPoms=false" sh "git commit -am \"Made new snapshot version 3.0.0-SNAPSHOT\"" // Pushing everything to remote repository sshagent(['Bitbucket']) { sh "git push" sh "git checkout master" sh "git push" } } } </code></pre>
42,474,908
Using multiple javascript service workers at the same domain but different folders
<p>My website offers an array of web apps for each client. Each client has a different mix of apps that can be used.</p> <p>Each web app is a hosted in a different folder.</p> <p>So I need to cache for each client only it's allowed web apps instead of caching all the apps, many of them he the user, will not use at all.</p> <p>I naively created a global service worker for the shell of the website and custom named service worker for each folder or app. </p> <p>However I noticed that after the first service worker, say sw_global.js service worker registers, installs, activates, fetches succesfully and creates a cache named cache-global, the second service worker, say sw_app1,js, which creates it's own cache cache-app1, clears all cache-global. </p> <p>How can I use custom service worker for each folder?. Please keep in mind that each folder is a microservice or a web app which is not necesarilly allowed for all users, so it's imperative to not cache all content from a unique service worker. </p> <p>Actually I code on vanilla.js, no angular, no react, no vue, no nada.</p>
42,489,119
2
0
null
2017-02-26 22:18:59.097 UTC
9
2020-05-19 15:07:54.587 UTC
null
null
null
null
1,869,094
null
1
23
javascript|caching|service-worker
13,508
<p>There's two things to keep in mind here:</p> <ol> <li><p>It's possible to register an arbitrary number of service workers for a given <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy" rel="noreferrer">origin</a>, as long as each service worker has its own unique <a href="https://developers.google.com/web/fundamentals/getting-started/primers/service-workers#register_a_service_worker" rel="noreferrer">scope</a>. It sounds like you're doing this already, registering both a top-level service worker with a scope of <code>/</code> and then additional service workers scoped to the paths from which each of your independent web apps run.</p></li> <li><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage" rel="noreferrer">Cache Storage API</a> (and other storage mechanisms, like <a href="https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API" rel="noreferrer">IndexedDB</a>) are shared throughout the entire origin, and by default there's no "sharding" or namespace segregation.</p></li> </ol> <p>Taking those two facts together, my guess is that what's happening is that you have some cache cleanup code in the <code>activate</code> handler of one of the service workers that's scoped to a specific web app, and that code retrieves a list of current cache names and deletes any caches that it thinks is out of date. That's a common thing to do in a service worker, but you can run into trouble if you don't take into account the fact that <code>caches.keys()</code> will return a list of <strong>all</strong> the caches in your origin, even the caches that were created by other service worker instances.</p> <p>Assuming that's what's going on here, a model that I'd recommend following is to include the value of <code>registration.scope</code> as part of the cache name when you create your caches. When it comes time to delete old cache entries in your <code>activate</code> handler, it's easy to make sure that you're only cleaning up caches that your specific service worker is supposed to manage by filtering out those that don't match <code>registration.scope</code>.</p> <p>E.g., something like this:</p> <pre><code>const CACHE_VERSION = 'v2'; const CACHE_NAME = `${registration.scope}!${CACHE_VERSION}`; self.addEventListener('install', (event) =&gt; { event.waitUntil( caches.open(CACHE_NAME).then(cache =&gt; { // Add entries to the cache... }) ); }); self.addEventListener('activate', (event) =&gt; { const cleanup = async () =&gt; { const cacheNames = await caches.keys(); const cachesToDelete = cachesNames.filter( (cacheName) =&gt; cacheName.startsWith(`${registration.scope}!`) &amp;&amp; cacheName !== CACHE_NAME); await Promise.all(cachesToDelete.map( (cacheName) =&gt; caches.delete(cacheName))); }; event.waitUntil(cleanup()); }); </code></pre>