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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
318,327 | Transparent Window (or Draw to screen) No Mouse Capture | <p>In an app I'm coding I would like to make an alert message to appear that displays a large semi-transparent warning message without affecting the users work. Basically I will fade in the message but never set it's opacity to 1 and I want the user to be able to click 'through' the message as if it isn't there.</p>
<p>I have started by using an always on top window and setting the window style to none and setting the background and transparency key to white. On this window there is a label with a large font which contains the alert message (later I'll probably override the paint event and paint the message using GDI). I use a timer to fade in the message by dialling up it's opacity before dialling it back down again. It works OK in that the focus isn't stolen from any apps but the transparent form captures the mouse events, not the form below it (actually most of the form which is transparent doesn't capture the mouse events, only the label text does).</p>
<p>Also I'm not sure it's the optimal approach, maybe I should be painting straight to the screen somehow.</p>
<p>How should I improve things.</p> | 318,433 | 1 | 0 | null | 2008-11-25 18:07:51.293 UTC | 11 | 2008-11-25 18:36:11.593 UTC | 2008-11-25 18:25:44.313 UTC | ChrisE | 29,411 | ChrisE | 29,411 | null | 1 | 9 | .net|winforms | 2,590 | <p>Override the CreateParams property on your Form class and make sure the WS_EX_NOACTIVATE extended style is set. Mine looks like this:</p>
<pre><code>protected override CreateParams CreateParams
{
get
{
CreateParams baseParams = base.CreateParams;
baseParams.ExStyle |= ( int )(
Win32.ExtendedWindowStyles.WS_EX_LAYERED |
Win32.ExtendedWindowStyles.WS_EX_TRANSPARENT |
Win32.ExtendedWindowStyles.WS_EX_NOACTIVATE |
Win32.ExtendedWindowStyles.WS_EX_TOOLWINDOW );
return baseParams;
}
}
</code></pre>
<p>Values for ExtendedWindowStyles used above are:</p>
<pre><code>WS_EX_LAYERED = 0x00080000,
WS_EX_NOACTIVATE = 0x08000000,
WS_EX_TOOLWINDOW = 0x00000080,
WS_EX_TRANSPARENT = 0x00000020,
</code></pre> |
904,421 | Defining foreign key relationships for Rails' models | <p>I have a Comment class with a :foreign_key of post_id in the Post class.</p>
<pre><code>class Comment < ActiveRecord::Base
belongs_to :post, :class_name => "Post", :foreign_key => "post_id", :counter_cache => true
belongs_to :author, :class_name => "User", :foreign_key => "author_id"
end
</code></pre>
<p><strong>But my CreateComments migration does not define a database-level foreign key:</strong></p>
<pre><code>class CreateComments < ActiveRecord::Migration
def self.up
create_table :comments do |t|
t.column "post_id", :integer, :default => 0, :null => false
t.column "author", :string, :default => "", :limit => 25, :null => false
t.column "author_email", :string, :default => "", :limit => 50, :null => false
t.column "content", :text, :null => false
t.column "status", :string, :default => "", :limit => 25, :null => false
t.timestamps
end
end
def self.down
drop_table :comments
end
end
</code></pre>
<p>Instead post_id is a simple Integer column. </p>
<p><strong>So, it seems that this foreign key relationship exists only in the mind of Rails, not at the database level.</strong> </p>
<p>Is this correct?</p>
<p><strong>Also, is it necessary for the corresponding Post model to also declare its reciprocal foreign key relationship with Comments using the :foreign_key attribute or could that be omitted?</strong></p>
<pre><code>class Post < ActiveRecord::Base
set_table_name("blog_posts")
belongs_to :author, :class_name => "User", :foreign_key => 'author_id'
has_many :comments, :class_name => "Comment",
:foreign_key => 'post_id', :order => "created_at desc", :dependent => :destroy
has_many :categorizations
has_many :categories, :through => :categorizations
named_scope :recent, :order => "created_at desc", :limit => 5
end
</code></pre> | 904,452 | 1 | 3 | null | 2009-05-24 18:50:45.053 UTC | 24 | 2009-06-24 14:05:10.657 UTC | 2009-06-24 14:05:10.657 UTC | null | 52,443 | null | 101,050 | null | 1 | 60 | ruby-on-rails|foreign-keys | 88,484 | <p>The Rails default behaviour is that the column used to hold the foreign key on a model is the name of the association with the suffix <code>_id</code> added. The <code>:foreign_key</code> option lets you set the name of the foreign key directly. The associations between your <code>Post</code> and <code>Comment</code> model classes should look like this:</p>
<pre><code>class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
end
</code></pre>
<p>—Note that you don't need <code>:class_name => "Post"</code> in your <code>Comment</code> model. Rails already has that information. You should only be specifying <code>:class_name</code> and <code>:foreign_key</code> when you need to override the Rails' conventions.</p>
<p>You're correct that Rails maintains the foreign key relationships for you. You can enforce them in the database layer if you want by adding foreign key constraints.</p>
<ul>
<li>I think you would benefit from reading <a href="http://guides.rubyonrails.org/association_basics.html" rel="noreferrer">A Guide to ActiveRecord Associations</a>.</li>
</ul> |
19,469,385 | Error: Reference to type claims it is defined, but it could not be found | <p>I have a solution with 3 projects:</p>
<ul>
<li><code>ParsersBase</code>, that defines an interface <code>IParseRule</code></li>
<li><code>ParsersLibrary</code>, that has a reference to <code>ParsersBase</code> and defines a class <code>HtmlImageUrlParseRule : IParseRule</code></li>
<li><code>ParsersLibraryTest</code>, that has a reference to <code>ParsersBase</code> and <code>ParsersLibrary</code> and defines a test class with some test methods</li>
</ul>
<p>When I'm trying to build it, I get a warning:</p>
<blockquote>
<p>Reference to type <code>'AVSoft.ParsersBase.IParseRule'</code> claims it is defined in <code>'c:\Users\Tim\Dropbox\projects\Image Downloader\ParsersLibrary\bin\Debug\ParsersLibrary.dll'</code>, but it could not be found</p>
</blockquote>
<p>Why is VS trying to find <code>AVSoft.ParsersBase.IParseRule</code> in <code>ParsersLibrary.dll</code>? <code>ParsersLibraryTest</code> has a reference to <code>ParsersBase</code>; it just doesn't make any sense.</p> | 19,475,526 | 18 | 0 | null | 2013-10-19 18:14:55.99 UTC | 9 | 2022-07-21 03:32:17.103 UTC | 2022-07-21 03:32:17.103 UTC | null | 241,211 | null | 996,879 | null | 1 | 74 | c#|visual-studio|assemblies | 90,135 | <p>It was my fault, I had a ParsersLibrary project at the start and then renamed it to ParsersBase, but I didn't rename an assembly name, then I added a ParsersLibrary project again.</p>
<p>So, two projects had the same assembly name and it's not very good, is it? :) Assemblies overlap each other, so I have this error.</p> |
2,725,529 | How to create ASCII animation in Windows Console application using C#? | <p>I would like it to display non-flickery animation like this awesome Linux command; <code>sl</code></p>
<p><a href="http://www.youtube.com/watch?v=9GyMZKWjcYU" rel="noreferrer">http://www.youtube.com/watch?v=9GyMZKWjcYU</a></p>
<p>I would appreciate a small & stupid example of say ... a fly.</p>
<p>Thanks!</p> | 2,725,584 | 2 | 2 | null | 2010-04-27 22:10:25.22 UTC | 14 | 2011-06-09 12:05:41.827 UTC | null | null | null | null | 231,677 | null | 1 | 15 | c#|animation|console-application|ascii-art | 34,922 | <p>Just use <code>Console.SetCursorPosition</code> for moving the cursor to a certain position, then <code>Console.Write</code> a character. Before each frame you have to delete the previous one by overwriting it with spaces. Heres a little example I just built:</p>
<pre><code>class Program
{
static void Main(string[] args)
{
char[] chars = new char[] { '.', '-', '+', '^', '°', '*' };
for (int i = 0; ; i++)
{
if (i != 0)
{
// Delete the previous char by setting it to a space
Console.SetCursorPosition(6 - (i-1) % 6 - 1, Console.CursorTop);
Console.Write(" ");
}
// Write the new char
Console.SetCursorPosition(6 - i % 6 - 1, Console.CursorTop);
Console.Write(chars[i % 6]);
System.Threading.Thread.Sleep(100);
}
}
}
</code></pre>
<p>You could for instance take an animated gif, extract all single frames/images from it (see how to do that <a href="http://www.vcskicks.com/csharp_animated_gif2.php" rel="noreferrer">here</a>), apply an ASCII transformation (how to do that is described <a href="http://www.c-sharpcorner.com/UploadFile/dheenu27/ImageToASCIIconverter03022007164455PM/ImageToASCIIconverter.aspx" rel="noreferrer">here</a> for example) and print these frame by frame like in the above code example.</p>
<p><strong>Update</strong></p>
<p>Just for fun, I implemented what I just described. Just try it out replacing <code>@"C:\some_animated_gif.gif"</code> with the path to some (not to large) animated gif. For example take an AJAX loader gif from <a href="http://ajaxload.info/" rel="noreferrer">here</a>.</p>
<pre><code>class Program
{
static void Main(string[] args)
{
Image image = Image.FromFile(@"C:\some_animated_gif.gif");
FrameDimension dimension = new FrameDimension(
image.FrameDimensionsList[0]);
int frameCount = image.GetFrameCount(dimension);
StringBuilder sb;
// Remember cursor position
int left = Console.WindowLeft, top = Console.WindowTop;
char[] chars = { '#', '#', '@', '%', '=', '+',
'*', ':', '-', '.', ' ' };
for (int i = 0; ; i = (i + 1) % frameCount)
{
sb = new StringBuilder();
image.SelectActiveFrame(dimension, i);
for (int h = 0; h < image.Height; h++)
{
for (int w = 0; w < image.Width; w++)
{
Color cl = ((Bitmap)image).GetPixel(w, h);
int gray = (cl.R + cl.G + cl.B) / 3;
int index = (gray * (chars.Length - 1)) / 255;
sb.Append(chars[index]);
}
sb.Append('\n');
}
Console.SetCursorPosition(left, top);
Console.Write(sb.ToString());
System.Threading.Thread.Sleep(100);
}
}
}
</code></pre> |
42,370,977 | How to save a new sheet in an existing excel file, using Pandas? | <p>I want to use excel files to store data elaborated with python. My problem is that I can't add sheets to an existing excel file. Here I suggest a sample code to work with in order to reach this issue</p>
<pre><code>import pandas as pd
import numpy as np
path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"
x1 = np.random.randn(100, 2)
df1 = pd.DataFrame(x1)
x2 = np.random.randn(100, 2)
df2 = pd.DataFrame(x2)
writer = pd.ExcelWriter(path, engine = 'xlsxwriter')
df1.to_excel(writer, sheet_name = 'x1')
df2.to_excel(writer, sheet_name = 'x2')
writer.save()
writer.close()
</code></pre>
<p>This code saves two DataFrames to two sheets, named "x1" and "x2" respectively. If I create two new DataFrames and try to use the same code to add two new sheets, 'x3' and 'x4', the original data is lost.</p>
<pre><code>import pandas as pd
import numpy as np
path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"
x3 = np.random.randn(100, 2)
df3 = pd.DataFrame(x3)
x4 = np.random.randn(100, 2)
df4 = pd.DataFrame(x4)
writer = pd.ExcelWriter(path, engine = 'xlsxwriter')
df3.to_excel(writer, sheet_name = 'x3')
df4.to_excel(writer, sheet_name = 'x4')
writer.save()
writer.close()
</code></pre>
<p>I want an excel file with four sheets: 'x1', 'x2', 'x3', 'x4'.
I know that 'xlsxwriter' is not the only "engine", there is 'openpyxl'. I also saw there are already other people that have written about this issue, but still I can't understand how to do that.</p>
<p>Here a code taken from this <a href="https://stackoverflow.com/questions/20219254/how-to-write-to-an-existing-excel-file-without-overwriting-data-using-pandas">link</a></p>
<pre><code>import pandas
from openpyxl import load_workbook
book = load_workbook('Masterfile.xlsx')
writer = pandas.ExcelWriter('Masterfile.xlsx', engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])
writer.save()
</code></pre>
<p>They say that it works, but it is hard to figure out how. I don't understand what "ws.title", "ws", and "dict" are in this context. </p>
<p>Which is the best way to save "x1" and "x2", then close the file, open it again and add "x3" and "x4"?</p> | 42,375,263 | 13 | 0 | null | 2017-02-21 15:07:04.85 UTC | 56 | 2022-07-26 18:55:25.743 UTC | 2017-05-23 12:09:55.743 UTC | null | -1 | null | 5,013,143 | null | 1 | 148 | python|pandas|openpyxl|xlsxwriter | 244,312 | <p>Thank you. I believe that a complete example could be good for anyone else who have the same issue:</p>
<pre><code>import pandas as pd
import numpy as np
path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"
x1 = np.random.randn(100, 2)
df1 = pd.DataFrame(x1)
x2 = np.random.randn(100, 2)
df2 = pd.DataFrame(x2)
writer = pd.ExcelWriter(path, engine = 'xlsxwriter')
df1.to_excel(writer, sheet_name = 'x1')
df2.to_excel(writer, sheet_name = 'x2')
writer.save()
writer.close()
</code></pre>
<p>Here I generate an excel file, from my understanding it does not really matter whether it is generated via the "xslxwriter" or the "openpyxl" engine.</p>
<p>When I want to write without loosing the original data then</p>
<pre><code>import pandas as pd
import numpy as np
from openpyxl import load_workbook
path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"
book = load_workbook(path)
writer = pd.ExcelWriter(path, engine = 'openpyxl')
writer.book = book
x3 = np.random.randn(100, 2)
df3 = pd.DataFrame(x3)
x4 = np.random.randn(100, 2)
df4 = pd.DataFrame(x4)
df3.to_excel(writer, sheet_name = 'x3')
df4.to_excel(writer, sheet_name = 'x4')
writer.save()
writer.close()
</code></pre>
<p>this code do the job!</p> |
39,426,287 | Xcode 8 cannot run on device, provisioning profile problems mentioning Apple Watch | <p>I am running OS X El Capitan and using the Xcode 8 GM seed (8A218a) and I am trying to run my app on my iPhone 6 with iOS 10 GM seed, 10.01 (14A403), which is paired to my Apple Watch running watchOS 3 GM seed (14S326).</p>
<p>I am using Match for handling provisioning profiles and certificates, it has been working beautifully so far.</p>
<p>I recently changed the bundle identifier, so created a new App Id in member center and reconfigured match etc. I have the development certificate and provisioning profile installed on my Mac. I have deleted the old certificates and the old provisioning profiles.</p>
<p>Everything is just working fine running on the simulator. But when I try to run it on my iPhone Xcode 8 is displaying on error:</p>
<blockquote>
<p>Provisioning profile "match Development com.XXX.YYY" doesn't include the currently selected device "ZZZ's Apple Watch".</p>
</blockquote>
<p>It shows another error as well:</p>
<blockquote>
<p>Code signing is required for product type 'Application' in SDK 'iOS 10.0'</p>
</blockquote>
<p>This is under <em>Target -> General</em>:
<a href="https://i.stack.imgur.com/pSvC5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pSvC5.png" alt="enter image description here"></a></p>
<p><em>Target -> Build Settings</em> looks like this:
<a href="https://i.stack.imgur.com/UXmSz.png" rel="noreferrer"><img src="https://i.stack.imgur.com/UXmSz.png" alt="target_build_settings"></a></p>
<p>I don't have an Apple Watch extension for this app. So why is Xcode 8 giving me errors relating to my Apple Watch?</p>
<p>Also what does the second error mean? <em>Code signing is required for product type 'Application' in SDK 'iOS 10.0'</em>? </p>
<p>Thanks!!</p> | 39,489,057 | 6 | 0 | null | 2016-09-10 12:56:35.603 UTC | 7 | 2018-11-06 15:12:06.923 UTC | null | null | null | null | 1,311,272 | null | 1 | 53 | ios|swift|ios10|xcode8|fastlane-match | 52,780 | <p>I had the same issue today - XCode Version 8.0 (8A218a) - and fixed it with two simple steps (instead of the more complicated approach above:</p>
<ul>
<li>add the Apple Watch to member center (did not find a copy&paste option either)</li>
<li>edit the development provisioning profile and add the watch to devices, save</li>
<li>go to XCode prefs, move the old provisioning profile to trash (right click on the name) and download the new version</li>
<li>set the new provisioning profile in project editor</li>
</ul>
<p>No restart, clean or anything else needed. Worked like a charm.</p> |
38,308,905 | What does IAppbuilder.UseWebApi do? | <p>I've recently been working on an MVC site that has an api and in the startup.cs there is a line that says <code>app.UseWebApi</code>. I did some searching but I couldn't find a decent answer of what it does. Can someone please explain the concept for me? Thanks!</p> | 38,309,141 | 2 | 0 | null | 2016-07-11 14:00:43.097 UTC | 6 | 2018-10-16 09:07:40.577 UTC | 2016-07-11 14:00:56.897 UTC | null | 2,704,659 | null | 4,433,819 | null | 1 | 37 | c#|asp.net-mvc|api | 25,617 | <p>It configures ASP.NET Web API to run on top of <a href="http://owin.org/">OWIN</a>. OWIN abstracts a web server and you can run it on top of both IIS as well as HTTP.SYS which allows you to provide a web server in your own console application. To be more specific the piece that runs on top of IIS or HTTP.SYS is <a href="http://katanaproject.codeplex.com/documentation">Katana</a> which is an implementation of the OWIN specification.</p>
<p>By calling <code>app.UseWebApi</code> you configure OWIN/Katana to send web requests through ASP.NET Web Api that in OWIN terminology is considered a middleware. This requires the NuGet package <a href="https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Owin/">Microsoft.AspNet.WebApi.Owin</a>.</p>
<p>Interestingly, ASP.NET MVC 5 cannot be configured as an OWIN/Katana middleware. it depends on <code>System.Web</code> and expects the <code>HttpContext</code> singleton to exist so it has to run on top of IIS. However, several NuGet packages that can be used in MVC projects (e.g. for authentication) is built on top of OWIN instead of taking a dependency on <code>HttpContext</code> which makes them more useful. That is one explanation of why you see OWIN used in a MVC project.</p> |
33,871,181 | Why are async state machines classes (and not structs) in Roslyn? | <p>Let’s consider this very simple async method:</p>
<pre><code>static async Task myMethodAsync()
{
await Task.Delay(500);
}
</code></pre>
<p>When I compile this with VS2013 (pre Roslyn compiler) the generated state-machine is a struct. </p>
<pre><code>private struct <myMethodAsync>d__0 : IAsyncStateMachine
{
...
void IAsyncStateMachine.MoveNext()
{
...
}
}
</code></pre>
<p>When I compile it with VS2015 (Roslyn) the generated code is this:</p>
<pre><code>private sealed class <myMethodAsync>d__1 : IAsyncStateMachine
{
...
void IAsyncStateMachine.MoveNext()
{
...
}
}
</code></pre>
<p>As you can see Roslyn generates a class (and not a struct). If I remember correctly the first implementations of the async/await support in the old compiler (CTP2012 i guess) also generated classes and then it was changed to struct from performance reasons. (in some cases you can completely avoid boxing and heap allocation…) (See <a href="https://stackoverflow.com/questions/23609110/why-are-awaiters-async-await-structs-and-not-classes-can-classes-be-used">this</a>)</p>
<p>Does anyone know why this was changed again in Roslyn? (I don’t have any problem regarding this, I know that this change is transparent and does not change the behavior of any code, I’m just curious) </p>
<p><strong>Edit:</strong></p>
<p>The answer from @Damien_The_Unbeliever (and the source code :) ) imho explains everything. The described behaviour of Roslyn only applies for debug build (and that's needed because of the CLR limitation mentioned in the comment). In Release it also generates a struct (with all the benefits of that..). So this seems to be a very clever solution to support both Edit and Continue and better performance in production. Interesting stuff, thanks for everyone who participated! </p> | 33,872,004 | 2 | 1 | null | 2015-11-23 12:31:12.253 UTC | 13 | 2015-11-27 19:33:23.473 UTC | 2017-05-23 12:18:04.403 UTC | null | -1 | null | 1,783,306 | null | 1 | 89 | c#|.net|language-lawyer|roslyn | 3,879 | <p>I didn't have any foreknowledge of this, but since Roslyn is open-source these days, we can go hunting through the code for an explanation.</p>
<p>And here, on <a href="https://github.com/dotnet/roslyn/blob/e6a3ec3348ccdf25083d43502bf42519429148f2/src/Compilers/CSharp/Portable/Lowering/AsyncRewriter/AsyncRewriter.cs#L60" rel="noreferrer">line 60 of the AsyncRewriter</a>, we find:</p>
<pre><code>// The CLR doesn't support adding fields to structs, so in order to enable EnC in an async method we need to generate a class.
var typeKind = compilationState.Compilation.Options.EnableEditAndContinue ? TypeKind.Class : TypeKind.Struct;
</code></pre>
<p>So, whilst there's some appeal to using <code>struct</code>s, the big win of allowing <a href="http://blogs.msdn.com/b/csharpfaq/archive/2015/02/23/edit-and-continue-and-make-object-id-improvements-in-ctp-6.aspx" rel="noreferrer">Edit and Continue</a> to work within <code>async</code> methods was obviously chosen as the better option.</p> |
1,750,972 | Upgrading from Drupal 6 to Drupal 7: best programmer's practices? | <p>Although I am using drupal since the D4 series, I only started developing professionally for it with D6, so - despite I did various site upgrades - I was never faced by the task of <strong>having to port my own code</strong> to a new version.</p>
<p>I know the Drupal community will come up with lot of technical support about changed API's and architectural changes (see the <strong><a href="http://drupal.org/project/deadwood" rel="noreferrer">deadwood module</a></strong> for D5-D6 or even these stubs of D6-D7 how-to's <a href="http://drupal.org/update/modules/6/7" rel="noreferrer"><strong>for modules</strong></a> <a href="http://drupal.org/update/theme/6/7" rel="noreferrer"><strong>and themes</strong></a>). </p>
<p>However what I am looking for with my question is more in the line of <em>strategy thinking</em>, or in other words, <strong>I am looking for inputs and advice on how to plan / implement / review the process of porting my own code</strong>, in the light of what colleague developers learned by previous experience. Some example:</p>
<ol>
<li>Would you advice to begin to port my modules as soon as I have time for doing it, and to maintain a concurrent D7 for some time (so I am "prepared" for the D-day) or would you advice to rather wait for the day in which the port will be actually <em>imminent</em> and then upgrade the modules to D7 and drop the D6 version?</li>
<li>Only some of my modules have full test coverage. Would you advice to complete test coverage for the D6 version so to have all tests working to check the D7 port, or would you advice to write my test directing at porting time, to test the D7 version?</li>
<li>Did you find that being an early adopter gives you an edge in terms of new features and better API's or did you rather find that is more convenient to delay the conversion so as to leverage the larger amount of readily available contrib modules?</li>
<li>Did you set for yourself quality standards / evaluation criteria or did you just set the bar to "if it works, I'm happy"? Why? If you set certain standards or goals, what did they where / what will they be? How did they help you?</li>
<li>Are there common pitfalls that you experienced in the past and that you think are applicable to the D6-D7 porting process?</li>
<li>Is porting a good moment to do some refactoring or it is just going to make everything more complex to be put back together?</li>
<li>...</li>
</ol>
<p>These questions are not an exhaustive list, but I hope they give an idea of what kind of information I am looking for. I would rather say: whatever you think is relevant and I did not list above gets a "plus"! :)</p>
<p>If I did not manage to express myself clearly enough, please post a comment with the info you think I should add in the question. Thank you in advance for your time!</p>
<p>PS: Yes I know... D7 is not yet out and it will take months before important contrib modules will be upgraded... but it's never too early to start thinking! :)</p> | 1,751,415 | 1 | 4 | 2009-11-28 15:17:01.103 UTC | 2009-11-17 18:52:37.77 UTC | 10 | 2009-11-17 21:37:17.147 UTC | null | null | null | null | 146,792 | null | 1 | 18 | drupal|drupal-6|upgrade|porting|drupal-7 | 4,962 | <p>Good questions, so let's see:</p>
<ol>
<li><p><em>(when to start porting)</em><br>
This certainly depends on the complexity of the modules to port. If there are really complex/large ones, it might be useful to start early in order to find tricky spots while not being under pressure. For smaller/standard ones, I'd try to find a bigger time slot later on where I can port many of them in a row in order to get the routine stuff memorized quickly (and benefit from the probably improved documentation).</p></li>
<li><p><em>(test coverage)</em><br>
Normally I'd say that having a good test coverage before starting refactoring/porting would certainly be advisable. But given that Drupal-7 introduces a major change concerning the testing framework by moving it to core, I'd expect the need to rewrite a significant amount of tests anyway. So if there is no need to maintain the Drupal-6 versions after the migration, I'd save the time/trouble and aim for increased coverage after the porting.</p></li>
<li><p><em>(early adopter vs. wait and see)</em><br>
Using Drupal since the 4.7 version, we have always waited for at least the first official release of a new major version before even thinking about porting. With Drupal 6, we waited for the views module before porting our first site, and we still have some smaller projects on Drupal-5, as they are working just fine and it would be hard to justify the extra bill for our clients as long as there are still maintenance/security fixes for it. There is just so much time in a day and there is always this backlog of bugs to fix, features to add, etc., so no use playing with unfinished technology while there are more imminent things to do that would immediately benefit our clients. Now this would certainly be different if we'd have to maintain one or more 'official' contributed modules, as offering an early port would be a good thing.<br>
I'm a bit in a bind here - being an early adopter certainly benefits the community, as someone has to find that bugs before they can get fixed, but on the other hand, it makes little business sense to fight hour after hour with bugs others might have found/fixed if you'd just waited a bit longer. As long as I have to do this for a living, I need to watch my resources, trying to strike an acceptable balance between serving the community and benefiting from it :-/</p></li>
<li><p><em>(quality standards)</em><br>
"If it works, I'm happy" just doesn't cut it, as I don't want to be happy momentarily only, but tomorrow as well. So one of my quality standards is that I need to be (somewhat) certain that I 'grokked' new concepts well enough in order to not just makes things work, but make them work like they should. Now this is hard to define more precisely, as it is obviously impossible to know if one 'got it' before 'getting it', so it boils down to a gut feeling/distinction of 'yeah, it kinda works' vs. 'yup, that looks right', and one has to accept that he will quite regularly be wrong about this.<br>
That said, one particular point I'm looking out for is 'intervene as early as possible'. As a beginner, I often tweaked stuff 'after the fact' during the theming stage, while it would have been much easier to apply the 'fix' earlier in the processing chain by means of one hook or the other. So right now, whenever I'm about to 'adjust' something in the theme layer, I deliberately take a small time out to check if this can not be done more cleanly/compatible within a hook earlier on. As I expect Drupal-7 to add even more hooking options, this is something I will pay extra attention to, as it usually reduces conflicts and sudden 'breaking of stuff' when adding new modules.</p></li>
<li><p><em>(common pitfalls)</em><br>
Well - mainly porting to early, finding out afterwards/in between that one or more needed modules were not available for the new version at all, or only in dev/alpha/early beta state. So I'd make sure to compile a <em>complete</em> list of used/needed modules first, listing their porting state, along with a quick inspection of their issue queues.<br>
Besides that, I have so far always been <em>very</em> pleased with the new versions and their improvements, and I'm looking forward for Drupal-7 again.</p></li>
<li><p><em>(refactoring while porting)</em><br>
One could say that porting is a rather large refactoring in itself, so there is no need to add to the complexity by restructuring non porting related stuff. On the other hand, if you already have to shred your modules to pieces anyway, why not use the opportunity to make it a major overhaul? I'd try to draw a line based on complexity - for big/complex modules, I'd do the port as straight as possible, and refactor more later on, if need be. For smaller modules, it shouldn't really matter, as the likelihood of introducing subtle bugs should be rather small.</p></li>
<li><p><em>(other stuff)</em><br>
... need to think about it ...</p></li>
</ol>
<hr>
<p>Ok, other stuff:</p>
<ul>
<li><p>Resource needs - given some of the Drupal-7 threads, it looks like they are likely to go up, so this should be evaluated before porting smaller sites that sit on a shared/restricted hosting account.</p></li>
<li><p>Latest versions first - This one is rather obvious and always stressed in the upgrade guides, but nevertheless worth mentioning: Upgrade core and all modules to their latest current version first before doing a major upgrade, as the upgrade code is highly likely to depend on the latest table/data structures to work correctly. Given Drupals 'piecemeal', one step at a time update strategy, it would be very hard to implement upgrade code that would detect different pre-upgrade states and acted accordingly.</p></li>
</ul> |
21,747,878 | How to populate a dropdown list with json data dynamically (section wise into three different dropdowns) and have an action encountered on click | <p>I am new to json and do not know a single thing about it, but seeing the power it gives, I am planning to switch over to it for a better performance. In my web application I have three different dropdown lists: say sedans, hatch and SUV.
<br> I want, whenever a user clicks on either of them, say hatch, the "name" of all the hatches in the json file gets loaded into the dropdown list. When the user clicks on any name of the hatch, corresponding price and carmaker company gets shown into the content of <code>id="show"</code> of the html page. <br>What should be the jquery snippet that I need to call to get this done/how shall I be proceeding. I'm a newbie to jquery, and know nothing about json, so a little help/guidance will be appreciated<br><br>Thanks in advance, please find the content of the files for more better idea.</p>
<p><strong>Contents of my html file (I'm using twitter bootstrap)</strong></p>
<pre><code><div id="abc">
<!-- btn-group --> <div class="btn-group"><button type="button" class="btn dropdown-toggle" data-toggle="dropdown">Hatch</button><ul class="dropdown-menu">
<li><a href="#">Hatch names here one below the other</a></li>
<li><a href="#">Next Hatch name here</a></li>
<li><a href="#">Next Hatch name here</a></li>
</ul>
</div><!-- /btn-group -->
<!-- btn-group --> <div class="btn-group"><button type="button" class="btn dropdown-toggle" data-toggle="dropdown">Sedan</button><ul class="dropdown-menu">
<li><a href="#">Sedan names here one below the other</a></li>
<li><a href="#">Next Sedan name here</a></li>
<li><a href="#">Next Sedan name here</a></li>
</ul>
</div><!-- /btn-group -->
<!-- btn-group --> <div class="btn-group"><button type="button" class="btn dropdown-toggle" data-toggle="dropdown">SUV</button><ul class="dropdown-menu">
<li><a href="#">SUV names here one below the other</a></li>
<li><a href="#">Next SUV name here</a></li>
<li><a href="#">Next SUV name here</a></li>
</ul>
</div><!-- /btn-group -->
</div>
<div id="show"><!-- Show the content related to the item clicked in either of the lists here --></div>
</code></pre>
<p><br><strong>Contents of my json file (<em>intended to store locally in the website's root folder</em>)</strong><br></p>
<pre><code>{
"Hatch": [
{
"name": "Fiesta",
"price": "1223",
"maker": "Ford"
},
{
"name": "Polo",
"price": "3453",
"maker": "VW"
}
],
"Sedan": [
{
"name": "Mustang",
"price": "1223",
"maker": "Ford"
},
{
"name": "Jetta",
"price": "3453",
"maker": "VW"
}
],
"SUV": [
{
"name": "Santa Fe",
"price": "1223",
"maker": "Hyundai"
},
{
"name": "Evoque",
"price": "3453",
"maker": "Land Rover"
}
]
}
</code></pre>
<p><br></p> | 21,748,943 | 2 | 0 | null | 2014-02-13 07:33:50.15 UTC | 8 | 2015-12-27 08:21:00.21 UTC | null | null | null | null | 1,697,773 | null | 1 | 8 | javascript|jquery|html|json|twitter-bootstrap | 29,012 | <p>It's to learn so look well, it's my day of kindness ^^^:</p>
<p><strong>Bootply</strong> : <a href="http://bootply.com/113296">http://bootply.com/113296</a></p>
<p><strong>JS</strong> : </p>
<pre><code> $(document).ready(function(){
for( index in json.Hatch )
{
$('#hatch ul').append('<li><a href="#" data-maker="'+json.Hatch[index].maker+'" data-price="'+json.Hatch[index].price+'">'+json.Hatch[index].name+'</a></li>');
}
for( index in json.Sedan )
{
$('#sedan ul').append('<li><a href="#" data-maker="'+json.Sedan[index].maker+'" data-price="'+json.Sedan[index].price+'">'+json.Sedan[index].name+'</a></li>');
}
for( index in json.SUV )
{
$('#suv ul').append('<li><a href="#" data-maker="'+json.SUV[index].maker+'" data-price="'+json.SUV[index].price+'">'+json.SUV[index].name+'</a></li>');
}
$('a').on('click', function(){
$('#show').html( 'Price : ' + $(this).attr('data-price') + '| Maker : ' + $(this).attr('data-maker') );
});
});
</code></pre> |
21,782,380 | Are Java 8 Streams the same as .Net IEnumerable? | <p>At first I thought Java Streams were necessarily related to I/O but they look really like the IEnumerable interface in .Net. </p>
<p>Is that comparison fair?</p> | 21,782,569 | 1 | 0 | null | 2014-02-14 14:47:21.997 UTC | 8 | 2019-03-27 14:16:44.547 UTC | 2014-02-14 14:52:18.597 UTC | null | 1,587,046 | null | 48,684 | null | 1 | 30 | java|.net|java-8 | 15,722 | <p>Maybe this is something interesting I found on google for you:</p>
<p><strong>Streams</strong></p>
<p>Java streams (not to be confused with InputStream and OutputStream) do more or less the same thing as LINQ, with parallel processing mirroring PLINQ. There isn't any nice SQL-like syntax to use, though - you have to do it function-style. And just as LINQ required extension methods, streams don't appear until Java 8 because they need defender methods to work with existing collection types.</p>
<p>Stream is largely equivalent to .NET IEnumerable. To see how they're similar, consider these examples:</p>
<pre><code>// Write each value in a collection to standard output on a separate line:
// C# - LINQ
myCollection.ForEach( x => Console.WriteLine(x) );
// Java - stream
myCollection.stream().forEach( x -> System.out.println(x) );
// Sum all the values in a (potentially large) collection, using parallelism
// if possible:
// C# - PLINQ
int sum = myCollection.AsParallel().Aggregate( (x, y) => x + y );
// Java - parallel stream
int sum = myCollection.stream().parallel().reduce( (x, y) -> x + y );
</code></pre>
<p>You would expect the stream() method to be on Iterable, in the same way as LINQ operates on IEnumerable, but it's on Collection instead. Perhaps it's because Java lacks yield-return semantics, so Iterable is just less interesting or useful in Java.</p>
<p>source: <a href="http://leftoblique.net/wp/2013/07/25/java-8-a-k-a-oracle-finally-catches-up-to-net-framework-3-0/" rel="noreferrer">http://leftoblique.net/wp/2013/07/25/java-8-a-k-a-oracle-finally-catches-up-to-net-framework-3-0/</a></p>
<p><strong>EDIT:</strong>
There is a lot to find about it on Google. Here are some more interesting articles:
<a href="https://web.archive.org/web/20130331002411/http://blog.informatech.cr/2013/03/24/java-streams-preview-vs-net-linq/" rel="noreferrer">https://web.archive.org/web/20130331002411/http://blog.informatech.cr/2013/03/24/java-streams-preview-vs-net-linq/</a></p> |
30,154,798 | Option for Cascade Delete for References or On Delete | <p>In Rails 4.2, when creating a table or adding a reference via references or add_reference how do you specify that the foreign key should cascade on delete.</p>
<p>Command to generate scaffold:</p>
<pre><code>rails g scaffold Child parent:references name:string
</code></pre>
<p>Resulting migration:</p>
<pre><code>create_table :childs do |t|
t.references :parent, index: true, foreign_key: true
t.string :name
t.timestamps null: false
end
</code></pre> | 31,800,320 | 2 | 0 | null | 2015-05-10 18:02:15.777 UTC | 7 | 2018-09-20 00:01:29.487 UTC | null | null | null | null | 1,015,686 | null | 1 | 33 | ruby-on-rails|ruby-on-rails-4|database-migration | 12,683 | <p>This should work</p>
<pre><code>create_table :childs do |t|
t.references :parent, index: true, foreign_key: {on_delete: :cascade}
t.string :name
t.timestamps null: false
end
</code></pre>
<p>According to <code>ActiveRecord::ConnectionAdapters::TableDefinition#references</code>, if a hash is specified on the <code>foreign_key</code> option, it is directly passed down into the <code>foreign_key</code> method.</p>
<p>source:</p>
<pre><code>foreign_key(col.to_s.pluralize, foreign_key_options.is_a?(Hash) ? foreign_key_options : {}) if foreign_key_options
</code></pre> |
29,874,274 | Bootstrap table. How to remove all borders from table? | <p>How to remove all (especially outer ones) borders from <a href="http://bootstrap-table.wenzhixin.net.cn/" rel="noreferrer">bootstrap table</a>? Here is a table without inner borders:</p>
<p><strong>HTML</strong></p>
<pre><code><style>
.table th, .table td {
border-top: none !important;
border-left: none !important;
}
</style>
<div class="row">
<div class="col-xs-1"></div>
<div class="col-xs-10">
<br/>
<table data-toggle="table" data-striped="true">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>B</td>
</tr>
<tr>
<td>C</td>
<td>D</td>
</tr>
<tr>
<td>E</td>
<td>F</td>
</tr>
</tbody>
</table>
</div>
<div class="col-xs-1"></div>
</row>
</code></pre>
<p><a href="http://jsfiddle.net/sba7wkvb/1/" rel="noreferrer">http://jsfiddle.net/sba7wkvb/1/</a></p>
<p>Which CSS styles need to be overriden to remove all borders?</p> | 29,874,402 | 11 | 0 | null | 2015-04-26 05:51:26.017 UTC | 1 | 2018-05-03 04:15:59.71 UTC | null | null | null | null | 4,556,720 | null | 1 | 15 | css|twitter-bootstrap|twitter-bootstrap-3|bootstrap-table | 67,482 | <p>In this case you need to set the border <strong>below the table</strong> and the borders <strong>around - table heade</strong>r, <strong>table data</strong>, <strong>table container</strong> all to 0px in-order to totally get rid of all borders.</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.table {
border-bottom:0px !important;
}
.table th, .table td {
border: 1px !important;
}
.fixed-table-container {
border:0px !important;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://rawgit.com/wenzhixin/bootstrap-table/master/src/bootstrap-table.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="https://rawgit.com/wenzhixin/bootstrap-table/master/src/bootstrap-table.js"></script>
<div class="row">
<div class="col-xs-1"></div>
<div class="col-xs-10">
<br/>
<table data-toggle="table" data-striped="true">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>B</td>
</tr>
<tr>
<td>C</td>
<td>D</td>
</tr>
<tr>
<td>E</td>
<td>F</td>
</tr>
</tbody>
</table>
</div>
<div class="col-xs-1"></div></code></pre>
</div>
</div>
</p> |
36,146,684 | Using seaborn, how can I draw a line of my choice across my scatterplot? | <p>I want to be able to draw a line of my specification across a plot generated in seaborn. The plot I chose was JointGrid, but any scatterplot will do. I suspect that seaborn maybe doesn't make it easy to do this?</p>
<p>Here is the code plotting the data (dataframes from the Iris dataset of petal length and petal width):</p>
<pre><code>import seaborn as sns
iris = sns.load_dataset("iris")
grid = sns.JointGrid(iris.petal_length, iris.petal_width, space=0, size=6, ratio=50)
grid.plot_joint(plt.scatter, color="g")
</code></pre>
<p><a href="https://i.stack.imgur.com/9II9Z.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9II9Z.png" alt="enter image description here"></a></p>
<p>If you take this graph from the iris dataset, how can I draw a line of my choice across it? For example, a line of negative slope might separate the clusters, and positive slope might run across them.</p> | 36,148,001 | 2 | 0 | null | 2016-03-22 05:20:41.32 UTC | 3 | 2017-07-02 14:06:01.157 UTC | 2016-03-22 19:22:47.807 UTC | null | 391,339 | null | 391,339 | null | 1 | 24 | python|matplotlib|seaborn | 63,623 | <p>It appears that you have imported <code>matplotlib.pyplot</code> as <code>plt</code> to obtain <code>plt.scatter</code> in your code. You can just use the matplotlib functions to plot the line:</p>
<pre><code>import seaborn as sns
import matplotlib.pyplot as plt
iris = sns.load_dataset("iris")
grid = sns.JointGrid(iris.petal_length, iris.petal_width, space=0, size=6, ratio=50)
grid.plot_joint(plt.scatter, color="g")
plt.plot([0, 4], [1.5, 0], linewidth=2)
</code></pre>
<p><a href="https://i.stack.imgur.com/pWh3H.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pWh3H.png" alt="enter image description here"></a></p> |
36,096,928 | compressing a video in iOS | <p>I've looked at <a href="https://stackoverflow.com/questions/5687341/iphoneprogrammatically-compressing-recorded-video-to-share">this question</a> and <a href="https://stackoverflow.com/questions/11751883/how-can-i-reduce-the-file-size-of-a-video-created-with-uiimagepickercontroller">this question</a>, neither have been able to help.</p>
<p>I have tried the following: </p>
<pre><code>- (void)compress:(NSURL *)videoPath completionBlock:(void(^)(id data, BOOL result))block{
self.outputFilePath = [[NSString alloc] initWithFormat:@"%@%@", NSTemporaryDirectory(), @"output.mov"];
NSURL *outputURL = [NSURL fileURLWithPath:self.outputFilePath];
[self compressVideoWithURL:self.movieURL outputURL:outputURL handler:^(AVAssetExportSession *exportSession) {
}];
}
- (void)compressVideoWithURL:(NSURL*)inputURL
outputURL:(NSURL*)outputURL
handler:(void (^)(AVAssetExportSession*))handler {
AVURLAsset *asset = [AVURLAsset assetWithURL:self.movieURL];
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetLowQuality];
exportSession.fileLengthLimit = 3000000;
exportSession.outputURL = outputURL;
exportSession.outputFileType = AVFileTypeQuickTimeMovie;
exportSession.shouldOptimizeForNetworkUse = YES;
[exportSession exportAsynchronouslyWithCompletionHandler:^{
NSData *newOutputData = [NSData dataWithContentsOfURL:outputURL];
NSLog(@"Size of New Video(bytes):%d",[newOutputData length]);
}];
}
</code></pre>
<p>I know that <code>self.movieUrl</code> is not <code>nil</code>. But when I printed the size (in bytes) of the <code>NSData</code> associated with the video, they were the same before and after, both 30,000,000 bytes. </p>
<p>But according to <a href="https://stackoverflow.com/questions/5687341/iphoneprogrammatically-compressing-recorded-video-to-share">this question</a>, the above code should work. </p>
<p>What am I doing wrong exactly?</p> | 36,097,287 | 2 | 0 | null | 2016-03-19 01:49:52.117 UTC | 8 | 2022-08-11 13:07:09.247 UTC | 2017-05-23 10:30:45.72 UTC | null | -1 | null | 5,136,425 | null | 1 | 7 | ios|avfoundation | 15,609 | <p>I have figured it out, thanks to this question (Swift version): <a href="https://stackoverflow.com/questions/29521789/ios-video-compression-swift-ios-8-corrupt-video-file">IOS Video Compression Swift iOS 8 corrupt video file</a></p>
<p>I have the objective C version. Here is the method:</p>
<pre><code> - (void)compressVideo:(NSURL*)inputURL
outputURL:(NSURL*)outputURL
handler:(void (^)(AVAssetExportSession*))completion {
AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:urlAsset presetName:AVAssetExportPresetMediumQuality];
exportSession.outputURL = outputURL;
exportSession.outputFileType = AVFileTypeQuickTimeMovie;
exportSession.shouldOptimizeForNetworkUse = YES;
[exportSession exportAsynchronouslyWithCompletionHandler:^{
completion(exportSession);
}];
}
</code></pre>
<p>And calling the method:</p>
<pre><code>NSURL* uploadURL = [NSURL fileURLWithPath:
[NSTemporaryDirectory() stringByAppendingPathComponent:@"temporaryPreview.mov"]];
[self compressVideo:self.movieURL outputURL:uploadURL handler:^(AVAssetExportSession *completion) {
if (completion.status == AVAssetExportSessionStatusCompleted) {
NSData *newDataForUpload = [NSData dataWithContentsOfURL:uploadURL];
NSLog(@"Size of new Video after compression is (bytes):%d",[newDataForUpload length]);
}
}];
</code></pre>
<p>This reduced the file size of my videos from 32 MB to 1.5 MB.</p> |
43,628,984 | Kotlin sequence "skip" first N entries | <p>How can I "skip" the first N entries of a kotlin sequence/list?</p>
<p>I am looking for the kotlin equivalent of <a href="https://msdn.microsoft.com/en-us/library/bb358985(v=vs.110).aspx" rel="noreferrer">C# LINQ "skip"</a>.</p> | 43,628,985 | 1 | 0 | null | 2017-04-26 08:37:47.677 UTC | 2 | 2017-04-26 08:37:47.677 UTC | null | null | null | null | 808,723 | null | 1 | 68 | kotlin|sequences | 21,780 | <p>You are probably looking for the <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/drop.html" rel="noreferrer">"drop" function</a> known for example from <a href="https://lodash.com/docs/4.17.4#drop" rel="noreferrer">from lodash</a>:</p>
<pre class="lang-kotlin prettyprint-override"><code>val seq = 1..10
seq.drop(5)
> [6, 7, 8, 9, 10]
</code></pre> |
49,527,159 | How to get the output shape of a layer in Keras? | <p>I have the following code in Keras (Basically I am modifying this code for my use) and I get this error:</p>
<p>'ValueError: Error when checking target: expected conv3d_3 to have 5 dimensions, but got array with shape (10, 4096)'</p>
<p>Code:</p>
<pre><code>from keras.models import Sequential
from keras.layers.convolutional import Conv3D
from keras.layers.convolutional_recurrent import ConvLSTM2D
from keras.layers.normalization import BatchNormalization
import numpy as np
import pylab as plt
from keras import layers
# We create a layer which take as input movies of shape
# (n_frames, width, height, channels) and returns a movie
# of identical shape.
model = Sequential()
model.add(ConvLSTM2D(filters=40, kernel_size=(3, 3),
input_shape=(None, 64, 64, 1),
padding='same', return_sequences=True))
model.add(BatchNormalization())
model.add(ConvLSTM2D(filters=40, kernel_size=(3, 3),
padding='same', return_sequences=True))
model.add(BatchNormalization())
model.add(ConvLSTM2D(filters=40, kernel_size=(3, 3),
padding='same', return_sequences=True))
model.add(BatchNormalization())
model.add(ConvLSTM2D(filters=40, kernel_size=(3, 3),
padding='same', return_sequences=True))
model.add(BatchNormalization())
model.add(Conv3D(filters=1, kernel_size=(3, 3, 3),
activation='sigmoid',
padding='same', data_format='channels_last'))
model.compile(loss='binary_crossentropy', optimizer='adadelta')
</code></pre>
<p>the data I feed is in the following format: [1, 10, 64, 64, 1].
So I would like to know where I am wrong and also how to see the output_shape of each layer.</p> | 49,527,269 | 2 | 0 | null | 2018-03-28 06:01:53.633 UTC | 5 | 2022-06-17 17:54:07.033 UTC | null | null | null | null | 8,234,464 | null | 1 | 26 | python|keras|lstm|recurrent-neural-network | 49,876 | <p>You can get the output shape of a layer by <a href="https://keras.io/layers/about-keras-layers/" rel="noreferrer"><code>layer.output_shape</code></a>.</p>
<pre><code>for layer in model.layers:
print(layer.output_shape)
</code></pre>
<p>Gives you:</p>
<pre><code>(None, None, 64, 64, 40)
(None, None, 64, 64, 40)
(None, None, 64, 64, 40)
(None, None, 64, 64, 40)
(None, None, 64, 64, 40)
(None, None, 64, 64, 40)
(None, None, 64, 64, 40)
(None, None, 64, 64, 40)
(None, None, 64, 64, 1)
</code></pre>
<p>Alternatively you can pretty print the model using <a href="https://keras.io/models/about-keras-models/" rel="noreferrer"><code>model.summary</code></a>:</p>
<pre><code>model.summary()
</code></pre>
<p>Gives you the details about the number of parameters and output shapes of each layer and an overall model structure in a pretty format:</p>
<pre><code>_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv_lst_m2d_1 (ConvLSTM2D) (None, None, 64, 64, 40) 59200
_________________________________________________________________
batch_normalization_1 (Batch (None, None, 64, 64, 40) 160
_________________________________________________________________
conv_lst_m2d_2 (ConvLSTM2D) (None, None, 64, 64, 40) 115360
_________________________________________________________________
batch_normalization_2 (Batch (None, None, 64, 64, 40) 160
_________________________________________________________________
conv_lst_m2d_3 (ConvLSTM2D) (None, None, 64, 64, 40) 115360
_________________________________________________________________
batch_normalization_3 (Batch (None, None, 64, 64, 40) 160
_________________________________________________________________
conv_lst_m2d_4 (ConvLSTM2D) (None, None, 64, 64, 40) 115360
_________________________________________________________________
batch_normalization_4 (Batch (None, None, 64, 64, 40) 160
_________________________________________________________________
conv3d_1 (Conv3D) (None, None, 64, 64, 1) 1081
=================================================================
Total params: 407,001
Trainable params: 406,681
Non-trainable params: 320
_________________________________________________________________
</code></pre>
<p>If you want to access information about a specific layer only, you can use <code>name</code> argument when constructing that layer and then call like this:</p>
<pre><code>...
model.add(ConvLSTM2D(..., name='conv3d_0'))
...
model.get_layer('conv3d_0')
</code></pre>
<hr>
<p><strong>EDIT:</strong> For reference sake it will always be same as <code>layer.output_shape</code> and please don't actually use Lambda or custom layers for this. But you can use <a href="https://keras.io/layers/core/#lambda" rel="noreferrer"><code>Lambda</code></a> layer to echo the shape of a passing tensor.</p>
<pre><code>...
def print_tensor_shape(x):
print(x.shape)
return x
model.add(Lambda(print_tensor_shape))
...
</code></pre>
<p>Or write a custom layer and print the shape of the tensor on <code>call()</code>.</p>
<pre><code>class echo_layer(Layer):
...
def call(self, x):
print(x.shape)
return x
...
model.add(echo_layer())
</code></pre> |
22,901,726 | How can I integrate Bower with Gulp.js? | <p>I am trying to write a gulp task that does a few things</p>
<ol>
<li>Install the Bower dependencies</li>
<li>Concat those dependencies into one file in the order of the dependencies</li>
</ol>
<p>I was hoping to do this without having to specify the paths to those dependencies. I know there is the command <code>bower list --paths</code> but I am unsure of if it is possible to tie it together. </p>
<p>Any thoughts?</p>
<h1>Edit</h1>
<p>So I am trying to use the <a href="https://github.com/ck86/gulp-bower-files">gulp-bower-files</a> and I am getting an eaccess error and its not generating the concatenated file.</p>
<p><strong>gulpfile.js</strong></p>
<pre><code>var gulp = require('gulp');
var bower = require('bower');
var concat = require('gulp-concat');
var bower_files = require('gulp-bower-files');
gulp.task("libs", function(){
bower_files()
.pipe(concat('./libs.js'))
.pipe(gulp.dest("/"));
});
</code></pre>
<p><strong>bower.json</strong></p>
<pre><code>{
"name": "ember-boilerplate",
"version": "0.0.0",
"dependencies": {
"ember": "1.6.0-beta.1",
"ember-data": "1.0.0-beta.7"
}
}
</code></pre>
<p>and I keep coming across this error</p>
<pre><code>events.js:72
throw er; // Unhandled 'error' event
^
Error: EACCES, open '/libs.js'
</code></pre> | 24,808,013 | 2 | 0 | null | 2014-04-07 00:25:05.57 UTC | 16 | 2017-01-11 22:11:01.143 UTC | 2014-04-07 03:15:53.183 UTC | null | 2,317,010 | null | 2,317,010 | null | 1 | 30 | bower|gulp | 26,531 | <p>Use <a href="https://github.com/ck86/main-bower-files" rel="nofollow noreferrer">main-bower-files</a></p>
<p>It grabs all production (main) files of your Bower packages defined in your project's bower.json and use them as your gulp src for your task.</p>
<p>integrate it in your gulpfile:</p>
<pre><code>var mainBowerFiles = require('main-bower-files');
</code></pre>
<p>I made this task that grabs all production files, filters css/js/fonts and outputs them in the public folder in their respective subfolders (css/js/fonts).</p>
<p>Here's an example: </p>
<pre><code>var gulp = require('gulp');
// define plug-ins
var flatten = require('gulp-flatten');
var gulpFilter = require('gulp-filter'); // 4.0.0+
var uglify = require('gulp-uglify');
var minifycss = require('gulp-minify-css');
var rename = require('gulp-rename');
var mainBowerFiles = require('main-bower-files');
// Define paths variables
var dest_path = 'www';
// grab libraries files from bower_components, minify and push in /public
gulp.task('publish-components', function() {
var jsFilter = gulpFilter('**/*.js');
var cssFilter = gulpFilter('**/*.css');
var fontFilter = gulpFilter(['**/*.eot', '**/*.woff', '**/*.svg', '**/*.ttf']);
return gulp.src(mainBowerFiles())
// grab vendor js files from bower_components, minify and push in /public
.pipe(jsFilter)
.pipe(gulp.dest(dest_path + '/js/'))
.pipe(uglify())
.pipe(rename({
suffix: ".min"
}))
.pipe(gulp.dest(dest_path + '/js/'))
.pipe(jsFilter.restore())
// grab vendor css files from bower_components, minify and push in /public
.pipe(cssFilter)
.pipe(gulp.dest(dest_path + '/css'))
.pipe(minifycss())
.pipe(rename({
suffix: ".min"
}))
.pipe(gulp.dest(dest_path + '/css'))
.pipe(cssFilter.restore())
// grab vendor font files from bower_components and push in /public
.pipe(fontFilter)
.pipe(flatten())
.pipe(gulp.dest(dest_path + '/fonts'));
});
</code></pre> |
40,485,398 | Retry logic with CompletableFuture | <p>I need to submit a task in an async framework I'm working on, but I need to catch for exceptions, and retry the same task multiple times before "aborting".</p>
<p>The code I'm working with is:</p>
<pre><code>int retries = 0;
public CompletableFuture<Result> executeActionAsync() {
// Execute the action async and get the future
CompletableFuture<Result> f = executeMycustomActionHere();
// If the future completes with exception:
f.exceptionally(ex -> {
retries++; // Increment the retry count
if (retries < MAX_RETRIES)
return executeActionAsync(); // <--- Submit one more time
// Abort with a null value
return null;
});
// Return the future
return f;
}
</code></pre>
<p>This currently doesn't compile because the return type of the lambda is wrong: it expects a <code>Result</code>, but the <code>executeActionAsync</code> returns a <code>CompletableFuture<Result></code>. </p>
<p>How can I implement this fully async retry logic?</p> | 40,497,164 | 9 | 3 | null | 2016-11-08 11:11:52.367 UTC | 11 | 2022-03-18 15:41:30.13 UTC | null | null | null | null | 6,570,821 | null | 1 | 33 | java|exception|asynchronous|concurrency|java-8 | 32,990 | <p>I think I was successfully. Here's an example class I created and the test code:</p>
<hr>
<h2>RetriableTask.java</h2>
<pre><code>public class RetriableTask
{
protected static final int MAX_RETRIES = 10;
protected int retries = 0;
protected int n = 0;
protected CompletableFuture<Integer> future = new CompletableFuture<Integer>();
public RetriableTask(int number) {
n = number;
}
public CompletableFuture<Integer> executeAsync() {
// Create a failure within variable timeout
Duration timeoutInMilliseconds = Duration.ofMillis(1*(int)Math.pow(2, retries));
CompletableFuture<Integer> timeoutFuture = Utils.failAfter(timeoutInMilliseconds);
// Create a dummy future and complete only if (n > 5 && retries > 5) so we can test for both completion and timeouts.
// In real application this should be a real future
final CompletableFuture<Integer> taskFuture = new CompletableFuture<>();
if (n > 5 && retries > 5)
taskFuture.complete(retries * n);
// Attach the failure future to the task future, and perform a check on completion
taskFuture.applyToEither(timeoutFuture, Function.identity())
.whenCompleteAsync((result, exception) -> {
if (exception == null) {
future.complete(result);
} else {
retries++;
if (retries >= MAX_RETRIES) {
future.completeExceptionally(exception);
} else {
executeAsync();
}
}
});
// Return the future
return future;
}
}
</code></pre>
<hr>
<h2>Usage</h2>
<pre><code>int size = 10;
System.out.println("generating...");
List<RetriableTask> tasks = new ArrayList<>();
for (int i = 0; i < size; i++) {
tasks.add(new RetriableTask(i));
}
System.out.println("issuing...");
List<CompletableFuture<Integer>> futures = new ArrayList<>();
for (int i = 0; i < size; i++) {
futures.add(tasks.get(i).executeAsync());
}
System.out.println("Waiting...");
for (int i = 0; i < size; i++) {
try {
CompletableFuture<Integer> future = futures.get(i);
int result = future.get();
System.out.println(i + " result is " + result);
} catch (Exception ex) {
System.out.println(i + " I got exception!");
}
}
System.out.println("Done waiting...");
</code></pre>
<hr>
<h2>Output</h2>
<pre><code>generating...
issuing...
Waiting...
0 I got exception!
1 I got exception!
2 I got exception!
3 I got exception!
4 I got exception!
5 I got exception!
6 result is 36
7 result is 42
8 result is 48
9 result is 54
Done waiting...
</code></pre>
<hr>
<p>Main idea and some glue code (<code>failAfter</code> function) come from <a href="http://www.nurkiewicz.com/2014/12/asynchronous-timeouts-with.html" rel="noreferrer">here</a>. </p>
<p>Any other suggestions or improvement are welcome.</p> |
64,095,094 | Command "python setup.py egg_info" failed with error code 1 in /tmp/..../ | <p>I got the following error installing a dependency with <code>pip</code>:</p>
<blockquote>
<p>pip9.exceptions.InstallationError
Command "python setup.py egg_info" failed with error code 1 in /tmp/tmpoons7qgkbuild/opencv-python/</p>
</blockquote>
<p>Below is the result of running the command <code>pipenv install opencv-python</code> on a recent linux (5.4.0 x64) system.</p>
<pre><code>Locking [packages] dependencies…
self.repository.get_dependencies(ireq):
File "/usr/lib/python3/dist-packages/pipenv/patched/piptools/repositories/pypi.py", line 174, in get_dependencies
legacy_results = self.get_legacy_dependencies(ireq)
File "/usr/lib/python3/dist-packages/pipenv/patched/piptools/repositories/pypi.py", line 222, in get_legacy_dependencies
result = reqset._prepare_file(self.finder, ireq, ignore_requires_python=True)
File "/usr/lib/python3/dist-packages/pipenv/patched/notpip/req/req_set.py", line 644, in _prepare_file
abstract_dist.prep_for_dist()
File "/usr/lib/python3/dist-packages/pipenv/patched/notpip/req/req_set.py", line 134, in prep_for_dist
self.req_to_install.run_egg_info()
File "/usr/lib/python3/dist-packages/pipenv/vendor/pip9/req/req_install.py", line 435, in run_egg_info
call_subprocess(
File "/usr/lib/python3/dist-packages/pipenv/vendor/pip9/utils/__init__.py", line 705, in call_subprocess
raise InstallationError(
pip9.exceptions.InstallationError: Command "python setup.py egg_info" failed with error code 1 in /tmp/tmpoons7qgkbuild/opencv-python/
</code></pre> | 64,095,095 | 10 | 1 | null | 2020-09-28 02:08:58.807 UTC | 8 | 2022-08-02 01:03:18.803 UTC | 2022-08-02 01:03:18.803 UTC | null | 6,674,599 | null | 6,674,599 | null | 1 | 40 | python|pip|pipenv | 138,039 | <h1>How to fix the <code>pip9.exceptions.InstallationError</code></h1>
<p>Make sure the version of your <code>pip</code> and <code>setuptools</code> is sufficient for <code>manylinux2014 wheels</code>.</p>
<p><strong>A) System Install</strong></p>
<pre><code>sudo python3 -m pip install -U pip
sudo python3 -m pip install -U setuptools
</code></pre>
<p><strong>B) Virtual Env / Pipenv</strong></p>
<pre><code># Within the venv
pip3 install -U pip
pip3 install -U setuptools
</code></pre>
<h1>Explanation</h1>
<p>For me, <code>python setup.py egg_info</code> probably failed because of a recent change in python wheels, as <code>manylinux1 wheels</code> were replaced by <code>manylinux2014 wheels</code> according to <a href="https://github.com/skvark/opencv-python#frequently-asked-questions" rel="noreferrer">open-cv faq</a>.</p> |
22,296,531 | Navigation drawer default fragment | <p>I am novice developer and I´m integrating Navigation drawer in my app with android-support v7 and I have one question. When I start the app the main layout is this:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
</code></pre>
<p></p>
<pre><code><!-- The main content view -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView
android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@android:color/white"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp" />
</code></pre>
<p></p>
<p>and this is my main activity:</p>
<pre><code>drawerList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
case 3:
fragment = new Fragment4();
break;
}
FragmentManager fragmentManager =
getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
drawerList.setItemChecked(position, true);
tituloSeccion = opcionesMenu[position];
getSupportActionBar().setTitle(tituloSeccion);
drawerLayout.closeDrawer(drawerList);
}
});
</code></pre>
<p>How can I set default fragment like main layout of the app? Thank you</p> | 22,296,764 | 7 | 1 | null | 2014-03-10 09:37:14.09 UTC | 8 | 2021-04-14 06:10:01.227 UTC | 2014-03-10 10:13:31.533 UTC | null | 3,162,390 | null | 3,383,415 | null | 1 | 22 | android|android-fragments | 45,277 | <p>If it is ok for you to load the default fragment every time your activity is created, you can put a <code>FragmentTransaction</code> in <code>onCreate()</code></p>
<p>Looks something like this:</p>
<pre><code>@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.content_frame, new Fragment1());
tx.commit();
}
</code></pre>
<p>If you want a more sophisticated way of doing this (for example switching to a different fragment when you go back to the main activity), you can use an <code>Intent</code> with extras determining the fragment in <code>onCreate()</code>, where you just put your default fragment in the <code>defaultValue</code> upon loading the extra:</p>
<pre><code>int position = getIntent().getIntExtra("position", 1);
switch(position){
...
}
</code></pre> |
25,505,045 | Display UIAlertController from UIView/NSObject class | <p>I have <em><code>working iOS application</code></em>
In order to <em><code>support iOS8</code></em>, I am replacing <em><code>UIAlertView/UIActionSheet with
UIAlertController</code></em>.</p>
<p><strong>Problem :</strong><br>
For display UIAlertController I need presentViewController
method of UIViewController class.<br>
<strong>But</strong> UIAlertView is display from classes which are <em><code>inherited</code></em> from
<em><code>UIView or NSObject</code></em>, <br>
I can not get <code>[self presentViewController...]</code> method for obvious reason.</p>
<p><strong>My Work :</strong><br>
I tried getting rootViewController form current window and display UIAlertController.</p>
<pre><code>[[[UIApplication sharedApplication] keyWindow].rootViewController presentViewController ...]
</code></pre>
<p>but have some rotation problems like if my current view controller do not have rotation support
it will rotate if UIAlertController is open.</p>
<p><strong>Question :</strong><br>
Did any one faced same problem and have safe solution ? <br>
if yes please provide me some example or give some guide</p> | 25,505,612 | 10 | 1 | null | 2014-08-26 11:44:28.15 UTC | 8 | 2020-05-31 09:09:41.483 UTC | null | null | null | null | 914,538 | null | 1 | 27 | objective-c|uialertview|ios8|uiactionsheet|uialertcontroller | 30,636 | <p>It looks like you are currently (pre-iOS8) triggering an alert view from within your view object. That's pretty bad practice, as in general alerts should be triggered from actions and logic. And that code should live in controllers.</p>
<p>I suggest you refactor your current code to move the logic that triggers the alert to the correct controller, and then you can easily upgrade to iOS 8 by using <code>self</code> as the controller.</p>
<p>If instead you're calling the alert from an outside object, then pass in the controller to the method that calls the alert. Somewhere upstream you must have knowledge of the controller.</p> |
30,351,465 | HTML-Email with inline attachments and non-inline attachments | <p>What is the correct way to create a HTML-Email with inline attachments and non-inline attachments?</p>
<p>In addition please tell me what Content-Type to use with only inline attachments and with only non-inline attachments.</p>
<p>Until now i did it like this:</p>
<pre><code>MIME-Version: 1.0
[some more headers]
Content-type: multipart/mixed;
boundary="myboundary"
--myboundary
Content-Type: text/html; charset=ISO-8859-15
Content-Transfer-Encoding: 7bit
[html with img cid:my_image]
--myboundary
Content-Type: image/png; name="my_image.png"
Content-Transfer-Encoding: base64
Content-ID: <my_image>
Content-Disposition: inline; filename="my_image.png"
[base64 image data]
--myboundary
Content-type: application/pdf; name="my_pdf.pdf"
Content-length: 1150
Content-Transfer-Encoding: base64
Content-ID: <my_pdf.pdf>
Content-Disposition: attachment; filename="my_pdf.pdf"
[base64 pdf data]
--myboundary--
</code></pre>
<p>The mail looks good in outlook. But I noticed that Thunderbird did not display my inline image and shows 2 attachments instead (My image and my PDF). So I did some debugging and noticed that inline images should be sent via <code>Content-Type: multipart/related</code>. </p>
<p>So I changed <code>Content-Type: multipart/mixed</code> to <code>Content-Type: multipart/related</code> and Thunderbird displayed it correct: The image is shown in html and one attachment, the PDF is shown.</p>
<p>I am not sure if this is the correct solution although it seems to work. Is it correct to use <code>multipart/related</code> always (in case if i have inline and non-inline attachments, in case if i have only inline attachments and in case if i have only non-inline attachments)?</p>
<p>Or is the correct way to use one boundary of type related to split the inline attachments and one other boundary of type mixed to split the non-inline attachments?</p>
<p>I hope you can provide me a sample for</p>
<ol>
<li>Email with inline only attachments</li>
<li>Email with non-inline only attachments</li>
<li>Email with inline and non-inline attachments</li>
</ol> | 30,424,938 | 1 | 1 | null | 2015-05-20 13:41:32.243 UTC | 18 | 2018-09-14 22:57:11.013 UTC | 2018-09-14 22:57:11.013 UTC | null | 761,963 | null | 811,131 | null | 1 | 22 | email|mime|email-attachments | 24,220 | <p><strong>Images</strong></p>
<p>Yes, it is correct approach to use <code>multipart/related</code> content type. Here is an example (please note 'Content-Type' and 'Content-Disposition' values):</p>
<p><img src="https://i.stack.imgur.com/3nw90.png" alt="enter image description here"></p>
<p><a href="https://www.campaignmonitor.com/blog/post/1759/embedding-images-revisited/" rel="noreferrer">Example source and detailed info</a></p>
<p>Here are samples you've requested:</p>
<ol>
<li>Email with inline only attachments</li>
<li>Email with non-inline only attachments</li>
<li>Email with inline and non-inline attachments</li>
</ol>
<p><strong>Sample 1: inline only</strong></p>
<p><img src="https://i.stack.imgur.com/BNLr8.png" alt="enter image description here"></p>
<pre><code>Subject: Test 01: inline only
To: Renat Gilmanov
Content-Type: multipart/related; boundary=089e0149bb0ea4e55c051712afb5
--089e0149bb0ea4e55c051712afb5
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
<div dir=3D"ltr">Lorem ipsum dolor sit amet, consectetur adipiscing elit. P=
ellentesque odio urna, bibendum eu ultricies in, dignissim in magna. Vivamu=
s risus justo, viverra sed dapibus eu, laoreet eget erat. Sed pretium a urn=
a id pulvinar.<br><br><img src=3D"cid:ii_ia6yo3z92_14d962f8450cc6f1" height=
=3D"218" width=3D"320"><br>=E2=80=8B<br>Cras eu velit ac purus feugiat impe=
rdiet nec sit amet ipsum. Praesent gravida lobortis justo, nec tristique ve=
lit sagittis finibus. Suspendisse porta ante id diam varius, in cursus ante=
luctus. Aenean a mollis mi. Pellentesque accumsan lacus sed erat vulputate=
, et semper tellus condimentum.<br><br>Best regards<br></div>
--089e0149bb0ea4e55c051712afb5
Content-Type: image/png; name="test-01.png"
Content-Disposition: inline; filename="test-01.png"
Content-Transfer-Encoding: base64
Content-ID: <ii_ia6yo3z92_14d962f8450cc6f1>
X-Attachment-Id: ii_ia6yo3z92_14d962f8450cc6f1
iVBORw0KGgoAAAANSUhEUgAAAUAAAADaCAYAAADXGps7AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz
AAALewAAC3sBSRnwgAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAALnSURB
...
QCDLAIEsAwSyDBDIMkAgywCBLAMEsgwQyDJAIMsAgSwDBLIMEMgyQCDLAIEsAwSyDBDIMkAg6wK+
4gU280YtuwAAAABJRU5ErkJggg==
--089e0149bb0ea4e55c051712afb5--
</code></pre>
<p><strong>Sample 2: only attachments</strong></p>
<p><img src="https://i.stack.imgur.com/nctFv.png" alt="enter image description here"></p>
<pre><code>Subject: Test 02: only attachments
To: Renat Gilmanov
Content-Type: multipart/mixed; boundary=047d7b41cc5c82ae5d051712c40c
--047d7b41cc5c82ae5d051712c40c
Content-Type: text/plain; charset=UTF-8
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque
odio urna, bibendum eu ultricies in, dignissim in magna. Vivamus risus
justo, viverra sed dapibus eu, laoreet eget erat. Sed pretium a urna
id pulvinar.
Cras eu velit ac purus feugiat imperdiet nec sit amet ipsum. Praesent
gravida lobortis justo, nec tristique velit sagittis finibus.
Suspendisse porta ante id diam varius, in cursus ante luctus. Aenean a
mollis mi. Pellentesque accumsan lacus sed erat vulputate, et semper
tellus condimentum.
Best regards
--047d7b41cc5c82ae5d051712c40c
Content-Type: image/png; name="test-02.png"
Content-Disposition: attachment; filename="test-02.png"
Content-Transfer-Encoding: base64
X-Attachment-Id: f_ia6yvl4b0
iVBORw0KGgoAAAANSUhEUgAAAUAAAADaCAYAAADXGps7AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz
AAALewAAC3sBSRnwgAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAALnSURB
...
gECWAQJZBghkGSCQZYBAlgECWQYIZBkgkGWAQJYBAlkGCGQZIJBlgECWAQJZBghkGSCQZYBA1gWV
ywTWDU1tpwAAAABJRU5ErkJggg==
--047d7b41cc5c82ae5d051712c40c--
</code></pre>
<p><strong>Sample 3: inline and attachments</strong></p>
<p><img src="https://i.stack.imgur.com/5ScoF.png" alt="enter image description here"></p>
<pre><code>Subject: Test 03: inline and attachments
To: Renat Gilmanov
Content-Type: multipart/mixed; boundary=001a11c24d809f1525051712cc78
--001a11c24d809f1525051712cc78
Content-Type: multipart/related; boundary=001a11c24d809f1523051712cc77
--001a11c24d809f1523051712cc77
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
<div dir=3D"ltr">Lorem ipsum dolor sit amet, consectetur adipiscing elit. P=
ellentesque odio urna, bibendum eu ultricies in, dignissim in magna. Vivamu=
s risus justo, viverra sed dapibus eu, laoreet eget erat. Sed pretium a urn=
a id pulvinar.<br><br><img src=3D"cid:ii_ia6yyemg0_14d9636d8ac7a587" height=
=3D"218" width=3D"320"><br>=E2=80=8B<br>Cras eu velit ac purus feugiat impe=
rdiet nec sit amet ipsum. Praesent gravida lobortis justo, nec tristique ve=
lit sagittis finibus. Suspendisse porta ante id diam varius, in cursus ante=
luctus. Aenean a mollis mi. Pellentesque accumsan lacus sed erat vulputate=
, et semper tellus condimentum.<br><br>Best regards</div>
--001a11c24d809f1523051712cc77
Content-Type: image/png; name="test-01.png"
Content-Disposition: inline; filename="test-01.png"
Content-Transfer-Encoding: base64
Content-ID: <ii_ia6yyemg0_14d9636d8ac7a587>
X-Attachment-Id: ii_ia6yyemg0_14d9636d8ac7a587
iVBORw0KGgoAAAANSUhEUgAAAUAAAADaCAYAAADXGps7AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz
AAALewAAC3sBSRnwgAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAALnSURB
...
QCDLAIEsAwSyDBDIMkAgywCBLAMEsgwQyDJAIMsAgSwDBLIMEMgyQCDLAIEsAwSyDBDIMkAg6wK+
4gU280YtuwAAAABJRU5ErkJggg==
--001a11c24d809f1523051712cc77--
--001a11c24d809f1525051712cc78
Content-Type: image/png; name="test-02.png"
Content-Disposition: attachment; filename="test-02.png"
Content-Transfer-Encoding: base64
X-Attachment-Id: f_ia6yymei1
iVBORw0KGgoAAAANSUhEUgAAAUAAAADaCAYAAADXGps7AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz
AAALewAAC3sBSRnwgAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAALnSURB
...
gECWAQJZBghkGSCQZYBAlgECWQYIZBkgkGWAQJYBAlkGCGQZIJBlgECWAQJZBghkGSCQZYBA1gWV
ywTWDU1tpwAAAABJRU5ErkJggg==
--001a11c24d809f1525051712cc78--
</code></pre>
<p><strong>Quick summary</strong></p>
<ol>
<li>Inline only attachments: use <code>multipart/related</code> </li>
<li>Non-inline only attachments: use <code>multipart/mixed</code> </li>
<li>Inline and non-inline attachments use <code>multipart/mixed</code> and <code>multipart/related</code></li>
</ol>
<p><strong>Update</strong></p>
<p>Here is a very interesting article: <a href="http://rodriguezcommaj.com/blog/using-images-in-html-email" rel="noreferrer">Using Images in HTML Email</a></p> |
29,513,813 | Celery & RabbitMQ running as docker containers: Received unregistered task of type '...' | <p>I am relatively new to docker, celery and rabbitMQ.</p>
<p>In our project we currently have the following setup:
1 physical host with multiple docker containers running:</p>
<p><strong>1x rabbitmq:3-management container</strong></p>
<pre><code># pull image from docker hub and install
docker pull rabbitmq:3-management
# run docker image
docker run -d -e RABBITMQ_NODENAME=my-rabbit --name some-rabbit -p 8080:15672 -p 5672:5672 rabbitmq:3-management
</code></pre>
<p><strong>1x celery container</strong></p>
<pre><code># pull docker image from docker hub
docker pull celery
# run celery container
docker run --link some-rabbit:rabbit --name some-celery -d celery
</code></pre>
<p>(there are some more containers, but they should not have to do anything with the problem)</p>
<p><strong>Task File</strong></p>
<p>To get to know celery and rabbitmq a bit, I created a tasks.py file on the physical host:</p>
<pre><code>from celery import Celery
app = Celery('tasks', backend='amqp', broker='amqp://guest:[email protected]/')
@app.task(name='tasks.add')
def add(x, y):
return x + y
</code></pre>
<p>The whole setup seems to be working quite fine actually. So when I open a python shell in the directory where tasks.py is located and run</p>
<pre><code>>>> from tasks import add
>>> add.delay(4,4)
</code></pre>
<p>The task gets queued and directly pulled from the celery worker.</p>
<p>However, the celery worker does not know the tasks module regarding to the logs:</p>
<pre><code>$ docker logs some-celery
[2015-04-08 11:25:24,669: ERROR/MainProcess] Received unregistered task of type 'tasks.add'.
The message has been ignored and discarded.
Did you remember to import the module containing this task?
Or maybe you are using relative imports?
Please see http://bit.ly/gLye1c for more information.
The full contents of the message body was:
{'callbacks': None, 'timelimit': (None, None), 'retries': 0, 'id': '2b5dc209-3c41-4a8d-8efe-ed450d537e56', 'args': (4, 4), 'eta': None, 'utc': True, 'taskset': None, 'task': 'tasks.add', 'errbacks': None, 'kwargs': {}, 'chord': None, 'expires': None} (256b)
Traceback (most recent call last):
File "/usr/local/lib/python3.4/site-packages/celery/worker/consumer.py", line 455, in on_task_received
strategies[name](message, body,
KeyError: 'tasks.add'
</code></pre>
<p>So the problem obviously seems to be, that the celery workers in the celery container do not know the tasks module.
Now as I am not a docker specialist, I wanted to ask how I would best import the tasks module into the celery container?</p>
<p>Any help is appreciated :)</p>
<hr>
<p><strong>EDIT 4/8/2015, 21:05:</strong></p>
<p>Thanks to Isowen for the answer. Just for completeness here is what I did:</p>
<p>Let's assume my <code>tasks.py</code> is located on my local machine in <code>/home/platzhersh/celerystuff</code>. Now I created a <code>celeryconfig.py</code> in the same directory with the following content:</p>
<pre><code>CELERY_IMPORTS = ('tasks')
CELERY_IGNORE_RESULT = False
CELERY_RESULT_BACKEND = 'amqp'
</code></pre>
<p>As mentioned by Isowen, celery searches <code>/home/user</code> of the container for tasks and config files. So we mount the <code>/home/platzhersh/celerystuff</code> into the container when starting:</p>
<pre><code>run -v /home/platzhersh/celerystuff:/home/user --link some-rabbit:rabbit --name some-celery -d celery
</code></pre>
<p>This did the trick for me. Hope this helps some other people with similar problems.
I'll now try to expand that solution by putting the tasks also in a separate docker container.</p> | 29,514,236 | 1 | 2 | null | 2015-04-08 11:51:29.083 UTC | 8 | 2015-04-08 19:19:06.76 UTC | 2015-04-08 19:19:06.76 UTC | null | 888,068 | null | 888,068 | null | 1 | 17 | python|docker|rabbitmq|celery|amqp | 9,364 | <p>As you suspect, the issue is because the celery worker does not know the tasks module. There are two things you need to do:</p>
<ol>
<li>Get your tasks definitions "into" the docker container.</li>
<li>Configure the celery worker to load those task definitions.</li>
</ol>
<p>For Item (1), the easiest way is probably to use a <a href="https://docs.docker.com/reference/run/#volume-shared-filesystems" rel="nofollow noreferrer">"Docker Volume"</a> to mount a host directory of your code onto the celery docker instance. Something like:</p>
<pre><code>docker run --link some-rabbit:rabbit -v /path/to/host/code:/home/user --name some-celery -d celery
</code></pre>
<p>Where <code>/path/to/host/code</code> is the your host path, and <code>/home/user</code> is the path to mount it on the instance. Why <code>/home/user</code> in this case? Because the <a href="https://github.com/docker-library/celery/blob/92bcbab09f2c2e342a57d3a1b643e7646908c76f/Dockerfile#L4" rel="nofollow noreferrer"><code>Dockerfile</code></a> for the celery image defines the working directory (<code>WORKDIR</code>) as <code>/home/user</code>.</p>
<p>(Note: Another way to accomplish Item (1) would be to build a custom docker image with the code "built in", but I will leave that as an exercise for the reader.)</p>
<p>For Item (2), you need to create a celery configuration file that imports the tasks file. This is a more general issue, so I will point to a previous stackoverflow answer: <a href="https://stackoverflow.com/questions/9769496/celery-received-unregistered-task-of-type-run-example">Celery Received unregistered task of type (run example)</a></p> |
4,244,206 | Passing parameters in a jQuery ajax call to an ASP.NET webmethod | <p>I know there are more threads about this but they dont help me and I'm going insane here!</p>
<p>I wanna pass some parameters in to a web method using jQuery Ajax.</p>
<pre><code>var paramList = '';
for(i = 0; i < IDList.length; i++){
if (paramList.length > 0) paramList += ',';
paramList += '"' + 'id' + '":"' + IDList[i].value + '"';
}
paramList = '{' + paramList + '}';
var jsonParams = JSON.stringify(paramList);
$.ajax({
type: "POST",
url: "editactivity.aspx/UpdateSequenceNumber",
data: jsonParams,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
}
});
</code></pre>
<p>In the ajax call, if I put data to paramList I get the error: "Invalid web service call, missing value for parameter: \u0027a\u0027."</p>
<p>If I put data to jsonParams I get the error: </p>
<blockquote>
<p>"Cannot convert object of type \u0027System.String\u0027 to type
\u0027System.Collections.Generic.IDictionary`2[System.String,System.Object]\u0027"</p>
</blockquote>
<p>If I write out <code>paramList</code>, it's in a correct JSON format like <code>{"id":"140", "id":"138"}</code></p>
<p>If I write out <code>jsonParams</code>, it's in an incorrect format like <code>"{\"id\":\"140\",\"id\":\"138\"}"</code></p>
<p>The web method: (it doesn't do that much yet..) </p>
<pre><code>[System.Web.Services.WebMethod]
public static string UpdateSequenceNumber(string a, string b)
{
return a+b;
}
</code></pre>
<p>What am I doing wrong? Can't seem to get this JSON thing right. </p>
<p><strong>UPDATE:</strong></p>
<p>After some help from the first answer I now send <code>{"id":["138","140"]}</code> in the AJAX request.</p>
<p>The web method now takes a string called <code>id</code> as the parameter instead.</p>
<pre><code>[System.Web.Services.WebMethod]
public static string UpdateSequenceNumber(string id)
{
return id;
}
</code></pre>
<p>Now I get the new error: </p>
<blockquote>
<p>"Type \u0027System.Array\u0027 is not supported for deserialization of
an array."</p>
</blockquote> | 4,244,279 | 1 | 0 | null | 2010-11-22 09:59:41.607 UTC | 1 | 2016-02-29 00:48:32.177 UTC | 2016-02-29 00:48:32.177 UTC | null | 1,282,237 | null | 405,805 | null | 1 | 10 | jquery|json|webforms|asp.net-ajax | 41,417 | <p>Your json parameter names must be same with the c# paramter names.</p>
<pre><code>{"a":"140", "b":"138"}
</code></pre>
<p>If you are sending unknown number of parameters to server, you may concat at client-side into one parameter and then split at server-side.</p> |
39,867,806 | Pushing a new branch in GIT | <p>I am using GIT, and I have created a new branch (named <code>foo</code>) on my local (one that doesn't exist on the repository). Now, I have made some changes to my original project (master) files and committed all those changes in this new branch. What I would now like to do is push this new branch to the remote repository. How can I do that? If I just run <code>git push</code> while I am on the branch <code>foo</code>, will this push the entire branch to the repo. I don't want my changes to be pushed to master. I just want to push this new branch to the main repository. </p> | 39,867,826 | 6 | 2 | null | 2016-10-05 07:25:24.247 UTC | 3 | 2022-04-22 05:09:59.273 UTC | null | null | null | null | 6,862,012 | null | 1 | 11 | git | 39,114 | <p>Yes. It'll prompt you to set the <code>upstream</code>.</p>
<p>Example </p>
<pre><code>git branch --set-upstream origin yourbranch
</code></pre>
<p>It's same for everything except for the branch name.
Follow the on screen guidelines.</p> |
20,320,263 | What does .:format mean in rake routes | <p>I type rake routes and I get a bunch of urls like this - <code>/articles/:id(.:format)</code></p>
<p>My question is - what does the <code>.:format</code> mean? It is not clear from the Rails Guides Routing article and there are no other helpful matches for <code>.:format</code> on StackOverflow or google. There is a similar format which is <code>/:controller(/:action(/:id(.:format)))</code> which I also don't understand. </p>
<p>Thanks</p>
<p>EDIT follow up question - </p>
<p>If I wanted to only route HTML pages. Would it be best practice to specify something like .:html in the route or to use .:format and just write a respond_to block for format.html? Would all other formats be ignored in that latter case? </p> | 20,320,286 | 2 | 1 | null | 2013-12-02 03:13:22.483 UTC | 10 | 2013-12-02 06:52:20.1 UTC | 2013-12-02 04:01:06.567 UTC | null | 2,981,429 | null | 2,981,429 | null | 1 | 38 | ruby-on-rails|rake | 14,054 | <p>That's the format of the file being requested. For instance, if you want an image, you'd probably have a file extension in the request - for instance, <code>example.com/example_image.png</code> would give you the format as <code>png</code>. This is then included in the request so you can vary response type based of of the format requested, need be. </p>
<p>For a usage example, you may want to allow a resource to be represented as a pdf, as a plain html page and as json - you'd probably write something like this:</p>
<pre><code>respond_to do |format|
format.html { ... }
format.pdf { ... }
format.json { ... }
end
</code></pre>
<p>Then have separate render calls under the respective formats. </p>
<hr>
<p><strong>EDIT:</strong></p>
<p>Explanation of <code>GET /:controller(/:action(/:id(.:format))) :controller#:action</code> -</p>
<p>First, a bit about formatting. The parentheses mean that a given piece of data is optional. The colon means that whatever string it finds in the corresponding URL should be passed to the controller within the params hash.</p>
<p>This is essentially a wildcard matcher will will attempt to match a very broad number of requests to a controller. For instance, lets say this is your only route, and someone tries to get '/users'. This will map <code>users</code> to the <code>UsersController</code>, and by default call/render <code>index</code> within it. If someone gets <code>users/new</code>, the <code>new</code> action within the controller will be called. If <code>id</code> and <code>format</code> are called, they too will be passed along to the controller.</p> |
6,363,130 | Is there a reason to initialize (not reset) signals in VHDL and Verilog? | <p>I have never initialized signals. That way any signal missing a reset or assignment would be unknown or initialized. In some reference code they have initialization. This defeats what I wish. Also since intialization isn't synthesizable, there could be a simulation/synthesis mismatch.</p>
<p>Is there any reason to initialize signals in this case?</p>
<p>EDIT 6/17/11: As @Adam12 asked, this is for both storage (Verilog reg) and combinatorial (wire) elements.</p> | 6,366,164 | 2 | 3 | null | 2011-06-15 19:26:34.37 UTC | 9 | 2014-04-10 22:54:51.233 UTC | 2011-06-17 14:54:44.663 UTC | null | 20,147 | null | 20,147 | null | 1 | 7 | initialization|simulation|vhdl|verilog | 39,156 | <p>(The following advice depends greatly on device architecture and synthesis tools, I speak from experience with Xilinx FPGAs such as Virtex-5 parts).</p>
<p>Your supposition that initialization is not synthesizable is incorrect. <em>Initializing a signal absolutely is synthesizable</em>! </p>
<p>For example, this can be synthesized so it programs the device with an initial value:</p>
<pre><code>signal arb_onebit : std_logic := '0';
signal arb_priority : std_logic_vector(3 downto 0) := "1011"
</code></pre>
<p>Additionally, you can achieve better Quality of Results (QoR) using initialization of signals and forgoing the traditional async or sync global reset schemes. This is because the tools no longer need to route reset signals to all your FFs around your part. While some older generation FPGAs might have had dedicated resources for resets, this is not the case in newer parts. This means that the resets are routed just like every other signal in your design, slowing down your build process and dragging down performance.</p>
<p>What you can do instead? Use signal initialization.</p>
<ol>
<li>Use dedicated "GSR" (global set/reset I believe). This is accessible through a dedicated Xilinx primitive. Note that when using the GSR not all memory elements of the device is reset. For example, BRAMs retain values I believe, but FFs are reset to initialized values.</li>
<li>PROGL your device. This will cause the entire device to be reprogrammed from the original bitstream (located in a PROM). Every time the device is loaded from a PROM all memory elements (FFs, BRAMs, etc) are brought up into a known state dictated by your initialization. If you do not initialize, I believe it defaults to a "0" state. You can verify the state that a memory element is initialized to by viewing the results using a tool like FPGA Editor (supplied as part of Xilinx toolset)</li>
</ol>
<p>If you really need to reset just a small part of your design (a "local" reset) then you should handle this as you typically handle resets.</p>
<p>Here are some references for Xilinx tools:</p>
<ul>
<li><a href="http://www.xilinx.com/support/documentation/white_papers/wp272.pdf" rel="noreferrer">White paper describing high level considerations for resets</a></li>
<li><a href="http://www.xilinx.com/support/documentation/sw_manuals/xilinx13_1/xst_v6s6.pdf" rel="noreferrer">XST 13.1 User Guide</a> See page 50 and 128</li>
<li><a href="http://www.youtube.com/watch?v=DMOJxjb8GGo&feature=channel_video_title" rel="noreferrer">Xilinx Virtex 5 YouTube training series</a>. Part 4 looks like what you want.</li>
</ul>
<p><strong>EDIT</strong></p>
<p>After some further research I have found that specifying initial values, while helpful in improving QoR in some cases, it can hurt it in others. It really boils down to how your synthesis tool vendor will honor the initial value. At its core, an initial value is a constraint on the tool. When your design is synthesized and then mapped to the part, a note gets added to your design that "when you implement this memory element, give it this initial value." In many cases, adding this constraint prevents the element from being optimized (removed, combined, etc).</p>
<p><em>Suggestion:</em> There is no hard/fast/one-size-fits-all rule for reset and initialization. For best optimization and resource utilization you <em>must</em> know your synthesis tool, and you <em>must</em> know your targeted technology.</p> |
6,967,073 | javascript delete all occurrences of a char in a string | <p>I want to delete all characters like <code>[</code> or <code>]</code> or <code>&</code> in a string i.E. :
"[foo] & bar" -> "foo bar"</p>
<p>I don't want to call replace 3 times, is there an easier way than just coding:</p>
<p><code>var s="[foo] & bar";</code></p>
<p><code>s=s.replace('[','');</code></p>
<p><code>s=s.replace(']','');</code></p>
<p><code>s=s.replace('&','');</code></p> | 6,967,082 | 2 | 0 | null | 2011-08-06 13:22:50.133 UTC | 6 | 2021-08-08 14:27:22.317 UTC | 2017-04-30 12:48:19.39 UTC | null | 1,033,581 | null | 781,553 | null | 1 | 32 | javascript|string | 61,727 | <p><a href="http://xkcd.com/208/" rel="noreferrer">Regular expressions <em><sup>[xkcd]</sup></em></a> (I feel like him ;)):</p>
<pre><code>s = s.replace(/[\[\]&]+/g, '');
</code></pre>
<p>Reference:</p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace" rel="noreferrer">MDN - <code>string.replace</code></a></li>
<li><a href="https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions" rel="noreferrer">MDN - Regular Expressions</a></li>
<li><a href="http://www.regular-expressions.info/" rel="noreferrer">http://www.regular-expressions.info/</a></li>
</ul>
<p><strong>Side note</strong>:</p>
<p>JavaScript's <code>replace</code> function only replaces the <em>first occurrence</em> of a character. So even your code would not have replaced all the characters, only the first one of each. If you want to replace <em>all occurrences</em>, you have to use a <em>regular expression</em> with the <em><code>g</code>lobal modifier</em>.</p> |
6,507,124 | How to center a text using PDFBox | <p>My question is very simple: how can I center a text on a PDF, using <code>PDFBox</code>?</p>
<p>I don't know the string in advance, I can't find the middle by trial. The string doesn't always have the same width.</p>
<p>I need either:</p>
<ul>
<li>A method that can center the text, something like <code>addCenteredString(myString)</code></li>
<li>A method that can give me the width of the string in pixels. I can then calculate the center, for I know the dimensions of the PDF.</li>
</ul>
<p>Any help is welcome!</p> | 6,531,362 | 2 | 0 | null | 2011-06-28 13:22:27.59 UTC | 11 | 2021-11-09 14:25:33.857 UTC | 2015-12-15 10:47:54.94 UTC | null | 2,254,048 | null | 771,469 | null | 1 | 45 | java|pdfbox|text-alignment | 30,951 | <p>Ok, I found the answer myself. Here is how to center some text on a page:</p>
<pre><code>String title = "This is my wonderful title!"; // Or whatever title you want.
int marginTop = 30; // Or whatever margin you want.
PDDocument document = new PDDocument();
PDPage page = new PDPage();
PDPageContentStream stream = new PDPageContentStream(document, page);
PDFont font = PDType1Font.HELVETICA_BOLD; // Or whatever font you want.
int fontSize = 16; // Or whatever font size you want.
float titleWidth = font.getStringWidth(title) / 1000 * fontSize;
float titleHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * fontSize;
stream.beginText();
stream.setFont(font, fontSize);
// Deprecated, only before 2.0:
// stream.moveTextPositionByAmount((page.getMediaBox().getWidth() - titleWidth) / 2, page.getMediaBox().getHeight() - marginTop - titleHeight);
// From 2.0 and beyond:
stream.newLineAtOffset((page.getMediaBox().getWidth() - titleWidth) / 2, page.getMediaBox().getHeight() - marginTop - titleHeight);
stream.drawString(title);
stream.endText();
stream.close();
</code></pre> |
6,538,283 | Get url of current path in Terminal SSH | <p>I am having trouble using git on my own server. I am having trouble where I add the origin path (remote add) as I am entering the wrong url. By finding out the correct path to the .git repository on my server, I should be able to enter that into <code>remote add</code> and it should now find the git repository. So, what I would like to know is how can you get the current path of the folder you are browsing via SSH?</p>
<p>Thanks</p> | 6,538,303 | 2 | 0 | null | 2011-06-30 16:52:07.63 UTC | 9 | 2015-03-21 16:56:13.593 UTC | null | null | null | null | 815,648 | null | 1 | 47 | git|ssh|terminal | 65,917 | <p>If the remote host is Unix-like, type <code>pwd</code>.</p> |
7,530,765 | Get the index of the values of one vector in another? | <p>I would guess this is a duplicate, but I can't find that so here goes...</p>
<p>I'd like to return the index of second in first:</p>
<pre><code>first = c( "a" , "c" , "b" )
second = c( "c" , "b" , "a" )
result = c( 2 , 3 , 1 )
</code></pre>
<p>I guarantee that first and second have unique values, and the same values between the two.</p> | 7,530,859 | 3 | 1 | null | 2011-09-23 14:41:19.583 UTC | 5 | 2021-11-13 23:31:47.557 UTC | 2011-09-23 14:53:39.77 UTC | null | 356,790 | null | 356,790 | null | 1 | 33 | r | 28,206 | <p>Getting indexes of values is what <code>match()</code> is for. </p>
<pre><code> first = c( "a" , "c" , "b" )
second = c( "c" , "b" , "a" )
match(second, first)
[1] 2 3 1
</code></pre> |
7,348,051 | Convert uint64_t to std::string | <p>How can I transfer uint64_t value to std::string?
I need to construct the std::string containing this value
For example something like this:</p>
<pre><code>void genString(uint64_t val)
{
std::string str;
//.....some code for str
str+=(unsigned int)val;//????
}
</code></pre>
<p>Thank you</p> | 7,348,075 | 4 | 2 | null | 2011-09-08 12:32:07.523 UTC | 3 | 2014-11-06 14:11:05.387 UTC | 2011-09-08 12:33:29.133 UTC | null | 14,860 | null | 466,056 | null | 1 | 19 | c++|string|std|uint64 | 42,069 | <p>use either <code>boost::lexical_cast</code> or <code>std::ostringstream</code></p>
<p>e.g.:</p>
<pre><code>str += boost::lexical_cast<std::string>(val);
</code></pre>
<p>or</p>
<pre><code>std::ostringstream o;
o << val;
str += o.str();
</code></pre> |
24,097,484 | "No 'Access-Control-Allow-Origin' header is present on the requested resource" error for response from http://www.google.com/ | <pre><code>//Create an Angular Module.
var newsModule = angular.module('NewsModule', []);
//Create an Angular Controller.
newsModule.controller('newsCtrl', ['$scope', '$http', function ($scope, $http) {
//function retrives POST,UPDATE,DELETE,GET data
$http.defaults.headers.put = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With'
};
$http.defaults.useXDomain = true;
$scope.throughdata = function (){
delete $http.defaults.headers.common['X-Requested-With'];
$http.get('http://www.google.com').then(function(data,error){
alert(data);
alert(error);
$scope.days=data.data;
});
}
}
]);
</code></pre>
<p>But I have getting following errors</p>
<blockquote>
<p>XMLHttpRequest cannot load <a href="http://www.google.com/" rel="nofollow noreferrer">http://www.google.com/</a>. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.</p>
</blockquote> | 24,097,520 | 1 | 1 | null | 2014-06-07 13:02:28.353 UTC | 7 | 2020-01-15 19:40:25.977 UTC | 2020-01-15 19:40:25.977 UTC | null | 441,757 | null | 1,678,124 | null | 1 | 26 | javascript|angularjs|cors | 93,810 | <p><code>Access-Control-Allow-Origin</code> <strong>is set on the response from server</strong>, <strong>not on client request</strong> to allow clients from different origins to have access to the response. </p>
<p>In your case, <a href="http://www.google.com/">http://www.google.com/</a> does not allow your origin to have access to the response. Therefore you cannot read it.</p>
<p>For more information about CORS: <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS">https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS</a></p> |
2,131,722 | CoreData (for iphone) storing images | <p>i wonder if its a wise choice to store images with core data into binary property</p>
<p>say i have a collection of movies and i want to save the image dvd cover into a property the avg size of a cover is 20/30kb (320x480px)</p>
<p>the reason i want to do this is for storage management, once i delete the movie i know the image is also deleted</p>
<p>i'm just not quite sure if it's a good idea, data load, speed?</p>
<p>anyone has experience with this ?</p> | 2,131,864 | 4 | 1 | null | 2010-01-25 10:55:11.4 UTC | 9 | 2012-11-21 17:26:58.16 UTC | 2010-01-27 07:16:55.563 UTC | null | 161,815 | null | 62,009 | null | 1 | 6 | iphone|objective-c|xcode|core-data|binary | 7,836 | <p>It seems to me that storing images in a core data isn't a good idea, and I'm pretty sure I've also read it on one of Apple's programming guides. Just consider this, when you fetch your collection, all the images will also be loaded into memory, even if you're only displaying 8 images, your entire image collection will be loaded by core data.</p>
<p>If you want to make sure you delete the image files when a move record was deleted I suggest you listen to notifications by the managedObjectContext and delete files when a movie was deleted:</p>
<p>You can either register for the willSave or didSave notification, each with it's own advantages/disadvantages.</p>
<pre><code> [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contextDidSave:) name:NSManagedObjectContextDidSaveNotification object:managedObjectContext];
</code></pre>
<p>Getting the deleted objects: </p>
<pre><code>- (void) contextDidSave:(NSNotification *)notification
{
NSDictionary *userInfo = [notification userInfo];
for (NSManagedObject *currObject in [userInfo objectForKey:NSDeletedObjectsKey])
{
// Code for deleting file associated with the NSManagedObject, you can still
// access the managed object's properties.
}
}
</code></pre> |
1,344,202 | Bad path warning, where is it coming from? | <p>When I compile my project with compiler warnings (JDK 1.5) I get a bunch of bad path element warnings:</p>
<p>Warning:: [path] bad path element "C:\Users\User\MyJava\common\lib\junit.jar": no such file or directory
Warning:: [path] bad path element "C:\Users\User\MyJava\common\lib\jdom.jar": no such file or directory
Warning:: [path] bad path element "C:\Users\User\MyJava\common\lib\xerces.jar": no such file or directory
Warning:: [path] bad path element "C:\Users\User\MyJava\common\lib\xml-apis.jar": no such file or directory</p>
<p>and many more.</p>
<p>This is using IDEA 8.1.3. I can't find anywhere in IDEA's configuration (I grepped the whole project) where anything points to these files. They are all indeed not there anymore under that name, but what references them?</p> | 1,345,093 | 4 | 0 | null | 2009-08-27 22:58:17.943 UTC | 7 | 2015-11-21 23:35:57.9 UTC | null | null | null | null | 77,779 | null | 1 | 30 | java|compiler-warnings | 14,960 | <p>I think @Yishai has the right of it (I'll give him an up-vote for getting the ball rolling). I run into this all the time. In what I think was a horrible decision for the Java language, they decided it would be alright to allow classpath settings to go into the MANIFEST files inside jar files. So essentially, Jars can have files inside them that point to other classes and jars located elsewhere and when those other things they point to don't exist, you see warnings like the ones you're getting. These warnings are coming out of Jar files that are on your compilation classpath. So what you need to do if you really care is track down the problem jar files, extract the contents of the jar files, remove the "Class-Path" settings in their manifest files and recreate them. Something like this (move the jar to a temp directory somewhere first):</p>
<pre><code>#Extract the jar file
jar xvf myfile.jar
rm myfile.jar
emacs ./META-INF/MANIFEST.MF
*Find the entry "Class-path:" and remove it completely and save the changes
#Rebuild the jar file
jar cvf myfile.jar ./*
</code></pre>
<p>That should do the trick!</p>
<p>I don't think you just want to suppress these messages because if you want full control over what's going onto your classpath, you should search out these manifest files and make sure they don't mess with the classpath in a way you don't know about. </p>
<p>Likely you'll have to look through a ton of jar files, so I usually end up using a shell loop to help me look through them. You can copy all your Jars in question to a temporary directory and run a loop like this (bash syntax):</p>
<pre><code>for i in *.jar; do echo $i; jar xf $i; grep -i 'class-path' ./META-INF/MANIFEST.MF; done
</code></pre>
<p>That will print the name of every Jar file in the current directory, extract its contents, and grep its manifest file for classpath entries. If the name of the jar file in the output has a "Class-Path" printout after it, that means that Jar has classpath settings in its manifest. This way you can hopefully figure out what Jars you need to take action on.</p> |
1,928,636 | How do closures work behind the scenes? (C#) | <p>I feel I have a pretty decent understanding of closures, how to use them, and when they can be useful. But what I don't understand is how they actually work behind the scenes in memory. Some example code:</p>
<pre><code>public Action Counter()
{
int count = 0;
Action counter = () =>
{
count++;
};
return counter;
}
</code></pre>
<p>Normally, if {count} was not captured by the closure, its lifecycle would be scoped to the Counter() method, and after it completes it would go away with the rest of the stack allocation for Counter(). What happens though when it is closured? Does the whole stack allocation for this call of Counter() stick around? Does it copy {count} to the heap? Does it never actually get allocated on the stack, but recognized by the compiler as being closured and therefore always lives on the heap?</p>
<p>For this particular question, I'm primarily interested in how this works in C#, but would not be opposed to comparisons against other languages that support closures.</p> | 1,928,654 | 4 | 6 | null | 2009-12-18 14:47:40.043 UTC | 17 | 2017-10-25 04:26:13.207 UTC | null | null | null | null | 17,803 | null | 1 | 47 | c#|.net|closures | 4,140 | <p>The <em>compiler</em> (as opposed to the runtime) creates another class/type. The function with your closure and any variables you closed over/hoisted/captured are re-written throughout your code as members of that class. A closure in .Net is implemented as one instance of this hidden class.</p>
<p>That means your count variable is a member of a different class entirely, and the lifetime of that class works like any other clr object; it's not eligible for garbage collection until it's no longer rooted. That means as long as you have a callable reference to the method it's not going anywhere.</p> |
10,332,132 | How to use null in switch | <pre class="lang-java prettyprint-override"><code>Integer i = ...
switch (i) {
case null:
doSomething0();
break;
}
</code></pre>
<p>In the code above I can't use null in the switch case statement. How can I do this differently? I can't use <code>default</code> because then I want to do something else.</p> | 10,332,167 | 14 | 2 | null | 2012-04-26 11:04:27.08 UTC | 28 | 2022-08-25 20:25:56.577 UTC | 2022-02-14 19:46:40.027 UTC | null | 12,335,762 | null | 431,769 | null | 1 | 262 | java|switch-statement | 270,035 | <p>This is was not possible with a <code>switch</code> statement in Java until Java 18. You had to check for <code>null</code> before the <code>switch</code>. But now, with pattern matching, this is a thing of the past. Have a look at <a href="https://openjdk.org/jeps/420" rel="nofollow noreferrer">JEP 420</a>:</p>
<blockquote>
<p>Pattern matching and null</p>
<p>Traditionally, switch statements and expressions throw
NullPointerException if the selector expression evaluates to null, so
testing for null must be done outside of the switch:</p>
</blockquote>
<pre><code>static void testFooBar(String s) {
if (s == null) {
System.out.println("oops!");
return;
}
switch (s) {
case "Foo", "Bar" -> System.out.println("Great");
default -> System.out.println("Ok");
}
}
</code></pre>
<blockquote>
<p>This was reasonable when switch supported only a few reference types.
However, if switch allows a selector expression of any type, and case
labels can have type patterns, then the standalone null test feels
like an arbitrary distinction, and invites needless boilerplate and
opportunity for error. It would be better to integrate the null test
into the switch:</p>
</blockquote>
<pre><code>static void testFooBar(String s) {
switch (s) {
case null -> System.out.println("Oops");
case "Foo", "Bar" -> System.out.println("Great");
default -> System.out.println("Ok");
}
}
</code></pre>
<p>More about <code>switch</code> (including example with null variable) in <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html" rel="nofollow noreferrer">Oracle Docs - Switch</a></p> |
28,628,773 | How to generate 2d numpy array? | <p>I'm trying to generate a 2d numpy array with the help of generators:</p>
<pre><code>x = [[f(a) for a in g(b)] for b in c]
</code></pre>
<p>And if I try to do something like this:</p>
<pre><code>x = np.array([np.array([f(a) for a in g(b)]) for b in c])
</code></pre>
<p>I, as expected, get a np.array of np.array. But I want not this, but ndarray, so I can get, for example, column in a way like this:</p>
<pre><code>y = x[:, 1]
</code></pre>
<p>So, I'm curious whether there is a way to generate it in such a way.</p>
<p>Of course it is possible with creating npdarray of required size and filling it with required values, but I want a way to do so in a line of code. </p> | 28,628,941 | 3 | 3 | null | 2015-02-20 12:14:56.42 UTC | 2 | 2021-10-25 05:09:42.93 UTC | 2015-07-20 16:36:21.587 UTC | null | 2,229,978 | null | 2,229,978 | null | 1 | 14 | python|numpy|generator | 48,397 | <p>This works:</p>
<pre><code>a = [[1, 2, 3], [4, 5, 6]]
nd_a = np.array(a)
</code></pre>
<p>So this should work too:</p>
<pre><code>nd_a = np.array([[x for x in y] for y in a])
</code></pre> |
28,689,851 | Remove Column Header into the Output Text file | <p>I want to create a flat file (text file) of my query from Oracle SQL Developer.</p>
<p>I have successfully created the text file using SPOOL, thru a script text file, but i want to remove the header of each column into my output.</p>
<p>I am getting this output:</p>
<pre>
Header000001 Header000002
------------ ------------
Adetail1 Bdetail1
Adetail2 Bdetail2
Adetail3 Bdetail3
</pre>
<p>But, I want to get this output:</p>
<pre>
Adetail1Bdetail1
Adetail2Bdetail2
Adetail3Bdetail3
</pre>
<p>I already tried the command "set heading off", but a message says:</p>
<pre><code>"SQLPLUS COMMAND Skipped: set heading off".
</code></pre>
<p>These are the inputs I've issued:</p>
<pre><code>spool on;
spool C:\SQLFiles\PSB_ATMLKP.txt;
set newpage 0;
set echo off;
set feedback off;
set heading off;
select terminal_number, terminal_name from terminal_table;
spool off;
</code></pre> | 28,689,893 | 2 | 3 | null | 2015-02-24 06:58:58.023 UTC | 4 | 2020-05-01 00:08:53.58 UTC | 2017-12-13 05:00:33.413 UTC | null | 1,033,581 | null | 4,586,443 | null | 1 | 39 | oracle|oracle-sqldeveloper|sqlplus|spool|columnheader | 123,259 | <blockquote>
<p>SQLPLUS COMMAND Skipped: set heading off</p>
</blockquote>
<p>That message is most likely because you are not executing it through <code>SQL*Plus</code>, but some GUI based tool. You are using SQLPlus command in SQL Developer. Not all SQL*Plus commands are guaranteed to work with <strong>SQL Developer</strong>. </p>
<p>I would suggest you execute the script in <strong>SQLPlus</strong> and you would see no issues.</p>
<p>You need:</p>
<pre><code>SET HEADING OFF
</code></pre>
<p>This will not include the column headers in the output.</p>
<p>Alternatively, you could also do this:</p>
<pre><code>SET PAGESIZE 0
</code></pre>
<p><strong>Using SQL Developer Version 3.2.20.10</strong>:</p>
<pre><code>spool ON
spool D:\test.txt
SET heading OFF
SELECT ename FROM emp;
spool off
</code></pre>
<p><img src="https://i.stack.imgur.com/8JRDv.jpg" alt="enter image description here"></p>
<p>Spool file got created with no issues:</p>
<pre><code>> set heading OFF
> SELECT ename FROM emp
SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER
14 rows selected
</code></pre> |
54,812,453 | Function lacks ending return statement and return type does not include 'undefined' | <blockquote>
<p>Function lacks ending return statement and return type does not include 'undefined'.</p>
</blockquote>
<p>In the following async await function I had return type of <code>Promise: <any></code> but I wanted to correct that so I did the following:</p>
<pre><code>export const getMarkets = async (): Promise<IGetMarketsRes> => {
try {
const nomicsUSD = prepHeaders('USD');
const marketUSD = await nomicsUSD.get(exchangeMarketPrices);
const nomicsUSDC = prepHeaders('USDC');
const marketUSDC = await nomicsUSDC.get(exchangeMarketPrices);
const nomicsUSDT = prepHeaders('USDT');
const marketUSDT = await nomicsUSDT.get(exchangeMarketPrices);
console.log('marketUSD', marketUSD);
return {
marketUSD: marketUSD.data,
marketUSDC: marketUSDC.data,
marketUSDT: marketUSDT.data
}
} catch (err) {
console.error(err);
}
}
</code></pre>
<p>However that creates the error above.</p>
<p><a href="https://i.stack.imgur.com/Mth4k.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Mth4k.png" alt="enter image description here"></a></p>
<p>Where <code>getMarkets</code> is called:</p>
<pre><code>export const fetchMarketPrices = (asset: string) => (dispatch: any) => {
dispatch(actionGetMarketPrices);
return getMarkets().then((res) => {
const { marketUSD, marketUSDC, marketUSDT } = res;
const combinedExchanges = marketUSD.concat(marketUSDC).concat(marketUSDT);
const exchangesForAsset = combinedExchanges.filter((marketAsset: IMarketAsset) =>
marketAsset.base === asset);
return dispatch(actionSetMarketPrices(exchangesForAsset));
});
}
</code></pre>
<p><strong>What is/are the proper Types for that</strong> <code>Promise<></code> <strong>syntax?</strong></p>
<hr>
<p>I also tried this which I expected to be the correct way, but got a missing return for Promise, but this is an async await function which is why the return is in the <code>try</code> statement:</p>
<p><code>export const getMarkets = async (): Promise<IGetMarketsRes> => {</code></p>
<p><a href="https://i.stack.imgur.com/rvK2d.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rvK2d.png" alt="enter image description here"></a></p> | 66,046,046 | 3 | 7 | null | 2019-02-21 16:59:49.767 UTC | 1 | 2022-08-08 11:04:21.65 UTC | 2019-02-21 17:05:30.85 UTC | null | 168,738 | null | 168,738 | null | 1 | 19 | javascript|reactjs|typescript|async-await | 50,361 | <p>The best solution would be to throw an error on the catch, instead of undefining the return type. The <code>undefined</code> type removes the whole point of using TypeScript otherwise.</p>
<p>Try this:</p>
<pre class="lang-js prettyprint-override"><code>export const getMarkets = async (): Promise<IGetMarketsRes> => {
try {
// Your code :)
} catch (err) {
// Throw error
throw(err)
}
}
</code></pre> |
7,640,133 | Running a python script produces: ImportError: no module named termcolor | <p>I created a new virtual environment:</p>
<pre><code>$ virtualenv --no-site-packages venv --python=python3.2
</code></pre>
<p>Then, I activate the virtual environment and install packages:</p>
<pre><code>$ source venv/bin/activate
$ pip install termcolor
$ python -m termcolor
</code></pre>
<p>This all works just fine. I then install my own project called Hermes which uses termcolor:</p>
<pre><code>$ python setup.py install
</code></pre>
<p>But when I run the executable that's installed to the virtualenv's bin directory, I get an error:</p>
<pre><code>ImportError: no module named termcolor
</code></pre>
<p>How do I install termcolor?</p> | 7,640,171 | 5 | 1 | null | 2011-10-03 20:11:28.387 UTC | null | 2022-07-15 11:54:02.593 UTC | 2013-12-08 07:40:45.793 UTC | null | 445,131 | null | 910,553 | null | 1 | 8 | python|virtualenv | 39,923 | <p>Another python executable must be in the path. Are you doing sudo or does your python file have a <code>#!/usr/bin/env python</code> line or anything? Try <code>python -v</code> and <code>which python</code> to figure out which python you are actually using. Are you running venv/bin/python?</p> |
7,463,507 | Sum of Numbers C++ | <p>I am supposed to write a program that asks the user for a positive integer value. The program should use a loop to get the sum of
all the integers from 1 up to the number entered. For example, if the user enters 50, the loop will find the sum of
1, 2, 3, 4, ... 50.</p>
<p>But for some reason it is not working, i am having trouble with my for loops but this is what i have down so far.</p>
<pre><code>#include <iostream>
using namespace std;
int main()
{
int positiveInteger;
int startingNumber = 1;
int i = 0;
cout << "Please input an integer up to 100." << endl;
cin >> positiveInteger;
for (int i=0; i < positiveInteger; i++)
{
i = startingNumber + 1;
cout << i;
}
return 0;
}
</code></pre>
<p>I am just at a loss right now why it isn't working properly. </p> | 7,463,544 | 8 | 11 | null | 2011-09-18 18:32:59.637 UTC | 1 | 2018-03-08 06:03:24.03 UTC | 2014-06-18 09:39:33.203 UTC | null | 759,866 | null | 330,396 | null | 1 | 4 | c++|for-loop|sum | 139,141 | <p>try this:</p>
<pre><code>#include <iostream>
using namespace std;
int main()
{
int positiveInteger;
int startingNumber = 1;
cout << "Please input an integer upto 100." << endl;
cin >> positiveInteger;
int result = 0;
for (int i=startingNumber; i <= positiveInteger; i++)
{
result += i;
cout << result;
}
cout << result;
return 0;
}
</code></pre> |
44,391,817 | Is there a way to list all resources in AWS | <p>Is there a way to list all resources in AWS? For all regions, all resources.. Such as list all EC2 instances, all VPCs, all APIs in API Gateway, etc... I would like to list all resources for my account, since it's hard for me to find which resources I can relinquish now.</p> | 44,402,449 | 21 | 5 | null | 2017-06-06 13:47:06.19 UTC | 57 | 2021-08-29 11:39:48.273 UTC | 2018-09-04 22:55:27.22 UTC | null | 251,034 | null | 8,120,027 | null | 1 | 339 | amazon-web-services | 202,734 | <blockquote>
<p><strong>Edit: This answer is deprecated and is incorrect</strong>. There are several ways to list AWS resources (the AWS Tag Editor, etc.). Check
the other answers for more details.</p>
</blockquote>
<hr>
<p>No.</p>
<p>Each AWS Service (eg Amazon EC2, Amazon S3) have their own set of API calls. Also, each <strong>Region</strong> is independent.</p>
<p>To obtain a list of all resources, you would have to make API calls to every service in every region.</p>
<p>You might want to activate <a href="http://docs.aws.amazon.com/config/latest/developerguide/WhatIsConfig.html" rel="nofollow noreferrer">AWS Config</a>:</p>
<blockquote>
<p>AWS Config provides a detailed view of the configuration of AWS resources in your AWS account. This includes how the resources are related to one another and how they were configured in the past so that you can see how the configurations and relationships change over time.</p>
</blockquote>
<p>However, AWS Config only collects information about EC2/VPC-related resources, not everything in your AWS account.</p> |
19,323,323 | Configure IIS Express 8 to enable CORS | <p>I'm writing WCF services that will be used by clients out in the wild so they need to handle cross-origin requests. I have a problem with enabling my development server to accept such requests. Here is the scenario:</p>
<ul>
<li>I'm running the WCF project in an instance of Visual Studio 2012, using IIS Express 8 as the server on a specific port.</li>
<li>I'm running the client project in another instance of Visual Studio 2012, also using IIS Express 8 as the server. This project uses AJAX to consume services in the other project.</li>
</ul>
<p>When I run the client project in IE there is no problem because IE does not send the preflight OPTIONS request. When I run it in Chrome however the preflight OPTIONS request returns a 405 Method Not Allowed and Chrome gives up on the service. Previous versions of Chrome would just ignore the error and continue with the actual POST request (or Get, whatever...) but later versions appear to be pickier.</p>
<p>I've also run into this with a deployed WCF project and solved it by moving the OPTIONSVerbHandler to the top of the Handler Mappings list in IIS.</p>
<p>I should point out that I'm using the most generous web.config settings I can think of to try to allow CORS. For instance I have this in the WCF project's configuration:</p>
<pre><code><httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Methods" value="*" />
<add name="X-Powered-By" value="*" />
</customHeaders>
</httpProtocol>
</code></pre>
<p>Regardless, any client cross-origin requests to the WCF project running from code fail with the 405 error.</p>
<p>Any help setting up either the WCF project itself or IIS Express 8 to enable CORS?</p>
<p>Thanks!</p> | 19,412,296 | 5 | 2 | null | 2013-10-11 16:47:19.717 UTC | 6 | 2018-11-19 13:42:20.467 UTC | null | null | null | null | 2,871,809 | null | 1 | 11 | wcf|visual-studio-2012|cross-domain|cors|iis-express | 40,629 | <p>The answer is that the configuration needed to enable WCF to accept CORS preflight messages has nothing to do with the IIS server; rather the WCF project itself needs to be configured to handle the HTTP request with OPTIONS verb.</p>
<p>Long story short: doing this is REALLY HARD. WCF is a jack of all trades when it comes to endpoints so setting it up to do something very specific with one (HTTP) is not advisable, although it can be done. The real solution is to use Web API, which is a master of HTTP and can be set up to do CORS very simply.</p> |
24,718,697 | PySpark Drop Rows | <p>how do you drop rows from an RDD in PySpark? Particularly the first row, since that tends to contain column names in my datasets. From perusing the API, I can't seem to find an easy way to do this. Of course I could do this via Bash / HDFS, but I just want to know if this can be done from within PySpark.</p> | 24,734,612 | 6 | 3 | null | 2014-07-13 01:08:33.563 UTC | 8 | 2020-02-02 08:07:02.58 UTC | 2020-02-02 08:07:02.58 UTC | null | 6,169,688 | null | 1,631,642 | null | 1 | 28 | python|apache-spark|pyspark | 50,188 | <p>AFAIK there's no 'easy' way to do this.</p>
<p>This should do the trick, though:</p>
<pre><code>val header = data.first
val rows = data.filter(line => line != header)
</code></pre> |
448,579 | Processing incoming email | <p>How do I programmatically read an incoming email with .NET. I need a method to take the content of email message (in this case XML) on a POP server and read it into my application. </p>
<p>Ideally this could be solved by:</p>
<ul>
<li>.NET code that I can run as a
background task on my webserver to
process the email.</li>
<li>A service that can POST the contents
of the email to my webserver.</li>
</ul>
<p>Although I'm open to other options. </p>
<p>EDIT: Copied from the "non-answer":</p>
<blockquote>
<p>Currently, we're looking at using the
email accounts our hosting company
provides.</p>
<p>Our own mail server could potentially
be an option, but its something the
we'd need to contact the host about.</p>
</blockquote> | 448,694 | 5 | 2 | null | 2009-01-15 21:44:32.633 UTC | 9 | 2017-07-19 00:45:50.463 UTC | 2009-01-16 14:51:29.563 UTC | Mike Schots | 35,487 | Mike Schots | 35,487 | null | 1 | 7 | .net|email|imap|pop3 | 9,647 | <p>We have actually just implemented the same kind of thing.</p>
<p>We process the content of email messages and push the data in to our CRM via a web service. We use c# with .net 3.5</p>
<p>To process the mail we went with IMap . There are a few .net client libraries on CodeProject. I think we used the one from <a href="http://www.lumisoft.ee/lsWWW/download/downloads/net/" rel="nofollow noreferrer">LumiSoft</a> .</p>
<p>We tried WebDav but didn't have much luck. This left us with Pop3 or IMap. IMap supports folders, which we needed, so we went with that. I'm sure it would be easy to do the same thing with POP3 if your server does not support IMap.</p>
<p>Basically we connect our Exchange server every hour and pull down any new email and process them.
So far it's working well.</p>
<p>Edit: We also use <a href="http://anmar.eu.org/projects/sharpmimetools/" rel="nofollow noreferrer">SharpMimeTools</a> to get the raw emails in to a more usable format.</p> |
158,557 | Get street address at lat/long pair | <p>I've seen that it's possible to get the latitude and longitude (geocoding, like in <a href="http://code.google.com/apis/maps/documentation/services.html#Geocoding" rel="nofollow noreferrer">Google Maps API</a>) from a street address, but is it possible to do the reverse and get the street address when you know what the lat/long already is?</p>
<p>The application would be an iPhone app (and why the app already knows lat/long), so anything from a web service to an iPhone API would work.</p> | 158,582 | 5 | 1 | null | 2008-10-01 16:38:55.903 UTC | 23 | 2015-09-05 14:51:19.833 UTC | 2010-05-21 16:11:21.35 UTC | null | 1,431 | Chris Wenham | 5,548 | null | 1 | 22 | iphone|web-services|gis|geocoding|street-address | 19,664 | <p>Google again</p>
<p><a href="http://nicogoeminne.googlepages.com/documentation.html" rel="nofollow noreferrer">http://nicogoeminne.googlepages.com/documentation.html</a></p>
<p><a href="http://groups.google.com/group/Google-Maps-API/web/resources-non-google-geocoders" rel="nofollow noreferrer">http://groups.google.com/group/Google-Maps-API/web/resources-non-google-geocoders</a></p> |
935,018 | Hide SQL database from Management Studio | <p>How can you hide databases you do not have access rights to when logging into <code>SQL Server 2005 / 2008</code>? </p>
<p>Currently if a user connects, they see all the databases on the server, meaning they have to scan though the list to find their database.</p> | 935,086 | 5 | 0 | null | 2009-06-01 14:17:39.51 UTC | 14 | 2018-03-29 15:50:26.49 UTC | 2018-03-22 11:53:53.777 UTC | null | 3,876,565 | null | 91,579 | null | 1 | 40 | sql-server | 39,271 | <p>You would need to revoke the permission 'VIEW ANY DATABASE' from the role PUBLIC (SQL SERVER 2005 onwards)</p> |
333,620 | Best Practice for Designing User Roles and Permission System? | <p>I need to add user roles and permission system into my web application built using PHP/MySQL. I want to have this functionality: </p>
<ol>
<li>One root user can create sub-roots, groups, rules and normal users( all privileges) .</li>
<li>Sub-roots can create only rules, permissions and users for his/her own group ( no groups).</li>
<li>A user can access either content created by him or his group, based on the permission assigned to him, by group root.</li>
</ol>
<p>I need the system to be flexible enough, so that new roles and permissions are assigned to content.</p>
<p>I have a <code>users</code> table storing group key along with other information. Currently I am using two feilds in each content table i.e. <code>createdBy</code> and <code>CreatedByGroup</code>, and using that as the point whether a certain user has permissions. But its not flexible enough, because for every new content, I have to go throug all data updates and permission updates. Please help me by discussing your best practices for schema design.</p> | 333,666 | 5 | 0 | null | 2008-12-02 10:56:04.44 UTC | 59 | 2018-09-26 13:55:46.207 UTC | 2014-03-22 09:03:45.61 UTC | null | 1,521,627 | hash | 29,656 | null | 1 | 52 | mysql|database|database-design | 98,940 | <p>The pattern that suits your needs is called <a href="http://en.wikipedia.org/wiki/Role-based_access_control" rel="noreferrer">role-based access control</a>.</p>
<p>There are several good implementations in PHP, including <a href="http://framework.zend.com/manual/1.12/en/zend.acl.html" rel="noreferrer">Zend_Acl</a> (good documenation), <a href="http://phpgacl.sourceforge.net/" rel="noreferrer">phpGACL</a> and <a href="http://sourceforge.net/projects/tackle/" rel="noreferrer">TinyACL</a>. Most frameworks also have their own implementations of an ACL in some form.</p>
<p>Even if you choose to roll your own, it'll help you to review well factored solutions such as those.</p> |
1,273,616 | How do I compare two hashes in Perl without using Data::Compare? | <p>How do I compare two hashes in Perl without using Data::Compare?</p> | 1,273,714 | 6 | 3 | null | 2009-08-13 17:59:38.877 UTC | 3 | 2020-09-17 10:34:47.133 UTC | 2009-08-14 11:51:13.643 UTC | null | 2,766,176 | null | 150,842 | null | 1 | 17 | perl|hash | 43,596 | <p>The best approach differs according to your purposes. The FAQ item mentioned by Sinan is a good resource: <a href="https://perldoc.perl.org/perlfaq4.html#How-do-I-test-whether-two-arrays-or-hashes-are-equal%3f" rel="nofollow noreferrer">How do I test whether two arrays or hashes are equal?</a>. During development and debugging (and of course when writing unit tests) I have found <a href="http://search.cpan.org/dist/Test-Simple/lib/Test/More.pm" rel="nofollow noreferrer"><code>Test::More</code></a> to be useful when comparing arrays, hashes, and complex data structures. A simple example:</p>
<pre><code>use strict;
use warnings;
my %some_data = (
a => [1, 2, 'x'],
b => { foo => 'bar', biz => 'buz' },
j => '867-5309',
);
my %other_data = (
a => [1, 2, 'x'],
b => { foo => 'bar', biz => 'buz' },
j => '867-5309x',
);
use Test::More tests => 1;
is_deeply(\%other_data, \%some_data, 'data structures should be the same');
</code></pre>
<p>Output:</p>
<pre><code>1..1
not ok 1 - data structures should be the same
# Failed test 'data structures should be the same'
# at _x.pl line 19.
# Structures begin differing at:
# $got->{j} = '867-5309x'
# $expected->{j} = '867-5309'
# Looks like you failed 1 test of 1.
</code></pre> |
1,203,815 | How to create a certificate for local development with SSL? | <p>I am currently doing local development on a webproject using a LAMP stack. Since my production application will be using https for login, I'd like to be able to mimic this in my local dev environment so that all the url's remain consistent. I am new to ssl certificates so could anyone please point me to some reference on how to do this? Would I need to sign my own certificate? Where do I put the certificate (I have virtualhost configurations using apache)? Thanks.</p> | 1,203,824 | 6 | 1 | null | 2009-07-30 00:28:17.743 UTC | 6 | 2020-08-11 07:50:50.497 UTC | null | null | null | null | 131,456 | null | 1 | 33 | apache|ssl|lamp | 45,355 | <p>I'm new here but go to this site and the information there</p>
<p><a href="https://www.akadia.com/services/ssh_test_certificate.html" rel="nofollow noreferrer">Creating a self signed Certificate</a></p> |
851,949 | Asymptotic complexity of .NET collection classes | <p>Are there any resources about the asymptotic complexity (big-O and the rest) of methods of .NET collection classes (<code>Dictionary<K,V></code>, <code>List<T></code> etc...)?</p>
<p>I know that the C5 library's documentation includes some information about it (<a href="http://www.itu.dk/research/c5/Release1.1/c5doc/types/C5.LinkedList_1.htm" rel="noreferrer">example</a>), but I'm interested in standard .NET collections too... (and PowerCollections' information would also be nice). </p> | 851,957 | 6 | 2 | null | 2009-05-12 09:31:25.543 UTC | 12 | 2021-12-16 14:07:22.683 UTC | 2009-05-12 10:57:11.847 UTC | null | 55,408 | null | 55,408 | null | 1 | 34 | .net|collections|big-o|asymptotic-complexity | 19,995 | <p>MSDN Lists these:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/xfhwa508.aspx" rel="noreferrer"><code>Dictionary<,></code></a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx" rel="noreferrer"><code>List<></code></a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.collections.sortedlist.aspx" rel="noreferrer"><code>SortedList<,></code></a> (edit: wrong link; here's the <a href="http://msdn.microsoft.com/en-us/library/ms132319.aspx" rel="noreferrer">generic version</a>)</li>
<li><a href="http://msdn.microsoft.com/en-us/library/f7fta44c.aspx" rel="noreferrer"><code>SortedDictionary<,></code></a></li>
</ul>
<p>etc. For example:</p>
<blockquote>
<p>The SortedList(TKey, TValue) generic
class is a binary search tree with
O(log n) retrieval, where n is the
number of elements in the dictionary.
In this, it is similar to the
SortedDictionary(TKey, TValue) generic
class. The two classes have similar
object models, and both have O(log n)
retrieval. Where the two classes
differ is in memory use and speed of
insertion and removal:</p>
<p>SortedList(TKey, TValue) uses less
memory than SortedDictionary(TKey,
TValue).</p>
<p>SortedDictionary(TKey, TValue) has
faster insertion and removal
operations for unsorted data, O(log n)
as opposed to O(n) for
SortedList(TKey, TValue).</p>
<p>If the list is populated all at once
from sorted data, SortedList(TKey,
TValue) is faster than
SortedDictionary(TKey, TValue).</p>
</blockquote> |
228,221 | How can I insert multiple rows into oracle with a sequence value? | <p>I know that I can insert multiple rows using a single statement, if I use the syntax in <a href="https://stackoverflow.com/questions/39576/best-way-to-do-multi-row-insert-in-oracle#39602">this answer</a>. </p>
<p>However, one of the values I am inserting is taken from a sequence, i.e. </p>
<pre><code>insert into TABLE_NAME
(COL1,COL2)
select MY_SEQ.nextval,'some value' from dual
union all
select MY_SEQ.nextval,'another value' from dual
;
</code></pre>
<p>If I try to run it, I get an ORA-02287 error. Is there any way around this, or should I just use a lot of INSERT statements?</p>
<p>EDIT:<br>
If I have to specify column names for all other columns other than the sequence, I lose the original brevity, so it's just not worth it. In that case I'll just use multiple INSERT statements.</p> | 228,294 | 6 | 1 | null | 2008-10-23 01:39:41.847 UTC | 13 | 2015-01-15 13:53:58.187 UTC | 2017-05-23 11:55:02.523 UTC | Ovesh | -1 | Ovesh | 3,751 | null | 1 | 44 | sql|oracle | 164,002 | <p>This works:</p>
<pre><code>insert into TABLE_NAME (COL1,COL2)
select my_seq.nextval, a
from
(SELECT 'SOME VALUE' as a FROM DUAL
UNION ALL
SELECT 'ANOTHER VALUE' FROM DUAL)
</code></pre> |
42,480,949 | What do the curly braces do in switch statement after case in es6? | <p>What's the difference between:</p>
<pre><code>switch (expression) {
case:
somethings;
break;
}
</code></pre>
<p>and</p>
<pre><code>switch (expression) {
case: {
somethings;
break;
}
}
</code></pre>
<p>At first I thought that I could return an object literal like so, but it turns out it's a syntax error. What's the difference actually?</p>
<p>Example from another question:
<a href="https://stackoverflow.com/questions/42475118/how-to-pass-switch-statement-as-function-argument-in-javascript-es6/42475344#42475344">How to pass switch statement as function argument in Javascript ES6?</a></p> | 42,481,784 | 2 | 5 | null | 2017-02-27 08:29:31.4 UTC | 6 | 2019-01-30 10:06:59.383 UTC | 2017-05-23 12:03:08.86 UTC | null | -1 | null | 2,190,425 | null | 1 | 63 | javascript|scope|ecmascript-6|switch-statement | 22,087 | <p>Curly braces used in this way establish their own block scope, in which you can define local <code>let</code> variables or <code>const</code> constants:</p>
<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>switch (false) {
case true: {
let x = "bar";
console.log(x);
break;
}
case false: {
let x = "baz";
console.log(x);
break;
}
}</code></pre>
</div>
</div>
</p>
<p>The example would throw without nested block scopes, since multiple <code>let</code>/<code>const</code> declarations with the same identifier are not allowed within the same scope in Ecmascript 2015.</p>
<p>Please note that the <code>switch</code> statement creates a block scope itself, i.e. whether you use nested block scopes or not, <code>let</code>/<code>const</code> declarations inside <code>switch</code> don't leak into the parent scope.</p>
<p>However, in the context of <code>switch</code>, curly brackets are also used purely decorative, to visually highlight the blocks of the individual <code>case</code> branches.</p> |
68,554,294 | android:exported needs to be explicitly specified for <activity>. Apps targeting Android 12 and higher are required to specify | <p>After upgrading to android 12, the application is not compiling. It shows</p>
<blockquote>
<p>"Manifest merger failed with multiple errors, see logs"</p>
</blockquote>
<p>Error showing in Merged manifest:</p>
<blockquote>
<p>Merging Errors:
Error: android:exported needs to be explicitly specified for . Apps targeting Android 12 and higher are required to specify an explicit value for <code>android:exported</code> when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details. main manifest (this file)</p>
</blockquote>
<p>I have set all the activity with <code>android:exported="false"</code>. But it is still showing this issue.</p>
<p>My manifest file:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="eu.siacs.conversations">
<uses-sdk tools:overrideLibrary="net.ypresto.androidtranscoder" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission
android:name="android.permission.READ_PHONE_STATE"
android:maxSdkVersion="22" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-feature
android:name="android.hardware.location"
android:required="false" />
<uses-feature
android:name="android.hardware.location.gps"
android:required="false" />
<uses-feature
android:name="android.hardware.location.network"
android:required="false" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
<uses-feature
android:name="android.hardware.camera.autofocus"
android:required="false" />
<uses-feature
android:name="android.hardware.microphone"
android:required="false" />
<application
android:name=".Application"
android:allowBackup="false"
android:allowClearUserData="true"
android:appCategory="social"
android:hardwareAccelerated="true"
android:icon="@mipmap/ic_app_launch"
android:label="@string/app_name"
android:largeHeap="true"
android:networkSecurityConfig="@xml/network_security_configuration"
android:requestLegacyExternalStorage="true"
android:roundIcon="@mipmap/ic_app_launch_round"
android:theme="@style/ConversationsTheme"
android:usesCleartextTraffic="true"
android:windowSoftInputMode="adjustPan|adjustResize"
tools:replace="android:label"
tools:targetApi="q">
<activity
android:name=".ui.search.GroupSearchActivity"
android:exported="true" />
<activity
android:name=".ui.profileUpdating.FavouritesActivity"
android:exported="true" />
<activity
android:name=".ui.profileUpdating.NameActivity"
android:exported="true" />
<activity
android:name=".ui.CompulsoryUpdateActivity"
android:exported="true" />
<activity android:name=".ui.payments.doPayment.DoPaymentActivity"
android:exported="true" />
<activity android:name=".ui.individualList.IndividualListActivity"
android:exported="true" />
<activity android:name=".ui.payments.setPayment.SetPaymentActivity"
android:exported="true" />
<activity android:name=".ui.login.otpActivity.OTPActivity"
android:exported="true" />
<activity android:name=".ui.login.loginActivity.LoginActivity"
android:exported="true" />
<service android:name=".services.XmppConnectionService" android:exported="true" />
<receiver android:name=".services.EventReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.intent.action.ACTION_SHUTDOWN" />
<action android:name="android.media.RINGER_MODE_CHANGED" />
</intent-filter>
</receiver>
<activity
android:name=".ui.ShareLocationActivity"
android:label="@string/title_activity_share_location"
android:exported="true"/>
<activity
android:name=".ui.SearchActivity"
android:label="@string/search_messages"
android:exported="true" />
<activity
android:name=".ui.RecordingActivity"
android:configChanges="orientation|screenSize"
android:theme="@style/ConversationsTheme.Dialog"
android:exported="true" />
<activity
android:name=".ui.ShowLocationActivity"
android:label="@string/title_activity_show_location"
android:exported="true" />
<activity
android:name=".ui.SplashActivity"
android:theme="@style/SplashTheme"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ui.ConversationsActivity"
android:label="@string/app_name"
android:launchMode="singleTask"
android:minWidth="300dp"
android:minHeight="300dp"
android:exported="true"
android:windowSoftInputMode="stateHidden" />
<activity
android:name=".ui.ScanActivity"
android:screenOrientation="portrait"
android:exported="true"
android:theme="@style/ConversationsTheme.FullScreen"
android:windowSoftInputMode="stateAlwaysHidden" />
<activity
android:name=".ui.UriHandlerActivity"
android:label="@string/app_name"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="xmpp" />
</intent-filter>
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https" />
<data android:host="im.app.in" />
<data android:pathPrefix="/i/" />
<data android:pathPrefix="/j/" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SENDTO" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="imto" />
<data android:host="jabber" />
</intent-filter>
</activity>
<activity
android:name=".ui.StartConversationActivity"
android:label="@string/title_activity_start_conversation"
android:launchMode="singleTop"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
</intent-filter>
</activity>
<activity
android:name=".ui.SettingsActivity"
android:label="@string/title_activity_settings"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.NOTIFICATION_PREFERENCES" />
</intent-filter>
</activity>
<activity
android:name=".ui.ChooseContactActivity"
android:label="@string/title_activity_choose_contact"
android:exported="true" />
<activity
android:name=".ui.BlocklistActivity"
android:label="@string/title_activity_block_list"
android:exported="true"/>
<activity
android:name=".ui.ChangePasswordActivity"
android:label="@string/change_password_on_server"
android:exported="true"/>
<activity
android:name=".ui.ChooseAccountForProfilePictureActivity"
android:enabled="false"
android:label="@string/choose_account"
android:exported="true">
<intent-filter android:label="@string/set_profile_picture">
<action android:name="android.intent.action.ATTACH_DATA" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
</activity>
<activity
android:name=".ui.ShareViaAccountActivity"
android:label="@string/title_activity_share_via_account"
android:launchMode="singleTop"
android:exported="true" />
<activity
android:name=".ui.EditAccountActivity"
android:launchMode="singleTop"
android:exported="true"
android:windowSoftInputMode="stateHidden|adjustResize" />
<activity
android:name=".ui.ConferenceDetailsActivity"
android:label="@string/action_muc_details"
android:exported="true"
android:windowSoftInputMode="stateHidden" />
<activity
android:name=".ui.ContactDetailsActivity"
android:exported="true"
android:windowSoftInputMode="stateHidden" />
<activity
android:name=".ui.PublishProfilePictureActivity"
android:label="@string/mgmt_account_publish_avatar"
android:exported="true"
android:windowSoftInputMode="stateHidden" />
<activity
android:name=".ui.PublishGroupChatProfilePictureActivity"
android:exported="true"
android:label="@string/group_chat_avatar" />
<activity
android:name=".ui.ShareWithActivity"
android:label="@string/app_name"
android:launchMode="singleTop"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="*/*" />
</intent-filter>
<!-- the value here needs to be the full class name; independent of the configured applicationId -->
<meta-data
android:name="android.service.chooser.chooser_target_service"
android:value="eu.siacs.conversations.services.ContactChooserTargetService" />
</activity>
<activity
android:name=".ui.TrustKeysActivity"
android:label="@string/trust_omemo_fingerprints"
android:exported="true"
android:windowSoftInputMode="stateAlwaysHidden" />
<activity
android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
android:exported="true"
android:theme="@style/Base.Theme.AppCompat" />
<activity android:name=".ui.MemorizingActivity"
android:exported="true" />
<activity
android:name=".ui.MediaBrowserActivity"
android:exported="true"
android:label="@string/media_browser" />
<service android:name=".services.ExportBackupService" android:exported="true"/>
<service android:name=".services.ImportBackupService" android:exported="true"/>
<service
android:name=".services.ContactChooserTargetService"
android:permission="android.permission.BIND_CHOOSER_TARGET_SERVICE"
android:exported="true">
<intent-filter>
<action android:name="android.service.chooser.ChooserTargetService" />
</intent-filter>
</service>
<service android:name=".services.CompulsoryUpdateService" android:exported="true"/>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.files"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
<provider
android:name=".services.BarcodeProvider"
android:authorities="${applicationId}.barcodes"
android:exported="false"
android:grantUriPermissions="true" />
<activity
android:name=".ui.ShortcutActivity"
android:label="@string/contact"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.CREATE_SHORTCUT" />
</intent-filter>
</activity>
<activity
android:name=".ui.MucUsersActivity"
android:exported="true"
android:label="@string/group_chat_members" />
<activity
android:name=".ui.ChannelDiscoveryActivity"
android:exported="true"
android:label="@string/discover_channels" />
<activity
android:name=".ui.RtpSessionActivity"
android:autoRemoveFromRecents="true"
android:exported="true"
android:launchMode="singleInstance"
android:supportsPictureInPicture="true" />
</application>
</manifest>
</code></pre>
<p>My second manifest file:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="eu.siacs.conversations">
<application tools:ignore="GoogleAppIndexingWarning">
<activity
android:name=".ui.ManageAccountActivity"
android:label="@string/title_activity_manage_accounts"
android:launchMode="singleTask"
android:exported="true"/>
<activity
android:name=".ui.MagicCreateActivity"
android:label="@string/create_new_account"
android:launchMode="singleTask"
android:exported="true"/>
<activity
android:name=".ui.EasyOnboardingInviteActivity"
android:label="@string/invite_to_app"
android:launchMode="singleTask" />
<activity
android:name=".ui.ImportBackupActivity"
android:label="@string/restore_backup"
android:launchMode="singleTask"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/vnd.conversations.backup" />
<data android:scheme="content" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/vnd.conversations.backup" />
<data android:scheme="file" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="content" />
<data android:host="*" />
<data android:mimeType="*/*" />
<data android:pathPattern=".*\\.ceb" />
<data android:pathPattern=".*\\..*\\.ceb" />
<data android:pathPattern=".*\\..*\\..*\\.ceb" />
<data android:pathPattern=".*\\..*\\..*\\..*\\.ceb" />
<data android:pathPattern=".*\\..*\\..*\\..*\\..*\\.ceb" />
<data android:pathPattern=".*\\..*\\..*\\..*\\..*\\..*\\.ceb" />
<data android:pathPattern=".*\\..*\\..*\\..*\\..*\\..*\\..*\\.ceb" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="file" />
<data android:host="*" />
<data android:mimeType="*/*" />
<data android:pathPattern=".*\\.ceb" />
<data android:pathPattern=".*\\..*\\.ceb" />
<data android:pathPattern=".*\\..*\\..*\\.ceb" />
<data android:pathPattern=".*\\..*\\..*\\..*\\.ceb" />
<data android:pathPattern=".*\\..*\\..*\\..*\\..*\\.ceb" />
<data android:pathPattern=".*\\..*\\..*\\..*\\..*\\..*\\.ceb" />
<data android:pathPattern=".*\\..*\\..*\\..*\\..*\\..*\\..*\\.ceb" />
</intent-filter>
</activity>
</application>
</manifest>
</code></pre>
<p>My gradle file:</p>
<pre><code>import com.android.build.OutputFile
// Top-level build file where you can add configuration options common to all
// sub-projects/modules.
buildscript {
ext.kotlin_version = "1.5.21"
repositories {
google()
mavenCentral()
maven { url 'https://jitpack.io' }
gradlePluginPortal()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.2.2'
classpath 'com.google.gms:google-services:4.3.8'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'com.google.gms.google-services'
repositories {
google()
mavenCentral()
jcenter()
maven { url 'https://jitpack.io' }
}
configurations {
conversationsFreeCompatImplementation
}
dependencies {
implementation 'androidx.viewpager:viewpager:1.0.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'org.sufficientlysecure:openpgp-api:10.0'
implementation 'com.theartofdev.edmodo:android-image-cropper:2.8.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'androidx.exifinterface:exifinterface:1.3.2'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
implementation 'androidx.emoji:emoji:1.1.0'
implementation 'com.google.android.material:material:1.4.0'
conversationsFreeCompatImplementation 'androidx.emoji:emoji-bundled:1.1.0'
implementation 'org.bouncycastle:bcmail-jdk15on:1.64'
//zxing stopped supporting Java 7 so we have to stick with 3.3.3
//https://github.com/zxing/zxing/issues/1170
implementation 'com.google.zxing:core:3.4.1'
implementation 'de.measite.minidns:minidns-hla:0.2.4'
implementation 'me.leolin:ShortcutBadger:1.1.22@aar'
implementation 'org.whispersystems:signal-protocol-java:2.8.1'
implementation 'com.makeramen:roundedimageview:2.3.0'
implementation "com.wefika:flowlayout:0.4.1"
implementation 'net.ypresto.androidtranscoder:android-transcoder:0.3.0'
implementation 'org.jxmpp:jxmpp-jid:1.0.1'
implementation 'org.osmdroid:osmdroid-android:6.1.10'
implementation 'org.hsluv:hsluv:0.2'
implementation 'org.conscrypt:conscrypt-android:2.5.2'
implementation 'me.drakeet.support:toastcompat:1.1.0'
implementation "com.leinardi.android:speed-dial:3.2.0"
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.9.0"
implementation "com.squareup.okhttp3:okhttp:5.0.0-alpha.2"
implementation 'com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.2'
implementation 'com.google.guava:guava:30.1.1-android'
implementation 'org.webrtc:google-webrtc:1.0.32006'
// Lifecycle Helper
implementation "androidx.activity:activity-ktx:1.3.0-rc02"
implementation "androidx.fragment:fragment-ktx:1.3.6"
//Navigation
implementation 'androidx.navigation:navigation-fragment-ktx:2.3.5'
implementation 'androidx.navigation:navigation-ui-ktx:2.3.5'
//CardView
implementation "androidx.cardview:cardview:1.0.0"
//Country Code Picker
implementation 'com.hbb20:ccp:2.5.3'
//Firebase
implementation 'com.google.firebase:firebase-bom:28.3.0'
implementation 'com.google.firebase:firebase-auth-ktx:21.0.1'
implementation 'androidx.browser:browser:1.3.0'
//OTP view
implementation 'com.github.mukeshsolanki:android-otpview-pinview:2.1.2'
//Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
//Gson
implementation 'com.google.code.gson:gson:2.8.7'
//Multidex
implementation 'androidx.multidex:multidex:2.0.1'
//Round Image
implementation 'de.hdodenhof:circleimageview:3.1.0'
// Button with image and text
implementation 'com.github.Omega-R:OmegaCenterIconButton:0.0.4@aar'
//Razor pay
implementation 'com.razorpay:checkout:1.6.10'
//Mixpanel Tracking
implementation 'com.mixpanel.android:mixpanel-android:5.9.1'
//Loading screen
implementation 'com.wang.avi:library:2.1.3'
//Loading
implementation 'com.wang.avi:library:2.1.3'
//Form
implementation 'com.quickbirdstudios:surveykit:1.1.0'
}
ext {
travisBuild = System.getenv("TRAVIS") == "true"
preDexEnabled = System.getProperty("pre-dex", "true")
abiCodes = ['armeabi-v7a': 1, 'x86': 2, 'x86_64': 3, 'arm64-v8a': 4]
}
android {
compileSdkVersion 31
defaultConfig {
minSdkVersion 24
targetSdkVersion 31
versionCode 44
versionName "2.0.4"
multiDexEnabled = true
archivesBaseName += "-$versionName"
applicationId "com.app.app"
resValue "string", "applicationId", applicationId
def appName = "app"
resValue "string", "app_name", appName
buildConfigField "String", "APP_NAME", "\"$appName\""
}
splits {
abi {
universalApk true
enable true
}
}
configurations {
compile.exclude group: 'org.jetbrains' , module:'annotations'
}
dataBinding {
enabled true
}
dexOptions {
// Skip pre-dexing when running on Travis CI or when disabled via -Dpre-dex=false.
preDexLibraries = preDexEnabled && !travisBuild
jumboMode true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
flavorDimensions("mode", "distribution", "emoji")
productFlavors {
conversations {
dimension "mode"
}
free {
dimension "distribution"
versionNameSuffix "+f"
}
compat {
dimension "emoji"
versionNameSuffix "c"
}
}
sourceSets {
conversationsFreeCompat {
java {
srcDir 'src/freeCompat/java'
srcDir 'src/conversationsFree/java'
}
}
}
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
versionNameSuffix "r"
}
debug {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
versionNameSuffix "d"
}
}
if (new File("signing.properties").exists()) {
Properties props = new Properties()
props.load(new FileInputStream(file("signing.properties")))
signingConfigs {
release {
storeFile file(props['keystore'])
storePassword props['keystore.password']
keyAlias props['keystore.alias']
keyPassword props['keystore.password']
}
}
buildTypes.release.signingConfig = signingConfigs.release
}
lintOptions {
disable 'MissingTranslation', 'InvalidPackage','AppCompatResource'
}
subprojects {
afterEvaluate {
if (getPlugins().hasPlugin('android') ||
getPlugins().hasPlugin('android-library')) {
configure(android.lintOptions) {
disable 'AndroidGradlePluginVersion', 'MissingTranslation'
}
}
}
}
packagingOptions {
exclude 'META-INF/BCKEY.DSA'
exclude 'META-INF/BCKEY.SF'
}
android.applicationVariants.all { variant ->
variant.outputs.each { output ->
def baseAbiVersionCode = project.ext.abiCodes.get(output.getFilter(OutputFile.ABI))
if (baseAbiVersionCode != null) {
output.versionCodeOverride = (100 * variant.versionCode) + baseAbiVersionCode
}
}
}
}
</code></pre> | 68,648,841 | 24 | 23 | null | 2021-07-28 04:09:31.697 UTC | 18 | 2022-06-24 15:52:55.19 UTC | 2021-07-28 09:12:57.273 UTC | null | 14,280,831 | null | 14,280,831 | null | 1 | 160 | java|android|kotlin|android-manifest|android-12 | 120,710 | <p>I had this issue and one of the libraries I used wasn't setting it correctly.</p>
<h1>Find location</h1>
<p>First of all, we need to find the exact location and/or cause for the error,<br />
which can be done with different approaches (see below).</p>
<h2>Find by inspecting merged-manifest <sup>(approach #1)</sup></h2>
<p>You can find it by doing the steps:</p>
<ul>
<li><p>Set target SDK to 30 (to silence 31+ errors).</p>
</li>
<li><p>Open application's manifest (<code>AndroidManifest.xml</code>) and click on "<code>Merged Manifest</code>" tab on bottom of your edit pane:<br />
<a href="https://i.stack.imgur.com/KOSek.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KOSek.png" alt="Merged Manifest in Android Studio" /></a></p>
<blockquote>
<p>Which if you configure <code>build.gradle</code> like:</p>
<pre><code>allprojects {
buildDir = "${rootProject.rootDir}/build/${project.name}"
}
</code></pre>
<p>Something similar should be in a sub-path like:</p>
<pre><code>build/my-app/intermediates/merged_manifest/debug/AndroidManifest.xml
</code></pre>
</blockquote>
</li>
<li><p>Go to the individual manifest file of all the libraries (You can skip this step if the merged manifest is created and you can just look into the merged manifest)</p>
</li>
<li><p>Search if there's any <strong>entry</strong> of type activity, service, receiver, or provider which does not have an <code>exported</code> attribute, and for each entry follow below "Fix found entries" section (or see once for how to set <code>exported</code> attribute).</p>
</li>
<li><p>Set target SDK back to 31 (or whatever it was before changing to 30).</p>
</li>
</ul>
<h2>Find by console logs <sup>(approach #2)</sup></h2>
<ul>
<li><p>In Git-bash run something like:</p>
<pre><code>./gradlew assembleDebug --stacktrace --info | tee my-logs.txt
</code></pre>
</li>
<li><p>Open <code>my-logs.txt</code> file (which previous step created, in your preferred text-editor).</p>
</li>
<li><p>Now, the exact location is <em>hidden</em> in the logs,
hence search in the created <code>my-logs.txt</code> file,
for these keywords:</p>
<ul>
<li><code>activity#</code></li>
<li><code>service#</code></li>
<li><code>receiver#</code></li>
<li><code>provider#</code></li>
</ul>
</li>
<li><p>Which should find something like:</p>
</li>
</ul>
<pre><code>activity#androidx.test.core.app.InstrumentationActivityInvoker$BootstrapActivity
ADDED from [androidx.test:core:1.2.0] C:\Users\Admin\.gradle\caches\transforms-3\709730c74fe4dc9f8fd991eb4d1c2adc\transformed\jetified-core-1.2.0\AndroidManifest.xml:27:9-33:20
</code></pre>
<ul>
<li>Open <code>AndroidManifest.xml</code> file that previous steps did find, search if there's any <strong>entry</strong> of type <code>activity</code>, <code>service</code>, <code>receiver</code>, or <code>provider</code> which does not have an <code>exported</code> attribute, and see below "Fix found entries" section (for how to set each entries <code>exported</code> attribute).</li>
</ul>
<blockquote>
<p><strong>Note</strong> that (at time of writting) passing <code>--stacktrace</code> alone did not include location <em>info</em> ;-)</p>
</blockquote>
<h1>Fix found entries</h1>
<p>If the real (not build-generated) source of found entry is in root-project's manifest (or somewhere you can alter),
set <code>exported</code> attribute to corresponding need (which is normally <code>false</code>) therein directly, like:</p>
<pre><code><receiver
android:name="<name_of_the_entry>"
android:exported="false or true"
tools:node="merge" />
</code></pre>
<blockquote>
<p><strong>Note</strong> that both <code>android:exported="..."</code> and <code>tools:node="merge"</code> are set above.</p>
</blockquote>
<p>But if found entry's specification is written in the manifest of a third-party library (which's real-source you can't alter),
override the specification of said library by adding it to our root-project's manifest, for example like:</p>
<pre class="lang-xml prettyprint-override"><code><provider
android:name="com.squareup.picasso.PicassoProvider"
android:exported="false"
tools:node="merge"
tools:overrideLibrary="com.squareup.picasso.picasso" />
</code></pre>
<blockquote>
<p><strong>Note</strong> that this time <code>tools:overrideLibrary="..."</code> is set as well.</p>
<p>For more information see <a href="https://android-doc.github.io/tools/building/manifest-merge.html" rel="noreferrer">Documentation</a>,<br />
and/or <a href="https://github.com/razorpay/razorpay-android-sample-app/issues/248" rel="noreferrer">Similar issue in a SDK</a>.</p>
</blockquote> |
21,289,319 | How to get the latest record from each group in ActiveRecord? | <p>In my Ruby on Rails application I have a database structure like this:</p>
<pre><code>Project.create(:group => "1", :date => "2014-01-01")
Project.create(:group => "1", :date => "2014-01-02")
Project.create(:group => "1", :date => "2014-01-03")
Project.create(:group => "2", :date => "2014-01-01")
Project.create(:group => "2", :date => "2014-01-02")
Project.create(:group => "2", :date => "2014-01-03")
# and so forth...
</code></pre>
<p>How can I get the latest record from each <code>group</code> using ActiveRecord?</p>
<p>The solution is probably simple but I can't get my head around this.</p>
<p>Thanks for any help.</p> | 21,289,909 | 6 | 3 | null | 2014-01-22 17:04:57.077 UTC | 9 | 2021-06-23 09:54:32.063 UTC | null | null | null | null | 976,691 | null | 1 | 43 | ruby-on-rails|ruby|activerecord | 29,937 | <h3>Postgres</h3>
<p>In Postgres, this can be achieved with the following query.</p>
<pre><code>SELECT DISTINCT ON ("group") * FROM projects
ORDER BY "group", date DESC, id DESC
</code></pre>
<p>Because the <code>date</code> column might not be unique here, I have added an additional <code>ORDER BY</code> clause on <code>id DESC</code> to break ties in favor of the record with the higher ID, in case two records in a group have the same date. You might instead want to use another column like the date/time of the last update or so, that depends on your use case.</p>
<p>Moving on, ActiveRecord unfortunately has no API for <code>DISTINCT ON</code>, but we can still use plain SQL with <code>select</code>:</p>
<pre><code>Project.select('DISTINCT ON ("group") *').order(:group, date: :desc, id: :desc)
</code></pre>
<p>or if you prefer using ARel instead of having raw SQL:</p>
<pre><code>p = Project.arel_table
Project.find_by_sql(
p.project(p[Arel.star])
.distinct_on(p[:group])
.order(p[:group], p[:date].desc, p[:id].desc)
)
</code></pre>
<h3>MySQL</h3>
<p>For other databases like MySQL this is unfortunately not as convenient. There are a variety of solutions available, see for example <a href="https://stackoverflow.com/a/1313293/192702">this answer</a>.</p> |
63,309,614 | How to install openjdk with brew? | <p>Seems like there's 3 packages "openjdk", "cask java" and "adoptopenjdk".</p>
<p>Which one should be used?</p> | 63,309,664 | 3 | 2 | null | 2020-08-07 21:57:14.387 UTC | 3 | 2022-02-24 10:59:45.67 UTC | null | null | null | null | 231,624 | null | 1 | 24 | java|homebrew | 51,810 | <p>Run <code>brew install openjdk@11</code></p>
<p>In case you are managing java versions with <a href="https://www.jenv.be/" rel="noreferrer">jenv</a>, also run:</p>
<pre class="lang-sh prettyprint-override"><code>sudo ln -sfn /opt/homebrew/opt/openjdk@11/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk-11.jdk
jenv add /Library/Java/JavaVirtualMachines/openjdk-11.jdk/Contents/Home/
</code></pre> |
61,354,866 | Is there a workaround for the Firebase Query "IN" Limit to 10? | <p>I have a query for firebase that has an array of IDs that has a size > 10. Firebase has restrictions on the number of records to query in one session. Is there a way to query against more than 10 at a time? </p>
<blockquote>
<p>[Unhandled promise rejection: FirebaseError: Invalid Query. 'in' filters support a maximum of 10 elements in the value array.]</p>
</blockquote>
<p><a href="https://cloud.google.com/firestore/docs/query-data/queries" rel="noreferrer">https://cloud.google.com/firestore/docs/query-data/queries</a></p>
<p><a href="https://i.stack.imgur.com/WTSeg.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WTSeg.png" alt="enter image description here"></a></p>
<pre><code> let query = config.db
.collection(USER_COLLECTION_NAME)
.where("id", "in", matchesIdArray);
const users = await query.get();
</code></pre>
<p>(matchesIdArray.length needs to be unlimited)</p> | 66,265,824 | 9 | 2 | null | 2020-04-21 23:27:04.533 UTC | 8 | 2022-08-15 17:32:07.05 UTC | 2021-12-22 14:38:51.713 UTC | null | 8,172,439 | null | 6,054,959 | null | 1 | 47 | javascript|firebase|react-native|google-cloud-platform|google-cloud-firestore | 17,670 | <p>I found this to work well for me without needing to make as many queries (loop and request in batches of 10).</p>
<pre class="lang-js prettyprint-override"><code>export async function getContentById(ids, path) {
// don't run if there aren't any ids or a path for the collection
if (!ids || !ids.length || !path) return [];
const collectionPath = db.collection(path);
const batches = [];
while (ids.length) {
// firestore limits batches to 10
const batch = ids.splice(0, 10);
// add the batch request to to a queue
batches.push(
collectionPath
.where(
firebase.firestore.FieldPath.documentId(),
'in',
[...batch]
)
.get()
.then(results => results.docs.map(result => ({ /* id: result.id, */ ...result.data() }) ))
)
}
// after all of the data is fetched, return it
return Promise.all(batches)
.then(content => content.flat());
}
</code></pre> |
23,228,694 | Saving related records in laravel | <p>I have users, and users belong to a dealership. </p>
<p>Upon user registration, I'm trying to save a new user, and a new dealership. </p>
<p>User database has a <code>dealership_id</code> column, which I want to be populated with the ID of the newly created dealership. </p>
<p>This is my current code in the <code>UserController</code> store method.</p>
<pre><code>public function store()
{
$user = new User();
$user->email = Input::get('email');
$user->password = Input::get('password');
$dealership = new Dealership();
$dealership->name = Input::get('dealership_name');
$user->push();
return "User Saved";
}
</code></pre>
<p>Trying to use <code>$user->push();</code> User data gets updated, but dealership is not created or updated. </p> | 23,228,949 | 4 | 2 | null | 2014-04-22 19:41:19.267 UTC | 18 | 2019-01-22 03:47:05.067 UTC | 2017-02-27 12:15:43.783 UTC | null | 1,216,451 | null | 1,615,360 | null | 1 | 52 | laravel|laravel-4|one-to-many|eloquent | 71,037 | <p>Eloquent's <code>push()</code> saves the model and its relationships, but first you have to tell what you want to be involved in the relationsship.</p>
<p>Since your user-model/table holds the id of the dealership, I assume that a user can belong to only one dealership, so the relationship should look like this:</p>
<p><strong>User Model:</strong></p>
<pre><code>public function dealership()
{
return $this->belongsTo('Dealership');
}
</code></pre>
<p><strong>Dealership Model:</strong></p>
<pre><code>public function users()
{
return $this->hasMany('User');
}
</code></pre>
<p>To save a User from the Dealership perspective, you do this:</p>
<pre><code>$dealership->users()->save($user);
</code></pre>
<p>To associate a dealership with a user, you do this:</p>
<pre><code>$user->dealership()->associate($dealership);
$user->save();
</code></pre> |
1,582,960 | Assembly language je jump function | <p>I am trying to find online the usage of the assembly language function "je". I read that je means jump if equal and that is exactly what I want. What is the actual usage of this function, or in other words, how to I type this function to check a value and jump if it is equal to something?</p>
<p>Please let me know.</p>
<p>BTW, I am using NASM if that makes a difference.</p> | 1,582,989 | 5 | 0 | null | 2009-10-17 19:04:36.67 UTC | 8 | 2015-06-23 20:05:25.243 UTC | 2015-06-23 20:05:25.243 UTC | null | 4,370,109 | null | 74,984 | null | 1 | 22 | assembly|conditional-statements | 116,358 | <p>Let's say you want to check if <code>EAX</code> is equal to <code>5</code>, and perform different actions based on the result of that comparison. An if-statement, in other words.</p>
<pre><code> ; ... some code ...
cmp eax, 5
je .if_true
; Code to run if comparison is false goes here.
jmp short .end_if
.if_true:
; Code to run if comparison is true goes here.
.end_if:
; ... some code ...
</code></pre> |
1,983,047 | Good Haskell coding standards | <p>Could someone provide a link to a good coding standard for Haskell? I've found <a href="http://urchin.earth.li/~ian/style/haskell.html" rel="noreferrer">this</a> and <a href="http://www.haskell.org/haskellwiki/Programming_guidelines" rel="noreferrer">this</a>, but they are far from comprehensive. Not to mention that the HaskellWiki one includes such "gems" as "use classes with care" and "defining symbolic infix identifiers should be left to library writers only."</p> | 1,983,310 | 5 | 1 | null | 2009-12-30 23:23:16.317 UTC | 59 | 2013-12-26 10:53:57.867 UTC | null | null | null | null | 9,204 | null | 1 | 75 | haskell|coding-style|conventions | 11,525 | <p>Really hard question. I hope your answers turn up something good. Meanwhile, here is a catalog of mistakes or other annoying things that I have found in beginners' code. There is some overlap with the Cal Tech style page that Kornel Kisielewicz points to. Some of my advice is every bit as vague and useless as the HaskellWiki "gems", but I hope at least it is better advice :-)</p>
<ul>
<li><p>Format your code so it fits in 80 columns. (Advanced users may prefer 87 or 88; beyond that is pushing it.)</p></li>
<li><p>Don't forget that <code>let</code> bindings and <code>where</code> clauses create a mutually recursive nest of definitions, <em>not</em> a <em>sequence</em> of definitions.</p></li>
<li><p>Take advantage of <code>where</code> clauses, especially their ability to see function parameters that are already in scope (nice vague advice). If you are really grokking Haskell, your code should have a lot more <code>where</code>-bindings than <code>let</code>-bindings. Too many <code>let</code>-bindings is a sign of an unreconstructed ML programmer or Lisp programmer.</p></li>
<li><p>Avoid redundant parentheses. Some places where redundant parentheses are particularly offensive are</p>
<ul>
<li><p>Around the condition in an <code>if</code> expression (brands you as an unreconstructed C programmer)</p></li>
<li><p>Around a function application which is itself the argument of an infix operator (<em>Function application binds tighter than any infix operator</em>. This fact should be burned into every Haskeller's brain, in much the same way that us dinosaurs had APL's right-to-left scan rule burned in.)</p></li>
</ul></li>
<li><p>Put spaces around infix operators. Put a space following each comma in a tuple literal.</p></li>
<li><p>Prefer a space between a function and its argument, even if the argument is parenthesized.</p></li>
<li><p>Use the <code>$</code> operator judiciously to cut down on parentheses. Be aware of the close relationship between <code>$</code> and infix <code>.</code>:</p>
<pre><code>f $ g $ h x == (f . g . h) x == f . g . h $ x
</code></pre></li>
<li><p>Don't overlook the built-in <code>Maybe</code> and <code>Either</code> types.</p></li>
<li><p>Never write <code>if <expression> then True else False</code>; the correct phrase is simply <code><expression></code>.</p></li>
<li><p>Don't use <code>head</code> or <code>tail</code> when you could use pattern matching.</p></li>
<li><p>Don't overlook function composition with the infix dot operator.</p></li>
<li><p>Use line breaks carefully. Line breaks can increase readability, but there is a tradeoff: Your editor may display only 40–50 lines at once. If you need to read and understand a large function all at once, you mustn't overuse line breaks.</p></li>
<li><p>Almost always prefer the <code>--</code> comments which run to end of line over the <code>{- ... -}</code> comments. The braced comments may be appropriate for large headers—that's it.</p></li>
<li><p>Give each top-level function an explicit type signature.</p></li>
<li><p>When possible, align <code>--</code> lines, <code>=</code> signs, and even parentheses and commas that occur in adjacent lines.</p></li>
<li><p>Influenced as I am by GHC central, I have a very mild preference to use <code>camelCase</code> for exported identifiers and <code>short_name</code> with underscores for local <code>where</code>-bound or <code>let</code>-bound variables.</p></li>
</ul> |
1,474,894 | Why isn't the [] operator const for STL maps? | <p>Contrived example, for the sake of the question:</p>
<pre><code>void MyClass::MyFunction( int x ) const
{
std::cout << m_map[x] << std::endl
}
</code></pre>
<p>This won't compile, since the [] operator is non-const. </p>
<p>This is unfortunate, since the [] syntax looks very clean. Instead, I have to do something like this:</p>
<pre><code>void MyClass::MyFunction( int x ) const
{
MyMap iter = m_map.find(x);
std::cout << iter->second << std::endl
}
</code></pre>
<p>This has always bugged me. Why is the [] operator non-const?</p> | 1,474,953 | 6 | 2 | null | 2009-09-25 00:45:09.437 UTC | 23 | 2018-09-04 02:53:42.81 UTC | 2009-09-25 12:42:09.64 UTC | null | 15,934 | null | 68,768 | null | 1 | 102 | c++|constants | 20,911 | <p>For <code>std::map</code> and <code>std::unordered_map</code>, <code>operator[]</code> will insert the index value into the container if it didn't previously exist. It's a little unintuitive, but that's the way it is.</p>
<p>Since it must be allowed to fail and insert a default value, the operator can't be used on a <code>const</code> instance of the container.</p>
<p><a href="http://en.cppreference.com/w/cpp/container/map/operator_at" rel="noreferrer">http://en.cppreference.com/w/cpp/container/map/operator_at</a></p> |
1,549,945 | Why would you ever want to allocate memory on the heap rather than the stack? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/102009/when-is-it-best-to-use-a-stack-instead-of-a-heap-and-vice-versa">When is it best to use a Stack instead of a Heap and vice versa?</a> </p>
</blockquote>
<p>I've read a few of the other questions regarding the heap vs stack, but they seem to focus more on what the heap/stack do rather than why you would use them.</p>
<p>It seems to me that stack allocation would almost always be preferred since it is quicker (just moving the stack pointer vs looking for free space in the heap), and you don't have to manually free allocated memory when you're done using it. The only reason I can see for using heap allocation is if you wanted to create an object in a function and then use it outside that functions scope, since stack allocated memory is automatically unallocated after returning from the function.</p>
<p>Are there other reasons for using heap allocation instead of stack allocation that I am not aware of? </p> | 1,549,957 | 9 | 2 | null | 2009-10-11 05:37:31.473 UTC | 13 | 2021-06-29 21:16:43.863 UTC | 2021-06-29 21:16:43.863 UTC | null | 5,459,839 | null | 128,948 | null | 1 | 23 | c|memory|memory-management|heap-memory|stack-memory | 16,255 | <p>There are a few reasons:</p>
<ul>
<li>The main one is that with heap allocation, you have the most flexible control over the object's lifetime (from <code>malloc</code>/<code>calloc</code> to <code>free</code>);</li>
<li>Stack space is typically a more limited resource than heap space, at least in default configurations;</li>
<li>A failure to allocate heap space can be handled gracefully, whereas running out of stack space is often unrecoverable.</li>
</ul>
<p>Without the flexible object lifetime, useful data structures such as binary trees and linked lists would be virtually impossible to write.</p> |
1,347,791 | "Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3 | <p>I am using Python 3.1 on a Windows 7 machine. Russian is the default system language, and utf-8 is the default encoding.</p>
<p>Looking at the answer to a <a href="https://stackoverflow.com/questions/778096/problem-opening-a-text-document-unicode-error">previous question</a>, I have attempting using the "codecs" module to give me a little luck. Here's a few examples:</p>
<pre class="lang-none prettyprint-override"><code>>>> g = codecs.open("C:\Users\Eric\Desktop\beeline.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape (<pyshell#39>, line 1)
</code></pre>
<pre class="lang-none prettyprint-override"><code>>>> g = codecs.open("C:\Users\Eric\Desktop\Site.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape (<pyshell#40>, line 1)
</code></pre>
<pre class="lang-none prettyprint-override"><code>>>> g = codecs.open("C:\Python31\Notes.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 11-12: malformed \N character escape (<pyshell#41>, line 1)
</code></pre>
<pre class="lang-none prettyprint-override"><code>>>> g = codecs.open("C:\Users\Eric\Desktop\Site.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape (<pyshell#44>, line 1)
</code></pre>
<p>My last idea was, I thought it might have been the fact that Windows "translates" a few folders, such as the "users" folder, into Russian (though typing "users" is still the correct path), so I tried it in the Python31 folder. Still, no luck. Any ideas?</p> | 1,347,854 | 10 | 3 | null | 2009-08-28 15:36:39.263 UTC | 147 | 2021-05-10 09:38:26.153 UTC | 2020-12-27 17:48:31.237 UTC | null | 4,621,513 | null | 158,790 | null | 1 | 395 | python|unicode|python-3.x | 1,161,357 | <p>The problem is with the string</p>
<pre><code>"C:\Users\Eric\Desktop\beeline.txt"
</code></pre>
<p>Here, <code>\U</code> in <code>"C:\Users</code>... starts an eight-character Unicode escape, such as <code>\U00014321</code>. In your code, the escape is followed by the character 's', which is invalid.</p>
<p>You either need to duplicate all backslashes:</p>
<pre><code>"C:\\Users\\Eric\\Desktop\\beeline.txt"
</code></pre>
<p>Or prefix the string with <code>r</code> (to produce a raw string):</p>
<pre><code>r"C:\Users\Eric\Desktop\beeline.txt"
</code></pre> |
2,016,894 | How can I split a large text file into smaller files with an equal number of lines? | <p>I've got a large (by number of lines) plain text file that I'd like to split into smaller files, also by number of lines. So if my file has around 2M lines, I'd like to split it up into 10 files that contain 200k lines, or 100 files that contain 20k lines (plus one file with the remainder; being evenly divisible doesn't matter).</p>
<p>I could do this fairly easily in Python, but I'm wondering if there's any kind of ninja way to do this using Bash and Unix utilities (as opposed to manually looping and counting / partitioning lines).</p> | 2,016,918 | 11 | 6 | null | 2010-01-06 22:40:39.823 UTC | 178 | 2022-01-24 10:54:49.577 UTC | 2021-08-11 23:07:51.863 UTC | null | 63,550 | null | 217,332 | null | 1 | 649 | bash|file|unix | 619,797 | <p>Have a look at the split command:</p>
<pre class="lang-none prettyprint-override"><code>$ split --help
Usage: split [OPTION] [INPUT [PREFIX]]
Output fixed-size pieces of INPUT to PREFIXaa, PREFIXab, ...; default
size is 1000 lines, and default PREFIX is `x'. With no INPUT, or when INPUT
is -, read standard input.
Mandatory arguments to long options are mandatory for short options too.
-a, --suffix-length=N use suffixes of length N (default 2)
-b, --bytes=SIZE put SIZE bytes per output file
-C, --line-bytes=SIZE put at most SIZE bytes of lines per output file
-d, --numeric-suffixes use numeric suffixes instead of alphabetic
-l, --lines=NUMBER put NUMBER lines per output file
--verbose print a diagnostic to standard error just
before each output file is opened
--help display this help and exit
--version output version information and exit
</code></pre>
<p>You could do something like this:</p>
<pre><code>split -l 200000 filename
</code></pre>
<p>which will create files each with 200000 lines named <code>xaa xab xac</code> ...</p>
<p>Another option, split by size of output file (still splits on line breaks):</p>
<pre><code> split -C 20m --numeric-suffixes input_filename output_prefix
</code></pre>
<p>creates files like <code>output_prefix01 output_prefix02 output_prefix03 ...</code> each of maximum size 20 megabytes.</p> |
8,918,851 | How to protect a private REST API in an AJAX app | <p>I know that there are many similar questions posted, but none of them refers to an HTML/javascript app where the user can access the code.</p>
<p>I have a private REST API written in nodejs. It is private because its only purpose is to server my HTML5 clients apps (Chrome app and Adobe Air app). So an API key is not a good solution since any user can see the javascript code. </p>
<p>I want to avoid bots creating accounts on my server and consuming my resources.</p>
<p>Is there any way to acomplish this?</p> | 8,918,896 | 2 | 2 | null | 2012-01-18 23:07:00.157 UTC | 15 | 2012-01-19 01:34:52.02 UTC | null | null | null | null | 492,696 | null | 1 | 22 | javascript|security|api|rest|node.js | 14,116 | <p>An API key is a decent solution especially if you require constraints on the API key's request origin; consider that you should only accept an API key if the originating web request comes from an authorized source, such as your private domain. If a web request comes from an unauthorized domain, you could simply deny processing the request.</p>
<p>You can improve the security of this mechanism by utilizing a specialized encoding scheme, such as a hash-based message authentication code (HMAC). The following resource explains this mechanism clearly:</p>
<p><a href="http://cloud.dzone.com/news/using-api-keys-effectively">http://cloud.dzone.com/news/using-api-keys-effectively</a></p> |
18,126,249 | "BadParcelableException: ClassNotFoundException when unmarshalling <myclass>" while using Parcel.read method that has a ClassLoader as argument | <p>Given a custom class <code>org.example.app.MyClass implements Parcelable</code>, I want to write a <code>List<MyClass></code> to a Parcel. I did the marshalling with</p>
<pre><code> List<MyClass> myclassList = ...
parcel.writeList(myclassList);
</code></pre>
<p>whenever I try to unmarshall the class with</p>
<pre><code> List<MyClass> myclassList = new ArrayList<MyClass>();
parcel.readList(myclassList, null);
</code></pre>
<p>there is an <code>"BadParcelableException: ClassNotFoundException when unmarshalling org.example.app.MyClass"</code> exception.</p>
<p>What is wrong here? Why is the class not found?</p> | 18,126,250 | 4 | 2 | null | 2013-08-08 12:38:42.173 UTC | 19 | 2018-09-18 08:47:39.617 UTC | 2014-04-26 22:34:46.997 UTC | null | 194,894 | null | 194,894 | null | 1 | 56 | android|marshalling|unmarshalling|parcel | 40,023 | <p>Don't unmarshall a custom class (i.e. one provided by your application and not by the Android framework) with the framework class loader that is used when you give <code>null</code> as the ClassLoader argument. Use the application class loader:</p>
<pre><code>parcel.readList(myclassList, getClass().getClassLoader());
</code></pre>
<p>Whenever a <code>Parcel.read*()</code> method also has a ClassLoader as an argument (e.g. <a href="https://developer.android.com/reference/android/os/Parcel.html#readList(java.util.List,%20java.lang.ClassLoader)" rel="noreferrer"><code>Parcel.readList(List outVal, ClassLoader loader)</code></a>) and you want to read an application class from a <code>Parcel</code>, use the application class loader that can be retrieved with <code>getClass().getClassLoader()</code>.</p>
<p><strong>Background:</strong> Android comes with two class loaders: the system class loader, that is able to load all system classes but the ones provided by your application; and the application class loader, which has set the system class loader as its parent and therefore is able to load all classes. If you give null as the class loader, <a href="https://github.com/android/platform_frameworks_base/blob/android-4.3_r2.1/core/java/android/os/Parcel.java#L2075" rel="noreferrer"><code>Parcel.readParcelableCreator()</code></a> <a href="https://github.com/android/platform_frameworks_base/blob/android-4.3_r2.1/core/java/android/os/Parcel.java#L2091" rel="noreferrer">will use the framework class loader</a>, causing a <a href="https://github.com/android/platform_frameworks_base/blob/android-4.3_r2.1/core/java/android/os/Parcel.java#L2102" rel="noreferrer">ClassNotFoundException</a>.</p>
<p><sup>Thanks to alexanderblom for providing <a href="https://stackoverflow.com/a/14093745/194894">the hint</a> that led me on the right track.</sup></p> |
17,931,874 | setting required on a json-schema array | <p>I am trying to figure out how to set <code>required</code> on my json-schema array of objects. The <code>required</code> property works fine on an object just not an array.</p>
<p>Here is the items part of my json schema:</p>
<pre><code> "items": {
"type": "array",
"properties": {
"item_id": {"type" : "number"},
"quantity": {"type": "number"},
"price": {"type" : "decimal"},
"title": {"type": "string"},
"description": {"type": "string"}
},
"required": ["item_id","quantity","price","title","description"],
"additionalProperties" : false
}
</code></pre>
<p>Here is the json array I am sending over. The json validation should fail since I am not passing a description in these items.</p>
<pre><code> "items": [
{
"item_id": 1,
"quantity": 3,
"price": 30,
"title": "item1 new name"
},
{
"item_id": 1,
"quantity": 16,
"price": 30,
"title": "Test Two"
}
]
</code></pre> | 17,940,765 | 4 | 0 | null | 2013-07-29 18:50:21.553 UTC | 4 | 2022-05-20 18:42:27.013 UTC | 2019-03-26 06:26:14.78 UTC | null | 3,457,761 | null | 834,516 | null | 1 | 23 | json|jsonschema | 51,933 | <p>I got it to work using <a href="http://json-schema-validator.herokuapp.com/">this validator</a> by nesting the part of the schema for the array elements inside a object with the name <code>items</code>. The schema now has two nested <code>items</code> fields, but that is because one is a keyword in JSONSchema and the other because your JSON actually has a field called <code>items</code></p>
<p>JSONSchema: </p>
<pre><code>{
"type":"object",
"properties":{
"items":{
"type":"array",
"items":{
"properties":{
"item_id":{
"type":"number"
},
"quantity":{
"type":"number"
},
"price":{
"type":"number"
},
"title":{
"type":"string"
},
"description":{
"type":"string"
}
},
"required":[
"item_id",
"quantity",
"price",
"title",
"description"
],
"additionalProperties":false
}
}
}
}
</code></pre>
<p>JSON:</p>
<pre><code>{
"items":[
{
"item_id":1,
"quantity":3,
"price":30,
"title":"item1 new name"
},
{
"item_id":1,
"quantity":16,
"price":30,
"title":"Test Two"
}
]
}
</code></pre>
<p>Output with two errors about missing description fields:</p>
<pre><code>[ {
"level" : "error",
"schema" : {
"loadingURI" : "#",
"pointer" : "/properties/items/items"
},
"instance" : {
"pointer" : "/items/0"
},
"domain" : "validation",
"keyword" : "required",
"message" : "missing required property(ies)",
"required" : [ "description", "item_id", "price", "quantity", "title" ],
"missing" : [ "description" ]
}, {
"level" : "error",
"schema" : {
"loadingURI" : "#",
"pointer" : "/properties/items/items"
},
"instance" : {
"pointer" : "/items/1"
},
"domain" : "validation",
"keyword" : "required",
"message" : "missing required property(ies)",
"required" : [ "description", "item_id", "price", "quantity", "title" ],
"missing" : [ "description" ]
} ]
</code></pre>
<p>Try pasting the above into <a href="http://json-schema-validator.herokuapp.com/">here</a> to see the same output generated.</p> |
41,882,616 | Why border is not visible with "position: sticky" when background-color exists? | <p><a href="https://developers.google.com/web/updates/2016/12/position-sticky" rel="noreferrer"><code>position: 'sticky'</code> landed in Chrome 56</a>, but it makes the border invisible in certain circumstances.</p>
<p>Consider the following example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
border-collapse: collapse;
}
thead {
position: sticky;
top: 0;
}
th {
background-color: #fff;
border-right: 5px solid red;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
<thead>
<tr>
<th>First</th>
<th>Second</th>
<th>Third</th>
</tr>
</thead>
</table></code></pre>
</div>
</div>
</p>
<p>In Chrome 56.0.2924.76, only the last <code><th></code>'s border is visible, and this is only when <code><th></code> has a <code>background-color</code> specified.</p>
<p>Is this a bug in Chrome?</p>
<p><a href="http://jsbin.com/fumolopicu/1/edit?html,css,output" rel="noreferrer">Playground</a></p> | 41,883,019 | 12 | 4 | null | 2017-01-26 20:41:34.257 UTC | 8 | 2020-05-21 23:38:03.23 UTC | 2017-01-26 23:40:55.537 UTC | null | 247,243 | null | 247,243 | null | 1 | 52 | css|google-chrome|sticky | 23,154 | <p>seems like to force a reflow will partially help :</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
border-collapse: collapse;
}
thead {
position: sticky;
top: 0;
}
th {
border-right: 5px solid red;
transform:scale(0.999);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <table>
<thead>
<tr>
<th>First</th>
<th>Second</th>
<th>Third</th>
</tr>
</thead>
</table></code></pre>
</div>
</div>
</p>
<p><code>background-clip</code> seems also efficient and harmless:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
margin-top: 1em;
border-collapse: collapse;
margin-bottom: 200vh
}
thead {
position: sticky;
top: 0;
}
th {
border-right: 5px solid red;
background:white;
background-clip: padding-box;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <table>
<thead>
<tr>
<th>First</th>
<th>Second</th>
<th>Third</th>
</tr>
</thead>
</table></code></pre>
</div>
</div>
</p> |
6,541,663 | "Object reference not set to an instance of an object" error connecting to SOAP server from PHP | <p>I'm making my first attempt to connect to a SOAP server from PHP, and I'm not understanding how to log in and get the data I need. The service I'm trying to connect to is the Hawley USA service <a href="http://hawleyusa.com/thcServices/StoreServices.asmx">http://hawleyusa.com/thcServices/StoreServices.asmx</a>). I've been looking at a few posts on how to connect, and I get the basics. I've verified that I have SOAP enabled in my PHP, and I'm just trying to get an inventory list. Here's the code I'm using:</p>
<pre><code><?php
ini_set("soap.wsdl_cache_enabled", "0"); // disabling WSDL cache
$wsdl_path = "http://hawleyusa.com/thcServices/StoreServices.asmx?WSDL";
$login_id = 'mylogin_id';
$password = 'mypassword';
$client = new SoapClient($wsdl_path);
try {
echo "<pre>\n";
print($client->InventoryList(array("LoginID" => $login_id, "Password" => $password)));
echo "\n";
}
catch (SoapFault $exception) {
echo $exception;
}
</code></pre>
<p>However, when I run this code, I get this error:</p>
<pre><code>SoapFault exception: [soap:Server] Server was unable to process request. ---> Object reference not set to an instance of an object. in /Users/steve/Sites/mysite/hawley_client.php:12
</code></pre>
<p>When debugging, I can see the $client instance initiated, so I'm not sure why I'm getting this error.</p>
<p>Second question: Am I passing the user ID and password correctly?</p>
<p>Thanks.</p>
<p><strong>Update</strong>: I threw in $client->__getLastRequest, and this is what I got:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://hawleyusa.com/thcServices/">
<SOAP-ENV:Body>
<ns1:InventoryList/>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code></pre>
<p>So I can see that I'm missing my login ID and password. How do I add them to my InventoryList call?</p> | 6,542,111 | 3 | 2 | null | 2011-06-30 22:07:47.39 UTC | 1 | 2021-10-21 07:39:39.63 UTC | 2011-06-30 22:40:42.767 UTC | null | 391,054 | null | 391,054 | null | 1 | 15 | php|soap|soap-client | 52,410 | <p>You're close. Looking at the WSDL the InventoryList method takes an object called "request". Modify your call line slightly:</p>
<pre><code>$client->InventoryList(array("request" => array("LoginId" => $login_id, "Password" => $password));
</code></pre> |
6,413,956 | C represent int in base 2 | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/2611764/can-i-use-a-binary-literal-in-c-or-c">Can I use a binary literal in C or C++?</a> </p>
</blockquote>
<p>I am learning C and i recently found out that we can represent integers in different ways, like that:</p>
<p>(Assuming <code>i</code> has "human-readable" value of <strong>512</strong>.) Here are the representations:</p>
<h2>Decimal:</h2>
<pre class="lang-c prettyprint-override"><code>int i = 512;
</code></pre>
<h2>Octal:</h2>
<pre class="lang-c prettyprint-override"><code>int i = 01000;
</code></pre>
<h2>Hexadecimal:</h2>
<pre class="lang-c prettyprint-override"><code>int i = 0x200;
</code></pre>
<h2>In base 2 (or binary representation) <strong>512</strong> is <strong>1000000000</strong>. How to write this in C?</h2>
<p>Something like <code>int i = 1000000000b</code>? This is funny but unfortunately no C compiler accepts that value.</p> | 6,413,998 | 4 | 2 | null | 2011-06-20 15:50:11.643 UTC | 8 | 2015-01-05 18:52:42.56 UTC | 2017-05-23 11:47:09.25 UTC | null | -1 | user562854 | null | null | 1 | 14 | c|binary|integer|representation | 70,926 | <p>The standard describes no way to create "binary literals". However, the latest versions of GCC and Clang support this feature using a syntax similar to the hex syntax, except it's <code>b</code> instead of <code>x</code>:</p>
<pre><code>int foo = 0b00100101;
</code></pre>
<p>As stated, using such binary literals locks you out of Visual Studio's C and C++ compilers, so you may want to take care where and how you use them.</p>
<p>C++14 (I know, I know, this isn't C) standardizes support for binary literals.</p> |
18,922,053 | AVAudioRecorder & AVAudioPlayer with iOS 7 not working properly | <p>i'm having some issue with AVFoundation framework.
I wrote a demo app to record audio, play it, and calculate decibels, with iOS 6.
It both worked with iOS simulator built-in xcode 4.6.3 and my iPhone with iOS 6.1.3</p>
<p>Now i've update xcode to version 5 and tested the appa again. With the built-in simulator it works (both with iOS 6.1 and iOS 7 simulators). But when i deploy the app to my iPhone, with iOS 7.0, it doesn't work anymore.</p>
<p>I'm using <code>AVAudioRecorder</code> and <code>AVAudioPlayer</code>.</p>
<p>I don't know what could be the problem. Any suggestions? thank you!</p> | 18,939,937 | 4 | 2 | null | 2013-09-20 16:57:54.113 UTC | 8 | 2015-07-30 13:00:12.04 UTC | 2015-07-30 13:00:12.04 UTC | null | 88,461 | null | 2,735,326 | null | 1 | 20 | avfoundation|avaudioplayer|ios7|avaudiorecorder|xcode5 | 10,064 | <p>I was having the same issue... It appears as if Apple is now requiring the use of <code>AVAudioSession</code> prior to using the <code>AVAudioRecorder</code>. I couldn't find any documentation on this change in requirement, however the recording portion of my app is now working.</p>
<p>All I did was create an <code>audioSession</code>, set the category, and set it to be active. I did this prior to calling <code>prepareToRecord</code> and I tried it after the call to <code>prepareToRecord...</code> both ways worked. </p>
<p>I hope this fixes your problem!</p>
<pre><code>AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[audioSession setActive:YES error:nil];
</code></pre> |
27,880,031 | How do I use UISearchController in iOS 8 where the UISearchBar is in my navigation bar and has scope buttons? | <p>I'm trying to use the new <code>UISearchController</code> from iOS 8, and embed its <code>UISearchBar</code> in my <code>UINavigationBar</code>. That's easily done as follows:</p>
<pre><code>searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.delegate = self
searchController.searchBar.delegate = self
searchController.dimsBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = false
navigationItem.titleView = searchController.searchBar
</code></pre>
<p>But when I add the scope buttons:</p>
<pre><code>searchController.searchBar.showsScopeBar = true
searchController.searchBar.scopeButtonTitles = ["Posts, Users, Subreddits"]
</code></pre>
<p>It adds the buttons behind the <code>UISearchBar</code> and obviously looks very odd.</p>
<p>How should I be doing this?</p> | 27,994,838 | 1 | 4 | null | 2015-01-10 18:59:31.91 UTC | 8 | 2015-03-20 14:15:05.9 UTC | null | null | null | null | 998,117 | null | 1 | 29 | ios|uinavigationcontroller|ios8|uisearchbar|uisearchcontroller | 18,969 | <p>You're bumping into a "design issue" where the <code>scopeBar</code> is expected to be hidden when the <code>searchController</code> is not active.</p>
<p>The scope bar buttons appear behind (underneath) the search bar since that's their location when the search bar becomes active and animates itself up into the navigation bar.</p>
<p><em>When the search is not active, a visible scope bar would take up space on the screen, distract from the content, and confuse the user (since the scope buttons have no results to filter).</em></p>
<p>Since your <code>searchBar</code> is already located in the titleView, the (navigation and search) bar animation that reveals the scope bar doesn't occur.</p>
<ul>
<li>The <strong>easiest</strong> option is to locate the search bar below the
navigation bar, and let the <code>searchBar</code> animate up into the title
area when activated. The navigation bar will animate its height,
making room to include the scope bar that was hidden. This will all
be handled by the search controller.</li>
<li><p>The second option, almost as easy, is to use a <strong>Search</strong> bar button
icon, which will animate the <code>searchBar</code> and <code>scopeBar</code> down into
view over the navigation bar.</p>
<pre><code>- (IBAction)searchButtonClicked:(UIBarButtonItem *)__unused sender {
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.hidesNavigationBarDuringPresentation = NO;
self.searchController.dimsBackgroundDuringPresentation = NO;
self.definesPresentationContext = YES;
self.searchController.searchBar.scopeButtonTitles = @[@"Posts", @"Users", @"Subreddits"];
[self presentViewController:self.searchController animated:YES completion:nil];
}</code></pre></li>
<li><p>If you want the <code>searchBar</code> to remain in the titleView, an animation
to do what you want is not built in. You'll have to roll your own
code to handle the navigationBar height change and display your own
scope bar (or hook into the internals, and animate the built-in
<code>scopeBar</code> down and into view).</p>
<p>If you're fortunate, someone else has written <code>willPresentSearchController:</code> code to handle the transition you want.</p></li>
<li><p>If you want to always see a <code>searchBar</code> and <code>scopeBar</code>, you'll probably have to ditch using the built-in <code>scopeBar</code>, and replace it with a <code>UISegmentedControl</code> which the user will always see, even when the search controller is not active.</p></li>
</ul>
<p><strong>Update:</strong></p>
<p><a href="https://stackoverflow.com/a/27909956/4151918">This answer</a> suggested subclassing <code>UISearchController</code> to change its searchBar's height.</p> |
5,496,549 | How to inject CSS in WebBrowser control? | <p>As per my knowledge,there is a way to inject javascript into the DOM. Below is the sample code that injects javascript with the <code>webbrowser</code> control:</p>
<pre><code>HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "function sayHello() { alert('hello') }";
head.AppendChild(scriptEl);
webBrowser1.Document.InvokeScript("sayHello");
</code></pre>
<p>Is there an easier way to inject css into the DOM?</p> | 5,496,632 | 2 | 0 | null | 2011-03-31 07:30:22.953 UTC | 9 | 2018-12-08 00:29:20.39 UTC | 2013-02-22 21:24:13.31 UTC | null | 918,414 | null | 500,529 | null | 1 | 21 | c#|.net|winforms|webbrowser-control | 33,249 | <p>I didn't try this myself but since CSS style rules can be included in a document using the <code><style></code> tag as in:</p>
<pre><code><html>
<head>
<style type="text/css">
h1 {color:red}
p {color:blue}
</style>
</head>
</code></pre>
<p>you could try giving:</p>
<pre><code>HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement styleEl = webBrowser1.Document.CreateElement("style");
IHTMLStyleElement element = (IHTMLStyleElement)styleEl.DomElement;
IHTMLStyleSheetElement styleSheet = element.styleSheet;
styleSheet.cssText = @"h1 { color: red }";
head.AppendChild(styleEl);
</code></pre>
<p>a go. You can find more info on the IHTMLStyleElement <a href="http://msdn.microsoft.com/en-us/library/aa768673(v=vs.85).aspx" rel="noreferrer">here</a>.</p>
<h3>Edit</h3>
<p>It seems the answer is much much simpler than I originally thought:</p>
<pre><code> using mshtml;
IHTMLDocument2 doc = (webBrowser1.Document.DomDocument) as IHTMLDocument2;
// The first parameter is the url, the second is the index of the added style sheet.
IHTMLStyleSheet ss = doc.createStyleSheet("", 0);
// Now that you have the style sheet you have a few options:
// 1. You can just set the content as text.
ss.cssText = @"h1 { color: blue; }";
// 2. You can add/remove style rules.
int index = ss.addRule("h1", "color: red;");
ss.removeRule(index);
// You can even walk over the rules using "ss.rules" and modify them.
</code></pre>
<p>I wrote a small test project to verify that this works. I arrived at this final result by doing a search on MSDN for IHTMLStyleSheet, upon which I happened across <a href="http://social.msdn.microsoft.com/Forums/en-US/ieextensiondevelopment/thread/49dc2c07-ea26-4734-aa2c-99a109ccb46a" rel="noreferrer">this page</a>, <a href="http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/f18898b2-9313-4327-a4d9-6104831bfd69/" rel="noreferrer">this page</a> and <a href="http://social.msdn.microsoft.com/forums/en-US/iewebdevelopment/thread/33fd33f7-e857-4f6f-978e-fd486eba7174/" rel="noreferrer">this one</a>.</p> |
16,187,110 | a section registered as allowDefinition='MachineToApplication' beyond application level | <p>After adding the assebly of System.Data.Entity to my web config I got this error:
It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS. </p>
<p>I have deleted the obj and bin folders, I removed the line authentication="windows", tried to reopen as some has said it worked, I have checked that there is only 1 web.config within the main folder (Entity Framework - Folder for forms, model, DAL and BLL)... </p>
<p>What other reasons is there that this will happen? I searched everywhere and it's basically the above reasons I found....</p>
<p>This is my web.config if it makes a difference:</p>
<pre><code> <configuration>
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
<add name="CStringVKB" connectionString="Data Source=.;Initial Catalog=VKB;Persist Security Info=True;User ID=websiteservice;Password=websiteservice" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" optimizeCompilations="true" targetFramework="4.0" >
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
<!--<authentication mode="Windows">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>-->
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
</code></pre>
<p>What can I do to solve this?</p> | 16,197,288 | 3 | 0 | null | 2013-04-24 08:30:06.103 UTC | null | 2018-07-18 13:38:19.707 UTC | 2013-04-24 09:06:05.513 UTC | null | 639,381 | null | 2,042,152 | null | 1 | 8 | asp.net|entity-framework|directory|virtual | 54,196 | <p>Basically, the error means that there is a web.config file in one of your subfolders that has a configuration element that it should not have. Is this you root/only web config file? If not, could you please post those as well?</p>
<p>Also, it sounds stupid, but I would double check that you're opening the website itself in your IDE (and not mistakenly opening a parent folder) I have seen people spend a couple hours trying to debug this same error, when all along they weren't in the right directory.</p>
<p>Here is a good explanation on how the web.config hierarchy is set up for ASP that will help you visualize how this works: <a href="http://scottonwriting.net/sowblog/archive/2010/02/17/163375.aspx">http://scottonwriting.net/sowblog/archive/2010/02/17/163375.aspx</a></p> |
31,868 | Upload a file to SharePoint through the built-in web services | <p>What is the best way to upload a file to a Document Library on a SharePoint server through the built-in web services that version WSS 3.0 exposes?</p>
<p><strong>Following the two initial answers...</strong></p>
<ul>
<li><p>We definitely need to use the Web Service layer as we will be making these calls from remote client applications.</p></li>
<li><p>The WebDAV method would work for us, but we would prefer to be consistent with the web service integration method.</p></li>
</ul>
<p><Blockquote>
There is additionally a web service to upload files, painful but works all the time.
</Blockquote></p>
<p>Are you referring to the “Copy” service?
We have been successful with this service’s <code>CopyIntoItems</code> method. Would this be the recommended way to upload a file to Document Libraries using only the WSS web service API?</p>
<p>I have posted our code as a suggested answer.</p> | 34,274 | 7 | 0 | null | 2008-08-28 08:53:00.507 UTC | 15 | 2014-04-28 19:00:41.043 UTC | 2008-09-11 10:10:22.343 UTC | Andy McCluggage | 3,362 | Andy McCluggage | 3,362 | null | 1 | 31 | sharepoint|wss | 65,506 | <p>Example of using the WSS "Copy" Web service to upload a document to a library...</p>
<pre><code>public static void UploadFile2007(string destinationUrl, byte[] fileData)
{
// List of desination Urls, Just one in this example.
string[] destinationUrls = { Uri.EscapeUriString(destinationUrl) };
// Empty Field Information. This can be populated but not for this example.
SharePoint2007CopyService.FieldInformation information = new
SharePoint2007CopyService.FieldInformation();
SharePoint2007CopyService.FieldInformation[] info = { information };
// To receive the result Xml.
SharePoint2007CopyService.CopyResult[] result;
// Create the Copy web service instance configured from the web.config file.
SharePoint2007CopyService.CopySoapClient
CopyService2007 = new CopySoapClient("CopySoap");
CopyService2007.ClientCredentials.Windows.ClientCredential =
CredentialCache.DefaultNetworkCredentials;
CopyService2007.ClientCredentials.Windows.AllowedImpersonationLevel =
System.Security.Principal.TokenImpersonationLevel.Delegation;
CopyService2007.CopyIntoItems(destinationUrl, destinationUrls, info, fileData, out result);
if (result[0].ErrorCode != SharePoint2007CopyService.CopyErrorCode.Success)
{
// ...
}
}
</code></pre> |
542,856 | How do I set HTTP_REFERER when testing in Rails? | <p>I'm trying to test a controller and I got this error. I understand the error, but don't know how to fix it.</p>
<pre><code>test: on CREATE to :user with completely invalid email should respond with
redirect
(UsersControllerTest):ActionController::RedirectBackError:
No HTTP_REFERER was set in the request to this action,
so redirect_to :back could not be called successfully.
If this is a test, make sure to specify request.env["HTTP_REFERER"].
</code></pre>
<p>Specify it where? I tried this:</p>
<pre><code>setup { post :create, { :user => { :email => 'invalid@abc' } },
{ 'referer' => '/sessions/new' } }
</code></pre>
<p>But got the same error.</p>
<p>Specify it with what, exactly? I guess the URI of the view I want it to go back to:</p>
<pre><code>'/sessions/new'
</code></pre>
<p>Is that what they mean?</p>
<hr>
<p>OK, so it turns out they mean do this:</p>
<pre><code>setup do
@request.env['HTTP_REFERER'] = 'http://localhost:3000/sessions/new'
post :create, { :user => { :email => 'invalid@abc' } }, {}
end
</code></pre>
<p>Can someone tell me where that's documented? I'd like to read up on the context of that information.</p>
<p>What if the domain is not "localhost:3000"? What if it's "localhost:3001" or something? Any way to anticipate that?</p>
<p>Why doesn't this work:</p>
<pre><code>setup { post :create, { :user => { :email => 'invalid@abc' } },
{ 'referer' => '/sessions/new' } }
</code></pre>
<p>The Rails docs <a href="http://apidock.com/rails/ActionController/Integration/Session/post" rel="noreferrer">specifically say</a> that's how you set the headers.</p> | 542,905 | 7 | 0 | null | 2009-02-12 19:25:05.543 UTC | 4 | 2020-04-06 07:20:06.097 UTC | 2009-02-12 19:55:22.083 UTC | Ethan | 42,595 | Ethan | 42,595 | null | 1 | 88 | ruby-on-rails|ruby|testing | 35,088 | <p>Their recommendation translates to the following:</p>
<pre><code>setup do
@request.env['HTTP_REFERER'] = 'http://test.com/sessions/new'
post :create, { :user => { :email => 'invalid@abc' } }
end
</code></pre> |
258,742 | Change texture opacity in OpenGL | <p>This is hopefully a simple question: I have an OpenGL texture and would like to be able to change its opacity, how do I do that? The texture already has an alpha channel and blending works fine, but I want to be able to decrease the opacity of the whole texture, to fade it into the background. I have fiddled with <code>glBlendFunc</code>, but with no luck – it seems that I would need something like <code>GL_SRC_ALPHA_MINUS_CONSTANT</code>, which is not available. I am working on iPhone, with OpenGL ES.</p> | 2,558,853 | 8 | 0 | null | 2008-11-03 14:21:55.88 UTC | 9 | 2020-05-21 20:23:16.24 UTC | 2010-06-18 23:19:05.403 UTC | zoul | 44,729 | zoul | 17,279 | null | 1 | 14 | iphone|opengl-es | 15,554 | <p>Thank You all for the ideas. I’ve played both with glColor4f and glTexEnv and at last forced myself to read the glTexEnv manpage carefully. The manpage says that in the GL_MODULATE texturing mode, the resulting color is computed by multiplying the incoming fragment by the texturing color (C=Cf×Ct), same goes for the alpha. I tried glColor4f(1, 1, 1, opacity) and that did not work, but passing the desired opacity into all four arguments of the call did the trick. (Still not sure why though.)</p> |
481,351 | Programmatically Clip/Cut image using Javascript | <p>Are there any documents/tutorials on how to clip or cut a large image so that the user only sees a small portion of this image? Let's say the source image is 10 frames of animation, stacked end-on-end so that it's really wide. What could I do with Javascript to only display 1 arbitrary frame of animation at a time?</p>
<p>I've looked into this "CSS Spriting" technique but I don't think I can use that here. The source image is produced dynamically from the server; I won't know the total length, or the size of each frame, until it comes back from the server. I'm hoping that I can do something like:</p>
<pre><code>var image = getElementByID('some-id');
image.src = pathToReallyLongImage;
// Any way to do this?!
image.width = cellWidth;
image.offset = cellWidth * imageNumber;
</code></pre> | 481,396 | 8 | 0 | null | 2009-01-26 21:08:24.617 UTC | 20 | 2016-09-27 09:03:44.153 UTC | null | null | null | Outlaw Programmer | 1,471 | null | 1 | 16 | javascript|image | 36,866 | <p>This can be done by enclosing your image in a "viewport" div. Set a width and height on the div (according to your needs), then set <code>position: relative</code> and <code>overflow: hidden</code> on it. Absolutely position your image inside of it and change the position to change which portions are displayed.</p>
<p>To display a 30x40 section of an image starting at (10,20):</p>
<pre><code><style type="text/css">
div.viewport {
overflow: hidden;
position: relative;
}
img.clipped {
display: block;
position: absolute;
}
</style>
<script type="text/javascript">
function setViewport(img, x, y, width, height) {
img.style.left = "-" + x + "px";
img.style.top = "-" + y + "px";
if (width !== undefined) {
img.parentNode.style.width = width + "px";
img.parentNode.style.height = height + "px";
}
}
setViewport(document.getElementsByTagName("img")[0], 10, 20, 30, 40);
</script>
<div class="viewport">
<img class="clipped" src="/images/clipped.png" alt="Clipped image"/>
</div>
</code></pre>
<p>The common CSS properties are associated with classes so that you can have multiple viewports / clipped images on your page. The <code>setViewport(…)</code> function can be called at any time to change what part of the image is displayed.</p> |
804,754 | How do I return only the matching regular expression when I select-string(grep) in PowerShell? | <p>I am trying to find a pattern in files. When I get a match using <code>Select-String</code> I do not want the entire line, I just want the part that matched. </p>
<p>Is there a parameter I can use to do this?</p>
<p>For example:</p>
<p>If I did </p>
<pre><code>select-string .-.-.
</code></pre>
<p>and the file contained a line with:</p>
<pre><code>abc 1-2-3 abc
</code></pre>
<p>I'd like to get a result of just <strong>1-2-3</strong> instead of the entire line getting returned.</p>
<p>I would like to know the Powershell equivalent of a <code>grep -o</code></p> | 804,903 | 8 | 1 | null | 2009-04-29 23:26:33.273 UTC | 13 | 2021-10-27 23:05:29.59 UTC | 2013-09-08 19:20:00.893 UTC | null | 63,550 | null | 81,008 | null | 1 | 60 | regex|powershell|grep | 92,578 | <p>David's on the right path. [regex] is a type accelerator for System.Text.RegularExpressions.Regex</p>
<pre><code>[regex]$regex = '.-.-.'
$regex.Matches('abc 1-2-3 abc') | foreach-object {$_.Value}
$regex.Matches('abc 1-2-3 abc 4-5-6') | foreach-object {$_.Value}
</code></pre>
<p>You could wrap that in a function if that is too verbose.</p> |
423,172 | Can I have multiple background images using CSS? | <p>Is it possible to have two background images? For instance, I'd like to have one image repeat across the top (repeat-x), and another repeat across the entire page (repeat), where the one across the entire page is behind the one which repeats across the top.</p>
<p>I've found that I can achieve the desired effect for two background images by setting the background of html and body:</p>
<pre class="lang-css prettyprint-override"><code>html {
background: url(images/bg.png);
}
body {
background: url(images/bgtop.png) repeat-x;
}
</code></pre>
<p>Is this "good" CSS? Is there a better method? And what if I wanted three or more background images?</p> | 423,190 | 8 | 0 | null | 2009-01-08 03:37:17.02 UTC | 76 | 2016-04-06 18:05:05.527 UTC | 2013-09-26 00:12:16.34 UTC | Shog9 | 331,508 | Rudd | 219 | null | 1 | 319 | css|background-image | 406,981 | <p>CSS3 allows this sort of thing and it looks like this:</p>
<pre class="lang-css prettyprint-override"><code>body {
background-image: url(images/bgtop.png), url(images/bg.png);
background-repeat: repeat-x, repeat;
}
</code></pre>
<p><a href="http://caniuse.com/#search=multiple%20backgrounds" rel="noreferrer">The current versions of all the major browsers now support it</a>, however if you need to support IE8 or below, then the best way you can work around it is to have extra divs:</p>
<pre><code><body>
<div id="bgTopDiv">
content here
</div>
</body>
</code></pre>
<pre class="lang-css prettyprint-override"><code>body{
background-image: url(images/bg.png);
}
#bgTopDiv{
background-image: url(images/bgTop.png);
background-repeat: repeat-x;
}
</code></pre> |
1,057,416 | how to make div click-able? | <pre><code><div><span>shanghai</span><span>male</span></div>
</code></pre>
<p>For div like above,when mouse on,it should become cursor:pointer,and when clicked,fire a </p>
<p>javascript function,how to do that job?</p>
<p><strong>EDIT</strong>: and how to change the background color of div when mouse is on?</p>
<p><strong>EDIT AGAIN</strong>:how to make the first span's width=120px?Seems not working in firefox</p> | 1,057,452 | 9 | 1 | null | 2009-06-29 09:33:56.407 UTC | 9 | 2018-05-10 15:18:27.497 UTC | 2011-07-16 20:34:55.3 UTC | null | 683,042 | null | 104,015 | null | 1 | 40 | javascript|css|html|click | 256,624 | <p>Give it an ID like "something", then:</p>
<pre><code>var something = document.getElementById('something');
something.style.cursor = 'pointer';
something.onclick = function() {
// do something...
};
</code></pre>
<p>Changing the background color (as per your updated question):</p>
<pre><code>something.onmouseover = function() {
this.style.backgroundColor = 'red';
};
something.onmouseout = function() {
this.style.backgroundColor = '';
};
</code></pre> |
672,466 | JUnit: how to avoid "no runnable methods" in test utils classes | <p>I have switched to JUnit4.4 from JUnit3.8. I run my tests using ant, all my tests run successfully but test utility classes fail with "No runnable methods" error. The pattern I am using is to include all classes with name *Test* under test folder.</p>
<p>I understand that the runner can't find any method annotated with @Test attribute. But they don't contain such annotation because these classes are not tests.
Surprisingly when running these tests in eclipse, it doesn't complain about these classes.</p>
<p>In JUnit3.8 it wasn't a problem at all since these utility classes didn't extend TestCase so the runner didn't try to execute them. </p>
<p>I know I can exclude these specific classes in the junit target in ant script. But I don't want to change the build file upon every new utility class I add. I can also rename the classes (but giving good names to classes was always my weakest talent :-) )</p>
<p>Is there any elegant solution for this problem?</p> | 672,497 | 10 | 5 | null | 2009-03-23 07:26:22.283 UTC | 8 | 2019-06-19 13:12:36.573 UTC | 2009-03-23 08:09:49.977 UTC | LiorH | 52,954 | LiorH | 52,954 | null | 1 | 121 | java|ant|junit|testing | 122,371 | <p>Assuming you're in control of the pattern used to find test classes, I'd suggest changing it to match <code>*Test</code> rather than <code>*Test*</code>. That way <code>TestHelper</code> won't get matched, but <code>FooTest</code> will.</p> |
193,780 | How can I find all the tables in MySQL with specific column names in them? | <p>I have 2-3 different column names that I want to look up in the entire database and list out all tables which have those columns. Is there any easy script?</p> | 193,860 | 11 | 1 | null | 2008-10-11 07:02:05.463 UTC | 307 | 2021-08-23 07:18:23.027 UTC | 2021-08-06 16:05:56.233 UTC | Ken | 63,550 | Joy | 8,091 | null | 1 | 982 | mysql|information-schema | 635,644 | <p>To get all tables with columns <code>columnA</code> or <code>ColumnB</code> in the database <code>YourDatabase</code>:</p>
<pre><code>SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('columnA','ColumnB')
AND TABLE_SCHEMA='YourDatabase';
</code></pre> |
899,565 | Is there a predefined enumeration for Month in the .NET library? | <p>I'm looking to see if there is an official enumeration for months in the .net framework.</p>
<p>It seems possible to me that there is one, because of how common the use of month is, and because there are other such enumerations in the .net framework.</p>
<p>For instance, there is an enumeration for the days in the week, System.DayOfWeek, which includes Monday, Tuesday, etc..</p>
<p>I'm wondering if there is one for the months in the year, i.e. January, February, etc?</p>
<p>Does anyone know?</p> | 899,589 | 12 | 0 | null | 2009-05-22 19:21:28.077 UTC | 16 | 2021-11-02 14:17:25.86 UTC | 2012-05-01 00:11:16.127 UTC | null | 13,793 | null | 25,847 | null | 1 | 114 | c#|.net|datetime|enumeration | 66,928 | <p>There isn't, but if you want the name of a month you can use:</p>
<pre><code>CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName (DateTime.Now.Month);
</code></pre>
<p>which will return a string representation (of the current month, in this case). Note that <code>GetMonth</code> takes arguments from 1 to 13 - January is 1, 13 is a blank string.</p> |
315,845 | Should I avoid using "text-align: justify;"? | <p>Is there any reason to avoid using <code>text-align: justify;</code>? </p>
<p>Does it reduce readability or cause problems?</p> | 657,528 | 13 | 1 | null | 2008-11-24 23:16:17.833 UTC | 26 | 2018-10-08 15:08:04.737 UTC | 2013-03-10 22:30:00.23 UTC | Toytown Mafia | 918,414 | Goondocks | 12,689 | null | 1 | 78 | css|usability|typography | 78,322 | <p>Firstly, this is purely a design-related problem and solution. The design of your grid specifies if justifying text is needed. I think justify align alone has no major effect on usability. Bad typography that makes text illegible is what decreases usability. That said, make sure you have solid contrasts and a good balance of spacing in your type. Font-size matters too.</p>
<p><a href="http://rebecamendez.com/" rel="noreferrer">This site</a> is a successful attempt at justifying text online. Since you can't control the spaces between letters and words nearly as much with CSS as you can with InDesign, it's a lot harder to justify text and not have 'rivers' of whitespace run down your rows, which happens when the spaces between words exceeds the spaces between lines. Things that make justifying text difficult: long words, row widths that don't hold enough words, and too much contrast between the text and the background colors; they make the rivers appear wider and more apparent.</p>
<p>The typographic ideal is to have an even text-block, where if you squint the text block becomes a uniform solid shade. So if you keep text at about 10px and 60% gray on white background, and have rows that fit about 20 words, justify align shouldn't look ugly. But keep in mind this does nothing to improve usability. Small, relatively light text annoys a lot of people, especially the older readers. </p>
<p>I should note that with <code>&shy;</code> (soft hyphenation) correctly separating long troublesome words like super­awesome you can mimic proper typesetting (e.g. InDesign). There's a lot of stuff out there to help you do this. I would recommend the logic for hiding, manipulating, and displaying the text to be done on the client side, perhaps with <a href="http://code.google.com/p/hyphenator/" rel="noreferrer">this</a>.</p>
<p><strong>Edit</strong>: As others mention below, <a href="http://caniuse.com/#feat=css-hyphens" rel="noreferrer">css hyphens</a> are possible now, except not feasible (not in Chrome). Plus, <a href="http://generatedcontent.org/post/44751461516" rel="noreferrer">css4 offers even more control</a>.</p> |
732,674 | When debugging ASP.NET MVC app, breakpoints are not hit | <p>When trying to debug a ASP.NET MVC app, the breakpoints in my controllers arent getting hit. When entering debug mode they just show an empty red circle with a warning triangle instead of the normal full circle. This is strange because debugging was working fine until now, and no configuration changes have been made in my environment for a while.</p>
<p>I have seen <a href="https://stackoverflow.com/questions/60093/why-would-breakpoints-in-vs2008-stop-working">this question</a> and had a look at my modules view and the correct ones aren't being loaded, however I'm not sure how to remedy this. Also all the relevant pdb files are in the bin folder of the site.</p>
<p>Any suggestions on how to fix this?</p>
<p>Cheers!</p>
<p><strong>EDIT:</strong> The app is running as a local site on IIS7 and I'm debugging with VS 2008</p> | 732,833 | 20 | 7 | null | 2009-04-09 03:29:45.387 UTC | 8 | 2021-12-16 12:55:53.29 UTC | 2017-05-23 12:25:57.647 UTC | null | -1 | null | 32,943 | null | 1 | 29 | visual-studio|debugging|breakpoints | 48,191 | <p>Ok so after 4 hours wasted, I find that setting my web project as the startup project solves the issue! This surely must be a bug...</p>
<p>I hope I save someone out there half a day :)</p> |
271,526 | Avoiding NullPointerException in Java | <p>I use <code>x != null</code> to avoid <a href="https://docs.oracle.com/javase/9/docs/api/java/lang/NullPointerException.html" rel="noreferrer"><code>NullPointerException</code></a>. Is there an alternative?</p>
<pre class="lang-java prettyprint-override"><code>if (x != null) {
// ...
}
</code></pre> | 271,874 | 66 | 11 | 2011-10-21 09:02:37.01 UTC | 2008-11-07 08:31:40.203 UTC | 1,564 | 2022-07-10 23:18:22.307 UTC | 2022-07-10 23:18:22.307 UTC | cletus | 365,102 | Goran Martinic | 34,856 | null | 1 | 4,315 | java|nullpointerexception|null | 1,395,399 | <p>This to me sounds like a reasonably common problem that junior to intermediate developers tend to face at some point: they either don't know or don't trust the contracts they are participating in and defensively overcheck for nulls. Additionally, when writing their own code, they tend to rely on returning nulls to indicate something thus requiring the caller to check for nulls.</p>
<p>To put this another way, there are two instances where null checking comes up:</p>
<ol>
<li><p>Where null is a valid response in terms of the contract; and</p>
</li>
<li><p>Where it isn't a valid response.</p>
</li>
</ol>
<p>(2) is easy. As of Java 1.7 you can use <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Objects.html#requireNonNull(T)" rel="noreferrer"><code>Objects.requireNonNull(foo)</code></a>. (If you are stuck with a previous version then <a href="https://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html" rel="noreferrer"><code>assert</code>ions</a> may be a good alternative.)</p>
<p>"Proper" usage of this method would be like below. The method returns the object passed into it and throws a <code>NullPointerException</code> if the object is null. This means that the returned value is always non-null. The method is primarily intended for validating parameters.</p>
<pre><code>public Foo(Bar bar) {
this.bar = Objects.requireNonNull(bar);
}
</code></pre>
<p>It can also be used like an <code>assert</code>ion though since it throws an exception if the object is null. In both uses, a message can be added which will be shown in the exception. Below is using it like an assertion and providing a message.</p>
<pre><code>Objects.requireNonNull(someobject, "if someobject is null then something is wrong");
someobject.doCalc();
</code></pre>
<p>Generally throwing a specific exception like <code>NullPointerException</code> when a value is null but shouldn't be is favorable to throwing a more general exception like <code>AssertionError</code>. This is the approach the Java library takes; favoring <code>NullPointerException</code> over <code>IllegalArgumentException</code> when an argument is not allowed to be null.</p>
<p>(1) is a little harder. If you have no control over the code you're calling then you're stuck. If null is a valid response, you have to check for it.</p>
<p>If it's code that you do control, however (and this is often the case), then it's a different story. Avoid using nulls as a response. With methods that return collections, it's easy: return empty collections (or arrays) instead of nulls pretty much all the time.</p>
<p>With non-collections it might be harder. Consider this as an example: if you have these interfaces:</p>
<pre><code>public interface Action {
void doSomething();
}
public interface Parser {
Action findAction(String userInput);
}
</code></pre>
<p>where Parser takes raw user input and finds something to do, perhaps if you're implementing a command line interface for something. Now you might make the contract that it returns null if there's no appropriate action. That leads the null checking you're talking about.</p>
<p>An alternative solution is to never return null and instead use the <a href="https://en.wikipedia.org/wiki/Null_Object_pattern" rel="noreferrer">Null Object pattern</a>:</p>
<pre><code>public class MyParser implements Parser {
private static Action DO_NOTHING = new Action() {
public void doSomething() { /* do nothing */ }
};
public Action findAction(String userInput) {
// ...
if ( /* we can't find any actions */ ) {
return DO_NOTHING;
}
}
}
</code></pre>
<p>Compare:</p>
<pre><code>Parser parser = ParserFactory.getParser();
if (parser == null) {
// now what?
// this would be an example of where null isn't (or shouldn't be) a valid response
}
Action action = parser.findAction(someInput);
if (action == null) {
// do nothing
} else {
action.doSomething();
}
</code></pre>
<p>to</p>
<pre><code>ParserFactory.getParser().findAction(someInput).doSomething();
</code></pre>
<p>which is a much better design because it leads to more concise code.</p>
<p>That said, perhaps it is entirely appropriate for the findAction() method to throw an Exception with a meaningful error message -- especially in this case where you are relying on user input. It would be much better for the findAction method to throw an Exception than for the calling method to blow up with a simple NullPointerException with no explanation.</p>
<pre><code>try {
ParserFactory.getParser().findAction(someInput).doSomething();
} catch(ActionNotFoundException anfe) {
userConsole.err(anfe.getMessage());
}
</code></pre>
<p>Or if you think the try/catch mechanism is too ugly, rather than Do Nothing your default action should provide feedback to the user.</p>
<pre><code>public Action findAction(final String userInput) {
/* Code to return requested Action if found */
return new Action() {
public void doSomething() {
userConsole.err("Action not found: " + userInput);
}
}
}
</code></pre> |
34,557,398 | Does C make a difference between compiling and executing a program? | <p>If an evaluation of an expression causes undefined behavior in C, and the expression is always evaluated when the program is executed (for example if it appears at the start of <code>main</code>), is it conforming if an implementation rejects it at <em>compile time</em>? Is there a difference in C between compiling/translating a program and executing it?</p>
<p>I know that there are interpreters for C. How are they handled by the C standard regarding this difference?</p>
<blockquote>
<p><em>Example (reading uninitialized local)</em></p>
<pre><code>int main() {
int i;
return i;
}
</code></pre>
</blockquote>
<p>When running it, at any stage of the execution (even before <code>main</code> is called), the program can do something funny. But can something funny also happen when we haven't even tried to run it? Can it cause a buffer overflow in the compiler itself?</p> | 34,557,522 | 3 | 19 | null | 2016-01-01 15:25:20.203 UTC | 6 | 2016-01-01 22:46:25.053 UTC | 2016-01-01 22:46:25.053 UTC | null | 1,300,910 | null | 34,509 | null | 1 | 36 | c|language-lawyer | 2,228 | <p>From a C11 draft:</p>
<blockquote>
<h2>3.4.3 undefined behavior</h2>
<p>behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard <strong>imposes no requirements</strong></p>
<p><sub>NOTE Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the
environment (with or without the issuance of a diagnostic message), <strong>to terminating a translation</strong> or execution (with the issuance of a diagnostic message).</sub></p>
</blockquote>
<p>Terminating the translation is mentioned as a possible consequence of undefined behavior in the (non-normative) note, so compile-time effects are clearly not intended to be excluded. The normative part certainly allows it - it allows anything. So conforming compiler can terminate the translation if it detects undefined behavior during compilation.</p>
<p>Additionally, in <em>$4 Conformance</em>:</p>
<blockquote>
<p>If a ‘‘shall’’ or ‘‘shall not’’ requirement that appears outside of a constraint or runtime-constraint is violated, the behavior is undefined. Undefined behavior is otherwise indicated in this International Standard by the words ‘‘undefined behavior’’ or by the omission of any explicit definition of behavior. There is no difference in emphasis among these three; they all describe ‘‘behavior that is undefined’’.</p>
</blockquote>
<p>There is no distinction made either in the normative definition or in the conformance description between "translation time" and "execution time". No difference is made between different "varieties" of undefined behavior.</p>
<p>Additionally, <a href="http://www.open-std.org/jtc1/sc22/wg14/docs/rr/dr_109.html" rel="nofollow noreferrer">Defect Report #109</a> pointed out by <a href="https://stackoverflow.com/a/34557922/635608">ouah</a> in <a href="https://stackoverflow.com/questions/18385020/can-code-that-will-never-be-executed-invoke-undefined-behavior"><em>Can code that will never be executed invoke undefined behavior?</em></a> has this in its response:</p>
<blockquote>
<p>[...] If an expression whose evaluation would result in undefined behavior appears in a context where a constant expression is required, the containing program is not strictly conforming. Furthermore, if every possible execution of a given program would result in undefined behavior, the given program is not strictly conforming. </p>
<p>A conforming implementation must not fail to translate a strictly conforming program simply because some possible execution of that program would result in undefined behavior. [...]</p>
</blockquote>
<p>This would indicate that a compiler cannot fail a translation if it cannot statically determine that all paths lead to undefined behavior.</p> |
6,967,632 | Unpacking, extended unpacking and nested extended unpacking | <p>Consider the following expressions. Note that some expressions are repeated to present the "context".</p>
<p>(this is a long list)</p>
<pre><code>a, b = 1, 2 # simple sequence assignment
a, b = ['green', 'blue'] # list asqignment
a, b = 'XY' # string assignment
a, b = range(1,5,2) # any iterable will do
# nested sequence assignment
(a,b), c = "XY", "Z" # a = 'X', b = 'Y', c = 'Z'
(a,b), c = "XYZ" # ERROR -- too many values to unpack
(a,b), c = "XY" # ERROR -- need more than 1 value to unpack
(a,b), c, = [1,2],'this' # a = '1', b = '2', c = 'this'
(a,b), (c,) = [1,2],'this' # ERROR -- too many values to unpack
# extended sequence unpacking
a, *b = 1,2,3,4,5 # a = 1, b = [2,3,4,5]
*a, b = 1,2,3,4,5 # a = [1,2,3,4], b = 5
a, *b, c = 1,2,3,4,5 # a = 1, b = [2,3,4], c = 5
a, *b = 'X' # a = 'X', b = []
*a, b = 'X' # a = [], b = 'X'
a, *b, c = "XY" # a = 'X', b = [], c = 'Y'
a, *b, c = "X...Y" # a = 'X', b = ['.','.','.'], c = 'Y'
a, b, *c = 1,2,3 # a = 1, b = 2, c = [3]
a, b, c, *d = 1,2,3 # a = 1, b = 2, c = 3, d = []
a, *b, c, *d = 1,2,3,4,5 # ERROR -- two starred expressions in assignment
(a,b), c = [1,2],'this' # a = '1', b = '2', c = 'this'
(a,b), *c = [1,2],'this' # a = '1', b = '2', c = ['this']
(a,b), c, *d = [1,2],'this' # a = '1', b = '2', c = 'this', d = []
(a,b), *c, d = [1,2],'this' # a = '1', b = '2', c = [], d = 'this'
(a,b), (c, *d) = [1,2],'this' # a = '1', b = '2', c = 't', d = ['h', 'i', 's']
*a = 1 # ERROR -- target must be in a list or tuple
*a = (1,2) # ERROR -- target must be in a list or tuple
*a, = (1,2) # a = [1,2]
*a, = 1 # ERROR -- 'int' object is not iterable
*a, = [1] # a = [1]
*a = [1] # ERROR -- target must be in a list or tuple
*a, = (1,) # a = [1]
*a, = (1) # ERROR -- 'int' object is not iterable
*a, b = [1] # a = [], b = 1
*a, b = (1,) # a = [], b = 1
(a,b),c = 1,2,3 # ERROR -- too many values to unpack
(a,b), *c = 1,2,3 # ERROR - 'int' object is not iterable
(a,b), *c = 'XY', 2, 3 # a = 'X', b = 'Y', c = [2,3]
# extended sequence unpacking -- NESTED
(a,b),c = 1,2,3 # ERROR -- too many values to unpack
*(a,b), c = 1,2,3 # a = 1, b = 2, c = 3
*(a,b) = 1,2 # ERROR -- target must be in a list or tuple
*(a,b), = 1,2 # a = 1, b = 2
*(a,b) = 'XY' # ERROR -- target must be in a list or tuple
*(a,b), = 'XY' # a = 'X', b = 'Y'
*(a, b) = 'this' # ERROR -- target must be in a list or tuple
*(a, b), = 'this' # ERROR -- too many values to unpack
*(a, *b), = 'this' # a = 't', b = ['h', 'i', 's']
*(a, *b), c = 'this' # a = 't', b = ['h', 'i'], c = 's'
*(a,*b), = 1,2,3,3,4,5,6,7 # a = 1, b = [2, 3, 3, 4, 5, 6, 7]
*(a,*b), *c = 1,2,3,3,4,5,6,7 # ERROR -- two starred expressions in assignment
*(a,*b), (*c,) = 1,2,3,3,4,5,6,7 # ERROR -- 'int' object is not iterable
*(a,*b), c = 1,2,3,3,4,5,6,7 # a = 1, b = [2, 3, 3, 4, 5, 6], c = 7
*(a,*b), (*c,) = 1,2,3,4,5,'XY' # a = 1, b = [2, 3, 4, 5], c = ['X', 'Y']
*(a,*b), c, d = 1,2,3,3,4,5,6,7 # a = 1, b = [2, 3, 3, 4, 5], c = 6, d = 7
*(a,*b), (c, d) = 1,2,3,3,4,5,6,7 # ERROR -- 'int' object is not iterable
*(a,*b), (*c, d) = 1,2,3,3,4,5,6,7 # ERROR -- 'int' object is not iterable
*(a,*b), *(c, d) = 1,2,3,3,4,5,6,7 # ERROR -- two starred expressions in assignment
*(a,b), c = 'XY', 3 # ERROR -- need more than 1 value to unpack
*(*a,b), c = 'XY', 3 # a = [], b = 'XY', c = 3
(a,b), c = 'XY', 3 # a = 'X', b = 'Y', c = 3
*(a,b), c = 'XY', 3, 4 # a = 'XY', b = 3, c = 4
*(*a,b), c = 'XY', 3, 4 # a = ['XY'], b = 3, c = 4
(a,b), c = 'XY', 3, 4 # ERROR -- too many values to unpack
</code></pre>
<p>How to correctly deduce the result of such expressions by hand?</p> | 6,968,451 | 4 | 4 | null | 2011-08-06 14:59:56.357 UTC | 123 | 2021-04-13 12:17:23.63 UTC | 2020-07-15 05:57:58.157 UTC | null | 1,206,051 | null | 1,206,051 | null | 1 | 127 | python|python-3.x|iterable-unpacking|argument-unpacking | 42,329 | <p>My apologies for the length of this post, but I decided to opt for completeness.</p>
<p>Once you know a few basic rules, it's not hard to generalize them. I'll do my best to explain with a few examples. Since you're talking about evaluating these "by hand," I'll suggest some simple substitution rules. Basically, you might find it easier to understand an expression if all the iterables are formatted in the same way.</p>
<p>For the purposes of unpacking only, the following substitutions are valid on the right side of the <code>=</code> (i.e. for <em>rvalues</em>):</p>
<pre><code>'XY' -> ('X', 'Y')
['X', 'Y'] -> ('X', 'Y')
</code></pre>
<p>If you find that a value doesn't get unpacked, then you'll undo the substitution. (See below for further explanation.)</p>
<p>Also, when you see "naked" commas, pretend there's a top-level tuple. Do this on both the left and the right side (i.e. for <em>lvalues</em> and <em>rvalues</em>):</p>
<pre><code>'X', 'Y' -> ('X', 'Y')
a, b -> (a, b)
</code></pre>
<p>With those simple rules in mind, here are some examples: </p>
<pre><code>(a,b), c = "XY", "Z" # a = 'X', b = 'Y', c = 'Z'
</code></pre>
<p>Applying the above rules, we convert <code>"XY"</code> to <code>('X', 'Y')</code>, and cover the naked commas in parens:</p>
<pre><code>((a, b), c) = (('X', 'Y'), 'Z')
</code></pre>
<p>The visual correspondence here makes it fairly obvious how the assignment works. </p>
<p>Here's an erroneous example:</p>
<pre><code>(a,b), c = "XYZ"
</code></pre>
<p>Following the above substitution rules, we get the below:</p>
<pre><code>((a, b), c) = ('X', 'Y', 'Z')
</code></pre>
<p>This is clearly erroneous; the nested structures don't match up. Now let's see how it works for a slightly more complex example:</p>
<pre><code>(a,b), c, = [1,2],'this' # a = '1', b = '2', c = 'this'
</code></pre>
<p>Applying the above rules, we get</p>
<pre><code>((a, b), c) = ((1, 2), ('t', 'h', 'i', 's'))
</code></pre>
<p>But now it's clear from the structure that <code>'this'</code> won't be unpacked, but assigned directly to <code>c</code>. So we undo the substitution.</p>
<pre><code>((a, b), c) = ((1, 2), 'this')
</code></pre>
<p>Now let's see what happens when we wrap <code>c</code> in a tuple:</p>
<pre><code>(a,b), (c,) = [1,2],'this' # ERROR -- too many values to unpack
</code></pre>
<p>Becomes</p>
<pre><code>((a, b), (c,)) = ((1, 2), ('t', 'h', 'i', 's'))
</code></pre>
<p>Again, the error is obvious. <code>c</code> is no longer a naked variable, but a variable inside a sequence, and so the corresponding sequence on the right is unpacked into <code>(c,)</code>. But the sequences have a different length, so there's an error. </p>
<p>Now for extended unpacking using the <code>*</code> operator. This is a bit more complex, but it's still fairly straightforward. A variable preceded by <code>*</code> becomes a list, which contains any items from the corresponding sequence that aren't assigned to variable names. Starting with a fairly simple example:</p>
<pre><code>a, *b, c = "X...Y" # a = 'X', b = ['.','.','.'], c = 'Y'
</code></pre>
<p>This becomes</p>
<pre><code>(a, *b, c) = ('X', '.', '.', '.', 'Y')
</code></pre>
<p>The simplest way to analyze this is to work from the ends. <code>'X'</code> is assigned to <code>a</code> and <code>'Y'</code> is assigned to <code>c</code>. The remaining values in the sequence are put in a list and assigned to <code>b</code>. </p>
<p>Lvalues like <code>(*a, b)</code> and <code>(a, *b)</code> are just special cases of the above. You can't have two <code>*</code> operators inside one lvalue sequence because it would be ambiguous. Where would the values go in something like this <code>(a, *b, *c, d)</code> -- in <code>b</code> or <code>c</code>? I'll consider the nested case in a moment. </p>
<pre><code>*a = 1 # ERROR -- target must be in a list or tuple
</code></pre>
<p>Here the error is fairly self-explanatory. The target (<code>*a</code>) must be in a tuple. </p>
<pre><code>*a, = (1,2) # a = [1,2]
</code></pre>
<p>This works because there's a naked comma. Applying the rules...</p>
<pre><code>(*a,) = (1, 2)
</code></pre>
<p>Since there are no variables other than <code>*a</code>, <code>*a</code> slurps up all the values in the rvalue sequence. What if you replace the <code>(1, 2)</code> with a single value?</p>
<pre><code>*a, = 1 # ERROR -- 'int' object is not iterable
</code></pre>
<p>becomes</p>
<pre><code>(*a,) = 1
</code></pre>
<p>Again, the error here is self-explanatory. You can't unpack something that isn't a sequence, and <code>*a</code> needs something to unpack. So we put it in a sequence</p>
<pre><code>*a, = [1] # a = [1]
</code></pre>
<p>Which is eqivalent to </p>
<pre><code>(*a,) = (1,)
</code></pre>
<p>Finally, this is a common point of confusion: <code>(1)</code> is the same as <code>1</code> -- you need a comma to distinguish a tuple from an arithmetic statement.</p>
<pre><code>*a, = (1) # ERROR -- 'int' object is not
</code></pre>
<p>Now for nesting. Actually this example wasn't in your "NESTED" section; perhaps you didn't realize it was nested?</p>
<pre><code>(a,b), *c = 'XY', 2, 3 # a = 'X', b = 'Y', c = [2,3]
</code></pre>
<p>Becomes</p>
<pre><code>((a, b), *c) = (('X', 'Y'), 2, 3)
</code></pre>
<p>The first value in the top-level tuple gets assigned, and the remaining values in the top-level tuple (<code>2</code> and <code>3</code>) are assigned to <code>c</code> -- just as we should expect. </p>
<pre><code>(a,b),c = 1,2,3 # ERROR -- too many values to unpack
*(a,b), c = 1,2,3 # a = 1, b = 2, c = 3
</code></pre>
<p>I've already explained above why the first line throws an error. The second line is silly but here's why it works:</p>
<pre><code>(*(a, b), c) = (1, 2, 3)
</code></pre>
<p>As previously explained, we work from the ends. <code>3</code> is assigned to <code>c</code>, and then the remaining values are assigned to the variable with the <code>*</code> preceding it, in this case, <code>(a, b)</code>. So that's equivalent to <code>(a, b) = (1, 2)</code>, which happens to work because there are the right number of elements. I can't think of any reason this would ever appear in working code. Similarly, </p>
<pre><code>*(a, *b), c = 'this' # a = 't', b = ['h', 'i'], c = 's'
</code></pre>
<p>becomes</p>
<pre><code>(*(a, *b), c) = ('t', 'h', 'i', 's')
</code></pre>
<p>Working from the ends, <code>'s'</code> is assigned to <code>c</code>, and <code>('t', 'h', 'i')</code> is assigned to <code>(a, *b)</code>. Working again from the ends, <code>'t'</code> is assigned to <code>a</code>, and <code>('h', 'i')</code> is assigned to b as a list. This is another silly example that should never appear in working code. </p> |
6,960,596 | Example of a regular expression for phone numbers | <p>I'm very new to javascript, I just want a reqular expression for validating phone numbers for one of my text field.</p>
<p>I can accept <code>-+ () 0-9</code> from users, do you have regex for this one or a regex for phone numbers better then the one i need?</p>
<p>Thanks in advance.</p> | 6,960,635 | 6 | 0 | null | 2011-08-05 17:57:51.7 UTC | 8 | 2022-02-26 14:53:45.03 UTC | 2022-02-26 14:53:45.03 UTC | null | 3,499,595 | null | 837,647 | null | 1 | 18 | javascript|regex|validation | 89,216 | <p>Use <a href="https://stackoverflow.com/q/2842345/764846">this</a> rexeg</p>
<pre><code>/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/
</code></pre>
<ul>
<li>(123) 456 7899</li>
<li>(123).456.7899</li>
<li>(123)-456-7899</li>
<li>123-456-7899</li>
<li>123 456 7899</li>
<li>1234567899</li>
</ul>
<p>supported</p> |
6,731,068 | Debugging CSS layout glitches in Android | <p>We have an existing web site, and I've been asked to test its compatibility with mobile browsers.</p>
<p>I've installed the Android SDK onto my desktop PC. I'm able to view my localhost site in the emulator, and I have identified a number of glitches in the page layout which occur in the Android browser. </p>
<p>But since none of these issues occur in any desktop browser, I've been struggling with how to debug them. For example, in Firefox, it's very easy to use Firebug to see what stylesheets have been appies and to adjust them on the fly to see how it affects the layout. But I haven't found a way to do anything similar on the Android emulator.</p>
<p>The question is, short of trial+error, how do I go about working out what is causing those layout issues? Does the Android browser (or the Android SDK) have any kind of tools that are useful for debugging CSS? If so, how do I use them?</p>
<p>[EDIT] I haven't found a solution to this, so I'm throwing open the doors to the bounty hunters...</p> | 6,824,808 | 6 | 0 | null | 2011-07-18 09:43:15.197 UTC | 8 | 2018-03-30 01:47:11.6 UTC | 2011-07-25 19:14:59.523 UTC | null | 352,765 | null | 352,765 | null | 1 | 32 | android|css|debugging | 10,640 | <p><a href="http://people.apache.org/~pmuellr/weinre/docs/latest/">Weinre</a> is probably the closest to what you're looking for:</p>
<p>If what you're looking for is something that allows you to tweak layout in realtime it should make you happy.</p> |
6,833,068 | Why is llvm considered unsuitable for implementing a JIT? | <p>Many dynamic languages implement (or want to implement) a JIT Compiler in order to speed up their execution times. Inevitably, someone from the peanut gallery asks why they don't use LLVM. The answer is often, "LLVM is unsuitable for building a JIT." (For Example, Armin Rigo's comment <a href="http://morepypy.blogspot.com/2008/04/float-operations-for-jit.html?showComment=1208773800000#c6322995253226647458">here.</a>)</p>
<p><strong>Why is LLVM Unsuitable for building a JIT?</strong></p>
<p>Note: I know LLVM has its own JIT. If LLVM used to be unsuitable, but now is suitable, please say what changed. I'm not talking about running LLVM Bytecode on the LLVM JIT, I'm talking about using the LLVM libraries to implement a JIT for a dynamic language.</p> | 6,833,494 | 6 | 5 | null | 2011-07-26 16:04:03.73 UTC | 24 | 2018-05-16 14:40:08.277 UTC | 2012-03-05 21:05:32.533 UTC | null | 117,587 | null | 117,587 | null | 1 | 57 | llvm|jit | 27,698 | <p>There are some notes about LLVM in the Unladen Swallow post-mortem blog post:
<a href="http://qinsb.blogspot.com/2011/03/unladen-swallow-retrospective.html" rel="noreferrer">http://qinsb.blogspot.com/2011/03/unladen-swallow-retrospective.html</a> .</p>
<blockquote>
<p>Unfortunately, LLVM in its current state is really designed as a static compiler optimizer and back end. LLVM code generation and optimization is good but expensive. The optimizations are all designed to work on IR generated by static C-like languages. Most of the important optimizations for optimizing Python require high-level knowledge of how the program executed on previous iterations, and LLVM didn't help us do that.</p>
</blockquote> |
6,880,902 | Start JBoss 7 as a service on Linux | <p>Previous versions of JBoss included a scripts (like <code>jboss_init_redhat.sh</code>) that could be copied to /etc/init.d in order to add it as a service - so it would start on boot up. I can't seem to find any similar scripts in JBoss 7. Has anyone already done something like this?</p>
<p>P.S.
I'm trying to achieve this in Ubuntu 10.04</p> | 6,881,418 | 12 | 0 | null | 2011-07-30 03:30:28.5 UTC | 30 | 2013-11-01 12:31:37.163 UTC | 2012-02-20 07:17:29.74 UTC | null | 50,776 | null | 350,103 | null | 1 | 36 | linux|ubuntu|ubuntu-10.04|jboss7.x|start-stop-daemon | 75,305 | <p>After spending a couple of hours of snooping around I ended up creating <code>/etc/init.d/jboss</code> with the following contents</p>
<pre><code>#!/bin/sh
### BEGIN INIT INFO
# Provides: jboss
# Required-Start: $local_fs $remote_fs $network $syslog
# Required-Stop: $local_fs $remote_fs $network $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start/Stop JBoss AS v7.0.0
### END INIT INFO
#
#source some script files in order to set and export environmental variables
#as well as add the appropriate executables to $PATH
[ -r /etc/profile.d/java.sh ] && . /etc/profile.d/java.sh
[ -r /etc/profile.d/jboss.sh ] && . /etc/profile.d/jboss.sh
case "$1" in
start)
echo "Starting JBoss AS 7.0.0"
#original:
#sudo -u jboss sh ${JBOSS_HOME}/bin/standalone.sh
#updated:
start-stop-daemon --start --quiet --background --chuid jboss --exec ${JBOSS_HOME}/bin/standalone.sh
;;
stop)
echo "Stopping JBoss AS 7.0.0"
#original:
#sudo -u jboss sh ${JBOSS_HOME}/bin/jboss-admin.sh --connect command=:shutdown
#updated:
start-stop-daemon --start --quiet --background --chuid jboss --exec ${JBOSS_HOME}/bin/jboss-admin.sh -- --connect command=:shutdown
;;
*)
echo "Usage: /etc/init.d/jboss {start|stop}"
exit 1
;;
esac
exit 0
</code></pre>
<p>Here's the content of <code>java.sh</code>:</p>
<pre><code>export JAVA_HOME=/usr/lib/jvm/java_current
export PATH=$JAVA_HOME/bin:$PATH
</code></pre>
<p>And <code>jboss.sh</code>:</p>
<pre><code>export JBOSS_HOME=/opt/jboss/as/jboss_current
export PATH=$JBOSS_HOME/bin:$PATH
</code></pre>
<p>Obviously, you need to make sure, you set JAVA_HOME and JBOSS_HOME appropriate to your environment.</p>
<p>then I ran <code>sudo update-rc.d jboss defaults</code> so that JBoss automatically starts on system boot</p>
<p>I found <a href="http://wiki.debian.org/LSBInitScripts" rel="noreferrer">this article</a> to be helpful in creating the start-up script above. Again, the script above is for Ubuntu (version 10.04 in my case), so using it in Fedora/RedHat or CentOS will probably not work (the setup done in the comments is different for those).</p> |
41,287,224 | Remove empty string properties from json serialized object | <p>I have a class. It has several properties lets say 10. Out of these 10, 3 are filled with data remaining 7 are blank.i.e. empty strings "" Used this <a href="https://stackoverflow.com/questions/15574506/how-to-remove-null-value-in-json-string">link</a> as reference. I would like only NON-NULL and NON-EMPTY string properties to be shown. But the end output has all 10 properties. I want only to see 3.</p>
<pre><code>namespace Mynamespace.ValueObjects
{
[DataContract]
public class User
{
[DataMember(Name ="userID", IsRequired = false,EmitDefaultValue = false)]
public string userID { get; set; }
[DataMember(Name ="ssn", IsRequired = false,EmitDefaultValue = false)]
public string ssn { get; set; }
[DataMember(Name ="empID", IsRequired = false,EmitDefaultValue = false)]
public string empID { get; set; }
[DataMember(Name ="schemaAgencyName", IsRequired = false,EmitDefaultValue = false)]
public string schemaAgencyName { get; set; }
[DataMember(Name ="givenName", IsRequired = false,EmitDefaultValue = false)]
public string givenName { get; set; }
[DataMember(Name ="familyName", IsRequired = false,EmitDefaultValue = false)]
public string familyName { get; set; }
[DataMember(Name ="password", IsRequired = false,EmitDefaultValue = false)]
public string password { get; set; }
....
}
</code></pre>
<p>}</p>
<p>I also tried with </p>
<pre><code> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
</code></pre>
<p>as the attribute too. No luck. I also did like this </p>
<pre><code> var t = JsonConvert.SerializeObject(usr, Newtonsoft.Json.Formatting.None,
new JsonSerializerSettings
{NullValueHandling = NullValueHandling.Ignore});
</code></pre>
<p>where 'usr' is the User instance. By no luck I mean, the 't' comes back with all the 10 properties </p>
<pre><code>{"userID":"vick187","ssn":"","empID":"","schemaAgencyName":"","givenName":"","familyName":"","password":"pwd1234",...}
</code></pre>
<p>So as you can see only userID and password are populated. But I have ssn, empID etc still showing up. I only want userID and password. Any help would be appreciated.</p> | 41,287,859 | 4 | 2 | null | 2016-12-22 16:03:58.2 UTC | 4 | 2020-07-31 00:44:54.557 UTC | 2017-05-23 12:16:22.26 UTC | null | -1 | null | 267,973 | null | 1 | 20 | c#|.net|json|serialization | 39,176 | <p>Just decorating the properties <code>[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]</code> ONLY should do what you want. Unless the property is getting set to an empty string. </p>
<p>Just wondering, why do you need the DataMemeber attribute?</p>
<p>Here is a link to a working <a href="https://dotnetfiddle.net/vWj5Zx" rel="noreferrer">dotnetfiddle</a></p>
<pre><code>using System;
using Newtonsoft.Json;
using System.ComponentModel;
public class Program
{
public static void Main()
{
var user = new User();
user.UserID = "1234";
user.ssn = "";
var settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
settings.DefaultValueHandling = DefaultValueHandling.Ignore;
Console.WriteLine(JsonConvert.SerializeObject(user, settings));
}
}
public class User
{
[DefaultValue("")]
public string UserID { get; set; }
[DefaultValue("")]
public string ssn { get; set; }
[DefaultValue("")]
public string empID { get; set; }
[DefaultValue("")]
public string schemaAgencyName { get; set; }
[DefaultValue("")]
public string givenName { get; set; }
[DefaultValue("")]
public string familyName { get; set; }
[DefaultValue("")]
public string password { get; set; }
}
</code></pre> |
15,562,438 | UITextField Only Top And Bottom Border | <p>I currently have a regular border. I would like to <strong>only have a top and bottom border</strong>.</p>
<p>How do I accomplish this?</p>
<p>Using the <code>UITextField</code>'s <code>layer</code> property, I have the following code:</p>
<pre><code> self.layer.borderColor = [[UIColor colorWithRed:160/255.0f green:160/255.0f blue:160/255.0f alpha:1.0f] CGColor];
self.layer.borderWidth = 4.0f;
</code></pre>
<p>I have kind of got it to work by <strong>making my UITextField extra long</strong>, so that the user does not see the left and right borders, but I was just wondering if there was a better, less hackish way of doing this?</p>
<p>I have <strong>checked the docs</strong>, and changing a <code>UITextField</code>'s <code>borderStyle</code> does not have this option.</p>
<p>From,</p>
<p>An iOS First Timer</p> | 26,609,227 | 11 | 1 | null | 2013-03-22 03:52:38.473 UTC | 14 | 2020-08-22 06:51:21.167 UTC | 2013-03-22 04:26:57.08 UTC | null | 1,355,704 | null | 2,081,621 | null | 1 | 26 | ios|objective-c|cocoa-touch|uitextfield | 41,936 | <p>One approach I have found works good is using layers. Here's a snippet:</p>
<pre><code>CALayer *bottomBorder = [CALayer layer];
bottomBorder.frame = CGRectMake(0.0f, self.frame.size.height - 1, self.frame.size.width, 1.0f);
bottomBorder.backgroundColor = [UIColor blackColor].CGColor;
[myTextField.layer addSublayer:bottomBorder];
</code></pre>
<p>Hope this helps someone.</p> |
10,512,845 | how to send email wth email template c# | <p>suppose i need to send mail to customer with customer detail and his order detail.
i have template html data in a html file.customer data is there and as well as order detail is also there in same html template file. my html look like </p>
<pre><code><html>
<body>
Hi {FirstName} {LastName},
Here are your orders:
{foreach Orders}
Order ID {OrderID} Quantity : {Qty} <strong>{Price}</strong>.
{end}
</body>
</html>
</code></pre>
<p>now i want to fill up all sample keyword surrounded with {} with actual value and also iterate and fill up orders. </p>
<p>i search google and found that microsoft provide a class called <strong>MailDefinition</strong>
by which we can generate mail body dynamically. i got a sample code also like</p>
<pre><code>MailDefinition md = new MailDefinition();
md.From = "[email protected]";
md.IsBodyHtml = true;
md.Subject = "Test of MailDefinition";
ListDictionary replacements = new ListDictionary();
replacements.Add("<%Name%>", "Martin");
replacements.Add("<%Country%>", "Denmark");
string body = "
Hello <%Name%> You're from <%Country%>.";
MailMessage msg = md.CreateMailMessage("[email protected]", replacements, body, new System.Web.UI.Control());
</code></pre>
<p>by the above code we can replace pseudo value with actual value but i don't know how iterate in Orders detail and populate orders data.</p>
<p>so if it is possible using MailDefinition class then please guide me with code that how can i iterate in loop and generate body for orders detail.</p> | 10,513,059 | 2 | 3 | null | 2012-05-09 08:57:50.693 UTC | 16 | 2018-12-18 05:43:42.377 UTC | 2015-10-07 07:40:07.67 UTC | null | 206,730 | null | 508,127 | null | 1 | 29 | c#|email-templates | 56,910 | <p>As an alternative to MailDefinition, have a look at RazorEngine <a href="https://github.com/Antaris/RazorEngine" rel="noreferrer">https://github.com/Antaris/RazorEngine</a>.</p>
<blockquote>
<p>RazorEngine is a simplified templating framework built around
Microsoft's new Razor parsing engine, used in both ASP.NET MVC3 and
Web Pages. <strong>RazorEngine provides a wrapper and additional services
built around the parsing engine to allow the parsing technology to
be used in other project types</strong>.</p>
</blockquote>
<p>It lets you use razor templates outside of ASP.NET MVC and then write something like this (<em>not tested</em>):</p>
<pre><code>string template =
@"<html>
<body>
Hi @Model.FirstName @Model.LastName,
Here are your orders:
@foreach(var order in Model.Orders) {
Order ID @order.Id Quantity : @order.Qty <strong>@order.Price</strong>.
}
</body>
</html>";
var model = new OrderModel {
FirstName = "Martin",
LastName = "Whatever",
Orders = new [] {
new Order { Id = 1, Qty = 5, Price = 29.99 },
new Order { Id = 2, Qty = 1, Price = 9.99 }
}
};
string mailBody = Razor.Parse(template, model);
</code></pre> |
10,693,845 | What do querySelectorAll and getElementsBy* methods return? | <p>Do <code>getElementsByClassName</code> (and similar functions like <code>getElementsByTagName</code> and <code>querySelectorAll</code>) work the same as <code>getElementById</code> or do they return an array of elements?</p>
<p>The reason I ask is because I am trying to change the style of all elements using <code>getElementsByClassName</code>. See below.</p>
<pre><code>//doesn't work
document.getElementsByClassName('myElement').style.size = '100px';
//works
document.getElementById('myIdElement').style.size = '100px';
</code></pre> | 10,693,852 | 12 | 3 | null | 2012-05-21 23:17:15.363 UTC | 54 | 2022-03-17 23:53:43.117 UTC | 2019-01-07 12:37:26.97 UTC | null | 10,078,895 | null | 1,402,121 | null | 1 | 191 | javascript|getelementsbyclassname|dom-traversal | 98,203 | <p>Your <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById" rel="noreferrer"><code>getElementById</code></a> code works since IDs have to be unique and thus the function always returns exactly one element (or <code>null</code> if none was found).</p>
<p>However, the methods
<a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName" rel="noreferrer"><code>getElementsByClassName</code></a>,
<a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName" rel="noreferrer"><code>getElementsByName</code></a>,
<a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName" rel="noreferrer"><code>getElementsByTagName</code></a>, and
<a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagNameNS" rel="noreferrer"><code>getElementsByTagNameNS</code></a>
return an iterable collection of elements.</p>
<p>The method names provide the hint: <code>getElement</code> implies <em>singular</em>, whereas <code>getElements</code> implies <em>plural</em>.</p>
<p>The method <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll" rel="noreferrer"><code>querySelector</code></a> also returns a single element, and <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll" rel="noreferrer"><code>querySelectorAll</code></a> returns an iterable collection.</p>
<p>The iterable collection can either be a <a href="https://developer.mozilla.org/en-US/docs/Web/API/NodeList" rel="noreferrer"><code>NodeList</code></a> or an <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection" rel="noreferrer"><code>HTMLCollection</code></a>.</p>
<p><a href="https://html.spec.whatwg.org/multipage/dom.html#the-document-object" rel="noreferrer"><code>getElementsByName</code></a> and <a href="https://dom.spec.whatwg.org/#interface-parentnode" rel="noreferrer"><code>querySelectorAll</code></a> are both specified to return a <code>NodeList</code>; the other <a href="https://dom.spec.whatwg.org/#interface-document" rel="noreferrer"><code>getElementsBy*</code> methods</a> are specified to return an <code>HTMLCollection</code>, but please note that some browser versions implement this differently.</p>
<p>Both of these collection types don’t offer the same properties that Elements, Nodes, or similar types offer; that’s why reading <code>style</code> off of <code>document.getElements</code>…<code>(</code>…<code>)</code> fails.
In other words: a <code>NodeList</code> or an <code>HTMLCollection</code> doesn’t have a <code>style</code>; only an <code>Element</code> has a <code>style</code>.</p>
<hr />
<p>These “array-like” collections are lists that contain zero or more elements, which you need to iterate over, in order to access them.
While you can iterate over them similarly to an array, note that they are <a href="https://stackoverflow.com/q/29707568"><em>different</em></a> from <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" rel="noreferrer"><code>Array</code>s</a>.</p>
<p>In modern browsers, you can convert these iterables to a proper Array with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from" rel="noreferrer"><code>Array.from</code></a>; then you can use <code>forEach</code> and other <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#instance_methods" rel="noreferrer">Array methods, e.g. iteration methods</a>:</p>
<pre class="lang-js prettyprint-override"><code>Array.from(document.getElementsByClassName("myElement"))
.forEach((element) => element.style.size = "100px");
</code></pre>
<p>In old browsers that don’t support <code>Array.from</code> or the iteration methods, you can still use <a href="https://stackoverflow.com/q/7056925"><code>Array.prototype.slice.call</code></a>.
Then you can iterate over it like you would with a real array:</p>
<pre class="lang-js prettyprint-override"><code>var elements = Array.prototype.slice
.call(document.getElementsByClassName("myElement"));
for(var i = 0; i < elements.length; ++i){
elements[i].style.size = "100px";
}
</code></pre>
<p>You can also iterate over the <code>NodeList</code> or <code>HTMLCollection</code> itself, but be aware that in most circumstances, these collections are <em>live</em> (<a href="https://developer.mozilla.org/en-US/docs/Web/API/NodeList#live_vs._static_nodelists" rel="noreferrer">MDN docs</a>, <a href="https://dom.spec.whatwg.org/#concept-collection-live" rel="noreferrer">DOM spec</a>), i.e. they are updated as the DOM changes.
So if you insert or remove elements as you loop, make sure to not accidentally <a href="https://stackoverflow.com/q/15562484">skip over some elements</a> or <a href="https://stackoverflow.com/q/9709351">create an infinite loop</a>.
MDN documentation should always note if a method returns a live collection or a static one.</p>
<p>For example, a <code>NodeList</code> offers some iteration methods such as <code>forEach</code> in modern browsers:</p>
<pre class="lang-js prettyprint-override"><code>document.querySelectorAll(".myElement")
.forEach((element) => element.style.size = "100px");
</code></pre>
<p>A simple <code>for</code> loop can also be used:</p>
<pre class="lang-js prettyprint-override"><code>var elements = document.getElementsByClassName("myElement");
for(var i = 0; i < elements.length; ++i){
elements[i].style.size = "100px";
}
</code></pre>
<p>Aside: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes" rel="noreferrer"><code>.childNodes</code></a> yields a <em>live</em> <code>NodeList</code> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/children" rel="noreferrer"><code>.children</code></a> yields a <em>live</em> <code>HTMLCollection</code>, so these two getters also need to be handled carefully.</p>
<hr />
<p>There are some libraries like <a href="https://jquery.com" rel="noreferrer">jQuery</a> which make DOM querying a bit shorter and create a layer of abstraction over “one element” and “a collection of elements”:</p>
<pre class="lang-js prettyprint-override"><code>$(".myElement").css("size", "100px");
</code></pre> |
25,267,089 | Convert a two byte UInt8 array to a UInt16 in Swift | <p>With Swift I want to convert bytes from a uint8_t array to an integer.</p>
<p>"C" Example:</p>
<pre><code>char bytes[2] = {0x01, 0x02};
NSData *data = [NSData dataWithBytes:bytes length:2];
NSLog(@"data: %@", data); // data: <0102>
uint16_t value2 = *(uint16_t *)data.bytes;
NSLog(@"value2: %i", value2); // value2: 513
</code></pre>
<p>Swift Attempt:</p>
<pre><code>let bytes:[UInt8] = [0x01, 0x02]
println("bytes: \(bytes)") // bytes: [1, 2]
let data = NSData(bytes: bytes, length: 2)
println("data: \(data)") // data: <0102>
let integer1 = *data.bytes // This fails
let integer2 = *data.bytes as UInt16 // This fails
let dataBytePointer = UnsafePointer<UInt16>(data.bytes)
let integer3 = dataBytePointer as UInt16 // This fails
let integer4 = *dataBytePointer as UInt16 // This fails
let integer5 = *dataBytePointer // This fails
</code></pre>
<p>What is the correct syntax or code to create a UInt16 value from a UInt8 array in Swift?</p>
<p>I am interested in the NSData version and am looking for a solution that does not use a temp array. </p> | 25,267,474 | 8 | 4 | null | 2014-08-12 14:35:48.183 UTC | 12 | 2022-06-13 11:27:21.797 UTC | 2014-08-12 15:02:17.48 UTC | null | 451,475 | null | 451,475 | null | 1 | 36 | swift | 34,907 | <p>If you want to go via <code>NSData</code> then it would work like this:</p>
<pre><code>let bytes:[UInt8] = [0x01, 0x02]
println("bytes: \(bytes)") // bytes: [1, 2]
let data = NSData(bytes: bytes, length: 2)
print("data: \(data)") // data: <0102>
var u16 : UInt16 = 0 ; data.getBytes(&u16)
// Or:
let u16 = UnsafePointer<UInt16>(data.bytes).memory
println("u16: \(u16)") // u16: 513
</code></pre>
<p>Alternatively:</p>
<pre><code>let bytes:[UInt8] = [0x01, 0x02]
let u16 = UnsafePointer<UInt16>(bytes).memory
print("u16: \(u16)") // u16: 513
</code></pre>
<p>Both variants assume that the bytes are in the host byte order.</p>
<p><strong>Update for Swift 3 (Xcode 8):</strong></p>
<pre><code>let bytes: [UInt8] = [0x01, 0x02]
let u16 = UnsafePointer(bytes).withMemoryRebound(to: UInt16.self, capacity: 1) {
$0.pointee
}
print("u16: \(u16)") // u16: 513
</code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.