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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
20,690,452 | Transform app.config for 3 different environment | <p>I need to be able to transform my app.config file using msbuild. I can transform the file if it is called app.DEBUG.config or app.Release.config, but I cannot if I add one called app.PROD.config.</p>
<p>Using regular XDT transforms msbuild recognizes different web.config files if I select a different PublishProfile</p>
<pre><code> msbuild path.to.project.csproj Configuration=Release PublishProfile=DEV
</code></pre>
<p>Apparently app.config does not work with this same setup. I can always create a specific build configuration for a DEV.config setup but it seems useless to have a separate build confirm for one app. A hacky way to do so is to just copy the correct app.config per environment POST-BUILD.</p>
<p>I've attempted to use the SlowCheetah plugin, but this only seems to transform the default DEBUG and RELEASE config files, which is not appropriate since I have more than two environments. If I indeed am using this wrong, please let me know what parameter I should pass at to msbuild to choose my app.DEV.config. </p>
<p>The expected result would be that msbuild would transform the app.config according to the transform that is customized called app.DEV.config or the one customized for app.PROD.config. I would expect that there is a parameter that I can pass to msbuild that would allow me to use the Release configuration but a transform with a different name per environment.</p> | 20,691,028 | 4 | 0 | null | 2013-12-19 19:51:51.317 UTC | 4 | 2021-02-18 17:23:16.067 UTC | 2013-12-19 20:05:38.787 UTC | null | 1,748,053 | null | 1,748,053 | null | 1 | 13 | c#|.net|msbuild|slowcheetah|xdt-transform | 39,577 | <p>This is what I use for this scenario:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- This target will run right before you run your app in Visual Studio -->
<Target Name="UpdateWebConfigBeforeRun" BeforeTargets="Build">
<Message Text="Configuration: $(Configuration) update from web.template.$(Configuration).config"/>
<TransformXml Source="web.template.config"
Transform="web.template.$(Configuration).config"
Destination="web.config" />
</Target>
<!-- Exclude the config template files from the created package -->
<Target Name="ExcludeCustomConfigTransformFiles" BeforeTargets="ExcludeFilesFromPackage">
<ItemGroup>
<ExcludeFromPackageFiles Include="web.template.config;web.template.*.config"/>
</ItemGroup>
<Message Text="ExcludeFromPackageFiles: @(ExcludeFromPackageFiles)" Importance="high"/>
</Target>
</Project>
</code></pre>
<p>I have the following setup:</p>
<pre><code>web.template.config
- web.template.debug.config
- web.template.production.config
- web.template.release.config etc
</code></pre>
<p>Should work cross pc without the need for extra plugins etc. In your scenario, you need to edit the contents to say <code>app.</code> instead of <code>web.</code></p> |
67,298,443 | When gcc-11 will appear in Ubuntu repositories? | <p>GCC 11.1 was finally released yesterday. However, now it can only be built from source, so I'm wondering when we can get it with <code>apt</code>?</p> | 67,406,788 | 4 | 3 | null | 2021-04-28 10:26:25.997 UTC | 10 | 2022-09-08 02:30:31.333 UTC | null | null | null | null | 14,727,976 | null | 1 | 35 | ubuntu|gcc|apt|gcc11 | 27,397 | <p>On Ubuntu 20.04, I followed the instructions here:</p>
<ul>
<li><a href="https://packages.ubuntu.com/hirsute/amd64/gcc-11-multilib/download" rel="noreferrer">https://packages.ubuntu.com/hirsute/amd64/gcc-11-multilib/download</a></li>
</ul>
<p>Which is to:</p>
<ol>
<li><p>Update the listed mirrors by adding a line to your /etc/apt/sources.list like this:</p>
<p><code>sudo add-apt-repository 'deb http://mirrors.kernel.org/ubuntu hirsute main universe'</code></p>
<p>Choose a mirror based on your location from the list. I chose the kernel
mirror as I am in North America.</p>
</li>
<li><p><code>sudo apt-get update</code></p>
</li>
<li><p>sudo apt-get install gcc-11</p>
</li>
</ol>
<p>After that <code>which gcc-11</code> should produce a path to gcc-11. On my machine it was:</p>
<pre><code>which gcc-11
</code></pre>
<p>produces: /usr/bin/gcc-11</p> |
5,927,258 | In App Purchase Receipt verification within app | <p>I want to verify the transaction receipt within my app,</p>
<p>Here is my code,</p>
<pre><code>- (void)recordTransaction:(SKPaymentTransaction *)transaction {
NSData *receiptData = [NSData dataWithData:transaction.transactionReceipt];
NSString *encodedString = [Base64 encode:receiptData];
NSURL *url = [NSURL URLWithString:@"https://sandbox.itunes.apple.com/verifyReceipt"];
ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:url];
[request setPostValue:encodedString forKey:@"receipt-data"];
[request setRequestMethod:@"POST"];
[request setDelegate:self];
[request startAsynchronous];
}
</code></pre>
<p>I am getting output: </p>
<blockquote>
<p>{"status":21002, "exception":"java.lang.NullPointerException"}</p>
</blockquote>
<p>Can someone help me to get proper receipt verification?</p> | 6,001,020 | 4 | 0 | null | 2011-05-08 11:52:53.99 UTC | 11 | 2014-10-07 11:07:21.45 UTC | 2014-10-07 11:07:21.45 UTC | null | 1,140,976 | null | 102,839 | null | 1 | 13 | ios|in-app-purchase | 24,832 | <p>After number of tries, I decided to do the receipt verification from server side. Actually this is the recommended way.</p>
<p>Here is my code,</p>
<pre><code>-(void)recordTransaction:(SKPaymentTransaction *)transaction {
NSString* receiptString = [[[NSString alloc] initWithData:transaction.transactionReceipt encoding:NSUTF8StringEncoding] autorelease];
// POST this string to your server
// I used ASIFormDataRequest
}
// server side
$url = 'https://sandbox.itunes.apple.com/verifyReceipt';
// encode the receipt data received from application
$purchase_encoded = base64_encode( $purchase_receipt );
//Create JSON
$encodedData = json_encode( Array(
'receipt-data' => $purchase_encoded
) );
// POST data
//Open a Connection using POST method, as it is required to use POST method.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encodedData);
$encodedResponse = curl_exec($ch);
curl_close($ch);
//Decode response data using json_decode method to get an object.
$response = json_decode( $encodedResponse );
// check response
if ($response->{'status'} != 0)
// Invalid receipt
else
// valid reciept
</code></pre>
<p>I found help form,</p>
<p><a href="http://gamesfromwithin.com/in-app-purchases-part-3" rel="noreferrer">http://gamesfromwithin.com/in-app-purchases-part-3</a></p> |
6,031,774 | What is the equivalent of ActionBar in earlier sdk versions? | <p>Since the ActionBar is available only in Android 3.0 and later, what is a good way to implement ActionBar-like widget in earlier sdk versions? I am looking to do this programmatically, if that helps. </p> | 6,371,538 | 4 | 1 | null | 2011-05-17 13:49:39.383 UTC | 18 | 2013-07-25 14:12:36.617 UTC | 2012-05-14 13:56:32.56 UTC | null | 747,536 | null | 747,536 | null | 1 | 38 | android|android-actionbar | 18,837 | <p>I have created a library, <a href="http://actionbarsherlock.com/" rel="noreferrer">ActionBarSherlock</a>, which is extended from the Android Compatibility Library to implement support for the native action bar all the way back to Android 1.6.</p>
<p>The key feature of this library is that it mimics the native action bar of Android 3.0+ and allows you to interact with it and theme it on all version of Android from 1.6 up through the current newest version, 3.1. There are samples and documentation on the website linked above which should give you a good idea about how it works.</p>
<p>You can also look on the <a href="https://github.com/JakeWharton/ActionBarSherlock/wiki/Implementations" rel="noreferrer">implementations page</a> on the GitHub wiki for real world applications of the library.</p>
<p><img src="https://i.stack.imgur.com/BhjKj.png" alt="enter image description here"></p> |
52,679,858 | Is it possible to make an editor split full-screen in VSCode? | <p>I'd like to have the ability to make one of multiple <code>split</code> editor windows full screen.</p>
<p>I usually have two vertically splitted windows with code and it would be useful to make sort of <em><strong>full-screen-zoom</strong></em> without explorer terminal and all other bars, just code.</p>
<p>Initally I have the following:</p>
<p><a href="https://i.stack.imgur.com/iI3WN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iI3WN.png" alt="enter image description here" /></a></p>
<p>but I would like to configure a shortcut to make an active window full-screen like this:</p>
<p><a href="https://i.stack.imgur.com/OmhlI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OmhlI.png" alt="enter image description here" /></a></p>
<p>It is like F11, closing the explorer, and merging the split. It is messy to do it by hand all the time...</p> | 52,680,112 | 7 | 1 | null | 2018-10-06 14:06:39.787 UTC | 4 | 2021-10-23 10:19:58.693 UTC | 2021-10-23 09:21:13.677 UTC | null | 362,951 | null | 2,786,156 | null | 1 | 27 | visual-studio-code | 42,605 | <blockquote>
<p>I would like to configure a shortcut to make an active window full-screen.</p>
</blockquote>
<p>You need to edit keybindings. Press <code>Ctrl+K</code> and then <code>Ctrl+S</code> to open keyboard shortcuts. </p>
<blockquote>
<p>If you're on a mac, use <code>Command</code> key instead of <code>Ctrl</code>.</p>
</blockquote>
<p>Search <strong><code>full screen</code></strong> in search bar. You will see something like this:</p>
<p><a href="https://i.stack.imgur.com/6kpat.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6kpat.png" alt="screenshot"></a></p>
<p>Click on the result. Press <code>Ctrl+K</code> and <code>Ctrl+K</code> (again!) or click pencil icon to edit the shortcut. Press desired key combination. That's it.</p>
<p>And here are some more shortcuts to learn:</p>
<p>Press <code>Ctrl+K</code> and then <code>Z</code> to open editor in full screen without explorer and terminal, etc. And you can use <code>Ctrl+B</code> to show/hide side bar and <code>Ctrl+J</code> to show terminal and console panel.</p>
<p>Download keyboard shortcuts file <a href="https://code.visualstudio.com/docs/getstarted/keybindings#_keyboard-shortcuts-reference" rel="noreferrer">here</a> for your favourite OS.</p>
<p><strong>To make these hotkeys work in vim-mode:</strong></p>
<p>Actually <code>VSCodeVim</code> will take over your control keys. This behaviour can be adjusted with the <code>useCtrlKeys</code> and handleKeys settings. Go to <code>File>>Preferences>>Keyboard Shortcuts</code>. Search for <code>Ctrl+k</code> in search bar. You will see <code>extension.vim_ctrl+k</code> as below:</p>
<p><a href="https://i.stack.imgur.com/d7Na8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/d7Na8.png" alt="screenshotVim"></a></p>
<p>Change this hotkey. Now it should work.</p> |
1,417,168 | ASP.NET MVC: Access controller instance from view | <p>How can I access a controller instance from the view? E.g. I have a <code>HomeController</code> which then returns my <code>Index</code> view. Inside of that view I want to access the <code>HomeController</code> instance that created the view. How do I do that?</p> | 1,417,170 | 2 | 1 | null | 2009-09-13 08:05:24.997 UTC | 8 | 2012-04-03 09:38:11.933 UTC | null | null | null | null | 114,916 | null | 1 | 48 | c#|.net|asp.net-mvc | 41,389 | <p>ViewContext.Controller, and you'll need to cast it.</p>
<pre><code><% var homeController = ViewContext.Controller as HomeController; %>
</code></pre>
<p>This is covered with a few extra wrinkles in post <a href="https://stackoverflow.com/questions/151963/asp-net-mvc-how-do-i-get-virtual-url-for-the-current-controller-view">Asp.Net MVC: How do I get virtual url for the current controller/view?</a>.</p>
<p><strong>EDIT</strong>: This is to add some meat to Mark Seemann's recommendation that you keep functionality out of the view as much as humanly possible. If you are using the controller to help determine the markup of the rendered page, you may want to use the <code>Html.RenderAction(actionName, controllerName)</code> method instead. This call will fire the action as though it was a separate request and include its view as part of the main page. </p>
<p>This approach will help to enforce separation-of-concerns because the action method redirected to can do all the heavy lifting with respect to presentation rules. It will need to return a Partial View to work correctly within your parent view.</p> |
2,259,926 | Testing IO actions with Monadic QuickCheck | <p>Can anyone give me a brief example of testing IO actions using Monadic QuickCheck?</p> | 2,946,515 | 2 | 1 | null | 2010-02-14 02:27:14.76 UTC | 21 | 2014-05-20 12:21:23.607 UTC | 2011-01-23 08:19:00.833 UTC | null | 427,158 | null | 126,855 | null | 1 | 54 | haskell|io|quickcheck | 6,598 | <p>The <a href="http://hackage.haskell.org/packages/archive/QuickCheck/2.1.0.2/doc/html/Test-QuickCheck-Monadic.html" rel="noreferrer">Test.QuickCheck.Monadic</a> module lets you test monadic code, even things that run in <code>IO</code>.</p>
<p>A monadic property test is of type <code>PropertyM m a</code>, where <code>m</code> is the monad the test runs in and <code>a</code> is ultimately ignored. In the case of <code>PropertyM IO a</code>, you convert the monadic test to a <code>Property</code> by using <code>monadicIO</code>; for all other monads, you use <code>monadic</code> instead (which takes a function to run the monad, something <code>IO</code> doesn't have).</p>
<p>In a monadic test, the value <code>return</code>ed out of the monad is ignored. To check an expression, use <code>assert</code>; <code>assert</code>ing a false value will fail the test. Use <code>run</code> to execute the code in the monad being tested.</p>
<p>There are other monadic actions at your disposal. For example, <code>pick</code> will generate new test inputs out of a <code>Gen a</code>, and <code>pre</code> will check test preconditions. These are useful if the test inputs or preconditions themselves depend on values computed via the monad being tested, in which case the normal way of generating inputs or checking precontions won't work.</p>
<p>Here's an example of testing some <code>IO</code> code: we check that after writing something to a temporary file, we can read that same data back. For demonstration purposes, we'll impose the precondition that we write at least one byte to the file. The two test properties do the same thing; one uses <code>pick</code> and <code>pre</code> unnecessarily while the other does not.</p>
<pre><code>import System.Directory (removeFile)
import System.IO (hGetContents, hPutStr, hSeek, openBinaryTempFile, SeekMode (..))
import Test.QuickCheck (arbitrary, Property, quickCheck, (==>))
import Test.QuickCheck.Monadic (assert, monadicIO, pick, pre, run)
-- Demonstrating pick and pre as well:
prop_writeThenRead :: Property
prop_writeThenRead = monadicIO $ do writtenData <- pick arbitrary
pre $ not (null writtenData)
readData <- run $ writeThenRead writtenData
assert $ writtenData == readData
-- A more idiomatic way to write the above:
prop_writeThenRead2 :: [Char] -> Property
prop_writeThenRead2 writtenData = not (null writtenData) ==> monadicIO test
where test = do readData <- run $ writeThenRead writtenData
assert $ writtenData == readData
writeThenRead :: [Char] -> IO [Char]
writeThenRead output = do (path, h) <- openBinaryTempFile "/tmp" "quickcheck.tmp"
removeFile path
hPutStr h output
hSeek h AbsoluteSeek 0
hGetContents h
main :: IO ()
main = do quickCheck prop_writeThenRead
quickCheck prop_writeThenRead2
</code></pre> |
29,286,714 | IntelliJ - java: Cannot find JDK '1.8' | <p>Update: Not sure why this is marked as a duplicate. I had already linked to the other post stating that none of the suggestions / answers work for me. In addition, their question seems to be related to an issue using Windows VMs via Mac, which is irrelevant for me.</p>
<p>I am using IntelliJ IDEA 14.0.3. I have selected the 'Java Hello World' sample. When I try and run the program I receive the error: "Error: java: Cannot find JDK '1.8' for module 'Deliverable4'. I have tried every single suggestion from this post <a href="https://stackoverflow.com/questions/14278936/intellij-java-cannot-find-jdk-1-7-for-module">intellij - java: Cannot find JDK '1.7' for module</a> but still can't this to work. Any help would be greatly appreciated.</p> | 29,286,919 | 4 | 1 | null | 2015-03-26 18:57:46.937 UTC | 4 | 2019-02-21 19:44:31.063 UTC | 2017-05-23 12:10:10.513 UTC | null | -1 | null | 1,030,126 | null | 1 | 28 | java|intellij-idea | 53,398 | <p>Updating from IntelliJ version 14.0.3 to 14.1 seemed to fix the problem.</p> |
5,803,881 | PHP Print keys from an object? | <p>I have an object BIRD and then there is [0] through [10] and each number has a subheading like "bug" or "beetle" or "gnat" and a value for each of those.</p>
<p>I want to print </p>
<pre><code>BIRD
[0]
bug = > value
</code></pre>
<p>I can't find out how to do this anywhere - there is talk of PUBLIC and PRIVATE and CLASS and that's where I fall off</p> | 5,804,065 | 5 | 1 | null | 2011-04-27 12:13:01.867 UTC | 1 | 2022-01-11 01:58:38.01 UTC | 2012-05-05 00:10:55.957 UTC | null | 11,343 | null | 723,220 | null | 1 | 28 | php|arrays|object|echo | 94,549 | <p>I could be wrong but try to use <code>array_keys</code> using a object as parameter. I believe that is possible in php.
<a href="http://php.net/manual/en/function.array-keys.php" rel="nofollow">http://php.net/manual/en/function.array-keys.php</a></p>
<p>Anyway, read about reflection.</p> |
6,255,344 | How can I use JQuery to post JSON data? | <p>I would like to post Json to a web service on the same server. But I don't know how to post Json using JQuery. I have tried with this code:</p>
<pre><code>$.ajax({
type: 'POST',
url: '/form/',
data: {"name":"jonas"},
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
</code></pre>
<p>But using this JQuery code the data is not received as Json on the server. This is the expected data at the server: <code>{"name":"jonas"}</code> but using JQuery the server receive <code>name=jonas</code>. Or in other words, it's "urlencoded" data and not Json.</p>
<p>Is there any way to post the data in Json format instead of urlencoded data using JQuery? Or do I have to use a manual ajax request?</p> | 6,255,394 | 6 | 0 | null | 2011-06-06 16:50:32.857 UTC | 15 | 2021-05-14 22:20:02.733 UTC | 2021-05-14 22:20:02.733 UTC | null | 213,269 | null | 213,269 | null | 1 | 81 | jquery|json|ajax|http-post | 176,637 | <p>You're passing an object, <em>not</em> a JSON string. When you pass an object, jQuery uses <a href="http://api.jquery.com/jquery.param" rel="noreferrer"><code>$.param</code></a> to serialize the object into name-value pairs.</p>
<p>If you pass the data as a string, it won't be serialized:</p>
<pre><code>$.ajax({
type: 'POST',
url: '/form/',
data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
</code></pre> |
6,022,302 | How to apply unmerged upstream pull requests from other forks into my fork? | <p>A project on GitHub that I have a fork of has a new pull requests that I want to pull into my fork that the author has not pulled in yet.</p>
<p>Is there a simple way to apply pull request from other forks into my fork? Is there something else here that I am missing?</p> | 6,022,366 | 7 | 3 | null | 2011-05-16 19:25:04.413 UTC | 239 | 2019-09-08 14:23:00.35 UTC | 2015-08-16 09:31:57.737 UTC | null | 895,245 | null | 3,765 | null | 1 | 520 | git|github|pull-request | 61,195 | <p>You can do it manually quite easily:</p>
<ul>
<li><p>add the other fork as a remote of your repo: </p>
<pre><code>git remote add otherfork git://github.com/request-author/project.git
</code></pre></li>
<li><p>fetch his repo's commits</p>
<pre><code>git fetch otherfork
</code></pre></li>
<li><p>You have then two options to apply the pull request (if you don't want to choose pick 1.)</p>
<ol>
<li><p>If you don't care about applying also the eventual commits that have been added between the origin and the pull request, you can just rebase the branch on which the pull request was formed</p>
<pre><code>git rebase master otherfork/pullrequest-branch
</code></pre></li>
<li><p>If you only want the commits in the pull request, identify their SHA1 and do</p>
<pre><code>git cherry-pick <first-SHA1> <second-SHA1> <etc.>
</code></pre></li>
</ol></li>
</ul> |
5,734,199 | Auto margins don't center image in page | <p>In <a href="http://jsfiddle.net/XnKDQ/" rel="noreferrer">this example</a> the image is not centered. Why? My browser is Google Chrome v10 on windows 7, not IE.</p>
<pre><code><img src="/img/logo.png" style="margin:0px auto;"/>
</code></pre> | 5,734,202 | 10 | 1 | null | 2011-04-20 17:24:11.857 UTC | 23 | 2020-11-08 03:20:02.96 UTC | 2015-04-09 20:30:23.513 UTC | null | 1,264,804 | null | 552,067 | null | 1 | 107 | css|google-chrome|margin|centering | 192,734 | <p>add <code>display:block;</code> and it'll work. Images are inline by default</p>
<p>To clarify, the default width for a <code>block</code> element is <code>auto</code>, which of course fills the entire available width of the containing element.</p>
<p>By setting the margin to <code>auto</code>, the browser assigns half the remaining space to <code>margin-left</code> and the other half to <code>margin-right</code>.</p> |
39,058,422 | How to set command timeout in aspnetcore/entityframeworkcore | <p>The place where the command timeout is set is no longer the same as earlier versions.</p>
<p>However, I cannot find anywhere that says how to change this.</p>
<p>What I am doing is uploading very large files which takes longer than the default 30 seconds to save.</p>
<p>Note that I ask about Command Timeout, not Migration Timeout as in another question.</p> | 47,313,244 | 5 | 2 | null | 2016-08-20 20:25:18.2 UTC | 12 | 2021-06-24 01:27:38.697 UTC | 2019-07-24 06:23:46.147 UTC | null | 70,345 | null | 425,823 | null | 1 | 83 | c#|asp.net-core|entity-framework-core | 79,228 | <p>If you're using the DI container to manage the DbContext (i.e. you're adding the DbContext to the service collection), the command timeout can be specified in the options.</p>
<p>In Startup.ConfigureServices:</p>
<pre><code>services.AddDbContext<YourDbContext>(options => options.UseSqlServer(
this.Configuration.GetConnectionString("YourConnectionString"),
sqlServerOptions => sqlServerOptions.CommandTimeout(60))
);
</code></pre> |
32,841,543 | Matchers.any() for null value in Mockito | <p>Suppose I am having this object <code>objectDemo</code> which calls to the method <code>objectDemoMethod</code> with 2 parameters <code>String</code> and <code>null</code>. Now I want to verify with Mockito that this method was called:</p>
<pre><code>objectDemo.objectDemoMethod("SAMPLE_STRING", null);
</code></pre>
<p>I have written this:</p>
<pre><code>Mockito.verify(objectDemo, Mockito.times(1)).objectDemoMethod(Matchers.any(String.class), null);
</code></pre>
<p>but it's giving an error:</p>
<blockquote>
<p>Invalid use of argument matchers for null value.</p>
</blockquote>
<p>Is there any another way to pass <code>null</code> value?</p> | 32,841,698 | 4 | 1 | null | 2015-09-29 10:22:15.353 UTC | 12 | 2020-12-16 17:56:40.217 UTC | 2020-12-16 17:56:40.217 UTC | null | 1,788,806 | null | 4,728,509 | null | 1 | 85 | java|mockito | 135,320 | <p>The error message you are getting is expected since you are using argument matcher for only one argument and not the other. From <a href="http://site.mockito.org/mockito/docs/current/org/mockito/Matchers.html"><code>Matchers</code></a> Javadoc:</p>
<blockquote>
<p>If you are using argument matchers, <strong>all arguments</strong> have to be provided by matchers. </p>
</blockquote>
<p>Therefore, the fix is to use a matcher for the second parameter of the method as well. In this case, it would be a matcher matching <code>null</code>. Depending on the version of Mockito and Java, you can have:</p>
<ul>
<li><p>Starting with Mockito 2, you can use <a href="https://static.javadoc.io/org.mockito/mockito-core/2.1.0/org/mockito/ArgumentMatchers.html#isNull()"><code>ArgumentMatchers.isNull()</code></a>. This works with Java 8 and above:</p>
<pre><code>verify(objectDemo, times(1)).objectDemoMethod(any(String.class), isNull());
</code></pre>
<p>Note that if you're running with Java 7 or older, you'll need an explicit cast to make this work, because the type inference in those versions of Java does not take into account the types of the method called:</p>
<pre><code>verify(objectDemo, times(1)).objectDemoMethod(any(String.class), (String) isNull());
</code></pre></li>
<li><p>If you're using Mockito 1, you can use the <a href="https://static.javadoc.io/org.mockito/mockito-core/1.10.19/org/mockito/Matchers.html#isNull(java.lang.Class)"><code>Matchers.isNull(clazz)</code></a> instead:</p>
<pre><code>verify(objectDemo, times(1)).objectDemoMethod(any(String.class), isNull(String.class));
</code></pre></li>
</ul>
<p>For the Java ≤ 7 or Mockito 1 cases, the examples uses a case where the second parameter was of type <code>String</code>: it would need to be replaced with the actual type of the method parameter.</p> |
9,154,672 | Which SSIS System Variable holds error text | <p>I am running a SSIS package using SQL Server 2008 Job. The package crash at some point while running. I have created my own mechanism to grab the error and record it in a table. So I can see that there is an error with an specific task, but could not find what the error is.</p>
<p>When I run the same package from BIDS, it works perfect. no error.</p>
<p>What I want to do is, I need to write that error string to my own table which shown in the "Execution Result" tab.</p>
<p>So the question is which system variable holds the error string in SSIS.</p> | 9,154,834 | 3 | 0 | null | 2012-02-06 01:22:25.003 UTC | null | 2018-12-27 19:53:23.047 UTC | 2012-02-06 02:05:49.4 UTC | null | 76,337 | null | 1,165,902 | null | 1 | 7 | ssis | 42,062 | <p>The error is stored in the <code>ErrorDescription</code> <a href="http://msdn.microsoft.com/en-us/library/ms141788.aspx" rel="noreferrer">system variable</a>. See <a href="http://msdn.microsoft.com/en-us/library/ms141679.aspx" rel="noreferrer">Handling Errors in the Data Flow</a> for an example of how to get the error description.</p>
<p>Also, if you want to capture error information into a table, SSIS supports <a href="http://msdn.microsoft.com/en-us/library/ms138020.aspx" rel="noreferrer">logging</a> to a table using the <a href="http://msdn.microsoft.com/en-us/library/ms140246.aspx" rel="noreferrer">SQL Server Log Provider</a>. You can also customize the logging.</p> |
9,568,042 | What is Application context and bean factory in spring framework | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/243385/new-to-spring-beanfactory-vs-applicationcontext">BeanFactory vs ApplicationContext</a> </p>
</blockquote>
<p>Simple word meaning of Application context and bean factory in spring framework.</p> | 9,568,098 | 1 | 0 | null | 2012-03-05 14:10:53.157 UTC | 14 | 2016-03-05 19:44:29.177 UTC | 2017-05-23 11:47:13.56 UTC | null | -1 | null | 1,143,806 | null | 1 | 19 | java|spring | 39,093 | <p><strong>BeanFactory</strong> </p>
<p>The <code>BeanFactory</code> is the actual container which instantiates, configures, and manages a number of beans. These beans typically collaborate with one another, and thus have dependencies between themselves. These dependencies are reflected in the configuration data used by the <code>BeanFactory</code> (although some dependencies may not be visible as configuration data, but rather be a function of programmatic interactions between beans at runtime).</p>
<p><strong>ApplicationContext</strong></p>
<p>While the beans package provides basic functionality for managing and manipulating beans, often in a programmatic way, the context package adds <code>ApplicationContext</code>, which enhances <code>BeanFactory</code> functionality in a more framework-oriented style. Many users will use <code>ApplicationContext</code> in a completely declarative fashion, not even having to create it manually, but instead relying on support classes such as <code>ContextLoader</code> to automatically start an ApplicationContext as part of the normal startup process of a Java EE web-app. Of course, it is still possible to programmatically create an ApplicationContext.</p>
<p>The basis for the context package is the <code>ApplicationContext</code> interface, located in the <code>org.springframework.context</code> package. Deriving from the <code>BeanFactory</code> interface, it provides all the functionality of <code>BeanFactory</code>. To allow working in a more framework-oriented fashion, using layering and hierarchical contexts, the context package also provides the following:</p>
<ul>
<li><p>MessageSource, providing access to messages in, i18n-style</p></li>
<li><p>Access to resources, such as URLs and files</p></li>
<li><p>Event propagation to beans implementing the ApplicationListener interface</p></li>
<li><p>Loading of multiple (hierarchical) contexts, allowing each to be focused on one particular layer, for example the web layer of an application</p></li>
</ul>
<p>As the <code>ApplicationContext</code> includes all functionality of the <code>BeanFactory</code>, it is generally recommended that it be used over the <code>BeanFactory</code>, except for a few limited situations such as perhaps in an applet, where memory consumption might be critical, and a few extra kilobytes might make a difference. The following sections described functionality which <code>ApplicationContext</code> adds to basic <code>BeanFactory</code> capabilities.</p>
<p><a href="http://static.springsource.org/spring/docs/1.2.x/reference/beans.html" rel="noreferrer">http://static.springsource.org/spring/docs/1.2.x/reference/beans.html</a></p> |
9,390,752 | android - do you ever have to add fragments to the manifest | <p>Im using a fragment that is supposed to display a webview. When I try to instantiate it from the class that uses it I get the following warning in my logcat.</p>
<pre><code>02-21 23:26:46.843: W/System.err(32468): android.content.ActivityNotFoundException: Unable to find explicit activity class {get.scanner/get.scanner.WebFrag}; have you declared this activity in your AndroidManifest.xml?
</code></pre>
<p>Im just learning how to use fragments and Ive never tried declaring them in my manifest and I havent seen anywhere telling you to do so.</p>
<p>Heres the WebFrag class. </p>
<pre><code>public class WebFrag extends Fragment{
private WebView viewer = null;
// if we weren't just using the compat library, we could use WebViewFragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
viewer = (WebView) inflater
.inflate(R.layout.webview, container, false);
WebSettings settings = viewer.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDefaultZoom(ZoomDensity.FAR);
return viewer;
}
@Override
public void onPause() {
if (viewer != null) {
viewer.onPause();
}
super.onPause();
}
@Override
public void onResume() {
super.onResume();
if (viewer != null) {
viewer.onResume();
}
}
public void updateUrl(String newUrl) {
if (viewer != null) {
viewer.loadUrl(newUrl);
}
}
}
</code></pre>
<p>EDIT: adding WebFrag as an activity to the manifest causes the following error</p>
<pre><code>02-22 00:17:55.711: E/AndroidRuntime(2524): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{get.scanner/get.scanner.WebFrag}: java.lang.ClassCastException: get.scanner.WebFrag
</code></pre>
<p>EDIT: Heres the main fragmentactivity where Im trying to use my class</p>
<pre><code>public class GetScannerActivity extends FragmentActivity {
private String mUrl = "http://www.yahoo.com/";
Button scanButton;
Button paint;
Button compTrans;
String yurl = "http://www.yahoo.com/";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
compTrans = (Button) findViewById(R.id.checkCurrentDeals);
compTrans.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
WebFrag viewer = (WebFrag) getSupportFragmentManager()
.findFragmentById(R.id.web_frag);
try{
if (viewer == null || !viewer.isInLayout()) {
Intent showContent = new Intent(getApplicationContext(),
WebFrag.class);
showContent.setData(Uri.parse(yurl));
try{
startActivity(showContent);
}catch(ActivityNotFoundException e){
e.printStackTrace();
}
} else {
viewer.updateUrl(yurl);
}
}catch(Exception e){
e.printStackTrace();
}
}
});
}
}
</code></pre> | 9,391,397 | 2 | 0 | null | 2012-02-22 07:33:25.1 UTC | 4 | 2020-01-31 19:53:46.193 UTC | 2012-02-22 08:34:51.077 UTC | null | 607,013 | null | 607,013 | null | 1 | 23 | android|manifest|fragment | 57,328 | <p>No don't add it to your manifest. You never need to add fragments to your manifest.</p>
<p>Do you create an Intent somewhere to start the WebActivity? How is it brought to the screen, that is probably where your problem lies.</p>
<p><em>EDIT</em></p>
<p>This is your problem:</p>
<pre><code> Intent showContent = new Intent(getApplicationContext(),
WebFrag.class);
startActivity(showContent);
</code></pre>
<p>You can't start a Fragment as an Activity, you'll have to wrap the fragment in an Activity that extends <a href="http://developer.android.com/reference/android/support/v4/app/FragmentActivity.html" rel="noreferrer">FragmentActivity</a></p> |
30,764,669 | What's Dead & Exploded in Swift's exception stack? | <p>In the exception stack for runtime crashes, Swift often says arguments are Dead or Exploded. What does it mean, and does it matter for debugging purposes?</p>
<p>For example:</p>
<pre><code>-> 0x100209cf0 <function signature specialization <Arg[0] = Exploded, Arg[1] = Exploded, Arg[2] = Dead, Arg[3] = Dead> of Swift._fatalErrorMessage (Swift.StaticString, Swift.StaticString, Swift.StaticString, Swift.UInt) -> ()+44>: brk #0x1
</code></pre>
<p>Thanks.</p> | 31,736,881 | 3 | 1 | null | 2015-06-10 18:38:51.373 UTC | 19 | 2019-06-27 16:35:22.927 UTC | null | null | null | null | 297,981 | null | 1 | 48 | ios|xcode|swift|error-handling|stack-trace | 7,650 | <blockquote>
<p>What does it mean?</p>
</blockquote>
<p>The Swift compiler marks function arguments for a number of reasons, mostly related to internal optimizations. For your question, we'll focus on the mangler, as that's what's contributing to your <a href="http://llvm.org/docs/doxygen/html/classllvm_1_1PrettyStackTraceEntry.html" rel="noreferrer">pretty stack trace</a>, and the Node Printer. As of the time of this post, the function specialization mangler has 6 marks it can apply to an argument:</p>
<ul>
<li><p><strong>Dead</strong></p>
<p>The argument is unused in the function body and can be removed in a dead argument elimination pass.</p>
</li>
<li><p><strong>Closure</strong></p>
<p>The argument is a closure and may require further mangling/demangling.</p>
</li>
<li><p><strong>Constant</strong></p>
<p>The argument is a constant.</p>
</li>
<li><p><strong>Owned to Guaranteed</strong></p>
<p>A caller-owned argument transfers ownership to the callee. The argument thus has a strong reference associated with it [the caller] and is guaranteed to live through the call, so the compiler allows the caller to elide the transfer and instead aggregate retains itself.</p>
</li>
<li><p><strong>SROA</strong></p>
<p>A <a href="https://llvm.org/docs/Passes.html#sroa-scalar-replacement-of-aggregates" rel="noreferrer">Scalar Replacement of Aggregates</a> pass should optimize this argument.</p>
</li>
<li><p><strong>In Out To Value</strong></p>
<p>The parameter was marked inout but the callee doesn't actually mutate it.</p>
</li>
</ul>
<p>The AST Node Printer adds one more mark</p>
<ul>
<li><p><strong>Exploded</strong></p>
<p>The value comes with an explosion schema that has been realized when the call was made.</p>
</li>
</ul>
<p>For all intents and purposes we only care about <code>Dead</code>, <code>Owned to Guaranteed</code>, and <code>Exploded</code>.</p>
<p>The only one that may still seem mystifying is <code>Exploded</code>. An <a href="https://github.com/silt-lang/silt/blob/master/Sources/InnerCore/Explosion.swift" rel="noreferrer">Explosion</a> is an optimization construct the Swift compiler uses to determine a strategy to unpack values from small structs and enums into registers. Thus, when the Node Printer says a value is <code>Exploded</code>, what it means it has already unpacked the value into registers before the call.</p>
<blockquote>
<p>does it matter for debugging purposes?</p>
</blockquote>
<p>Nope.</p> |
10,304,989 | Open Windows Explorer and select a file | <p>Is there a way to open a Windows Explorer window from a vba form, navigate to a specific file and select it so that the file name is placed in a text box?</p> | 10,305,150 | 1 | 1 | null | 2012-04-24 19:47:55.53 UTC | 10 | 2017-02-06 15:20:47.027 UTC | 2018-07-09 19:34:03.733 UTC | null | -1 | null | 1,029,888 | null | 1 | 28 | vba|excel | 126,235 | <p>Check out this snippet:</p>
<pre><code>Private Sub openDialog()
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
' Set the title of the dialog box.
.Title = "Please select the file."
' Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls"
.Filters.Add "All Files", "*.*"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox
End If
End With
End Sub
</code></pre>
<p>I think this is what you are asking for.</p> |
22,756,344 | How do I extract data from a doc/docx file using Python | <p>I know there are similar questions out there, but I couldn't find something that would answer my prayers. What I need is a way to access certain data from MS-Word files and save it in an XML file.
Reading up on <a href="https://github.com/mikemaccana/python-docx/issues/64" rel="noreferrer">python-docx</a> did not help, as it only seems to allow one to write into word documents, rather than read.
To present my task exactly (or how i chose to approach my task): I would like to search for a key word or phrase in the document (the document contains tables) and extract text data from the table where the key word/phrase is found.
Anybody have any ideas?</p> | 22,929,707 | 4 | 1 | null | 2014-03-31 07:57:41.793 UTC | 10 | 2021-01-06 05:14:41.267 UTC | 2014-03-31 08:06:14.303 UTC | null | 3,429,197 | null | 3,429,197 | null | 1 | 10 | python|ms-word|docx|doc | 39,027 | <p>It seems that pywin32 does the trick. You can iterate through all the tables in a document and through all the cells inside a table. It's a bit tricky to get the data (the last 2 characters from every entry have to be omitted), but otherwise, it's a ten minute code.
If anyone needs additional details, please say so in the comments.</p> |
7,337,266 | How to disable places on google map V3? | <p>I'm trying to migrate my application to latest version of Google map API and found that Google appends it's own items by default from Google Places directory to the map.
It does not look right together with my own records as it creates duplicate items on the map which can be placed in correctly.</p>
<p>Is there an option how to hide this local businesses or to control what is shown and what is not?</p>
<p>here is sample code:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Google Maps JavaScript API v3 Example: Map Simple</title>
<meta name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<style type="text/css">
html, body, #map_canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
function initialize() {
var myOptions = {
zoom: 16,
center: new google.maps.LatLng(37.422833333333,25.323166666667),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>
</code></pre>
<p>As you can see on map, there are few tiny icons, which you can click on and information would appear in bubble. I need to hide this icons or at least disable on click event for this items.</p> | 7,337,629 | 2 | 1 | null | 2011-09-07 16:22:27.057 UTC | 5 | 2020-02-14 15:14:05.667 UTC | 2011-09-07 16:54:40.097 UTC | null | 118,222 | null | 118,222 | null | 1 | 22 | javascript|google-maps-api-3 | 39,489 | <p>Just a pointer - this seems possible with <a href="http://code.google.com/apis/maps/documentation/javascript/styling.html#style_array_example" rel="noreferrer">custom styled maps</a>. If I'm not mistaken, the feature type you're looking for would be <code>poi.business</code>, whose <code>visiblity</code> you would turn <code>off</code>.</p>
<p>There's a <a href="https://mapstyle.withgoogle.com/" rel="noreferrer">wizard</a> to help you build the options array.</p> |
23,126,282 | Java APNS Certificate Error with "DerInputStream.getLength(): lengthTag=109, too big." | <p>When I try to using java APNS to send the push notification to iOS, I got this error message:</p>
<p><strong>com.notnoop.exceptions.InvalidSSLConfig: java.io.IOException: DerInputStream.getLength(): lengthTag=109, too big.</strong></p>
<p>I already try converting the certificate to Personal Information Exchange (.p12) also getting the same error. Anyone know to problem and how to resolve it?</p>
<p><strong>Here are my java code:</strong></p>
<pre><code>ApnsService service =
APNS.newService()
.withCert("src/net/notification/ck.jks", "******")
.withSandboxDestination()
.build();
String payload = APNS.newPayload().alertBody(record.getSendMsg()).build();
String token = record.getToken();
service.push(token, payload);
</code></pre>
<p>Thanks.</p> | 24,994,910 | 6 | 1 | null | 2014-04-17 06:42:34.39 UTC | 2 | 2022-09-23 09:13:20.873 UTC | 2014-04-17 06:47:43.793 UTC | null | 3,085,625 | null | 3,479,640 | null | 1 | 19 | java|ios|javapns | 47,385 | <p>I had the same problem but my solution will help you only if you are using <strong>maven</strong>.</p>
<p>Maven resource filtering (that let's you include variables in your resource files) can mess up your binaries - and certificates are especially sensitive to modification.</p>
<p>In general, binary content shouldn't be filtered. But I couldn't just simply disable resource filtering because I have some .properties files that include variables. So the solution was to <strong>exclude .p12 files from filtering</strong>.</p>
<pre><code><build>
[...]
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>**/*.p12</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<includes>
<include>**/*.p12</include>
</includes>
</resource>
</resources>
[...]
</build>
</code></pre>
<p>More about maven resource filtering:
<a href="http://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html">http://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html</a></p> |
23,302,270 | How do I run graphx with Python / pyspark? | <p>I am attempting to run Spark graphx with Python using pyspark. My installation appears correct, as I am able to run the pyspark tutorials and the (Java) GraphX tutorials just fine. Presumably since GraphX is part of Spark, pyspark should be able to interface it, correct?</p>
<p>Here are the tutorials for pyspark:
<a href="http://spark.apache.org/docs/0.9.0/quick-start.html">http://spark.apache.org/docs/0.9.0/quick-start.html</a>
<a href="http://spark.apache.org/docs/0.9.0/python-programming-guide.html">http://spark.apache.org/docs/0.9.0/python-programming-guide.html</a></p>
<p>Here are the ones for GraphX:
<a href="http://spark.apache.org/docs/0.9.0/graphx-programming-guide.html">http://spark.apache.org/docs/0.9.0/graphx-programming-guide.html</a>
<a href="http://ampcamp.berkeley.edu/big-data-mini-course/graph-analytics-with-graphx.html">http://ampcamp.berkeley.edu/big-data-mini-course/graph-analytics-with-graphx.html</a></p>
<p>Can anyone convert the GraphX tutorial to be in Python?</p> | 28,638,270 | 3 | 1 | null | 2014-04-25 20:18:44.143 UTC | 9 | 2019-05-14 06:16:56.507 UTC | null | null | null | null | 1,866,674 | null | 1 | 33 | python|hadoop|graph-theory|apache-spark | 38,097 | <p>It looks like the python bindings to GraphX are delayed at least to Spark <strike>1.4</strike> <strike>1.5</strike> ∞. It is waiting behind the Java API.</p>
<p>You can track the status at <a href="https://issues.apache.org/jira/browse/SPARK-3789">SPARK-3789 GRAPHX Python bindings for GraphX - ASF JIRA</a></p> |
18,783,763 | Bootstrap 3.0 Button in Navbar | <p>I upgraded bootstrap 3.0 now. And "a" tag which looks like btn (by the help of class .btn) is ruined on navbar.</p>
<pre><code><li>
<a href="<?php echo BASE_PATH; ?>register.php" class="btn btn-primary btn-sm">
<?php echo "<strong>" . _('Bayilik Başvurusu') . "</strong>"; ?>
</a>
</li>
</code></pre>
<p>But it is not working correctly. Bootstrap changed the system i think.</p> | 24,775,091 | 5 | 1 | null | 2013-09-13 10:12:36.097 UTC | 17 | 2016-12-04 07:13:02.29 UTC | 2014-07-20 11:14:57.38 UTC | null | 142,014 | null | 2,773,954 | null | 1 | 79 | css|twitter-bootstrap-3 | 90,751 | <p>Wrap a <code><p class="navbar-btn"></code> around the <code><a class="btn"></code>:</p>
<pre class="lang-html prettyprint-override"><code><nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<ul class="nav navbar-nav">
<li>
<p class="navbar-btn">
<a href="#" class="btn btn-default">I'm a link button!</a>
</p>
</li>
</ul>
</div>
</nav>
</code></pre>
<p>JSFiddle: <a href="http://jsfiddle.net/lachlan/398kj/">http://jsfiddle.net/lachlan/398kj/</a></p>
<p>Screenshot:<br>
<img src="https://i.stack.imgur.com/NnCJ9.png" alt="Bootstrap link button in navbar"></p> |
3,430,315 | What is the purpose of static keyword in array parameter of function like "char s[static 10]"? | <p>While browsing some source code I came across a function like this:</p>
<pre><code>void someFunction(char someArray[static 100])
{
// do something cool here
}
</code></pre>
<p>With some experimentation it appears other qualifiers may appear there too:</p>
<pre><code>void someFunction(char someArray[const])
{
// do something cool here
}
</code></pre>
<p>It appears that qualifiers are only allowed inside the <code>[</code> <code>]</code> when the array is declared as a parameter of a function. What do these do? Why is it different for function parameters?</p> | 3,430,353 | 1 | 0 | null | 2010-08-07 11:58:37.103 UTC | 82 | 2020-03-16 10:07:54.01 UTC | 2016-05-10 20:23:26.033 UTC | null | 895,245 | null | 10,320 | null | 1 | 176 | c|arrays|parameters|static | 24,094 | <p>The first declaration tells the compiler that <code>someArray</code> is <strong>at least</strong> 100 elements long. This can be used for optimizations. For example, it also means that <code>someArray</code> is never <code>NULL</code>.</p>
<p>Note that the C Standard does not require the compiler to diagnose when a call to the function does not meet these requirements (i.e., it is silent undefined behaviour).</p>
<p>The second declaration simply declares <code>someArray</code> (not <code>someArray</code>'s elements!) as const, i.e., you can not write <code>someArray=someOtherArray</code>. It is the same as if the parameter were <code>char * const someArray</code>. </p>
<p>This syntax is only usable within the innermost <code>[]</code> of an array declarator in a function parameter list; it would not make sense in other contexts. </p>
<p>The Standard text, which covers both of the above cases, is in C11 6.7.6.3/7 (was 6.7.5.3/7 in C99):</p>
<blockquote>
<p>A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’, where the type qualifiers (if any) are those specified within the <code>[</code> and <code>]</code> of the array type derivation. If the keyword static also appears within the <code>[</code> and <code>]</code> of the array type derivation, then for each call to the function, the value of the corresponding actual argument shall provide access to the first element of an array with at least as many
elements as specified by the size expression.</p>
</blockquote> |
21,216,347 | Achieving animated zoom with d3 and Leaflet | <p>Using d3 to plot SVG artefacts on top of a Leaflet map is a simple way to get a solid map controller combined with the strength of d3. There are numerous examples and guides as how to achieve this and the two main approaches seem to be:</p>
<ol>
<li><p>Appending a new SVG element on Leaflet's "overlay pane" as demonstrated by Bostock here: <a href="http://bost.ocks.org/mike/leaflet/">http://bost.ocks.org/mike/leaflet/</a></p></li>
<li><p>Implementing a custom vector tile layer that hooks in to Leaflets native tile layer ecosystem as demonstrated by Nelson Minar here: <a href="http://bl.ocks.org/NelsonMinar/5624141">http://bl.ocks.org/NelsonMinar/5624141</a></p></li>
</ol>
<p>The first approach avoids Leaflets scale-based zooming by attaching a leaflet-class so that any d3-elements are hidden while the scaling takes place. When the zoom animation is over, the element coordinates are re-calculated and redrawn whereafter the hide-class is removed to expose the elements again. This works, but gives a less clean zoom in/out experience than with Leaflet's native GeoJSON layer, as the latter supports animated zoom.</p>
<p>The second approach does not contain any implementation specific code that adress the zooming behaviour but does somehow work anyway! The d3 elements are scaled during animated zoom and then replaced neatly with the next zoom levels vectors.</p>
<p>What I would like to achieve is a combination of the two. I would like to plot non-tile-based vectors based on Geo/TopoJSON that are animated during zoom in/out. I've fiddled around with using different leaflet css-classes, different event-hooks, and attaching and/or reusing the SVG elements in numerous ways but have not yet achieved a behaviour that is similar to the behaviour experienced when using Leaflet's native GeoJSON vector layer. The reason I don't want to use the native layer is that I want to make use of plenty of other d3 functionality simply not part of the Leaflet implementation.</p>
<p>Question: Has anyone achieved animated zooming when combining Leaflet and d3 using non-tile-based vectors? If so - how?</p> | 21,599,738 | 1 | 2 | null | 2014-01-19 11:50:06.773 UTC | 9 | 2014-05-26 11:03:41.673 UTC | null | null | null | null | 2,297,898 | null | 1 | 21 | d3.js|leaflet | 9,401 | <p><strong>Example</strong></p>
<p>I think <a href="https://gist.github.com/ZJONSSON/3087431">this</a> is one of the best solutions I have found for combining Leaflet and d3, by <a href="https://github.com/ZJONSSON">ZJONSSON</a>.</p>
<p><strong>d3 + Leaflet Integration</strong></p>
<p>In this example the Leaflet map is initiated as SVG here <code>map._initPathRoot()</code>, with the SVG then selected using d3 <code>var svg = d3.select("#map").select("svg"),
g = svg.append("g");</code>, after which all the d3 fun can be had.</p>
<p>In this example, the Leaflet map event <code>map.on("viewreset", update);</code> is used to call <code>update</code> and transition the d3 layer on map <code>viewreset</code>. After this, d3 transition options will determine how the d3 layer reacts to the Leaflet map pan/zoom event.</p>
<p>In this way you have the full scope of the d3 + Leaflet libraries without the hassle of calculating map bounds etc, as this is handled nicely by Leaflet.</p>
<p><strong>Animated Vector Zooming</strong></p>
<p>For animation, the latest Leaflet release includes a <a href="http://leafletjs.com/reference.html#map-zoompanoptions">Pan and Zoom animation</a> option. Whilst this is not as customisable as d3, you could always edit the Leaflet src code to alter the transition duration! Leaflet GeoJSON vector layers (<code>L.geoJson</code>) will not need to be updated on a Leaflet map event (in <code>update</code>), as they are already added to the map as SVG and handled by Leaflet.</p>
<p>Note that if implementing <code>L.geoJson</code>, this also means you wont need to <code>map._initPathRoot()</code>, as Leaflet will add the layer to the map as SVG, so you can just <code>d3.select</code> it. </p>
<p>It is also possible to add a <code>className</code> variable in the <code>L.geoJson</code> layer options so you can style via CSS or <code>d3.select</code> a feature via a unique class id assigned during Leaflet <code>onEachFeature</code>.</p> |
20,993,092 | Make UISearchBar background clear | <p>I am not able to clear search bar I have tried to make it clear by setting its background color clear and I have also placed one image under searchbar</p>
<p>I have also made clear background of searchbar</p>
<pre><code> for (UIView *subview in self.searchBarHome.subviews) {
if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
[subview removeFromSuperview];//please help me to make clear background of uisearchbar
break;
}
}
[self.searchBarHome setBackgroundColor:[UIColor clearColor]];
</code></pre> | 20,993,635 | 18 | 3 | null | 2014-01-08 10:35:29.667 UTC | 2 | 2021-04-30 02:57:53.097 UTC | 2016-09-14 20:35:06.403 UTC | null | 1,634,890 | null | 3,164,253 | null | 1 | 28 | ios|objective-c|uisearchbar | 32,541 | <p>For iOS7+, all you need to do is:</p>
<pre><code>[self.searchBarHome setBackgroundColor:[UIColor clearColor]];
[self.searchBarHome setBarTintColor:[UIColor clearColor]]; //this is what you want
</code></pre>
<p><em><strong>NOTE</strong>: This will not work for iOS6</em></p>
<hr>
<p>For iOS6+, the following will take care of it even in iOS7:</p>
<pre><code>[self.searchBarHome setBackgroundColor:[UIColor clearColor]];
[self.searchBarHome setBackgroundImage:[UIImage new]];
[self.searchBarHome setTranslucent:YES];
</code></pre> |
28,318,799 | Strange values in a lambda returning initializer_list | <p>Consider this <strong>C++11</strong> code snippet:</p>
<pre><code>#include <iostream>
#include <set>
#include <stdexcept>
#include <initializer_list>
int main(int argc, char ** argv)
{
enum Switch {
Switch_1,
Switch_2,
Switch_3,
Switch_XXXX,
};
int foo_1 = 1;
int foo_2 = 2;
int foo_3 = 3;
int foo_4 = 4;
int foo_5 = 5;
int foo_6 = 6;
int foo_7 = 7;
auto get_foos = [=] (Switch ss) -> std::initializer_list<int> {
switch (ss) {
case Switch_1:
return {foo_1, foo_2, foo_3};
case Switch_2:
return {foo_4, foo_5};
case Switch_3:
return {foo_6, foo_7};
default:
throw std::logic_error("invalid switch");
}
};
std::set<int> foos = get_foos(Switch_1);
for (auto && foo : foos) {
std::cout << foo << " ";
}
std::cout << std::endl;
return 0;
}
</code></pre>
<p>Whatever compiler I try, all seem to handle it incorrectly. This makes me think that I am doing something wrong rather than it's a common bug across multiple compilers.</p>
<p><strong>clang 3.5</strong> output:</p>
<pre><code>-1078533848 -1078533752 134518134
</code></pre>
<p><strong>gcc 4.8.2</strong> output:</p>
<pre><code>-1078845996 -1078845984 3
</code></pre>
<p><strong>gcc 4.8.3</strong> output (compiled on <a href="http://www.tutorialspoint.com" rel="noreferrer">http://www.tutorialspoint.com</a>):</p>
<pre><code>1 2 267998238
</code></pre>
<p><strong>gcc (unknown version)</strong> output (compiled on <a href="http://coliru.stacked-crooked.com" rel="noreferrer">http://coliru.stacked-crooked.com</a>)</p>
<pre><code>-1785083736 0 6297428
</code></pre>
<p>The problem seems to be caused by using <code>std::initializer_list<int></code> as a return value of lambda. When changing lambda definition to <code>[=] (Switch ss) -> std::set<int> {...}</code> returned values are correct.</p>
<p>Please, help me solve this mystery.</p> | 28,319,001 | 3 | 1 | null | 2015-02-04 10:17:53.973 UTC | 5 | 2015-02-10 15:31:56.07 UTC | 2015-02-04 20:10:33.037 UTC | null | 1,381,108 | null | 966,376 | null | 1 | 34 | c++|c++11|lambda|initializer-list | 3,104 | <p>From: <a href="http://en.cppreference.com/w/cpp/utility/initializer_list">http://en.cppreference.com/w/cpp/utility/initializer_list</a></p>
<blockquote>
<p>The underlying array is not guaranteed to exist after the lifetime of the original initializer list object has ended. The storage for std::initializer_list is unspecified (i.e. it could be automatic, temporary, or static read-only memory, depending on the situation).</p>
</blockquote>
<p>I don't think the initializer list is copy-constructable. <code>std::set</code> and other containers are. Basically it looks like your code behaves similar to "returning a reference to a temporary".</p>
<p>C++14 has something slightly different to say about the underlying storage - extending <em>its</em> lifetime - but that does not fix anything having to do with the lifetime of the <code>initializer_list</code> object, let alone copies thereof. Hence, the issue remains, even in C++14.</p>
<blockquote>
<p>The underlying array is a temporary array, in which each element is copy-initialized (except that narrowing conversions are invalid) from the corresponding element of the original initializer list. The lifetime of the underlying array is the same as any other temporary object, <strong>except that initializing an initializer_list object from the array extends the lifetime of the array exactly like binding a reference to a temporary</strong> (with the same exceptions, such as for initializing a non-static class member). The underlying array may be allocated in read-only memory.</p>
</blockquote> |
2,286,186 | How to get the value for each key in dictionary in Objective-C? | <p>I'm maintaining a <code>NSMutableDictionary</code> which holds key and value pair.Now i need to perform some operation for each value in it.How to retrive value from dictionary.</p>
<pre><code>// this is NSMutableDIctionary
NSMutableDictionary *dictobj = [[NSMutableDictionary alloc]init];
// in methodA
-(void)methodA
{
//get the value for each key and peform an operation on it.
}
</code></pre>
<p>How to proceed? plz help</p> | 2,286,219 | 3 | 0 | null | 2010-02-18 03:55:39.34 UTC | 1 | 2016-01-27 15:06:02.253 UTC | 2013-06-01 11:52:04.293 UTC | null | 1,571,232 | null | 119,570 | null | 1 | 20 | objective-c|nsmutabledictionary | 52,150 | <pre><code>for (id key in dictobj)
{
id value = [dictobj objectForKey:key];
[value doSomething];
}
</code></pre> |
1,820,353 | Is there a well-established naming convention for PHP namespaces? | <p>So far, I've seen many different naming conventions used for PHP namespaces. Some people use <code>PascalCase\Just\Like\For\Classes</code>, some use <code>underscored\lower_case\names</code>, some even use the Java convention for package names: <code>com\domain\project\package</code>. </p>
<p>The question is very simple -- can any of these (or other) conventions be called well-established? Why? Are any of them recommended by authorities like Zend or the developers of well-known PHP frameworks?</p> | 3,705,695 | 3 | 0 | null | 2009-11-30 15:05:05.04 UTC | 4 | 2013-04-18 16:12:36.413 UTC | 2013-04-18 16:12:36.413 UTC | null | 367,456 | null | 153,569 | null | 1 | 37 | php|coding-style|namespaces|naming-conventions | 17,928 | <p>A PHP Standards Working Group made up of contributors to many different PHP frameworks and projects came up with the following proposal for appropriate namespace usage:</p>
<p><a href="https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md" rel="noreferrer">https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md</a></p> |
2,169,645 | Vim's autocomplete is excruciatingly slow | <p>Most of the time the autocomplete feature in Vim works nicely for me, but sometimes it seems to be scanning files which the current file references, and then it becomes painfully slow, sometimes taking several seconds to release focus back to me.</p>
<p>Sometimes Vim tells me simply that it is "Scanning" other times, it's saying "Scanning tags"</p>
<p>I've only this happen in Ruby files, and it happens mostly when there is a require in the file.</p>
<p>My guess would be that this is some kind of feature which checks related files for autocomplete options, but I don't really need that, and would prefer quicker autocomplete.</p> | 2,460,593 | 3 | 2 | null | 2010-01-30 22:10:32.64 UTC | 29 | 2017-08-20 00:52:03.797 UTC | 2017-08-19 22:52:36.107 UTC | null | 4,694,621 | null | 1,504,796 | null | 1 | 70 | vim|autocomplete|code-completion | 14,012 | <p>As I mentioned in a comment I had the same problem. Here's what I found;</p>
<p>There's a setting telling VIM where to look for completions, called <code>complete</code>.</p>
<pre><code>:set complete
complete=.,w,b,u,t,i
</code></pre>
<p>this is the default value. My problem is (was actually..) the 'i', which scans all included files. Here are two problems, first one, <em>finding</em> all those files might take quite a while, especially if you, like me, have</p>
<pre><code>:set path=**
</code></pre>
<p>Second problem, once found, they need to be read, and if you're using a networked file system (I'm on clearcase) both finding and reading all those files might trigger cache misses, making it painfully slow.</p>
<p>I've removed the i for now, as I have a tags-file and more often than not, I also have the relevant files in my buffers (loaded or unloaded) which will be searched as a result of 'b' and 'u'.</p>
<p>Use</p>
<pre><code>set complete-=i
</code></pre>
<p>to remove the i from the list, note that this is local to the buffer.</p> |
2,274,695 | `new function()` with lower case "f" in JavaScript | <p>My colleague has been using "new function()" with a lower case "f" to define new objects in JavaScript. It seems to work well in all major browsers and it also seems to be fairly effective at hiding private variables. Here's an example:</p>
<pre><code> var someObj = new function () {
var inner = 'some value';
this.foo = 'blah';
this.get_inner = function () {
return inner;
};
this.set_inner = function (s) {
inner = s;
};
};
</code></pre>
<p>As soon as "this" is used, it becomes a public property of someObj. So someObj.foo, someObj.get_inner() and someObj.set_inner() are all available publicly. In addition, set_inner() and get_inner() are privileged methods, so they have access to "inner" through closures.</p>
<p>However, I haven't seen any reference to this technique anywhere. Even Douglas Crockford's JSLint complains about it:</p>
<blockquote>
<ul>
<li>weird construction. Delete 'new'</li>
</ul>
</blockquote>
<p>We're using this technique in production and it seems to be working well, but I'm a bit anxious about it because it's not documented anywhere. Does anyone know if this is a valid technique?</p> | 2,274,742 | 3 | 15 | null | 2010-02-16 17:01:13.183 UTC | 49 | 2014-01-10 08:07:35.38 UTC | 2013-02-28 06:16:24.703 UTC | null | 31,671 | null | 188,740 | null | 1 | 106 | javascript|function|object|instantiation | 32,811 | <p>I've seen that technique before, it's valid, you are using a function expression as if it were a <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function" rel="noreferrer">Constructor Function</a>.</p>
<p>But IMHO, you can achieve the same with an auto-invoking function expression, I don't really see the point of using the <code>new</code> operator in that way:</p>
<pre><code>var someObj = (function () {
var instance = {},
inner = 'some value';
instance.foo = 'blah';
instance.get_inner = function () {
return inner;
};
instance.set_inner = function (s) {
inner = s;
};
return instance;
})();
</code></pre>
<p>The purpose of the <code>new</code> operator is to create new object instances, setting up the <code>[[Prototype]]</code> internal property, you can see how this is made by the <a href="http://bclary.com/2004/11/07/#a-13.2.2" rel="noreferrer"><code>[Construct]</code></a> internal property.</p>
<p>The above code will produce an equivalent result.</p> |
8,860,725 | Cannot implicitly convert type 'System.Drawing.Image' to 'System.Drawing.Bitmap'` | <p>Declared a bitmap which was</p>
<pre><code>private Bitmap img1 = null;
private Bitmap img2 = null;
</code></pre>
<p>the image will be putted after selecting it from <strong>openFileDialog</strong>.<br>
the selected images were placed in an array.</p>
<pre><code>imgName = openFD.FileNames;
</code></pre>
<p>then button1 to display these image.</p>
<pre><code>pictureBox1.Image = Image.FromFile(imgName[0]);
pictureBox2.Image = Image.FromFile(imgName[1]);
</code></pre>
<p>i replaced the button1 code with this</p>
<pre><code>img1 = Image.FromFile(imgName[0]);
img2 = Image.FromFile(imgName[1]);
</code></pre>
<p>but an error occurs </p>
<blockquote>
<p>Cannot implicitly convert type 'System.Drawing.Image' to 'System.Drawing.Bitmap'</p>
</blockquote>
<p>I'd try to change the code to <code>img1 = Bitmap.FromFile(imgName[0]);</code>. but still has the same error.<br>
Any suggestion how to correct or do this right?</p> | 8,860,739 | 4 | 1 | null | 2012-01-14 07:03:01.653 UTC | null | 2020-10-27 16:22:04.703 UTC | 2012-01-14 17:03:59.073 UTC | null | 366,904 | null | 1,131,630 | null | 1 | 6 | c#|.net|bitmap | 42,176 | <pre><code>img1 = new Bitmap(imgName[0]);
img2 = new Bitmap(imgName[1]);
</code></pre> |
8,624,886 | PDF to JPG conversion using PHP | <p>I'm trying to convert PDF to IMG (JPG) with help PHP.</p>
<p>I'm using imagick extension.</p>
<p>this is my code</p>
<pre><code> $fp_pdf = fopen($pdf, 'rb');
$img = new imagick(); // [0] can be used to set page number
$img->readImageFile($fp_pdf);
$img->setImageFormat( "jpg" );
$img->setImageCompression(imagick::COMPRESSION_JPEG);
$img->setImageCompressionQuality(90);
$img->setResolution(300,300);
$img->setImageUnits(imagick::RESOLUTION_PIXELSPERINCH);
$data = $img->getImageBlob();
</code></pre>
<p>my source pdf file has right dimension (210x297 mm, like A4 has). And everything looks good.
But my jpg has page dimension as 842x595 px, and DPI is 72.</p>
<p>and img file much more smaller on paper then pdf, when i had print it.</p>
<p>what is a proper way to make image file from pdf and make it so big as pdf (on paper)</p> | 8,697,441 | 5 | 1 | null | 2011-12-24 13:40:08.373 UTC | 12 | 2013-04-23 14:53:54.727 UTC | 2011-12-24 13:43:47.413 UTC | null | 635,608 | null | 1,016,265 | null | 1 | 28 | php|pdf|imagemagick|imagick | 79,154 | <p>ImageMagick uses GhostScript to process JPEGs, so you'd do better to <code>exec</code> GhostScript directly, which would be much more efficient and give you more control. It would also be only 1 <code>exec</code> statement, instead of playing around with the IMagick functions.</p> |
996,198 | Execute Immediate within a stored procedure keeps giving insufficient priviliges error | <p>Here is the definition of the stored procedure:</p>
<pre><code>CREATE OR REPLACE PROCEDURE usp_dropTable(schema VARCHAR, tblToDrop VARCHAR) IS
BEGIN
DECLARE v_cnt NUMBER;
BEGIN
SELECT COUNT(*)
INTO v_cnt
FROM all_tables
WHERE owner = schema
AND table_name = tblToDrop;
IF v_cnt > 0 THEN
EXECUTE IMMEDIATE('DROP TABLE someschema.some_table PURGE');
END IF;
END;
END;
</code></pre>
<p>Here is the call:</p>
<pre><code>CALL usp_dropTable('SOMESCHEMA', 'SOME_TABLE');
</code></pre>
<p>For some reason, I keep getting insufficient privileges error for the EXECUTE IMMEDIATE command. I looked online and found out that the insufficient privileges error usually means the oracle user account does not have privileges for the command used in the query that is passes, which in this case is DROP. However, I have drop privileges. I am really confused and I can't seem to find a solution that works for me.</p>
<p>Thanks to you in advance.</p>
<p>SOLUTION:</p>
<p>As Steve mentioned below, Oracle security model is weird in that it needs to know explicitly somewhere in the procedure what kind of privileges to use. The way to let Oracle know that is to use AUTHID keyword in the CREATE OR REPLACE statement. If you want the same level of privileges as the creator of the procedure, you use AUTHID DEFINER. If you want Oracle to use the privileges of the user currently running the stored procedure, you want to use AUTHID CURRENT_USER. The procedure declaration looks as follows:</p>
<pre><code>CREATE OR REPLACE PROCEDURE usp_dropTable(schema VARCHAR, tblToDrop VARCHAR)
AUTHID CURRENT_USER IS
BEGIN
DECLARE v_cnt NUMBER;
BEGIN
SELECT COUNT(*)
INTO v_cnt
FROM all_tables
WHERE owner = schema
AND table_name = tblToDrop;
IF v_cnt > 0 THEN
EXECUTE IMMEDIATE('DROP TABLE someschema.some_table PURGE');
END IF;
END;
END;
</code></pre>
<p>Thank you everyone for responding. This was definitely very annoying problem to get to the solution.</p> | 996,709 | 4 | 2 | 2009-06-15 13:45:31.403 UTC | 2009-06-15 13:45:31.483 UTC | 10 | 2017-05-18 08:56:17.46 UTC | 2009-06-16 13:51:18.233 UTC | null | 59,968 | null | 59,968 | null | 1 | 41 | sql|stored-procedures|oracle10g|privileges | 116,708 | <p>Oracle's security model is such that when executing dynamic SQL using Execute Immediate (inside the context of a PL/SQL block or procedure), the user does not have privileges to objects or commands that are granted via role membership. Your user likely has "DBA" role or something similar. You must explicitly grant "drop table" permissions to this user. The same would apply if you were trying to select from tables in another schema (such as sys or system) - you would need to grant explicit SELECT privileges on that table to this user.</p> |
25,904,440 | JSPDF - addHTML() Multiple Canvas Page | <p>I noticed already have a release "addHTML() can now split the canvas into multiple pages" which can find through this link : <a href="https://github.com/MrRio/jsPDF/releases/tag/v1.0.138" rel="noreferrer">https://github.com/MrRio/jsPDF/releases/tag/v1.0.138</a>. </p>
<p>May i know how it work? In my case, i just tried it out when click on "save as pdf" button, it just render a single page instead of multiple pages (sometimes didn't worked, i assume because the content is too long to be generated as pdf).</p>
<p>Would appreciate if there are some examples for this case. Thanks!</p>
<p>Attached my codes below:</p>
<pre><code>var pdf = new jsPDF('p', 'pt', 'a4');
pdf.addHTML($(".pdf-wrapper"), function () {
var string = pdf.output('datauristring');
pdf.save("test.pdf");
});
</code></pre> | 25,907,361 | 4 | 0 | null | 2014-09-18 04:59:12.46 UTC | 6 | 2021-08-05 10:16:38.74 UTC | null | null | null | null | 2,939,780 | null | 1 | 15 | javascript|jquery|canvas|html2canvas|jspdf | 79,982 | <p>Splitting canvas into multiple pages work by providing a "pagesplit" option:</p>
<pre><code>var pdf = new jsPDF('p', 'pt', 'a4');
var options = {
pagesplit: true
};
pdf.addHTML($(".pdf-wrapper"), options, function()
{
pdf.save("test.pdf");
});
</code></pre> |
55,627,780 | Evaluating pytorch models: `with torch.no_grad` vs `model.eval()` | <p>When I want to evaluate the performance of my model on the validation set, is it preferred to use <code>with torch.no_grad:</code> or <code>model.eval()</code>?</p> | 55,627,781 | 3 | 1 | null | 2019-04-11 08:16:55.07 UTC | 28 | 2022-01-05 23:37:58.68 UTC | 2021-05-09 13:04:28.813 UTC | null | 9,067,615 | null | 5,353,461 | null | 1 | 59 | python|machine-learning|deep-learning|pytorch|autograd | 18,946 | <h2>TL;DR:</h2>
<p><a href="https://github.com/pytorch/pytorch/issues/19160#issuecomment-482188706" rel="noreferrer">Use <em>both</em></a>. They do different things, and have different scopes.</p>
<ul>
<li><code>with torch.no_grad</code> - disables tracking of gradients in <code>autograd</code>.</li>
<li><code>model.eval()</code> changes the <code>forward()</code> behaviour of the module it is called upon</li>
<li>eg, it disables dropout and has batch norm use the entire population statistics</li>
</ul>
<hr />
<h3><code>with torch.no_grad</code></h3>
<p>The <a href="https://pytorch.org/docs/stable/autograd.html#torch.autograd.no_grad" rel="noreferrer"><code>torch.autograd.no_grad</code> documentation</a> says:</p>
<blockquote>
<p>Context-manager that disabled [sic] gradient calculation.</p>
</blockquote>
<blockquote>
<p>Disabling gradient calculation is useful for inference, when you are sure that you will not call <code>Tensor.backward()</code>. It will reduce memory consumption for computations that would otherwise have <code>requires_grad=True</code>. In this mode, the result of every computation will have <code>requires_grad=False</code>, even when the inputs have <code>requires_grad=True</code>.</p>
</blockquote>
<h3><code>model.eval()</code></h3>
<p>The <a href="https://pytorch.org/docs/stable/nn.html#torch.nn.Module.eval" rel="noreferrer"><code>nn.Module.eval</code> documentation</a> says:</p>
<blockquote>
<p>Sets the module in evaluation mode.</p>
</blockquote>
<blockquote>
<p>This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g. <code>Dropout</code>, <code>BatchNorm</code>, etc.</p>
</blockquote>
<hr />
<p><a href="https://github.com/pytorch/pytorch/issues/19160#issuecomment-482188706" rel="noreferrer">The creator of pytorch said the documentation should be updated to suggest the usage of both</a>, and I raised the <a href="https://github.com/pytorch/pytorch/pull/46173" rel="noreferrer">pull request</a>.</p> |
19,517,538 | Ignoring SSL certificate in Apache HttpClient 4.3 | <p>How to ignore SSL certificate (trust all) for <a href="http://hc.apache.org/httpcomponents-client-4.3.x/index.html" rel="noreferrer">Apache HttpClient 4.3</a>?</p>
<p>All the answers that I have found on SO treat previous versions, and the API changed.</p>
<p>Related:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/2703161/how-to-ignore-ssl-certificate-errors-in-apache-httpclient-4-0">How to ignore SSL certificate errors in Apache HttpClient 4.0</a></li>
<li><a href="https://stackoverflow.com/questions/1828775/how-to-handle-invalid-ssl-certificates-with-apache-httpclient">How to handle invalid SSL certificates with Apache HttpClient?</a></li>
<li><a href="https://stackoverflow.com/questions/6789597/need-to-trust-all-the-certificates-during-the-development-using-spring">Need to trust all the certificates during the development using Spring</a></li>
<li><a href="https://stackoverflow.com/questions/12060250/ignore-ssl-certificate-errors-with-java">Ignore SSL Certificate Errors with Java</a></li>
</ul>
<p>Edit:</p>
<ul>
<li>It is only for test purposes. Kids, don't try it at home (or in production)</li>
</ul> | 19,518,383 | 16 | 0 | null | 2013-10-22 12:12:01.407 UTC | 67 | 2020-09-03 21:53:44.88 UTC | 2017-05-23 12:10:29.88 UTC | null | -1 | null | 497,208 | null | 1 | 111 | java|ssl|apache-httpcomponents | 212,000 | <p>The code below works for trusting self-signed certificates. You have to use the <a href="http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/conn/ssl/TrustSelfSignedStrategy.html" rel="noreferrer">TrustSelfSignedStrategy</a> when creating your client:</p>
<pre><code>SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
builder.build());
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(
sslsf).build();
HttpGet httpGet = new HttpGet("https://some-server");
CloseableHttpResponse response = httpclient.execute(httpGet);
try {
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
} finally {
response.close();
}
</code></pre>
<p>I did not include the <code>SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER</code> on purpose: The point was to allow testing with self signed certificates so you don't have to acquire a proper certificate from a certification authority. You can easily create a self-signed certificate with the correct host name, so do that instead of adding the <code>SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER</code> flag.</p> |
33,749,792 | Changing TabLayout icons on left, top, right or bottom in com.android.support:design:23.1.0 | <p>I'm pretty new to android development. So bear with me.</p>
<p>I've been trying to align the icon and text in same line in <strong>com.android.support:design:23.1.0</strong> for a day.</p>
<p>Apparently in com.android.support:design:<strong>23.1.0</strong> they've changed the default icon position to top and text on the bottom.</p>
<p>Previously in com.android.support:design:<strong>23.0.1</strong> the default was the icon on left and text in same line as the icon</p>
<p>So here's an <em>easy way</em> to solve it (though it might have drawbacks, idk tbh):</p>
<pre><code>change the version in your app's build.gradle. ex: 23.1.0 to 23.0.1 and build.
</code></pre>
<p>And there's a better way to do it (this way you can also align icons on left,right,top,bottom):</p>
<ol>
<li>create a <strong>custom_tab.xml</strong> in <strong>res/layout</strong></li>
</ol>
<pre class="lang-xml prettyprint-override"><code><TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAlignment="center"/>
</code></pre>
<p>2. in your activity java</p>
<pre class="lang-java prettyprint-override"><code>TextView newTab = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
newTab.setText("tab1"); //tab label txt
newTab.setCompoundDrawablesWithIntrinsicBounds(your_drawable_icon_here, 0, 0, 0);
tabLayout.getTabAt(tab_index_here_).setCustomView(newTab);
</code></pre>
<p>So far I've achieved to make icons appear on any side like this:</p>
<p><a href="https://i.stack.imgur.com/NcWf6.png"><img src="https://i.stack.imgur.com/NcWf6.png" alt="TabLayout icons"></a></p>
<p>PS: <strong>setCompoundDrawablesWithIntrinsicBounds</strong> function arguments are 4 side icons like this:
</p>
<pre><code>setCompoundDrawablesWithIntrinsicBounds(leftDrawable, topDrawable, rightDrawable, bottomDrawable)
</code></pre> | 41,642,954 | 4 | 1 | null | 2015-11-17 05:27:45.917 UTC | 15 | 2022-01-18 23:42:12.69 UTC | 2015-12-16 09:42:06.81 UTC | null | 3,040,429 | null | 3,040,429 | null | 1 | 31 | android|android-support-library|android-tablayout|android-support-design | 21,283 | <p>Thank you Atu for this good tip!</p>
<p>In my case, I have to add a linear layout to center tablayout title. I have also added some space characters to get margin between the icon and the text.</p>
<p><strong>custom_tab.xml:</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:id="@+id/tabContent"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textAlignment="center"
android:textColor="@android:color/white"
android:gravity="center"/>
</LinearLayout>
</code></pre>
<p><strong>Initialization code:</strong></p>
<pre><code>LinearLayout tabLinearLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
TextView tabContent = (TextView) tabLinearLayout.findViewById(R.id.tabContent);
tabContent.setText(" "+getApplicationContext().getResources().getString(tabTitles[i]));
tabContent.setCompoundDrawablesWithIntrinsicBounds(tabIcons[i], 0, 0, 0);
mTabLayout.getTabAt(i).setCustomView(tabContent);
</code></pre> |
22,949,300 | Partial animal string matching in R | <p>I have a dataframe,</p>
<pre><code>d<-data.frame(name=c("brown cat", "blue cat", "big lion", "tall tiger",
"black panther", "short cat", "red bird",
"short bird stuffed", "big eagle", "bad sparrow",
"dog fish", "head dog", "brown yorkie",
"lab short bulldog"), label=1:14)
</code></pre>
<p>I'd like to search the <code>name</code> column and if the words
"cat", "lion", "tiger", and "panther" appear, I want to assign the character string <code>feline</code> to a new column and corresponding row <code>species</code>.</p>
<p>If the words <code>"bird", "eagle", and "sparrow"</code> appear, I want to assign the character string <code>avian</code> to a new column and corresponding row <code>species</code>.</p>
<p>If the words "dog", "yorkie", and "bulldog" appear, I want to assign the character string <code>canine</code> to a new column and corresponding row <code>species</code>.</p>
<p>Ideally, I'd store this in a list or something similar that I can keep at the beginning of the script, because as new variants of the species show up in the name category, it would be nice to have easy access to update what qualifies as a <code>feline</code>, <code>avian</code>, and <code>canine</code>.</p>
<p>This question is almost answered here (<em><a href="https://stackoverflow.com/questions/19747384/how-to-create-new-column-in-dataframe-based-on-partial-string-matching-other-col">How to create new column in dataframe based on partial string matching other column in R</a></em>), but it doesn't address the multiple name twist that is present in this problem.</p> | 22,949,536 | 3 | 0 | null | 2014-04-08 22:18:59.713 UTC | 9 | 2021-11-13 16:07:43.263 UTC | 2017-05-28 13:27:42.353 UTC | null | 63,550 | null | 3,033,594 | null | 1 | 16 | r|string|dataframe|matching | 28,489 | <p>There may be a more elegant solution than this, but you could use <code>grep</code> with <code>|</code> to specify alternative matches.</p>
<pre><code>d[grep("cat|lion|tiger|panther", d$name), "species"] <- "feline"
d[grep("bird|eagle|sparrow", d$name), "species"] <- "avian"
d[grep("dog|yorkie", d$name), "species"] <- "canine"
</code></pre>
<p>I've assumed you meant "avian", and left out "bulldog" since it contains "dog".</p>
<p>You might want to add <code>ignore.case = TRUE</code> to the grep.</p>
<p>output:</p>
<pre><code># name label species
#1 brown cat 1 feline
#2 blue cat 2 feline
#3 big lion 3 feline
#4 tall tiger 4 feline
#5 black panther 5 feline
#6 short cat 6 feline
#7 red bird 7 avian
#8 short bird stuffed 8 avian
#9 big eagle 9 avian
#10 bad sparrow 10 avian
#11 dog fish 11 canine
#12 head dog 12 canine
#13 brown yorkie 13 canine
#14 lab short bulldog 14 canine
</code></pre> |
29,926,773 | Run shell command in jenkins as root user? | <p>I have recently started using Jenkins for integration. All was well until I was running jobs on master node without shell command but I have to run jobs on master as well as slave node which contains shell commands to. I am not able to run those shell commands as root user. I have tried</p>
<ol>
<li>Using <code>SSH Keys</code>. </li>
<li>Setting user name in shell commands. </li>
<li>Using <code>sudo</code>.</li>
</ol>
<p>I am getting <code>permission denied</code> error every time I use any of the above methods.</p> | 29,927,081 | 5 | 0 | null | 2015-04-28 18:05:32.767 UTC | 13 | 2022-01-07 12:00:11.487 UTC | 2015-04-28 18:23:48.927 UTC | null | 4,673,106 | null | 4,673,106 | null | 1 | 18 | linux|shell|jenkins|root | 99,008 | <p>You need to modify the permission for <code>jenkins</code> user so that you can run the shell commands.
You can install the jenkins as as service (download the rpm package), You might need to change the ports because by default it runs http on 8080 and AJP on 8009 port.</p>
<p><br><br>
Following process is for <code>CentOS</code><br>
1. Open up the this script (using VIM or other editor):</p>
<pre><code>vim /etc/sysconfig/jenkins
</code></pre>
<p>2. Find this <code>$JENKINS_USER</code> and change to “root”:</p>
<pre><code>$JENKINS_USER="root"
</code></pre>
<p>3. Then change the ownership of Jenkins home, webroot and logs:</p>
<pre><code>chown -R root:root /var/lib/jenkins
chown -R root:root /var/cache/jenkins
chown -R root:root /var/log/jenkins
</code></pre>
<p>4) Restart Jenkins and check the user has been changed:</p>
<pre><code>service jenkins restart
ps -ef | grep jenkins
</code></pre>
<h2>Now you should be able to run the Jenkins jobs as the root user and all the shell command will be executed as <code>root</code>.</h2> |
20,521,737 | How to check if connected to database in Laravel 4? | <p>How can I check if laravel is connected to the database? I've searched around and I can't find anything that would tell me how this is done.</p> | 20,522,337 | 3 | 0 | null | 2013-12-11 14:27:23.977 UTC | 9 | 2015-11-06 07:07:43.453 UTC | 2013-12-11 16:26:46.01 UTC | null | 1,959,747 | null | 1,318,205 | null | 1 | 23 | laravel|laravel-4 | 25,675 | <p>You can use </p>
<pre><code>if(DB::connection()->getDatabaseName())
{
echo "Connected sucessfully to database ".DB::connection()->getDatabaseName().".";
}
</code></pre>
<p>It will give you the database name for the connected database, so you can use it to check if your app is connected to it.</p>
<p>But... Laravel will only connect to database once it needs something from database and, at the time of a connection try, if it finds any errors it will raise a <code>PDOException</code>, so this is what you can do to redirect your user to a friendly page:</p>
<pre><code>App::error(function(PDOException $exception)
{
Log::error("Error connecting to database: ".$exception->getMessage());
return "Error connecting to database";
});
</code></pre>
<p>Add this to your <code>app/filters.php</code> file.</p>
<p>In my opinion, you don't really need to check if it is connceted or not, just take the proper action in the exception handling closure.</p> |
17,901,504 | Navigation drawer - disable swipe | <p>Is there any way to disable swipe gesture to open navigation drawer? Its really annoying when menu appears while swiping between tabs.</p> | 17,902,303 | 1 | 0 | null | 2013-07-27 19:14:17.39 UTC | 16 | 2014-11-24 09:54:00.48 UTC | null | null | null | null | 2,287,404 | null | 1 | 93 | android | 37,172 | <p>You can use </p>
<p><code>mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);</code></p>
<p>to lock your <code>DrawerLayout</code> so it won't be able to open with gestures. And unlock it with: </p>
<p><code>mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);</code></p>
<p>Here you can find more info about <code>DrawerLayout</code>: <a href="http://developer.android.com/reference/android/support/v4/widget/DrawerLayout.html" rel="noreferrer">Android API - DrawerLayout</a></p> |
36,200,143 | The subscription is not registered to use namespace 'Microsoft.DataFactory error | <p>Going through <a href="https://azure.microsoft.com/en-us/documentation/articles/data-factory-get-started-using-vs/" rel="noreferrer">this tutorial</a> "Create a pipeline with Copy Activity using Visual Studio"
and recieving this error when i hit publish.</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Creating datafactory-Name:VSTutorialFactory,Tags:,Subscription:Pay-As-You-Go,ResourceGroup:MyAppGroup,Location:North Europe,
24/03/2016 11:30:34- Error creating data factory:
Microsoft.WindowsAzure.CloudException: MissingSubscriptionRegistration:
The subscription is not registered to use namespace 'Microsoft.DataFactory'.</code></pre>
</div>
</div>
</p>
<p>Error not mentioned anywhere on net and very little help/knowledge on azure generally on web.</p> | 36,200,351 | 9 | 0 | null | 2016-03-24 12:23:49.073 UTC | 11 | 2021-08-02 00:36:28.407 UTC | null | null | null | null | 964,787 | null | 1 | 67 | visual-studio|azure|azure-data-factory | 66,713 | <p>In Azure, for each functionality there's a resource provider (Microsoft.DataFactory for example). </p>
<p>By default, your Azure Subscription is not registered with all resource providers and because your Subscription is not registered with <code>Microsoft.DataFactory</code> resource provider, you're getting this error. </p>
<p>What you have to do is manually register your subscription with a resource provider. If you're using Azure PowerShell, you can use <code>Register-AzureRmResourceProvider</code> Cmdlet to achieve the same. You would need to use syntax like below:</p>
<pre><code>Register-AzureRmResourceProvider -ProviderNamespace Microsoft.DataFactory
</code></pre>
<p>Once your Subscription is registered with this resource provider, this error will go away.</p> |
35,958,826 | Swift Images change to wrong images while scrolling after async image loading to a UITableViewCell | <p>I'm trying to async load pictures inside my FriendsTableView (UITableView) cell. The images load fine but when I'll scroll the table the images will change a few times and wrong images are getting assigned to wrong cells. </p>
<p>I've tried all methods I could find in StackOverflow including adding a tag to the raw and then checking it but that didn't work. I'm also verifying the cell that should update with indexPath and check if the cell exists. So I have no idea why this is happening.</p>
<p>Here is my code:</p>
<pre><code> func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("friendCell", forIndexPath: indexPath) as! FriendTableViewCell
var avatar_url: NSURL
let friend = sortedFriends[indexPath.row]
//Style the cell image to be round
cell.friendAvatar.layer.cornerRadius = 36
cell.friendAvatar.layer.masksToBounds = true
//Load friend photo asyncronisly
avatar_url = NSURL(string: String(friend["friend_photo_url"]))!
if avatar_url != "" {
getDataFromUrl(avatar_url) { (data, response, error) in
dispatch_async(dispatch_get_main_queue()) { () -> Void in
guard let data = data where error == nil else { return }
let thisCell = tableView.cellForRowAtIndexPath(indexPath)
if (thisCell) != nil {
let updateCell = thisCell as! FriendTableViewCell
updateCell.friendAvatar.image = UIImage(data: data)
}
}
}
}
cell.friendNameLabel.text = friend["friend_name"].string
cell.friendHealthPoints.text = String(friend["friend_health_points"])
return cell
}
</code></pre> | 35,958,896 | 12 | 0 | null | 2016-03-12 14:26:06.853 UTC | 9 | 2020-10-14 06:39:05.327 UTC | 2016-03-12 14:31:27.46 UTC | null | 4,065,477 | null | 4,065,477 | null | 1 | 17 | ios|swift|image|uitableview|asynchronous | 18,411 | <p>This is because UITableView reuses cells. Loading them in this way causes the async requests to return at different time and mess up the order.</p>
<p>I suggest that you use some library which would make your life easier like Kingfisher. It will download and cache images for you. Also you wouldn't have to worry about async calls.</p>
<p><a href="https://github.com/onevcat/Kingfisher" rel="noreferrer">https://github.com/onevcat/Kingfisher</a></p>
<p>Your code with it would look something like this:</p>
<pre><code>func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("friendCell", forIndexPath: indexPath) as! FriendTableViewCell
var avatar_url: NSURL
let friend = sortedFriends[indexPath.row]
//Style the cell image to be round
cell.friendAvatar.layer.cornerRadius = 36
cell.friendAvatar.layer.masksToBounds = true
//Load friend photo asyncronisly
avatar_url = NSURL(string: String(friend["friend_photo_url"]))!
if avatar_url != "" {
cell.friendAvatar.kf_setImageWithURL(avatar_url)
}
cell.friendNameLabel.text = friend["friend_name"].string
cell.friendHealthPoints.text = String(friend["friend_health_points"])
return cell
}
</code></pre> |
43,590,808 | Incompatible units: 'rem' and 'px' - Bootstrap 4 and Laravel Mix | <p>I just installed a fresh Laravel 5.4, and bootstrap 4 alpha 6. Laravel mix wont compile SASS:
Here is one error:</p>
<pre><code> Module build failed: ModuleBuildError: Module build failed:
$input-height: (($font-size-base * $input-line-height) + ($input-padding-y * 2)) !default;
^
Incompatible units: 'rem' and 'px'.
in /Volumes/HDD/nicolae/Dev/htdocs/test/node_modules/bootstrap/scss/_variables.scss (line 444, column 34)
at runLoaders (/Volumes/HDD/nicolae/Dev/htdocs/test/node_modules/webpack/lib/NormalModule.js:192:19)
at /Volumes/HDD/nicolae/Dev/htdocs/test/node_modules/loader-runner/lib/LoaderRunner.js:364:11
at /Volumes/HDD/nicolae/Dev/htdocs/test/node_modules/loader-runner/lib/LoaderRunner.js:230:18
at context.callback (/Volumes/HDD/nicolae/Dev/htdocs/test/node_modules/loader-runner/lib/LoaderRunner.js:111:13)
at Object.asyncSassJobQueue.push [as callback] (/Volumes/HDD/nicolae/Dev/htdocs/test/node_modules/sass-loader/lib/loader.js:57:13)
at Object.<anonymous> (/Volumes/HDD/nicolae/Dev/htdocs/test/node_modules/sass-loader/node_modules/async/dist/async.js:2262:31)
at apply (/Volumes/HDD/nicolae/Dev/htdocs/test/node_modules/sass-loader/node_modules/async/dist/async.js:20:25)
at Object.<anonymous> (/Volumes/HDD/nicolae/Dev/htdocs/test/node_modules/sass-loader/node_modules/async/dist/async.js:56:12)
at Object.callback (/Volumes/HDD/nicolae/Dev/htdocs/test/node_modules/sass-loader/node_modules/async/dist/async.js:944:16)
at options.error (/Volumes/HDD/nicolae/Dev/htdocs/test/node_modules/node-sass/lib/index.js:294:32)
@ multi ./resources/assets/js/app.js ./resources/assets/sass/app.scss
</code></pre>
<p>Someone passed this? And how?</p> | 43,597,016 | 4 | 0 | null | 2017-04-24 14:28:01.38 UTC | 2 | 2022-06-25 12:12:09.95 UTC | null | null | null | null | 4,273,925 | null | 1 | 27 | laravel|webpack|bootstrap-4|bootstrap-sass | 41,023 | <p>Solved </p>
<ol>
<li>remove the bootstrap entry from package.json and replace it with
"bootstrap": "4.0.0-alpha.6", in resources/assets/sass/app.scss, </li>
<li>comment out the import of variables. change the path of bootstrap to
@import "node_modules/bootstrap/scss/bootstrap.scss"; </li>
<li>in resources/assets/js/bootstrap.js, look for require('bootsrap-sass');
and change it to require('bootstrap');</li>
</ol>
<p><a href="https://laracasts.com/discuss/channels/tips/tip-using-bootstrap-4-alpha-6-with-laravel-54" rel="noreferrer">Link!</a></p> |
49,500,339 | Can't prevent `touchmove` from scrolling window on iOS | <p>We are trying to scroll an element on our iOS web app while preventing the window itself from scrolling. We are capturing the <code>touchmove</code> event on the window, scrolling the element programmatically and (trying to) prevent the window itself from scroll by calling <code>preventDefault</code> on the event.</p>
<p>Unfortunately this doesn't work in Mobile Safari. The window continues to scroll underneath our element. The issue sounds exactly like the Webkit bug described in <a href="https://bugs.webkit.org/show_bug.cgi?id=163207" rel="noreferrer">https://bugs.webkit.org/show_bug.cgi?id=163207</a>, but that issue was supposedly fixed in iOS 10.3 whereas I am running 11.3.</p>
<p>Catching <code>touchforcestart</code> and calling <code>preventDefault</code> does seem to prevent scrolling of the window, but we are calling it in <code>touchstart</code>, which seems to be "too late" since the window still scrolls. Scrolling is only prevented next time <code>touchstart</code> is called.</p>
<p>Any ideas about what is going on? We are baffled since this is clearly a bug but it seems to have been fixed some time ago.</p> | 49,582,193 | 3 | 0 | null | 2018-03-26 20:46:50.33 UTC | 15 | 2022-04-06 07:24:46.48 UTC | null | null | null | null | 502,149 | null | 1 | 35 | ios|scroll|mobile-safari|preventdefault|touchmove | 25,308 | <p>I recently ran into this same problem. You'll need to pass <code>{ passive: false }</code> when registering the <code>touchmove</code> event listener. e.g.</p>
<pre class="lang-js prettyprint-override"><code>document.addEventListener('touchmove', function(e) {
e.preventDefault();
}, { passive: false });
</code></pre>
<p>This is because document touch event listeners are now passive by default in Safari 11.1, which is bundled with iOS 11.3. This change is documented in the Safari 11.1 <a href="https://developer.apple.com/library/content/releasenotes/General/WhatsNewInSafari/Articles/Safari_11_1.html" rel="noreferrer">release notes</a>:</p>
<blockquote>
<h2>Web APIs<br></h2>
<ul>
<li>[...]</li>
<li>Updated root document touch event listeners to use passive mode improving scrolling performance and reducing crashes.</li>
</ul>
</blockquote> |
46,121,467 | Differentiate implicit broadcast receiver vs explicit broadcast receiver in the manifest | <p>According to the migration guide to Android O given by Google, most of the implicit broadcast intent should not be registered in the Manifest (minus a few exceptions found <a href="https://developer.android.com/guide/components/broadcast-exceptions.html" rel="noreferrer">here</a>) but explicit broadcast intents remain untouched.</p>
<p>We are looking to move any needed broadcast away from the manifest. But how do we recognise if a receiver is implicit? Is there a general rule?</p>
<p>Here is a sample of the broadcasts we register in the manifest. Should we look only at the "action" tag and see if it is whitelisted to keep it in the manifest?</p>
<pre><code><receiver
android:name=".receiver.ImageBroadcastReceiver"
android:enabled="true" >
<intent-filter>
<action android:name="android.hardware.action.NEW_PICTURE" />
<category android:name="android.intent.category.OPENABLE" />
<data android:mimeType="image/*" />
</intent-filter>
</receiver>
<receiver
android:name=".receiver.InstallReferrerReceiver"
android:exported="true">
<intent-filter>
<action android:name="com.android.vending.INSTALL_REFERRER" />
</intent-filter>
</receiver>
<receiver android:name=".receiver.JoinEventReceiver" >
<intent-filter>
<action android:name="JOIN_ACTION" />
<action android:name="CANCEL_ACTION" />
<action android:name="DECLINE_ACTION" />
</intent-filter>
</receiver>
</code></pre>
<p>For example, the "com.android.vending.INSTALL_REFERRER" intent is not whitelisted. Should we register it in an Activity? If so wouldn't it be never fired as when we register it the app is already installed? This is what confuses me when trying to understand if a broadcast receiver is implicit or explicit as I thought I only had to check that "action" tag.</p> | 46,121,548 | 1 | 0 | null | 2017-09-08 17:07:27.71 UTC | 9 | 2018-01-11 10:18:11.07 UTC | 2018-01-11 10:18:11.07 UTC | null | 3,413,324 | null | 3,413,324 | null | 1 | 28 | android|android-intent|android-manifest|android-broadcast|android-8.0-oreo | 19,387 | <blockquote>
<p>But how do we recognise if a receiver is implicit?</p>
</blockquote>
<p>If the <code>Intent</code> has a <code>ComponentName</code>, the <code>Intent</code> is explicit. Otherwise, it is implicit.</p>
<p>That <code>ComponentName</code> can be obtained in one of a few ways, including:</p>
<ul>
<li><p>It can be directly put on the <code>Intent</code> (e.g., <code>new Intent(this, TheReallyAwesomeReceiver.class</code>)</p></li>
<li><p>It can be directly put on the <code>Intent</code> after using <code>PackageManager</code> and <code>queryIntentReceivers()</code> to find the right one based on action strings, etc.</p></li>
<li><p>It can be derived by the system from the action string, etc. plus the package defined via <code>setPackage()</code></p></li>
</ul>
<blockquote>
<p>Should we look only at the "action" tag and see if it is whitelisted to keep it in the manifest?</p>
</blockquote>
<p>No. You also need to think about the nature of the broadcast: is it going to <em>any</em> registered receiver, or only to a specific app?</p>
<blockquote>
<p>For example, the "com.android.vending.INSTALL_REFERRER" intent is not whitelisted. Should we register it in an Activity?</p>
</blockquote>
<p>No. That broadcast will only go to the app that was recently installed, and so it must be an explicit <code>Intent</code>. The action string and such are there to help the system determine which of your registered receivers is the relevant one.</p>
<p>Contrast that with <code>ACTION_PACKAGE_ADDED</code>. That is broadcast to any registered receiver; it is not going to just one specific app. Hence, that <code>Intent</code> must be implicit (as otherwise it would have a <code>ComponentName</code> identifying a specific receiver in a specific app). And, since <code>ACTION_PACKAGE_ADDED</code> is not on the whitelist, the assumption should be that you cannot register for this broadcast in the manifest on Android 8.0+.</p> |
37,514,603 | Hyper-parameter tuning using pure ranger package in R | <p>Love the speed of the ranger package for random forest model creation, but can't see how to tune mtry or number of trees. I realize I can do this via caret's train() syntax, but I prefer the speed increase that comes from using pure ranger.</p>
<p>Here's my example of basic model creation using ranger (which works great):</p>
<pre><code>library(ranger)
data(iris)
fit.rf = ranger(
Species ~ .,
training_data = iris,
num.trees = 200
)
print(fit.rf)
</code></pre>
<p>Looking at the official documentation for tuning options, it seems like the csrf() function may provide the ability to tune hyper-parameters, but I can't get the syntax right:</p>
<pre><code>library(ranger)
data(iris)
fit.rf.tune = csrf(
Species ~ .,
training_data = iris,
params1 = list(num.trees = 25, mtry=4),
params2 = list(num.trees = 50, mtry=4)
)
print(fit.rf.tune)
</code></pre>
<p>Results in: </p>
<pre><code>Error in ranger(Species ~ ., training_data = iris, num.trees = 200) :
unused argument (training_data = iris)
</code></pre>
<p>And I'd prefer to tune with the regular (read: non-csrf) rf algorithm ranger provides. Any idea as to a hyper-parameter tuning solution for either path in ranger? Thank you!</p> | 37,514,982 | 5 | 0 | null | 2016-05-29 20:24:50.197 UTC | 12 | 2020-08-03 07:22:30.62 UTC | 2016-05-29 20:58:34.453 UTC | null | 5,636,012 | null | 5,636,012 | null | 1 | 11 | r|model|random-forest|hyperparameters | 11,904 | <p>I think there are at least two errors:</p>
<p>First, the function <code>ranger</code> does not have a parameter called <code>training_data</code>. Your error message <code>Error in ranger(Species ~ ., training_data = iris, num.trees = 200) : unused argument (training_data = iris)</code> refers to that. You can see that when you look at <code>?ranger</code> or <code>args(ranger)</code>.</p>
<p>Second, the function <code>csrf</code>, on the other hand, has <code>training_data</code> as input, but also requires <code>test_data</code>. Most importantly, these two arguments do not have any defaults, implying that you must provide them. The following works without problems:</p>
<pre><code>fit.rf = ranger(
Species ~ ., data = iris,
num.trees = 200
)
fit.rf.tune = csrf(
Species ~ .,
training_data = iris,
test_data = iris,
params1 = list(num.trees = 25, mtry=4),
params2 = list(num.trees = 50, mtry=4)
)
</code></pre>
<p>Here, I have just provided <code>iris</code> as both training and test dataset. You would obviously not want to do that in your real application. Moreover, note that <code>ranger</code> also take <code>num.trees</code> and <code>mtry</code> as input, so you could try tuning it there. </p> |
35,438,104 | JavaFX alignment of Label in GridPane | <p>I'm confused as to why setting the Label.setAlignment(Pos.CENTER_RIGHT) does not affect the alignment of a label that is then added into a GridPane? The only way to do it is seemingly through the grid (e.g. ColumnConstraints) or by e.g. adding the Label to a HBox that has right alignment.</p>
<p>Why does setting the alignment of the label to CENTER_RIGHT have no effect? I can see the API says: "Specifies how the text and graphic within the Labeled should be aligned when there is empty space within the Labeled." But how do I get empty space in a label?</p> | 35,438,985 | 1 | 0 | null | 2016-02-16 16:40:13.277 UTC | 2 | 2016-02-16 20:13:04.787 UTC | null | null | null | null | 3,780,370 | null | 1 | 18 | javafx|grid|alignment|label | 44,159 | <p><strong>TL:DR version</strong>: instead of <code>label.setAlignment(Pos.CENTER_RIGHT);</code> use <code>GridPane.setHalignment(label, HPos.RIGHT);</code>.</p>
<p>JavaFX uses a top-down layout. So the scene sizes the root node to the size of the scene, the root node sizes and positions each of its child nodes depending on its layout strategy and the amount of space the scene gave it, each child node then sizes and positions its child nodes depending on its own layout strategy and the amount of space it has available, and so on down the scene graph.</p>
<p>According to the documentation for <a href="http://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Labeled.html#alignmentProperty--" rel="noreferrer"><code>Label</code></a>, the <code>alignmentProperty</code> </p>
<blockquote>
<p>Specifies how the text and graphic within the Labeled should be aligned when there is empty space within the Labeled.</p>
</blockquote>
<p>Of course, the amount of space available to the label is determined by its parent, which in this case is the grid pane. You can of course find out about the grid pane's layout strategy and how to configure it by reading its <a href="http://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/GridPane.html" rel="noreferrer">documentation</a>. In brief, though:</p>
<p>By default, a grid pane will allocate each node its preferred size, and, if the cell it's placed in has additional space, will align the node in the top left of the grid cell. The preferred size for a label is of course the computed size: just big enough to hold its content. Hence you see that simply placing a label into a grid pane and setting alignment on the label will not have any effect, because the label is sized just large enough to hold its content, and there is no extra space to align the text/graphic. You can visualize this by placing a background color or border on the label.</p>
<p>So you could set the alignment on the label to <code>CENTER_RIGHT</code>, and then instruct the grid pane to let the label grow. This needs two things: first, tell the grid pane to let the label fill the width of the cell:</p>
<pre><code>GridPane.setFillWidth(label, true);
</code></pre>
<p>and, since the grid pane will also respect the child node's maximum size, and the label by default uses its preferred size as its maximum size, allow the label to grow:</p>
<pre><code>label.setMaxWidth(Double.MAX_VALUE);
</code></pre>
<p>Then the label will grow to the size of the cell, and so if you also have</p>
<pre><code>label.setAlignment(Pos.CENTER_RIGHT);
</code></pre>
<p>it will align its own content to the right.</p>
<p>A more sensible approach is probably just to tell the grid pane how to align the label in the cell:</p>
<pre><code>GridPane.setHalignment(label, HPos.RIGHT);
</code></pre>
<p>Then let the label take on its default size and alignment and everything will work.</p>
<p>You can also use a <code>ColumnConstraints</code> object to set the default alignment for all labels in a particular column, which is by far the more convenient approach if you are building a form.</p> |
37,464,966 | What causes deprecation warning: ActiveRecord::Base.raise_in_transactional_callbacks=? | <p>I get this message when I run my feature specs:</p>
<blockquote>
<p>DEPRECATION WARNING: ActiveRecord::Base.raise_in_transactional_callbacks= is deprecated, has no effect and will be removed without replacement.</p>
</blockquote>
<p>I am using Rails 5.0.0.rc1 and am not sure what is throwing this deprecation warning. </p>
<p>I had this in my <code>application.rb</code> file. I removed it and the deprecation warning went away:</p>
<pre><code>config.active_record.raise_in_transactional_callbacks = true
</code></pre>
<p>I'd like tips on what this deprecation warning actually means and to know what triggers this deprecation warning.</p> | 37,465,836 | 2 | 1 | null | 2016-05-26 15:20:39.51 UTC | 1 | 2019-01-02 11:35:42.423 UTC | 2016-05-26 16:04:59.88 UTC | null | 567,762 | null | 4,044,009 | null | 1 | 28 | ruby-on-rails|ruby | 13,284 | <p>I believe this behaviour was added between 4.1 and 4.2 as a temporary solution to a problem which is no longer relevant in rails 5:</p>
<p><a href="http://edgeguides.rubyonrails.org/upgrading_ruby_on_rails.html#error-handling-in-transaction-callbacks" rel="noreferrer">http://edgeguides.rubyonrails.org/upgrading_ruby_on_rails.html#error-handling-in-transaction-callbacks</a></p>
<blockquote>
<p>Currently, Active Record suppresses errors raised within
after_rollback or after_commit callbacks and only prints them to the
logs. In the next version, these errors will no longer be suppressed.
Instead, the errors will propagate normally just like in other Active
Record callbacks.</p>
<p>When you define an after_rollback or after_commit callback, you will
receive a deprecation warning about this upcoming change. When you are
ready, you can opt into the new behavior and remove the deprecation
warning by adding following configuration to your
config/application.rb:</p>
<p><code>config.active_record.raise_in_transactional_callbacks = true</code></p>
</blockquote>
<p>For clarification, as @pixelearth suggests my comment below isn't clear/prominent enough. In Rails 5 and later remove the line from <code>config/application.rb</code>:</p>
<blockquote>
<p><code>config.active_record.raise_in_transactional_callbacks = true</code></p>
</blockquote> |
20,756,320 | How to prevent phabricator from eating my commit history | <p>Here is the scenario that is pretty much annoying me.</p>
<p>Jack works in foobar a software house, Jack is a <a href="http://www.codinghorror.com/blog/2009/04/the-eight-levels-of-programmers.html">Working Programmer</a>, he loves coding and commits frequently. Paul who is jack's manager tells him that we are going to start using a new code review tool, phabricator. Jack complies, Jack creates a local branch and starts working. He adds features and commits to his local branch very frequently. Now at the end of the day he sends a phabricator request.</p>
<pre><code>arc diff development
</code></pre>
<p>John who is jacks team member reviews his code and accepts his changes.
Now Jack opens the terminal and moves to his repository directory.
Jack types the following command to close the revision and merge his code with the development branch.</p>
<pre><code>arc land --onto development
</code></pre>
<p>He sees the following message</p>
<pre><code>Landing current branch 'feature-awesome-features'.
Switched to branch development. Updating branch...
The following commit(s) will be landed:
b2ff76e Added the foo to bar
33f33ba Added a really important check which can destroy the project or save it
31a4c9a Added that new awesome feature
8cae3bf rewrote that awful code john wrote
bc54afb bug fixes
Switched to branch feature-awesome-features. Identifying and merging...
Landing revision 'D1067: Added the awesome feature'...
Rebasing feature-awesome-features onto development
Already up-to-date.
Pushing change...
</code></pre>
<p>Now jack opens Github to see his code , his beautiful commits. but what he sees is pure horror all of his commits have been replaced by a single commit which basically says something like this</p>
<pre><code>Summary: Added the awesome feature
Test Plan: do foo bar testing
Reviewers: John
Reviewed By: John
CC: Paul
Differential Revision: http://phabricator.foobar.com/D1067
</code></pre>
<p>Now jack is sad, because he wants to see all of his commits, jack thinks that this commit makes him look like <a href="http://www.aaronstannard.com/post/2013/12/19/The-Taxonomy-of-Terrible-Programmers.aspx">The Hoarder</a> which he is not. He wants to fix this so he goes to ask a question on stackoverflow.</p>
<pre><code>That how may he prevent phabricator from eating his commit history.
</code></pre> | 20,756,986 | 7 | 1 | null | 2013-12-24 06:55:57.083 UTC | 7 | 2020-07-18 15:49:26.577 UTC | 2016-11-03 13:53:18.9 UTC | null | 590,534 | null | 421,031 | null | 1 | 35 | git|github|phabricator | 8,712 | <p>You should use the native git flow such as <code>git merge</code> and <code>git push</code> directly instead. From phabricator <a href="http://www.phabricator.com/docs/phabricator/article/Arcanist_User_Guide_arc_diff.html" rel="nofollow">arc documentation</a>:</p>
<blockquote>
<p>After changes have been accepted, you generally push them and close
the revision. arc has several workflows which help with this, by:</p>
<pre><code>* squashing or merging changes from a feature branch into a master branch
* formatting a good commit message with all the information from Differential
* and automatically closing the revision.
</code></pre>
<p>You don't need to use any of these workflows: you can just run git
push, hg push or svn commit and then manually close the revision from
the web.</p>
</blockquote>
<p><code>arc</code> is squashing your commits on purpose.</p> |
4,200,011 | Video Streaming and Android | <p>Today for one of my app (Android 2.1), I wanted to stream a video from an URL.</p>
<p>As far as I explored Android SDK it's quite good and I loved <em>almost</em> every piece of it.
But now that it comes to video stream I am kind of lost.</p>
<p>For any information you need about Android SDK you have thousands of blogs telling you how to do it. When it comes to video streaming, it's different. Informations is that abundant.</p>
<p>Everyone did it it's way tricking here and there.</p>
<p>Is there any well-know procedure that allows one to stream a video?</p>
<p>Did google think of making it easier for its developers?</p> | 4,200,718 | 1 | 1 | null | 2010-11-16 23:12:56.44 UTC | 19 | 2017-03-04 19:56:26.96 UTC | null | null | null | null | 290,613 | null | 1 | 27 | android|streaming|video-streaming | 28,795 | <p>If you want to just have the OS play a video using the default player you would use an intent like this:</p>
<pre><code>String videoUrl = "insert url to video here";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(videoUrl));
startActivity(i);
</code></pre>
<p>However if you want to create a view yourself and stream video to it, one approach is to create a videoview in your layout and use the mediaplayer to stream video to it. Here's the videoview in xml:</p>
<pre><code><VideoView android:id="@+id/your_video_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
</code></pre>
<p>Then in onCreate in your activity you find the view and start the media player.</p>
<pre><code> VideoView videoView = (VideoView)findViewById(R.id.your_video_view);
MediaController mc = new MediaController(this);
videoView.setMediaController(mc);
String str = "the url to your video";
Uri uri = Uri.parse(str);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();
</code></pre>
<p>Check out the videoview listeners for being notified when the video is done playing or an error occurs (VideoView.setOnCompletionListener, VideoView.setOnErrorListener, etc).</p> |
34,607,052 | Predefined type 'System.Void' is not defined or imported during Visual Studio Online build of ASP.NET 5 | <p>I get this error when I try to build the project in Visual Studio Online:</p>
<pre><code>…\Frontend\Startup.cs(65,49): Error CS0518: Predefined type 'System.Void' is not defined or imported
…\Frontend\Startup.cs(65,49): DNXCore,Version=v5.0 error CS0518: Predefined type 'System.Void' is not defined or imported [C:\a\1\s\Frontend\src\Frontend\Frontend.xproj]
</code></pre>
<p>It seems that the error happens in the place where I reference another library (package class library).</p>
<p>P.S. I had some conversation about this here: <a href="https://stackoverflow.com/questions/34316193/easy-way-to-build-and-deploy-to-azure-asp-net-5-in-visual-studio-team-services">Easy way to build and deploy (to Azure) ASP.NET 5 in Visual Studio Team Services</a>, but there was no answer after all, so I still cannot build it...</p>
<p>Web project.json:</p>
<pre><code>"dependencies": {
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
"Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
"Web.Common": "1.0.0-*"
},
"frameworks": {
"dnx451": { },
"dnxcore50": { }
},
</code></pre>
<p>Library project.json</p>
<pre><code>"frameworks": {
"dnx451": { },
"dnxcore50": {
"dependencies": {
"Microsoft.CSharp": "4.0.1-beta-23516",
"System.Collections": "4.0.11-beta-23516",
"System.Linq": "4.0.1-beta-23516",
"System.Runtime": "4.0.21-beta-23516",
"System.Threading": "4.0.11-beta-23516"
}
}
},
"dependencies": {
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final"
}
</code></pre>
<h2>Update (problem and solution):</h2>
<p>The problem was in the fact that my library reference was not in the same folder and the script by default does not run dnu-restore there, so I had to go one level up and start finding project.json recursively there</p>
<pre><code>$SourceRoot = Split-Path -Path $PSScriptRoot -Parent
# run DNU restore on all project.json files in the src folder including 2>1 to redirect stderr to stdout for badly behaved tools
Get-ChildItem -Path $SourceRoot -Filter project.json -Recurse | ForEach-Object { & dnu restore $_.FullName 2>1 }
</code></pre>
<p>Thanks Eddie - MSFT for help!</p> | 34,646,591 | 11 | 4 | null | 2016-01-05 08:20:59.33 UTC | 2 | 2022-08-08 04:42:24.263 UTC | 2022-01-21 09:03:01.43 UTC | null | 392,626 | null | 1,671,558 | null | 1 | 18 | msbuild|asp.net-core|azure-web-app-service|tfsbuild|azure-devops | 44,995 | <p>I just reproduced this issue after updating the code in "PreBuild.ps1" script to only restore the "project.json" file for web project.</p>
<p>Original Code (Build Success):</p>
<pre><code>Get-ChildItem -Path $PSScriptRoot\src -Filter project.json -Recurse | ForEach-Object { & dnu restore $_.FullName 2>1 }
</code></pre>
<p>Updated Code (Build fail with: Predefined type 'System.Void' is not defined or imported):</p>
<pre><code>Get-ChildItem -Path $PSScriptRoot\src\WebProjectName -Filter project.json -Recurse | ForEach-Object { & dnu restore $_.FullName 2>1 }
</code></pre>
<p>So you need to check the PreBuild.ps1 script and the build logs for PowerShell step to check if the project.json files for Web project and Library project are both restored.</p> |
39,840,749 | Casting types in Java 8 streams | <p>To gain some experience with Java's new streams, I've been developing a framework for handling playing cards. Here's the first version of my code for creating a <code>Map</code> containing the number of cards of each suit in a hand (<code>Suit</code> is an <code>enum</code>): </p>
<pre><code>Map<Suit, Long> countBySuit = contents.stream() // contents is ArrayList<Card>
.collect( Collectors.groupingBy( Card::getSuit, Collectors.counting() ));
</code></pre>
<p>This worked great and I was happy. Then I refactored, creating separate Card subclasses for "Suit Cards" and Jokers. So the <code>getSuit()</code> method was moved from the <code>Card</code> class to its subclass <code>SuitCard</code>, since Jokers don't have a suit. New code: </p>
<pre><code>Map<Suit, Long> countBySuit = contents.stream() // contents is ArrayList<Card>
.filter( card -> card instanceof SuitCard ) // reject Jokers
.collect( Collectors.groupingBy( SuitCard::getSuit, Collectors.counting() ) );
</code></pre>
<p>Notice the clever insertion of a filter to make sure that the card being considered is in fact a Suit Card and not a Joker. But it doesn't work! Apparently the <code>collect</code> line doesn't realize that the object it's being passed is GUARANTEED to be a <code>SuitCard</code>. </p>
<p>After puzzling over this for a good while, in desperation I tried inserting a <code>map</code> function call, and amazingly it worked! </p>
<pre><code>Map<Suit, Long> countBySuit = contents.stream() // contents is ArrayList<Card>
.filter( card -> card instanceof SuitCard ) // reject Jokers
.map( card -> (SuitCard)card ) // worked to get rid of error message on next line
.collect( Collectors.groupingBy( SuitCard::getSuit, Collectors.counting() ) );
</code></pre>
<p>I had no idea that casting a type was considered an executable statement. Why does this work? And why does the compiler make it necessary? </p> | 39,840,976 | 4 | 2 | null | 2016-10-03 21:32:20.107 UTC | 8 | 2016-10-04 06:02:18.8 UTC | null | null | null | null | 6,683,344 | null | 1 | 21 | java|lambda|casting|java-8 | 52,536 | <p>Remember that a <code>filter</code> operation will not change the compile-time type of the <code>Stream</code>'s elements. Yes, logically we see that everything that makes it past this point will be a <code>SuitCard</code>, all that the <code>filter</code> sees is a <code>Predicate</code>. If that predicate changes later, then that could lead to other compile-time issues.</p>
<p>If you want to change it to a <code>Stream<SuitCard></code>, you'd need to add a mapper that does a cast for you:</p>
<pre><code>Map<Suit, Long> countBySuit = contents.stream() // Stream<Card>
.filter( card -> card instanceof SuitCard ) // still Stream<Card>, as filter does not change the type
.map( SuitCard.class::cast ) // now a Stream<SuitCard>
.collect( Collectors.groupingBy( SuitCard::getSuit, Collectors.counting() ) );
</code></pre>
<p>I refer you to the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html" rel="noreferrer">Javadoc</a> for the full details.</p> |
48,848,020 | Dockerfile is not a valid repository/tag: invalid reference format | <p>I am receiving the "is not a valid repository/tag: invalid reference format" error when building an image on a jenkins agent.</p>
<ul>
<li><p>This error is generally known to occur when docker versions < 17.05 attempt to build a modern multi-stage dockerfile.</p></li>
<li><p>The agent is running on a Kubernetes cluster (server and nodes running 1.9.2-gke.1) and was provisioned by the below Jenkinsfile.</p></li>
</ul>
<p>Is it because I am binding <code>/var/run/docker.sock</code> from the client to the server that this is executing on the 17.03 version of docker?</p>
<p><strong>The JenkinsFile:</strong></p>
<pre><code>#!/usr/bin/groovy
podTemplate(label: 'jenkins-pipeline', containers: [
containerTemplate(name: 'jnlp', image: 'jenkinsci/jnlp-slave:latest', args: '${computer.jnlpmac} ${computer.name}'),
containerTemplate(name: 'docker', image: 'docker:latest', command: 'cat', ttyEnabled: true),
containerTemplate(name: 'helm', image: 'lachlanevenson/k8s-helm:latest', command: 'cat', ttyEnabled: true)
],
volumes:[ hostPathVolume(mountPath: '/var/run/docker.sock', hostPath: '/var/run/docker.sock'), ]) {
node ('jenkins-pipeline') {
stage('build') {
container('docker') {
dir ('src') {
sh "docker version"
sh "docker build -t ${tag} ."
}
}
}
}
}
</code></pre>
<p><strong>Check the version of docker:</strong></p>
<pre><code># docker version
Client:
Version: 18.02.0-ce
API version: 1.27 (downgraded from 1.36)
Go version: go1.9.3
Git commit: fc4de44
Built: Wed Feb 7 21:12:37 2018
OS/Arch: linux/amd64
Experimental: false
Orchestrator: swarm
Server:
Engine:
Version: 17.03.2-ce
API version: 1.27 (minimum version 1.12)
Go version: go1.9.1
Git commit: f5ec1e2
Built: Thu Dec 7 20:13:20 2017
OS/Arch: linux/amd64
Experimental: false
</code></pre>
<p><strong>The dockerfile in question:</strong></p>
<pre><code>FROM microsoft/aspnetcore:2.0 AS base
WORKDIR /app
EXPOSE 80
FROM microsoft/aspnetcore-build:2.0 AS build
WORKDIR /src
COPY XXXXXX.API.csproj ./
RUN dotnet restore
COPY . .
WORKDIR /src
RUN dotnet build -c Release -o /app
FROM build AS publish
RUN dotnet publish -c Release -o /app
FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "XXXXXX.API.dll"]
</code></pre> | 48,863,391 | 2 | 5 | null | 2018-02-18 02:56:26.363 UTC | 1 | 2018-06-12 17:48:46.82 UTC | 2018-02-19 04:45:07.87 UTC | null | 198,506 | null | 198,506 | null | 1 | 13 | docker|kubernetes|jenkins-pipeline | 53,539 | <p>Docker builds are run on the server, and <a href="https://blog.docker.com/2017/07/multi-stage-builds/" rel="noreferrer">multi stage builds were introduced in 17.06</a>. You'll need to run the build on a newer server version to support that syntax.</p> |
39,114,446 | How can I write a ESLint rule for "linebreak-style", changing depending on Windows or Unix? | <p>As we all know, the linebreaks (new line) used in Windows are usually carriage returns (CR) followed by a line feed (LF) i.e. (CRLF) whereas, Linux and Unix use a simple line feed (LF)</p>
<p>Now, in my case, my build server uses supports Linux and Unix format so, below rule is working perfectly on build server:</p>
<pre><code>linebreak-style: ["error", "unix"]
</code></pre>
<p>But I am doing development on Windows and I need to update rule on each <em>git pull/git push</em> as below,</p>
<pre><code>linebreak-style: ["error", "windows"]
</code></pre>
<p>So, is there any way to write a generic <em>linebreak-style</em> rule to support both environments, Linux/Unix and Windows?</p>
<p><strong>Note</strong>: I am using ECMAScript6[js], WebStorm[ide] for development</p>
<p>Any solutions/suggestions would be highly appreciated. Thanks! </p> | 39,122,799 | 9 | 4 | null | 2016-08-24 04:29:12.04 UTC | 25 | 2022-08-12 09:09:35.55 UTC | 2017-10-18 14:36:23.883 UTC | null | 123,671 | null | 3,578,755 | null | 1 | 67 | javascript|windows|unix|eslint|line-endings | 90,127 | <p>The eslint configuration file can be <strong>a regular <code>.js</code> file</strong> (ie, not JSON, but full JS with logic) that exports the configuration object.</p>
<p>That means you could change the configuration of the <code>linebreak-style</code> rule depending on your current environment (or any other JS logic you can think of). </p>
<p>For example, to use a different <code>linebreak-style</code> configuration when your node environment is 'prod':</p>
<pre><code>module.exports = {
"root": true,
"parserOptions": {
"sourceType": "module",
"ecmaVersion": 6
},
"rules": {
// windows linebreaks when not in production environment
"linebreak-style": ["error", process.env.NODE_ENV === 'prod' ? "unix" : "windows"]
}
};
</code></pre>
<p>Example usage:</p>
<pre><code>$ NODE_ENV=prod node_modules/.bin/eslint src/test.js
src/test.js
1:25 error Expected linebreaks to be 'CRLF' but found 'LF' linebreak-style
2:30 error Expected linebreaks to be 'CRLF' but found 'LF' linebreak-style
3:36 error Expected linebreaks to be 'CRLF' but found 'LF' linebreak-style
4:26 error Expected linebreaks to be 'CRLF' but found 'LF' linebreak-style
5:17 error Expected linebreaks to be 'CRLF' but found 'LF' linebreak-style
6:50 error Expected linebreaks to be 'CRLF' but found 'LF' linebreak-style
7:62 error Expected linebreaks to be 'CRLF' but found 'LF' linebreak-style
8:21 error Expected linebreaks to be 'CRLF' but found 'LF' linebreak-style
✖ 8 problems (8 errors, 0 warnings)
$ NODE_ENV=dev node_modules/.bin/eslint src/test.js
$ # no errors
</code></pre> |
26,476,352 | What does a dot after an integer mean in python? | <p>I am looking at this line of python code (which seems to run properly):</p>
<pre><code>import numpy as np
yl = 300 + 63*np.exp(-x/35.)
</code></pre>
<p>What is the dot doing after the 35? what does it do? Is it a signal to python that 35 is a float and not an integer? I have not seen this before. Thanks! </p> | 26,476,379 | 3 | 1 | null | 2014-10-20 23:03:23.66 UTC | null | 2017-05-24 08:12:53.747 UTC | null | null | null | null | 821,742 | null | 1 | 28 | python | 22,088 | <p>This is easy to test, and you're right. The dot signals a float.</p>
<pre><code>$ python
>>> 1.
1.0
>>> type(1.)
<type 'float'>
</code></pre> |
20,089,820 | Where NOT in pivot table | <p>In Laravel we can setup relationships like so:</p>
<pre><code>class User {
public function items()
{
return $this->belongsToMany('Item');
}
}
</code></pre>
<p>Allowing us to to get all items in a pivot table for a user:</p>
<pre><code>Auth::user()->items();
</code></pre>
<p>However what if I want to get the opposite of that. And get all items the user DOES NOT have yet. So NOT in the pivot table.</p>
<p>Is there a simple way to do this?</p> | 20,100,392 | 7 | 1 | null | 2013-11-20 07:25:18.497 UTC | 9 | 2015-08-18 23:40:45.467 UTC | null | null | null | null | 1,200,670 | null | 1 | 29 | laravel|laravel-4|pivot-table|eloquent | 21,442 | <p>For simplicity and symmetry you could create a new method in the User model:</p>
<pre><code>// User model
public function availableItems()
{
$ids = \DB::table('item_user')->where('user_id', '=', $this->id)->lists('user_id');
return \Item::whereNotIn('id', $ids)->get();
}
</code></pre>
<p>To use call:</p>
<pre><code>Auth::user()->availableItems();
</code></pre> |
6,374,664 | Rails and modal jquery dialog form | <p>I'm new to using jquery modal dialog boxes with rails and was wondering how I can :</p>
<ol>
<li>show a jquery modal dialog box
with 1 field (eg "title")</li>
<li>post this form to a rails controller (via
ajax) </li>
<li>have the modal dialog form
redisplay if field is not filled in
(with normal red css in error field)</li>
</ol>
<p>Any tutorials or examples welcome.</p>
<p>Using Rails 3 and jQuery. Thanks for your time.</p> | 6,375,497 | 2 | 0 | null | 2011-06-16 15:44:38.973 UTC | 11 | 2016-06-25 12:04:12.35 UTC | null | null | null | null | 541,744 | null | 1 | 21 | ruby-on-rails|jquery | 14,285 | <p>Here's an example of how I'd do it: <a href="https://github.com/ramblex/modal-form">https://github.com/ramblex/modal-form</a>.</p>
<p>You should be able to:</p>
<ol>
<li>download the app</li>
<li>run bundle</li>
<li>rake db:migrate</li>
<li>rails s</li>
<li>Go to localhost:3000/articles and the modal form should come up when you click on the 'New article' link.</li>
</ol>
<p>An error message should be shown when the title field is left empty. Otherwise it should create the article and display it.</p>
<p>Hope it helps.</p> |
6,751,086 | Visual Studio Text Editor Extension | <p>I am trying to get started in Visual Studio (2010) extensions and I am having a hard time finding the right materials. I have the SDK, but the included samples seem to be things like adorners, windows, and icons. </p>
<p>I am trying to make an extension that will work directly with the text editor (to alphabetize all of my method names in a class, or make all constant names upper case for example) but I can't find a demo for this type of functionality, or even a tutorial. </p>
<p>Does anyone know where I can find this kind of stuff?</p> | 9,856,189 | 2 | 3 | null | 2011-07-19 17:04:14.013 UTC | 22 | 2017-07-14 15:09:41.673 UTC | 2011-07-28 12:48:52.653 UTC | null | 472,614 | null | 472,614 | null | 1 | 38 | c#|visual-studio|visual-studio-2010|visual-studio-extensions | 16,196 | <p>I had the exact same question and now have browsed the web several hours until I was being able to understand and explain how you'd need to start with such an extension.</p>
<p>In my following example we will create a small and dumb extension which will always add "Hello" to the beginning of a code file when an edit has been made. It's very basic but should give you an idea how to continue developing this thing.</p>
<p>Be warned: You have to parse the code files completely on your own - Visual Studio does not give you any information about where classes, methods or whatever are and what they contain. That's the biggest hurdle to be taken when doing a code formatting tool and will not be covered in this answer.[*]</p>
<p>For those who skipped to this answer, make sure you downloaded and installed the Visual Studio SDK first or you will not find the project type mentioned in step one.</p>
<p><strong>Creating the project</strong></p>
<ol>
<li><p>Start by creating a new project of the type "Visual C# > Extensibility > VSIX Project" (only visible if you selected .NET Framework 4 as the target framework). <em>Please note that you may have to select the "Editor Classifier" project type instead of the "VSIX Project" type to get it working, s. comment below.</em></p></li>
<li><p>After the project has been created, the "source.extension.vsixmanifest" file will be opened, giving you the ability to set up product name, author, version, description, icon and so on. I think this step is pretty self-explaining, you can close the tab now and restore it later by opening the vsixmanifest file.</p></li>
</ol>
<p><strong>Creating a listener class to get notified about text editor instance creations</strong></p>
<p>Next, we need to listen whenever a text editor has been created in Visual Studio and bind our code formatting tool to it. A text editor in VS2010 is an instance of <code>IWpfTextView</code>.</p>
<ol>
<li><p>Add a new class to our project and name it <code>TextViewCreationListener</code>. This class has to implement the <code>Microsoft.VisualStudio.Text.Editor.IWpfTextViewCreationListener</code> interface. You need to add a reference to <em>Microsoft.VisualStudio.Text.UI.Wpf</em> to your project. The assembly DLL is found in your Visual Studio SDK directory under <em>VisualStudioIntegration\Common\Assemblies\v4.0</em>.</p></li>
<li><p>You have to implement the <code>TextViewCreated</code> method of the interface. This method has a parameter specifying the instance of the text editor which has been created. We will create a new code formatting class which this instance is passed to later on.</p></li>
<li><p>We need to make the <code>TextViewCreationListener</code> class visible to Visual Studio by specifying the attribute <code>[Export(typeof(IWpfTextViewCreationListener))]</code>. Add a reference to <em>System.ComponentModel.Composition</em> to your project for the <code>Export</code> attribute.</p></li>
<li><p>Additionally, we need to specify with which types of files the code formatter should be bound to the text editor. We only like to format code files and not plain text files, so we add the attribute <code>[ContentType("code")]</code> to the listener class. You have to add a reference to <em>Microsoft.VisualStudio.CoreUtility</em> to your project for this.</p></li>
<li><p>Also, we only want to change editable code and not the colors or adornments around it (as seen in the example projects), so we add the attribute <code>[TextViewRole(PredefinedTextViewRoles.Editable)]</code> to the class. Again you need a new reference, this time to <em>Microsoft.VisualStudio.Text.UI</em>.</p></li>
<li><p>Mark the class as internal sealed. At least that's my recommendation. Now your class should look similar to this:</p>
<pre><code>[ContentType("code")]
[Export(typeof(IWpfTextViewCreationListener))]
[TextViewRole(PredefinedTextViewRoles.Editable)]
internal sealed class TextViewCreationListener : IWpfTextViewCreationListener
{
public void TextViewCreated(IWpfTextView textView)
{
}
}
</code></pre></li>
</ol>
<p><strong>Creating a class for code formatting</strong></p>
<p>Next, we need a class handling the code formatting logic, sorting methods and so on. Again, in this example it will simply add "Hello" to the start of the file whenever an edit has been made.</p>
<ol>
<li><p>Add a new class called <code>Formatter</code> to your project.</p></li>
<li><p>Add a constructor which takes one <code>IWpfTextView</code> argument. Remember that we wanted to pass the created editor instance to this formatting class in the <code>TextViewCreated</code> method of our listener class (simply add <code>new Formatter(textView);</code> to the method there).</p></li>
<li><p>Save the passed instance in a member variable. It'll become handy when formatting the code later on (e.g. for retrieving the caret position). Also tie up the <code>Changed</code> and <code>PostChanged</code> events of the <code>TextBuffer</code> property of the editor instance:</p>
<pre><code>public Formatter(IWpfTextView view)
{
_view = view;
_view.TextBuffer.Changed += new EventHandler<TextContentChangedEventArgs>(TextBuffer_Changed);
_view.TextBuffer.PostChanged += new EventHandler(TextBuffer_PostChanged);
}
</code></pre></li>
<li><p>The <code>Changed</code> event is called every time an edit has been made (e.g. typing a char, pasting code or programmatical changes). Because it also reacts on programmatical changes I use a bool determining if our extension or the user / anything else is changing the code at the moment and call my custom <code>FormatCode()</code> method only if our extension is not already editing. Otherwise you'll recursively call this method which would crash Visual Studio:</p>
<pre><code>private void TextBuffer_Changed(object sender, TextContentChangedEventArgs e)
{
if (!_isChangingText)
{
_isChangingText = true;
FormatCode(e);
}
}
</code></pre></li>
<li><p>We have to reset this bool member variable in the <code>PostChanged</code> event handler again to <code>false</code>.</p></li>
<li><p>Let's pass the event args of the <code>Changed</code> event to our custom <code>FormatCode</code> method because they contain what has changed between the last edit and now. Those edits are stored in the array <code>e.Changes</code> of the type <code>INormalizedTextChangeCollection</code> (s. the link at the end of my post for more information about this type). We loop through all those edits and call our custom <code>HandleChange</code> method with the new text which this edit has produced.</p>
<pre><code>private void FormatCode(TextContentChangedEventArgs e)
{
if (e.Changes != null)
{
for (int i = 0; i < e.Changes.Count; i++)
{
HandleChange(e.Changes[0].NewText);
}
}
}
</code></pre></li>
<li><p>In the <code>HandleChange</code> method we could actually scan for keywords to handle those in a specific way (remember, you have to parse any code on yourself!) - but here we just dumbly add "Hello" to the start of the file for testing purposes. E.g. we have to change the <code>TextBuffer</code> of our editor instance. To do so, we need to create an <code>ITextEdit</code> object with which we can manipulate text and apply it's changes afterwards. The code is pretty self-explaining:</p>
<pre><code>private void HandleChange(string newText)
{
ITextEdit edit = _view.TextBuffer.CreateEdit();
edit.Insert(0, "Hello");
edit.Apply();
}
</code></pre></li>
</ol>
<p>When compiling this add-in, an experimental hive of Visual Studio starts up with only our extension loaded. Create a new C# file and start typing to see the results.</p>
<p>I hope this gives you some ideas how to continue in this topic. I have to explore it myself now.</p>
<p>I highly recommend the documentation of the text model of the editor on MSDN to get hints about how you could do this and that.
<a href="http://msdn.microsoft.com/en-us/library/dd885240.aspx#textmodel" rel="noreferrer">http://msdn.microsoft.com/en-us/library/dd885240.aspx#textmodel</a></p>
<hr>
<p><strong>Footnotes</strong></p>
<p>[*] Note that Visual Studio 2015 or newer come with the Rosyln Compiler Platform, which indeed already analyzes C# and VB.NET files for you (and probably other pre-installed languages too) and exposes their hierarchical syntactical structure, but I'm not an expert in this topic yet to give an answer on how to use these new services. The basic progress of starting an editor extension stays the same as described in this answer anyway. Be aware that - if you use these services - you will become dependent on Visual Studio 2015+, and the extension will not work in earlier versions.</p> |
7,267,390 | Xcode letters beside files in Project Navigator | <p><img src="https://i.stack.imgur.com/KbMGQ.jpg" alt="enter image description here"></p>
<p>What are the significance of the letters beside the files in the Project Navigator? (e.g M,A)</p> | 7,267,424 | 3 | 0 | null | 2011-09-01 07:47:27 UTC | 11 | 2019-10-22 08:43:35.74 UTC | 2011-09-01 17:53:58.097 UTC | null | 111,783 | null | 602,995 | null | 1 | 62 | xcode | 24,007 | <p>Those letters beside files in the Project Navigator of Xcode show the status of files that are under version control systems, such as SVN or Git. So, for instance:</p>
<ul>
<li>M - means the file has changed and it should be merged into SCM</li>
<li>A - means this is a new file and should be added to SCM</li>
<li>U - means this is a newer version of a file on SCM and you need to update it</li>
<li>? - means the file has not been added to source control</li>
<li>etc...</li>
</ul>
<p>P.S. You can find list of statuses (at least for SVN) <a href="http://svnbook.red-bean.com/en/1.2/svn.ref.svn.c.status.html" rel="noreferrer">here</a></p> |
8,179,137 | How to manage multiple JSON schema files? | <p>I'm trying to validate my JSON API using node.js + json-schema.js from commonjs-utils. Just single validation was easy but could not find right way how to manage multiple schema files to enable referencing each other.</p>
<p>Suppose that I got two Models & two APIs.</p>
<pre><code>// book
{
"type": "object",
"properties": {
"title": { "type": "string" },
"author": { "type": "string" }
}
}
// author
{
"type": "object",
"properties": {
"first_name": { "type": "string" },
"last_name": { "type": "string" }
}
}
// authors API
{
"type": "array",
"items": { "$ref": "author" }
}
// books API: list of books written by same author
{
"type": "object",
"properties": {
"author": { "$ref": "author" }
"books": { "type": "array", "items": { "$ref": "book" } }
}
}
</code></pre>
<p>Each schema should be divided in separate file and be online? Or Can I combine into single schema file like below? If it is possible, how can I reference local schema?</p>
<pre><code>// single schema file {
"book": { ... },
"author": { ... },
"authors": { ... },
"books": { ... } }
</code></pre> | 9,083,830 | 1 | 0 | null | 2011-11-18 07:31:20.753 UTC | 12 | 2018-02-08 11:09:07.437 UTC | 2016-10-12 12:10:15.237 UTC | null | 3,886,961 | null | 259,228 | null | 1 | 41 | json|node.js|schema|jsonschema | 29,519 | <p>In JSON Schemas, you can either put a schema per file and then access them using their URL (where you stored them), or a big schema with <code>id</code> tags.</p>
<p>Here is for one big file:</p>
<pre><code>{
"id": "#root",
"properties": {
"author": {
"id": "#author",
"properties": {
"first_name": {
"type": "string"
},
"last_name": {
"type": "string"
}
},
"type": "object"
},
// author
"author_api": {
"id": "#author_api",
"items": {
"$ref": "author"
},
"type": "array"
},
// authors API
"book": {
"id": "#book",
"properties": {
"author": {
"type": "string"
},
"title": {
"type": "string"
}
},
"type": "object"
},
// books API: list of books written by same author
"books_api": {
"id": "#books_api",
"properties": {
"author": {
"$ref": "author"
},
"books": {
"items": {
"$ref": "book"
},
"type": "array"
}
},
"type": "object"
}
}
}
</code></pre>
<p>You can then reference your validator to one of those sub schemas (which are defined with an <code>id</code>).</p>
<p>From outside of your schema, this:</p>
<pre><code>{ "$ref": "url://to/your/schema#root/properties/book" }
</code></pre>
<p>is equivalent to this:</p>
<pre><code>{ "$ref": "url://to/your/schema#book" }
</code></pre>
<p>… which is equivalent, from inside, to this:</p>
<pre><code>{ "$ref": "#root/properties/book" }
</code></pre>
<p>or this (still from inside):</p>
<pre><code>{ "$ref": "#book" }
</code></pre>
<p>See my <a href="https://stackoverflow.com/questions/8595832/does-json-schema-validation-in-common-js-utils-support-references/9083630#9083630">answer here</a> for more information.</p> |
1,813,117 | Making a Python script Object-Oriented | <p>I'm writing an application in Python that is going to have a lot of different functions, so logically I thought it would be best to split up my script into different modules. Currently my script reads in a text file that contains code which has been converted into tokens and spellings. The script then reconstructs the code into a string, with blank lines where comments would have been in the original code.</p>
<p>I'm having a problem making the script object-oriented though. Whatever I try I can't seem to get the program running the same way it would as if it was just a single script file. Ideally I'd like to have two script files, one that contains a class and function that cleans and reconstructs the file. The second script would simply call the function from the class in the other file on a file given as an argument from the command line. This is my current script:</p>
<pre><code>import sys
tokenList = open(sys.argv[1], 'r')
cleanedInput = ''
prevLine = 0
for line in tokenList:
if line.startswith('LINE:'):
lineNo = int(line.split(':', 1)[1].strip())
diff = lineNo - prevLine - 1
if diff == 0:
cleanedInput += '\n'
if diff == 1:
cleanedInput += '\n\n'
else:
cleanedInput += '\n' * diff
prevLine = lineNo
continue
cleanedLine = line.split(':', 1)[1].strip()
cleanedInput += cleanedLine + ' '
print cleanedInput
</code></pre>
<p>After following Alex Martelli advice below, I now have the following code which gives me the same output as my original code.</p>
<pre><code>def main():
tokenList = open(sys.argv[1], 'r')
cleanedInput = []
prevLine = 0
for line in tokenList:
if line.startswith('LINE:'):
lineNo = int(line.split(':', 1)[1].strip())
diff = lineNo - prevLine - 1
if diff == 0:
cleanedInput.append('\n')
if diff == 1:
cleanedInput.append('\n\n')
else:
cleanedInput.append('\n' * diff)
prevLine = lineNo
continue
cleanedLine = line.split(':', 1)[1].strip()
cleanedInput.append(cleanedLine + ' ')
print cleanedInput
if __name__ == '__main__':
main()
</code></pre>
<p>I would still like to split my code into multiple modules though. A 'cleaned file' in my program will have other functions performed on it so naturally a cleaned file should be a class in its own right?</p> | 1,813,167 | 4 | 2 | null | 2009-11-28 17:19:36.02 UTC | 24 | 2009-11-29 09:33:38.687 UTC | 2009-11-28 19:04:01.363 UTC | null | 205,877 | null | 205,877 | null | 1 | 27 | python|oop | 21,859 | <p>To speed up your existing code measurably, add <code>def main():</code> before the assignment to <code>tokenList</code>, indent everything after that 4 spaces, and at the end put the usual idiom</p>
<pre><code>if __name__ == '__main__':
main()
</code></pre>
<p>(The guard is not actually necessary, but it's a good habit to have nevertheless since, for scripts with reusable functions, it makes them importable from other modules).</p>
<p>This has little to do with "object oriented" anything: it's simply faster, in Python, to keep all your substantial code in functions, <em>not</em> as top-level module code.</p>
<p>Second speedup, change <code>cleanedInput</code> into a list, i.e., its first assignment should be <code>= []</code>, and wherever you now have <code>+=</code>, use <code>.append</code> instead. At the end, <code>''.join(cleanedInput)</code> to get the final resulting string. This makes your code take linear time as a function of input size (<code>O(N)</code> is the normal way of expressing this) while it currently takes quadratic time (<code>O(N squared)</code>).</p>
<p>Then, correctness: the two statements right after <code>continue</code> never execute. Do you need them or not? Remove them (and the <code>continue</code>) if not needed, remove the <code>continue</code> if those two statements are actually needed. And the tests starting with <code>if diff</code> will fail dramatically unless the previous <code>if</code> was executed, because <code>diff</code> would be undefined then. Does your code as posted perhaps have indentation errors, i.e., is the indentation of what you posted different from that of your actual code?</p>
<p>Considering these important needed enhancements, and the fact that it's hard to see what advantage you are pursuing in making this tiny code OO (and/or modular), I suggest clarifying the indenting / correctness situation, applying the enhancements I've proposed, and leaving it at that;-).</p>
<p><strong>Edit</strong>: as the OP has now applied most of my suggestions, let me follow up with one reasonable way to hive off most functionality to a class in a separate module. In a new file, for example <code>foobar.py</code>, in the same directory as the original script (or in <code>site-packages</code>, or elsewhere on <code>sys.path</code>), place this code:</p>
<pre><code>def token_of(line):
return line.partition(':')[-1].strip()
class FileParser(object):
def __init__(self, filename):
self.tokenList = open(filename, 'r')
def cleaned_input(self):
cleanedInput = []
prevLine = 0
for line in self.tokenList:
if line.startswith('LINE:'):
lineNo = int(token_of(line))
diff = lineNo - prevLine - 1
cleanedInput.append('\n' * (diff if diff>1 else diff+1))
prevLine = lineNo
else:
cleanedLine = token_of(line)
cleanedInput.append(cleanedLine + ' ')
return cleanedInput
</code></pre>
<p>Your main script then becomes just:</p>
<pre><code>import sys
import foobar
def main():
thefile = foobar.FileParser(sys.argv[1])
print thefile.cleaned_input()
if __name__ == '__main__':
main()
</code></pre> |
1,395,593 | Managing resources in a Python project | <p>I have a Python project in which I am using many non-code files. Currently these are all images, but I might use other kinds of files in the future. What would be a good scheme for storing and referencing these files?</p>
<p>I considered just making a folder "resources" in the main directory, but there is a problem; Some images are used from within sub-packages of my project. Storing these images that way would lead to coupling, which is a disadvantage.</p>
<p>Also, I need a way to access these files which is independent on what my current directory is.</p> | 1,396,657 | 4 | 0 | null | 2009-09-08 18:37:39.547 UTC | 24 | 2020-10-23 16:03:30.22 UTC | 2009-09-13 18:31:46.483 UTC | null | 81,019 | null | 76,701 | null | 1 | 65 | python|resources|setuptools|distutils|decoupling | 48,669 | <p>You may want to use <code>pkg_resources</code> library that comes with <code>setuptools</code>.</p>
<p>For example, I've made up a quick little package <code>"proj"</code> to illustrate the resource organization scheme I'd use:</p>
<pre>proj/setup.py
proj/proj/__init__.py
proj/proj/code.py
proj/proj/resources/__init__.py
proj/proj/resources/images/__init__.py
proj/proj/resources/images/pic1.png
proj/proj/resources/images/pic2.png
</pre>
<p>Notice how I keep all resources in a separate subpackage.</p>
<p><code>"code.py"</code> shows how <code>pkg_resources</code> is used to refer to the resource objects:</p>
<pre><code>from pkg_resources import resource_string, resource_listdir
# Itemize data files under proj/resources/images:
print resource_listdir('proj.resources.images', '')
# Get the data file bytes:
print resource_string('proj.resources.images', 'pic2.png').encode('base64')
</code></pre>
<p>If you run it, you get:</p>
<pre>['__init__.py', '__init__.pyc', 'pic1.png', 'pic2.png']
iVBORw0KGgoAAAANSUhE ...
</pre>
<p>If you need to treat a resource as a fileobject, use <code>resource_stream()</code>.</p>
<p>The code accessing the resources may be anywhere within the subpackage structure of your project, it just needs to refer to subpackage containing the images by full name: <code>proj.resources.images</code>, in this case.</p>
<p>Here's <code>"setup.py"</code>:</p>
<pre><code>#!/usr/bin/env python
from setuptools import setup, find_packages
setup(name='proj',
packages=find_packages(),
package_data={'': ['*.png']})
</code></pre>
<p><em>Caveat:</em>
To test things "locally", that is w/o installing the package first, you'll have to invoke your test scripts from directory that has <code>setup.py</code>. If you're in the same directory as <code>code.py</code>, Python won't know about <code>proj</code> package. So things like <code>proj.resources</code> won't resolve.</p> |
7,335,266 | Unit testing/continuous integration with Simulink/Stateflow | <p>How can I perform unit testing in Simulink, or preferably, Stateflow?</p>
<p>I'm a fan of agile software methods, including test driven development. I'm responsible for the development of safety critical control software and we're using Matlab/Simulink/Stateflow for the development of it. This toolset is selected because of the link with plant (hardware) models. (model-in-the-loop, hardware-in-the-loop)</p>
<p>I have found some links on Stackoverflow: <a href="https://stackoverflow.com/questions/3992295/unit-testing-framework-for-matlab">Unit-testing framework for MATLAB</a>: <a href="http://www.mathworks.com/matlabcentral/fileexchange/22846-matlab-xunit-test-framework" rel="noreferrer">xunit</a>, <a href="http://sourceforge.net/projects/mlunit/" rel="noreferrer">slunit</a> and <a href="http://www.mathworks.com/matlabcentral/fileexchange/28862-doctest-embed-testable-examples-in-your-functions-help-comments" rel="noreferrer">doctest</a>.</p>
<ul>
<li>Does anyone have experience in using those or different unit test frameworks?</li>
<li>How to link this to continuous integration systems (i.e. Hudson)?</li>
</ul> | 23,347,768 | 8 | 0 | null | 2011-09-07 14:07:43.467 UTC | 9 | 2020-11-03 19:40:33.22 UTC | 2017-05-23 12:17:11.353 UTC | null | -1 | null | 147,820 | null | 1 | 24 | unit-testing|matlab|continuous-integration|simulink|stateflow | 9,505 | <p>EDIT: This is now much easier and getting easier all the time with the <a href="https://plugins.jenkins.io/matlab/" rel="nofollow noreferrer">Jenkins plugin for MATLAB</a></p>
<p>ORIGINAL ANSWER:</p>
<p>As Craig mentioned there is indeed a framework in MATLAB introduced in R2013a. Furthermore, this framework added a <a href="http://www.mathworks.com/help/matlab/ref/matlab.unittest.plugins.tapplugin-class.html" rel="nofollow noreferrer">TAPPlugin</a> in R2014a which outputs the <a href="http://testanything.org/" rel="nofollow noreferrer">Test Anything Protocal</a>. Using that protocol you can set up your CI build with a TAPPlugin (eg. <a href="https://wiki.jenkins-ci.org/display/JENKINS/TAP+Plugin" rel="nofollow noreferrer">Jenkins</a>, <a href="https://github.com/pavelsher/teamcity-tap-parser" rel="nofollow noreferrer">TeamCity</a>) so that the CI system can fail the build if the tests fail.</p>
<p>Your CI build may look like a shell command to start MATLAB and run all your tests:</p>
<pre><code>/your/path/to/matlab/bin/matlab -nosplash -nodisplay -nodesktop -r "runAllMyTests"
</code></pre>
<p>Then the runAllMyTests creates the suite to run and runs it with the tap output being redirected to a file. You'll need to tweak specifics here, but perhaps this can help you get started:</p>
<pre><code>function runAllMyTests
import matlab.unittest.TestSuite;
import matlab.unittest.TestRunner;
import matlab.unittest.plugins.TAPPlugin;
import matlab.unittest.plugins.ToFile;
try
% Create the suite and runner
suite = TestSuite.fromPackage('packageThatContainsTests', 'IncludingSubpackages', true);
runner = TestRunner.withTextOutput;
% Add the TAPPlugin directed to a file in the Jenkins workspace
tapFile = fullfile(getenv('WORKSPACE'), 'testResults.tap');
runner.addPlugin(TAPPlugin.producingOriginalFormat(ToFile(tapFile)));
runner.run(suite);
catch e;
disp(e.getReport);
exit(1);
end;
exit force;
</code></pre>
<p><strong>EDIT:</strong> I used this topic as the <a href="http://blogs.mathworks.com/developer/2015/01/20/the-other-kind-of-continuous-integration/" rel="nofollow noreferrer">first</a> <a href="http://blogs.mathworks.com/developer/2015/01/29/tap-plugin/" rel="nofollow noreferrer">two</a> posts of a <a href="http://blogs.mathworks.com/developer/" rel="nofollow noreferrer">new developer oriented blog</a> launched this year</p> |
7,547,945 | Disable postback at click on a button | <p>I want do disable postback after clicking a <code><asp:Button></code>. I've tried to do that by assigning <code>onclick="return false"</code>, but in the button doesn't work.</p>
<p>How can I fix this?</p> | 7,574,945 | 10 | 2 | null | 2011-09-25 19:19:48.337 UTC | 2 | 2021-02-14 20:15:16.877 UTC | 2011-09-25 19:21:56.747 UTC | null | 719,034 | user947344 | null | null | 1 | 23 | c#|asp.net|postback | 104,683 | <p>I could fix that using an UpdatePanel which includes the implicated controls/elements.</p> |
13,831,008 | What is the minimum latency of USB 3.0 | <p>First up, I don't know much about USB, so apologies in advance if my question is wrong.</p>
<p>In USB 2.0 the polling interval was 0.125ms, so the best possible latency for the host to read some data from the device was 0.125ms. I'm hoping for reduced latency in USB 3.0 devices, but I'm finding it hard to learn what the minimum latency is. The USB 3.0 spec says, "USB 2.0 style polling has been replaced with asynchronous notifications", which implies the 0.125ms polling interval may no longer be a limit.</p>
<p>I found some benchmarks for a USB 3.0 SSDs that look like data can be read from the device in just slightly less than 0.125ms, and that includes all time spent in the host OS and the device's flash controller.</p>
<p><a href="http://www.guru3d.com/articles_pages/ocz_enyo_usb_3_portable_ssd_review,8.html" rel="noreferrer">http://www.guru3d.com/articles_pages/ocz_enyo_usb_3_portable_ssd_review,8.html</a></p>
<p>Can someone tell me what the lowest possible latency is? A theoretical answer is fine. An answer including the practical limits of the various versions of Linux and Windows USB stacks would be awesome.</p>
<p>To head-off the "tell me what you're trying to achieve" question, I'm creating a debug interface for the ASICs my company designs. ie A PC connects to one of our ASICs via a debug dongle. One possible use case is to implement conditional breakpoints when the ASIC hardware only implements simple breakpoints. To do so, I need to determine when a simple breakpoint has been hit, evaluate the condition, if false set the processor running again. The simple breakpoint may be hit millions of times before the condition becomes true. We might implement the debug dongle on an FPGA or an off-the-shelf USB 3.0 enabled micro-controller.</p> | 26,918,988 | 4 | 0 | null | 2012-12-12 00:48:54.287 UTC | 5 | 2020-06-05 15:13:37.117 UTC | null | null | null | null | 66,088 | null | 1 | 32 | usb|hardware | 41,379 | <p>Answering my own question...</p>
<p>I've come to realise that this question kind-of misses the point of USB 3.0. Unlike 2.0, it is not a shared-bus system. Instead it uses a point-to-point link between the host and each device (I'm oversimplifying but the gist is true). With USB 2.0, the 125 us polling interval was critical to how the bus was time-division multiplexed between devices. However, because 3.0 uses point-to-point links, there is no multiplexing to be done and thus the polling interval no longer exists. As a result, the latency on packet delivery is <em>much</em> less than with USB 2.0.</p>
<p>In my experiments with a Cypress FX-3 devkit, I have found that it is easy enough to get an average round trip from Windows application to the device and back with an <strong>average latency of 30 us</strong>. I suspect that the vast majority of that time is spent in various OS delays, eg the user-space to kernel-space mode switch and the DPC latency within the driver.</p> |
13,883,686 | Compile C files in C++ project which do not use precompiled header? | <p>Can I disable precompile header for .c files in my C++ project? </p>
<p>I'm getting these errors when I want to add the .C files to my program for a scripting virtual/abstract machine which is in C:</p>
<p>Error 1 error C1853: 'Release\pluginsa.pch' precompiled header file is from a previous version of the compiler, or the precompiled header is C++ and you are using it from C (or vice versa) Z:\Profile\Rafal\Desktop\samod\source\amx\amx.c 1 1 pluginsa</p>
<p>All other stuff is C++ and uses my precompiled header.</p> | 13,883,733 | 1 | 0 | null | 2012-12-14 17:41:00.227 UTC | 20 | 2017-02-22 10:34:51.087 UTC | null | null | null | user1182183 | null | null | 1 | 48 | c++|c|visual-c++|compiler-errors|precompiled-headers | 45,422 | <p>In the <em>Solution Explorer</em> window right click on the *.c file(s) and select <em>Properties</em>. Go to <em>C / C++ -> Precompiled Headers</em> and set the <em>Precompiled Header</em> option to <em>Not Using Precompiled Headers</em>.</p>
<p>Also, unless you actually need precompiled headers, I'd say turn it off project-wide. </p>
<p>Another option would be to compile your C files as C++ and keep using the precompiled headers. To do that, right click on the project name (or each .c file name), and set <em>C / C++ -> Advanced -> Compiles As</em> to <em>Compile as C++ code</em>.</p> |
14,048,098 | COUNT DISTINCT with CONDITIONS | <p>I want to count the number of distinct items in a column subject to a certain condition, for example if the table is like this:</p>
<pre><code>tag | entryID
----+---------
foo | 0
foo | 0
bar | 3
</code></pre>
<p>If I want to count the number of distinct tags as "tag count" and count the number of distinct tags with entry id > 0 as "positive tag count" in the same table, what should I do?</p>
<p>I'm now counting from two different tables where in the second table I've only selected those rows with entryID larger than zero. I think there should be a more compact way to solve this problem.</p> | 14,048,147 | 6 | 0 | null | 2012-12-27 00:51:36.313 UTC | 44 | 2022-01-06 15:20:37.933 UTC | null | null | null | null | 634,042 | null | 1 | 147 | sql | 434,496 | <p>You can try this:</p>
<pre><code>select
count(distinct tag) as tag_count,
count(distinct (case when entryId > 0 then tag end)) as positive_tag_count
from
your_table_name;
</code></pre>
<p>The first <code>count(distinct...)</code> is easy.
The second one, looks somewhat complex, is actually the same as the first one, except that you use <code>case...when</code> clause. In the <code>case...when</code> clause, you filter only positive values. Zeros or negative values would be evaluated as <code>null</code> and won't be included in count.</p>
<p>One thing to note here is that this can be done by reading the table once. When it seems that you have to read the same table twice or more, it can actually be done by reading once, in most of the time. As a result, it will finish the task a lot faster with less I/O.</p> |
43,718,391 | Laravel throws 'The bootstrap/cache directory must be present and writable' error after update | <p>I used 'composer update', which updated a few packages. During the updating process the website still functions. However, after it says 'The compiled services file has been removed', the website doesn't load and instead says:</p>
<pre><code>Exception in ProviderRepository.php line 190:
The bootstrap/cache directory must be present and writable.
</code></pre>
<p>The weirdest thing is, when I run 'composer update' again, the website starts to work again, until the compiled services file is removed, at which point it throws the same error again. I have already tried the usual things that should be done when this error appears (chown -R everything to the right user/group and chmod all the files and folders 664 and 775 respectively). </p>
<p>I don't know what to do anymore, as the error doesn't seem 'correct'..</p> | 43,810,756 | 15 | 2 | null | 2017-05-01 11:28:51.487 UTC | 10 | 2022-07-29 01:41:04.8 UTC | null | null | null | null | 1,663,235 | null | 1 | 81 | php|laravel|laravel-5|composer-php | 129,902 | <p>Try this after you have run the composer update:</p>
<pre><code>php artisan cache:clear
</code></pre> |
30,100,725 | Why are some float < integer comparisons four times slower than others? | <p>When comparing floats to integers, some pairs of values take much longer to be evaluated than other values of a similar magnitude.</p>
<p>For example:</p>
<pre><code>>>> import timeit
>>> timeit.timeit("562949953420000.7 < 562949953421000") # run 1 million times
0.5387085462592742
</code></pre>
<p>But if the float or integer is made smaller or larger by a certain amount, the comparison runs much more quickly:</p>
<pre><code>>>> timeit.timeit("562949953420000.7 < 562949953422000") # integer increased by 1000
0.1481498428446173
>>> timeit.timeit("562949953423001.8 < 562949953421000") # float increased by 3001.1
0.1459577925548956
</code></pre>
<p>Changing the comparison operator (e.g. using <code>==</code> or <code>></code> instead) does not affect the times in any noticeable way. </p>
<p>This is not <em>solely</em> related to magnitude because picking larger or smaller values can result in faster comparisons, so I suspect it is down to some unfortunate way the bits line up. </p>
<p>Clearly, comparing these values is more than fast enough for most use cases. I am simply curious as to why Python seems to struggle more with some pairs of values than with others.</p> | 30,100,743 | 2 | 8 | null | 2015-05-07 12:11:08.723 UTC | 50 | 2016-04-15 05:00:19.06 UTC | 2015-05-07 14:35:53.623 UTC | null | 3,923,281 | null | 3,923,281 | null | 1 | 290 | python|performance|floating-point|cpython|python-internals | 14,059 | <p>A comment in the Python source code for float objects acknowledges that:</p>
<blockquote>
<p><a href="https://hg.python.org/cpython/file/ea33b61cac74/Objects/floatobject.c#l285" rel="noreferrer">Comparison is pretty much a nightmare</a></p>
</blockquote>
<p>This is especially true when comparing a float to an integer, because, unlike floats, integers in Python can be arbitrarily large and are always exact. Trying to cast the integer to a float might lose precision and make the comparison inaccurate. Trying to cast the float to an integer is not going to work either because any fractional part will be lost.</p>
<p>To get around this problem, Python performs a series of checks, returning the result if one of the checks succeeds. It compares the signs of the two values, then whether the integer is "too big" to be a float, then compares the exponent of the float to the length of the integer. If all of these checks fail, it is necessary to construct two new Python objects to compare in order to obtain the result.</p>
<p>When comparing a float <code>v</code> to an integer/long <code>w</code>, the worst case is that:</p>
<ul>
<li><code>v</code> and <code>w</code> have the same sign (both positive or both negative),</li>
<li>the integer <code>w</code> has few enough bits that it can be held in the <a href="https://stackoverflow.com/a/2550799/3923281"><code>size_t</code></a> type (typically 32 or 64 bits),</li>
<li>the integer <code>w</code> has at least 49 bits,</li>
<li>the exponent of the float <code>v</code> is the same as the number of bits in <code>w</code>.</li>
</ul>
<p>And this is exactly what we have for the values in the question:</p>
<pre><code>>>> import math
>>> math.frexp(562949953420000.7) # gives the float's (significand, exponent) pair
(0.9999999999976706, 49)
>>> (562949953421000).bit_length()
49
</code></pre>
<p>We see that 49 is both the exponent of the float and the number of bits in the integer. Both numbers are positive and so the four criteria above are met.</p>
<p>Choosing one of the values to be larger (or smaller) can change the number of bits of the integer, or the value of the exponent, and so Python is able to determine the result of the comparison without performing the expensive final check.</p>
<p>This is specific to the CPython implementation of the language.</p>
<hr>
<h3>The comparison in more detail</h3>
<p>The <a href="https://hg.python.org/cpython/file/ea33b61cac74/Objects/floatobject.c#l301" rel="noreferrer"><code>float_richcompare</code></a> function handles the comparison between two values <code>v</code> and <code>w</code>.</p>
<p>Below is a step-by-step description of the checks that the function performs. The comments in the Python source are actually very helpful when trying to understand what the function does, so I've left them in where relevant. I've also summarised these checks in a list at the foot of the answer.</p>
<p>The main idea is to map the Python objects <code>v</code> and <code>w</code> to two appropriate C doubles, <code>i</code> and <code>j</code>, which can then be easily compared to give the correct result. Both Python 2 and Python 3 use the same ideas to do this (the former just handles <code>int</code> and <code>long</code> types separately).</p>
<p>The first thing to do is check that <code>v</code> is definitely a Python float and map it to a C double <code>i</code>. Next the function looks at whether <code>w</code> is also a float and maps it to a C double <code>j</code>. This is the best case scenario for the function as all the other checks can be skipped. The function also checks to see whether <code>v</code> is <code>inf</code> or <code>nan</code>: </p>
<pre class="lang-C prettyprint-override"><code>static PyObject*
float_richcompare(PyObject *v, PyObject *w, int op)
{
double i, j;
int r = 0;
assert(PyFloat_Check(v));
i = PyFloat_AS_DOUBLE(v);
if (PyFloat_Check(w))
j = PyFloat_AS_DOUBLE(w);
else if (!Py_IS_FINITE(i)) {
if (PyLong_Check(w))
j = 0.0;
else
goto Unimplemented;
}
</code></pre>
<p>Now we know that if <code>w</code> failed these checks, it is not a Python float. Now the function checks if it's a Python integer. If this is the case, the easiest test is to extract the sign of <code>v</code> and the sign of <code>w</code> (return <code>0</code> if zero, <code>-1</code> if negative, <code>1</code> if positive). If the signs are different, this is all the information needed to return the result of the comparison:</p>
<pre class="lang-C prettyprint-override"><code> else if (PyLong_Check(w)) {
int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
int wsign = _PyLong_Sign(w);
size_t nbits;
int exponent;
if (vsign != wsign) {
/* Magnitudes are irrelevant -- the signs alone
* determine the outcome.
*/
i = (double)vsign;
j = (double)wsign;
goto Compare;
}
}
</code></pre>
<p>If this check failed, then <code>v</code> and <code>w</code> have the same sign. </p>
<p>The next check counts the number of bits in the integer <code>w</code>. If it has too many bits then it can't possibly be held as a float and so must be larger in magnitude than the float <code>v</code>:</p>
<pre class="lang-C prettyprint-override"><code> nbits = _PyLong_NumBits(w);
if (nbits == (size_t)-1 && PyErr_Occurred()) {
/* This long is so large that size_t isn't big enough
* to hold the # of bits. Replace with little doubles
* that give the same outcome -- w is so large that
* its magnitude must exceed the magnitude of any
* finite float.
*/
PyErr_Clear();
i = (double)vsign;
assert(wsign != 0);
j = wsign * 2.0;
goto Compare;
}
</code></pre>
<p>On the other hand, if the integer <code>w</code> has 48 or fewer bits, it can safely turned in a C double <code>j</code> and compared:</p>
<pre class="lang-C prettyprint-override"><code> if (nbits <= 48) {
j = PyLong_AsDouble(w);
/* It's impossible that <= 48 bits overflowed. */
assert(j != -1.0 || ! PyErr_Occurred());
goto Compare;
}
</code></pre>
<p>From this point onwards, we know that <code>w</code> has 49 or more bits. It will be convenient to treat <code>w</code> as a positive integer, so change the sign and the comparison operator as necessary:</p>
<pre class="lang-C prettyprint-override"><code> if (nbits <= 48) {
/* "Multiply both sides" by -1; this also swaps the
* comparator.
*/
i = -i;
op = _Py_SwappedOp[op];
}
</code></pre>
<p>Now the function looks at the exponent of the float. Recall that a float can be written (ignoring sign) as significand * 2<sup>exponent</sup> and that the significand represents a number between 0.5 and 1:</p>
<pre class="lang-C prettyprint-override"><code> (void) frexp(i, &exponent);
if (exponent < 0 || (size_t)exponent < nbits) {
i = 1.0;
j = 2.0;
goto Compare;
}
</code></pre>
<p>This checks two things. If the exponent is less than 0 then the float is smaller than 1 (and so smaller in magnitude than any integer). Or, if the exponent is less than the number of bits in <code>w</code> then we have that <code>v < |w|</code> since significand * 2<sup>exponent</sup> is less than 2<sup>nbits</sup>. </p>
<p>Failing these two checks, the function looks to see whether the exponent is greater than the number of bit in <code>w</code>. This shows that significand * 2<sup>exponent</sup> is greater than 2<sup>nbits</sup> and so <code>v > |w|</code>:</p>
<pre class="lang-C prettyprint-override"><code> if ((size_t)exponent > nbits) {
i = 2.0;
j = 1.0;
goto Compare;
}
</code></pre>
<p>If this check did not succeed we know that the exponent of the float <code>v</code> is the same as the number of bits in the integer <code>w</code>.</p>
<p>The only way that the two values can be compared now is to construct two new Python integers from <code>v</code> and <code>w</code>. The idea is to discard the fractional part of <code>v</code>, double the integer part, and then add one. <code>w</code> is also doubled and these two new Python objects can be compared to give the correct return value. Using an example with small values, <code>4.65 < 4</code> would be determined by the comparison <code>(2*4)+1 == 9 < 8 == (2*4)</code> (returning false).</p>
<pre class="lang-C prettyprint-override"><code> {
double fracpart;
double intpart;
PyObject *result = NULL;
PyObject *one = NULL;
PyObject *vv = NULL;
PyObject *ww = w;
// snip
fracpart = modf(i, &intpart); // split i (the double that v mapped to)
vv = PyLong_FromDouble(intpart);
// snip
if (fracpart != 0.0) {
/* Shift left, and or a 1 bit into vv
* to represent the lost fraction.
*/
PyObject *temp;
one = PyLong_FromLong(1);
temp = PyNumber_Lshift(ww, one); // left-shift doubles an integer
ww = temp;
temp = PyNumber_Lshift(vv, one);
vv = temp;
temp = PyNumber_Or(vv, one); // a doubled integer is even, so this adds 1
vv = temp;
}
// snip
}
}
</code></pre>
<p>For brevity I've left out the additional error-checking and garbage-tracking Python has to do when it creates these new objects. Needless to say, this adds additional overhead and explains why the values highlighted in the question are significantly slower to compare than others.</p>
<hr>
<p>Here is a summary of the checks that are performed by the comparison function.</p>
<p>Let <code>v</code> be a float and cast it as a C double. Now, if <code>w</code> is also a float:</p>
<ul>
<li><p>Check whether <code>w</code> is <code>nan</code> or <code>inf</code>. If so, handle this special case separately depending on the type of <code>w</code>.</p></li>
<li><p>If not, compare <code>v</code> and <code>w</code> directly by their representations as C doubles.</p></li>
</ul>
<p>If <code>w</code> is an integer:</p>
<ul>
<li><p>Extract the signs of <code>v</code> and <code>w</code>. If they are different then we know <code>v</code> and <code>w</code> are different and which is the greater value.</p></li>
<li><p>(<em>The signs are the same.</em>) Check whether <code>w</code> has too many bits to be a float (more than <code>size_t</code>). If so, <code>w</code> has greater magnitude than <code>v</code>.</p></li>
<li><p>Check if <code>w</code> has 48 or fewer bits. If so, it can be safely cast to a C double without losing its precision and compared with <code>v</code>.</p></li>
<li><p>(<em><code>w</code> has more than 48 bits. We will now treat <code>w</code> as a positive integer having changed the compare op as appropriate.</em>) </p></li>
<li><p>Consider the exponent of the float <code>v</code>. If the exponent is negative, then <code>v</code> is less than <code>1</code> and therefore less than any positive integer. Else, if the exponent is less than the number of bits in <code>w</code> then it must be less than <code>w</code>.</p></li>
<li><p>If the exponent of <code>v</code> is greater than the number of bits in <code>w</code> then <code>v</code> is greater than <code>w</code>.</p></li>
<li><p>(<em>The exponent is the same as the number of bits in <code>w</code>.</em>)</p></li>
<li><p>The final check. Split <code>v</code> into its integer and fractional parts. Double the integer part and add 1 to compensate for the fractional part. Now double the integer <code>w</code>. Compare these two new integers instead to get the result.</p></li>
</ul> |
9,137,591 | How to animate UIImageViews like hatch doors opening | <p>I'm trying to create an animation that would look like 2 french doors (or 2 hatch doors) opening towards the user.</p>
<p>I tried using the built in UIViewAnimationOptionTransitionFlipFromRight transition, but the origin of the transition seems to be the center of the UIImageView rather than the left edge. Basically I have 2 UIImageViews that each fill have the screen. I would like the animation to look like the UIImageViews are lifting from the center of the screen to the edges.</p>
<pre><code>[UIView transitionWithView:leftView
duration:1.0
options:UIViewAnimationOptionTransitionFlipFromRight
animations:^ { leftView.alpha = 0; }
completion:^(BOOL finished) {
[leftView removeFromSuperview];
}];
</code></pre>
<p>Has anyone done something like this before? Any help would be awesome!</p>
<p>UPDATE:
Working code thanks to Nick Lockwood</p>
<pre><code>leftView.layer.anchorPoint = CGPointMake(0, 0.5); // hinge around the left edge
leftView.frame = CGRectMake(0, 0, 160, 460); //reset view position
rightView.layer.anchorPoint = CGPointMake(1.0, 0.5); //hinge around the right edge
rightView.frame = CGRectMake(160, 0, 160, 460); //reset view position
[UIView animateWithDuration:0.75 animations:^{
CATransform3D leftTransform = CATransform3DIdentity;
leftTransform.m34 = -1.0f/500; //dark magic to set the 3D perspective
leftTransform = CATransform3DRotate(leftTransform, -M_PI_2, 0, 1, 0);
leftView.layer.transform = leftTransform;
CATransform3D rightTransform = CATransform3DIdentity;
rightTransform.m34 = -1.0f/500; //dark magic to set the 3D perspective
rightTransform = CATransform3DRotate(rightTransform, M_PI_2, 0, 1, 0);
rightView.layer.transform = rightTransform;
}];
</code></pre> | 9,137,676 | 1 | 1 | null | 2012-02-04 01:19:18.707 UTC | 13 | 2012-02-04 02:31:01.04 UTC | 2012-02-04 02:31:01.04 UTC | null | 178,727 | null | 178,727 | null | 1 | 14 | ios|uiimageview|uiviewanimation | 6,950 | <p>First add the QuartzCore library to your project and <code>#import <QuartzCore/QuartzCore.h></code></p>
<p>Every view has a <code>layer</code> property with sub-properties that are animatable. This is where you'll find all the really cool stuff when it comes to animation capabilities (I suggest reading up on the <code>CALayer</code> class properties you can set - it will blow your mind - dynamic soft drop shadows on any view?)</p>
<p>Anyway, back on topic. To rotate your doors open in 3D, first position them as if they were closed, so with each door filling half the screen.</p>
<p>Now set their <code>view.layer.anchorPoint</code> properties as follows</p>
<pre><code>leftDoorView.layer.anchorPoint = CGPoint(0, 0.5); // hinge around the left edge
rightDoorView.layer.anchorPoint = CGPoint(1.0, 0.5); // hinge around the right edge
</code></pre>
<p>Now apply the following animation</p>
<pre><code>[UIView animateWithDuration:0.5 animations:^{
CATransform3D leftTransform = CATransform3DIdentity;
leftTransform.m34 = -1.0f/500; //dark magic to set the 3D perspective
leftTransform = CATransform3DRotate(leftTransform, M_PI_2, 0, 1, 0); //rotate 90 degrees about the Y axis
leftDoorView.layer.transform = leftTransform;
//do the same thing but mirrored for the right door, that probably just means using -M_PI_2 for the angle. If you don't know what PI is, Google "radians"
}];
</code></pre>
<p>And that should do it.</p>
<p>DISCLAIMER: I've not actually tested this, so the angles may be backwards, and the perspective may be screwy, etc. but it should be a good start at least.</p>
<p>UPDATE: Curiosity got the better of me. Here is fully working code (this assumes that the left and right doors are laid out in the closed position in the nib file):</p>
<pre><code>- (void)viewDidLoad
{
[super viewDidLoad];
leftDoorView.layer.anchorPoint = CGPointMake(0, 0.5); // hinge around the left edge
leftDoorView.center = CGPointMake(0.0, self.view.bounds.size.height/2.0); //compensate for anchor offset
rightDoorView.layer.anchorPoint = CGPointMake(1.0, 0.5); // hinge around the right edge
rightDoorView.center = CGPointMake(self.view.bounds.size.width,self.view.bounds.size.height/2.0); //compensate for anchor offset
}
- (IBAction)open
{
CATransform3D transform = CATransform3DIdentity;
transform.m34 = -1.0f/500;
leftDoorView.layer.transform = transform;
rightDoorView.layer.transform = transform;
[UIView animateWithDuration:0.5 animations:^{
leftDoorView.layer.transform = CATransform3DRotate(transform, M_PI_2, 0, 1, 0);
rightDoorView.layer.transform = CATransform3DRotate(transform, -M_PI_2, 0, 1, 0);
}];
}
- (IBAction)close
{
[UIView animateWithDuration:0.5 animations:^{
CATransform3D transform = CATransform3DIdentity;
transform.m34 = -1.0f/500;
leftDoorView.layer.transform = transform;
rightDoorView.layer.transform = transform;
}];
}
</code></pre> |
9,072,126 | LINQ + Foreach vs Foreach + If | <p>I need to iterate over a List of objects, doing something only for the objects that have a boolean property set to true. I'm debating between this code</p>
<pre><code>foreach (RouteParameter parameter in parameters.Where(p => p.Condition))
{ //do something }
</code></pre>
<p>and this code</p>
<pre><code>foreach (RouteParameter parameter in parameters)
{
if !parameter.Condition
continue;
//do something
}
</code></pre>
<p>The first code is obviously cleaner, but I suspect it's going to loop over the list twice - once for the query and once for the foreach. This won't be a huge list so I'm not overly concerned about performance, but the idea of looping twice just <em>bugs</em> me.</p>
<p>Question: Is there a clean/pretty way to write this without looping twice?</p> | 9,072,356 | 4 | 1 | null | 2012-01-30 23:02:42.16 UTC | 19 | 2014-12-05 15:36:17.027 UTC | null | null | null | null | 288,252 | null | 1 | 57 | c#|linq|foreach | 22,804 | <p>Jon Skeet sometimes does a live-action LINQ demo to explain how this works. Imagine you have three people on stage. On the left we have one guy who has a shuffled deck of cards. In the middle we have one guy who only passes along red cards, and on the right, we have a guy who wants cards.</p>
<p>The guy on the right pokes the guy in the middle. The guy in the middle pokes the guy on the left. The guy on the left hands the guy in the middle a card. If it is black, the guy in the middle throws it on the floor and pokes again until he gets a red card, which he then hands to the guy on the right. Then the guy on the right pokes the guy in the middle again.</p>
<p>This continues until the guy on the left runs out of cards.</p>
<p><strong>The deck was not gone through from start to finish more than once.</strong> However, both the guy on the left and the guy in the middle handled 52 cards, and the guy on the right handled 26 cards. There were a total of 52 + 52 + 26 operations on cards, but <em>the deck was only looped through once</em>. </p>
<p>Your "LINQ" version and the "continue" version are the same thing; if you had</p>
<pre><code>foreach(var card in deck)
{
if (card.IsBlack) continue;
... use card ...
</code></pre>
<p>then there are 52 operations that fetch each card from the deck, 52 operations that test to see if each card is black, and 26 operations that act on the red card. Same thing exactly.</p> |
19,711,956 | Alternative to Files.probeContentType? | <p>In a web project, users upload their files, but when I receive them on the server, they are being stored as .tmp files rather than their original file extension (this is my preferred behavior as well).</p>
<p>However, this is causing a problem with <code>Files.probeContentType()</code>. While locally for me, on my Linux dev machine, <code>Files.probeContentType()</code> works correctly and does determine the right mime type, when I upload my project to the production server (amazon beanstalk), it doesn't seem to correctly determine the mime type.</p>
<p>From reading the javadocs, it seems that the implementation of <code>Files.probeContentType()</code> are different, and I think that on production server, it is reading the file extension and so, is unable to determine the content type.</p>
<p>What's a good, and quick alternative to <code>Files.probeContentType()</code> which will accept a <code>File</code> argument and return a string like <code>image/png</code> as the resulting mime type?</p> | 19,712,063 | 3 | 2 | null | 2013-10-31 16:32:32.74 UTC | 3 | 2020-04-14 09:34:47.747 UTC | null | null | null | null | 49,153 | null | 1 | 33 | java | 19,139 | <p>Take a look at the <a href="http://tika.apache.org/" rel="noreferrer">Apache Tika</a>. It can easily determine a mime type:</p>
<pre><code> Tika tika = new Tika();
File file = ...
String mimeType = tika.detect(file);
</code></pre>
<p>Here's a minimal required maven dependency:</p>
<pre><code> <dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>1.12</version>
</dependency>
</code></pre> |
34,398,279 | Map and filter an array at the same time | <p>I have an array of objects that I want to iterate over to produce a new filtered array. But also, I need to filter out some of the objects from the new array depending of a parameter. I'm trying this:</p>
<pre><code>function renderOptions(options) {
return options.map(function (option) {
if (!option.assigned) {
return (someNewObject);
}
});
}
</code></pre>
<p>Is that a good approach? Is there a better method? I'm open to use any library such as lodash.</p> | 34,398,349 | 15 | 3 | null | 2015-12-21 14:43:13.89 UTC | 49 | 2022-04-25 19:29:04.9 UTC | 2019-03-20 09:37:21.09 UTC | null | 107,625 | null | 1,274,923 | null | 1 | 278 | javascript|arrays | 275,078 | <p>You should use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce" rel="noreferrer"><code>Array.reduce</code></a> for this.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var options = [
{ name: 'One', assigned: true },
{ name: 'Two', assigned: false },
{ name: 'Three', assigned: true },
];
var reduced = options.reduce(function(filtered, option) {
if (option.assigned) {
var someNewValue = { name: option.name, newProperty: 'Foo' }
filtered.push(someNewValue);
}
return filtered;
}, []);
document.getElementById('output').innerHTML = JSON.stringify(reduced);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Only assigned options</h1>
<pre id="output"> </pre></code></pre>
</div>
</div>
</p>
<hr>
<p>Alternatively, the reducer can be a pure function, like this</p>
<pre class="lang-js prettyprint-override"><code>var reduced = options.reduce(function(result, option) {
if (option.assigned) {
return result.concat({
name: option.name,
newProperty: 'Foo'
});
}
return result;
}, []);
</code></pre> |
33,975,431 | How can I capture an image via the user's webcam using getUserMedia? | <p>I want to make a program on the web which will capture an image via the user's webcam. </p>
<p>I am using the <code>getUserMedia</code> Web API. Here is my code, but it does not work. How can I change it to capture the webcam image? </p>
<pre><code><div id="container">
<video autoplay="true" id="videoElement">
</video>
</div>
<script>
</script>
</code></pre>
<p>There is the JS:</p>
<pre><code>var video = document.querySelector("#videoElement");
navigator.getUserMedia, elem = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;
console.log(navigator.getUserMedia);
if (navigator.getUserMedia) {
navigator.getUserMedia({video: true}, handleVideo, videoError);
}
function handleVideo(stream) {
video.src = window.URL.createObjectURL(stream);
}
function videoError(e) {
// do something
}
</code></pre> | 33,976,646 | 3 | 3 | null | 2015-11-28 19:20:17.277 UTC | 8 | 2021-07-06 08:43:34.553 UTC | 2015-11-28 19:34:05.133 UTC | null | 550,349 | null | 4,383,715 | null | 1 | 17 | javascript|html|getusermedia | 63,181 | <p>You can use this working sample</p>
<pre><code> <!DOCTYPE html>
<html>
<head>
</head>
<body onload="init();">
<h1>Take a snapshot of the current video stream</h1>
Click on the Start WebCam button.
<p>
<button onclick="startWebcam();">Start WebCam</button>
<button onclick="stopWebcam();">Stop WebCam</button>
<button onclick="snapshot();">Take Snapshot</button>
</p>
<video onclick="snapshot(this);" width=400 height=400 id="video" controls autoplay></video>
<p>
Screenshots : <p>
<canvas id="myCanvas" width="400" height="350"></canvas>
</body>
<script>
//--------------------
// GET USER MEDIA CODE
//--------------------
navigator.getUserMedia = ( navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
var video;
var webcamStream;
function startWebcam() {
if (navigator.getUserMedia) {
navigator.getUserMedia (
// constraints
{
video: true,
audio: false
},
// successCallback
function(localMediaStream) {
video = document.querySelector('video');
video.srcObject=localMediaStream;
webcamStream = localMediaStream;
},
// errorCallback
function(err) {
console.log("The following error occured: " + err);
}
);
} else {
console.log("getUserMedia not supported");
}
}
function stopWebcam() {
webcamStream.stop();
}
//---------------------
// TAKE A SNAPSHOT CODE
//---------------------
var canvas, ctx;
function init() {
// Get the canvas and obtain a context for
// drawing in it
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext('2d');
}
function snapshot() {
// Draws current image from the video element into the canvas
ctx.drawImage(video, 0,0, canvas.width, canvas.height);
}
</script>
</html>
</code></pre> |
923,238 | Linq Select Certain Properties Into Another Object? | <p>So say I have a collection of Bloops</p>
<pre><code>Class Bloop
Public FirstName
Public LastName
Public Address
Public Number
Public OtherStuff
End Class
</code></pre>
<p>Then I have a class of Razzies</p>
<pre><code>Class Razzie
Public FirstName
Public LastName
End Class
</code></pre>
<p>Is it possible using Linq to select the FirstName and LastName out of all the Bloops in the collection of Bloops and return a collection of Razzies? Or am i limited to a For-Loop to do my work?</p>
<p>To clear up any confusion, either VB or C# will do. Also this will probably lead to me asking the question of (What about using a "Where" clause).</p> | 923,260 | 5 | 0 | null | 2009-05-28 21:12:52.387 UTC | 6 | 2014-05-19 19:37:38.183 UTC | 2009-05-28 21:28:31.933 UTC | null | 48,450 | null | 48,450 | null | 1 | 29 | c#|.net|vb.net|linq|.net-3.5 | 53,648 | <p>This should do the job:</p>
<pre><code>Dim results = From item In bloops _
Select New Razzie() With _
{ _
.FirstName = item.FirstName, _
.LastName = item.LastName _
}
</code></pre>
<p>And if you want to convert the result from <code>IEnumerable<Bloop></code> (what the LINQ query returns) to an array or <code>List<Bloop></code>, just append a call to the <code>ToArray()</code> or <code>ToList()</code> extension methods respectively.</p>
<p>Edit: Corrected the code so that it now has valid VB.NET 9 syntax.</p> |
1,301,907 | How should I think about Scala's Product classes? | <p>The package "scala" has a number of classes named Product, Product1, Product2, and so on, up to Product22.</p>
<p>The descriptions of these classes are surely precise. For example:</p>
<pre><code>Product4 is a cartesian product of 4 components
</code></pre>
<p>Precise, yes. Communicative? Not so much. I expect that this is the perfect wording for someone who already understands the sense of "cartesian product" being used here. For someone who doesn't, it sounds a bit circular. "Oh yes, well of course Product4 is the <em>mumble</em> product of 4 <em>mumble-mumbles</em>."</p>
<p>Please help me understand the correct functional-language viewpoint. What is the sense of "cartesian product" being used here? What do the Product classes' "projection" members indicate?</p> | 1,302,004 | 5 | 0 | null | 2009-08-19 18:48:25.983 UTC | 16 | 2020-09-27 13:38:06.103 UTC | null | null | null | user73774 | null | null | 1 | 76 | scala|functional-programming | 19,284 | <p><a href="http://en.wiktionary.org/wiki/Cartesian_product" rel="nofollow noreferrer">"The set of all possible pairs of elements whose components are members of two sets."</a></p>
<p><a href="http://en.wikipedia.org/wiki/Cartesian_product" rel="nofollow noreferrer">"Specifically, the Cartesian product of two sets X (for example the points on an x-axis) and Y (for example the points on a y-axis), denoted X × Y, is the set of all possible ordered pairs whose first component is a member of X and whose second component is a member of Y (e.g. the whole of the x-y plane)"</a></p>
<p>Perhaps better understanding can be gained by knowing who derives from it:</p>
<p><em>Direct Known Subclasses:</em>
<code>Tuple4</code></p>
<p>Or by, knowing it "<em>extends Product</em>", know what other classes can make use of it, by virtue of extending <code>Product</code> itself. I won't quote that here, though, because it's rather long.</p>
<p>Anyway, if you have types <code>A</code>, <code>B</code>, <code>C</code> and <code>D</code>, then <code>Product4[A,B,C,D]</code> is a class whose instances are all possible elements of the cartesian product of <code>A</code>, <code>B</code>, <code>C</code> and <code>D</code>. Literally.</p>
<p>Except, of course, that <code>Product4</code> is a Trait, not a class. It just provides a few useful methods for classes that are cartesian products of four different sets.</p> |
508,961 | What are some good resources for getting started with COBOL programming? | <p>I'm thinking about learning COBOL. Where should I start?</p> | 508,964 | 6 | 3 | null | 2009-02-03 21:25:37.24 UTC | 9 | 2013-02-08 16:33:33.59 UTC | 2009-03-08 15:54:15.263 UTC | Kb | 49,544 | joeforker | 36,330 | null | 1 | 7 | cobol | 8,168 | <p>I started with this excellent <a href="http://www.csis.ul.ie/COBOL/" rel="noreferrer">tutorial</a>.</p>
<p>There is an open-source COBOL compiler called <a href="http://www.opencobol.org/" rel="noreferrer">OpenCOBOL</a> which you could use to work through the exercises.</p>
<p>And a COBOL <a href="http://www.cobolportal.com/index.asp?bhcp=1" rel="noreferrer">Portal</a>.</p> |
1,014,535 | float.Parse() doesn't work the way I wanted | <p>I have a text file,which I use to input information into my application.The problem is that some values are float and sometimes they are null,which is why I get an exception.</p>
<pre><code> var s = "0.0";
var f = float.Parse(s);
</code></pre>
<p>The code above throws an exception at line 2 "Input string was not in a correct format."</p>
<p>I believe the solution would be the advanced overloads of float.Parse,which include IFormatProvider as a parameter,but I don't know anything about it yet.</p>
<p>How do I parse "0.0"?</p> | 1,014,575 | 6 | 2 | null | 2009-06-18 18:55:21.83 UTC | 5 | 2020-06-02 22:07:12.19 UTC | null | null | null | null | 81,800 | null | 1 | 18 | c# | 38,457 | <p>Dot symbol "." is not used as separator (this depends on Culture settings). So if you want to be absolutely sure that dot is parsed correctly you need to write something like this:</p>
<pre><code>CultureInfo ci = (CultureInfo)CultureInfo.CurrentCulture.Clone();
ci.NumberFormat.CurrencyDecimalSeparator = ".";
avarage = double.Parse("0.0",NumberStyles.Any,ci);
</code></pre> |
618,878 | How to compare just the date part and not the time of two Dates? | <p>I want to compare just the date part (and Not the time) of two VB.NET Date objects.
Is there a way to do that?</p> | 618,886 | 6 | 0 | null | 2009-03-06 13:37:08.493 UTC | 5 | 2018-12-04 08:29:23.81 UTC | 2012-01-09 22:05:36.567 UTC | null | 6,651 | Ylva D | 452,983 | null | 1 | 28 | vb.net|date|compare | 92,681 | <p>Just take the date part of each via the <code>Date</code> property and compare the two:</p>
<pre><code>date1.Date.CompareTo(date2.Date)
</code></pre>
<p>Or:</p>
<pre><code>If date1.Date < date2.Date Then
</code></pre> |
932,745 | How do I get the complete virtual path of an ASP.NET application | <p>How do I know the the complete virtual path that my application is currently hosted? For example:</p>
<pre><code>http://www.mysite.com/myApp
</code></pre>
<p>or</p>
<pre><code>http://www.mysite.com/myApp/mySubApp
</code></pre>
<p>I know the application path of HttpRequest but it only returns the folder name that my application is currently hosted, but how do I get the initial part?</p> | 932,764 | 6 | 0 | null | 2009-05-31 20:03:33.09 UTC | 11 | 2019-03-19 15:21:57.637 UTC | 2009-05-31 20:10:08.867 UTC | null | 7,277 | null | 115,195 | null | 1 | 36 | asp.net|path|virtual | 83,064 | <p>The domain name part of the path is not really a property of the application itself, but depends on the requesting URL. You might be able to reach a single Web site from many different host names. To get the domain name associated with the <strong>current request</strong>, along with the virtual path of the current application, you could do:</p>
<pre><code>Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath
</code></pre>
<p>Technically, an "application" is a virtual directory defined in IIS and <code>Request.ApplicationPath</code> returns exactly that. If you want to get the folder in which the current <strong>request</strong> is handled, you can do this:</p>
<pre><code>VirtualPathUtility.GetDirectory(Request.Path)
</code></pre>
<p>ASP.NET has no idea how to distinguish your sub-application from a bigger application if it's not defined as a virtual directory in IIS. Without registering in IIS, it just sees the whole thing as a single app.</p> |
866,761 | Setting a provisioning profile from within xcodebuild when making iPhone apps | <p>I'm using <code>xcodebuild</code> to compile my iPhone app from the command line. Is there a way to pass in some sort of option to set the provisioning profile? There seems to be not very much information about xcodebuild in general.</p> | 867,477 | 6 | 0 | null | 2009-05-15 02:34:23.637 UTC | 44 | 2022-01-04 20:31:43.137 UTC | 2009-06-04 02:16:35.67 UTC | null | 48,311 | null | 24,817 | null | 1 | 44 | iphone|xcode|xcodebuild|provisioning | 78,757 | <p><a href="http://developer.apple.com/DOCUMENTATION/Darwin/Reference/ManPages/man1/xcodebuild.1.html" rel="nofollow noreferrer">Documentation</a></p>
<p>It seems from the doc, you can't set the provisioning file BUT you can specify the target:</p>
<p>[-target targetname]</p>
<p>So, if you create a target for each provisioning file, you could select the proper target from the command line.</p>
<p>This would basically accomplish what your asking.</p> |
1,091,756 | Are multiple classes in a single file recommended? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/106896/how-many-python-classes-should-i-put-in-one-file">How many Python classes should I put in one file?</a> </p>
</blockquote>
<p>Coming from a C++ background I've grown accustomed to organizing my classes such that, for the most part, there's a 1:1 ratio between classes and files. By making it so that a single file contains a single class I find the code more navigable. As I introduce myself to Python I'm finding lots of examples where a single file contains multiple classes. Is that the recommended way of doing things in Python? If so, why?</p>
<p>Am I missing this convention in the <a href="http://www.python.org/dev/peps/pep-0008/" rel="noreferrer">PEP8</a>?</p> | 1,091,816 | 6 | 1 | null | 2009-07-07 11:14:33.943 UTC | 10 | 2018-02-21 01:30:05.493 UTC | 2017-12-18 01:42:11.073 UTC | null | 355,230 | null | 2,494 | null | 1 | 64 | python|class | 75,860 | <p>Here are some possible reasons:</p>
<ol>
<li>Python is not exclusively class-based - the natural unit of code decomposition in Python is the module. Modules are just as likely to contain functions (which are first-class objects in Python) as classes. In Java, the unit of decomposition is the class. Hence, Python has one module=one file, and Java has one (public) class=one file.</li>
<li>Python is much more expressive than Java, and if you restrict yourself to one class per file (which Python does not prevent you from doing) you will end up with lots of very small files - more to keep track of with very little benefit.</li>
</ol>
<p>An example of roughly equivalent functionality: Java's log4j => a couple of dozen files, ~8000 SLOC. Python logging => 3 files, ~ 2800 SLOC.</p> |
42,441,211 | Python: urllib.error.HTTPError: HTTP Error 404: Not Found | <p>I wrote a script to find spelling mistakes in SO questions' titles.
I used it for about a month.This was working fine. </p>
<p>But now, when I try to run it, I am getting this.</p>
<pre><code>Traceback (most recent call last):
File "copyeditor.py", line 32, in <module>
find_bad_qn(i)
File "copyeditor.py", line 15, in find_bad_qn
html = urlopen(url)
File "/usr/lib/python3.4/urllib/request.py", line 161, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python3.4/urllib/request.py", line 469, in open
response = meth(req, response)
File "/usr/lib/python3.4/urllib/request.py", line 579, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python3.4/urllib/request.py", line 507, in error
return self._call_chain(*args)
File "/usr/lib/python3.4/urllib/request.py", line 441, in _call_chain
result = func(*args)
File "/usr/lib/python3.4/urllib/request.py", line 587, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found
</code></pre>
<p>This is my code</p>
<pre><code>import json
from urllib.request import urlopen
from bs4 import BeautifulSoup
from enchant import DictWithPWL
from enchant.checker import SpellChecker
my_dict = DictWithPWL("en_US", pwl="terms.dict")
chkr = SpellChecker(lang=my_dict)
result = []
def find_bad_qn(a):
url = "https://stackoverflow.com/questions?page=" + str(a) + "&sort=active"
html = urlopen(url)
bsObj = BeautifulSoup(html, "html5lib")
que = bsObj.find_all("div", class_="question-summary")
for div in que:
link = div.a.get('href')
name = div.a.text
chkr.set_text(name.lower())
list1 = []
for err in chkr:
list1.append(chkr.word)
if (len(list1) > 1):
str1 = ' '.join(list1)
result.append({'link': link, 'name': name, 'words': str1})
print("Please Wait.. it will take some time")
for i in range(298314,298346):
find_bad_qn(i)
for qn in result:
qn['link'] = "https://stackoverflow.com" + qn['link']
for qn in result:
print(qn['link'], " Error Words:", qn['words'])
url = qn['link']
</code></pre>
<p><strong>UPDATE</strong></p>
<p>This is the url causing the problem.Even though this url exists.</p>
<p><a href="https://stackoverflow.com/questions?page=298314&sort=active">https://stackoverflow.com/questions?page=298314&sort=active</a></p>
<p>I tried changing the range to some lower values. It works fine now.</p>
<p>Why this happened with above url?</p> | 42,441,391 | 4 | 3 | null | 2017-02-24 14:32:08.433 UTC | 3 | 2021-11-28 01:46:04.003 UTC | 2017-02-24 14:37:54.6 UTC | null | 6,281,993 | null | 6,281,993 | null | 1 | 9 | python|python-3.x|urllib | 84,470 | <p>So apparently the default display number of questions per page is 50 so the range you defined in the loop goes out of the available number of pages with 50 questions per page. The range should be adapted to be within the number of total pages with 50 questions each.</p>
<p>This code will catch the 404 error which was the reason you got an error and ignore it just in case you go out of the range.</p>
<pre><code>from urllib.request import urlopen
def find_bad_qn(a):
url = "https://stackoverflow.com/questions?page=" + str(a) + "&sort=active"
try:
urlopen(url)
except:
pass
print("Please Wait.. it will take some time")
for i in range(298314,298346):
find_bad_qn(i)
</code></pre> |
31,054,910 | Get functions (methods) of a class | <p>I have to dynamically fetch the properties and functions of a ES6 class. Is this even possible? </p>
<p>Using a for...in loop, I only get to loop through the properties of a class instance:</p>
<pre><code>class Foo {
constructor() {
this.bar = "hi";
}
someFunc() {
console.log(this.bar);
}
}
var foo = new Foo();
for (var idx in foo) {
console.log(idx);
}
</code></pre>
<p>Output:</p>
<pre><code>bar
</code></pre> | 31,055,217 | 5 | 2 | null | 2015-06-25 15:41:55.01 UTC | 27 | 2021-06-19 14:15:04.88 UTC | 2016-01-27 10:11:49.02 UTC | null | 1,263,942 | null | 2,111,533 | null | 1 | 98 | javascript|oop|ecmascript-6 | 94,908 | <p>This function will get all functions. Inherited or not, enumerable or not. All functions are included.</p>
<pre><code>function getAllFuncs(toCheck) {
const props = [];
let obj = toCheck;
do {
props.push(...Object.getOwnPropertyNames(obj));
} while (obj = Object.getPrototypeOf(obj));
return props.sort().filter((e, i, arr) => {
if (e!=arr[i+1] && typeof toCheck[e] == 'function') return true;
});
}
</code></pre>
<p><strong>Do test</strong></p>
<p><code>getAllFuncs([1,3]);</code></p>
<p><em>console output:</em></p>
<pre><code>["constructor", "toString", "toLocaleString", "join", "pop", "push", "concat", "reverse", "shift", "unshift", "slice", "splice", "sort", "filter", "forEach", "some", "every", "map", "indexOf", "lastIndexOf", "reduce", "reduceRight", "entries", "keys", "constructor", "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "__defineGetter__", "__lookupGetter__", "__defineSetter__", "__lookupSetter__"]
</code></pre>
<p><strong>Note</strong></p>
<p>It doesn't return functions defined via symbols;</p> |
37,821,148 | Why can't I import AndroidJUnit4 and ActivityTestRule into my unit test class? | <p>I'm having trouble importing some of the Android UI testing framework classes - I just can't figure out what is going wrong!</p>
<p>This is my class:</p>
<pre><code>@RunWith(AndroidJUnit4.class)
@LargeTest
public class ExampleUnitTest {
@Rule
public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule(MainActivity.class);
@Test
public void listGoesOverTheFold() {
onView(withText("Hello world!")).check(matches(isDisplayed()));
}
}
</code></pre>
<p>But for some reason I get the errors 'cannot find symbol ActivityTestRule' and 'cannot find symbol AndroidJUnit4'. I've tried to import them but they cannot be found.</p>
<p>The dependencies in build.gradle are set to:</p>
<pre><code>compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
androidTestCompile 'com.android.support:support-annotations:23.4.0'
androidTestCompile 'com.android.support.test:runner:0.4'
androidTestCompile 'com.android.support.test:rules:0.4'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.2'
</code></pre>
<p>So I think I have all the dependencies setup - I've been trying many things but with no luck.</p>
<p>Anyone have any ideas?</p> | 37,840,321 | 10 | 3 | null | 2016-06-14 20:05:59.017 UTC | 14 | 2022-07-17 10:33:49.28 UTC | 2020-05-10 09:27:08.68 UTC | null | 8,371,844 | null | 1,185,226 | null | 1 | 85 | android|android-support-library|junit4|android-espresso | 51,665 | <p>There are two different types of tests you can set up in Android</p>
<p><strong>Unit Tests</strong> </p>
<ul>
<li>These run directly on the JVM and do not have access to the Android framework classes.</li>
<li>They are kept in the <code>test/java</code> package</li>
<li>Dependencies need to added in the build.gradle file with the command <code>testCompile</code></li>
<li>You generally use Mockito, Robolectric & JUnit for these tests</li>
</ul>
<p><strong>Instrumentation Tests</strong></p>
<ul>
<li>These run on an Android emulator and have full access to all the Android classes</li>
<li>They are kept in the <code>androidTest/java</code> package</li>
<li>Dependencies need to be added to build.gradle with <code>androidTestCompile</code></li>
<li>You generally use Espresso and JUnit for these tests</li>
</ul>
<p>From what I can tell you are trying to write instrumentation tests with Espresso but have your test in the <code>test/java</code> package which is for unit tests. In that case you need to move your test class to the <code>androidTest/java</code> package.</p> |
23,293,782 | MVC-Web API: 405 method not allowed | <p>So, I am stuck in a strange behavior, that is, I am able to send(or POST) data using <code>Postman (plugin of chrome)</code> or using <code>RESTClient(extension of Firefox)</code>, </p>
<p><img src="https://i.stack.imgur.com/EQxjZ.jpg" alt="enter image description here"></p>
<p>but not able to send it from my html file which lies outside the project. It shows following error when i open the html in chrome: </p>
<pre><code>OPTIONS http://localhost:1176/api/user/ 405 (Method Not Allowed)
XMLHttpRequest cannot load http://localhost:1176/api/user/. Invalid HTTP status code 405
</code></pre>
<p>I am not able to make out why is this happening. Following are the details, you might need to help me solve my error:</p>
<p><strong>UserController.cs:</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebAPIv2.Models;
namespace WebAPIv2.Controllers
{
public class UserController : ApiController
{
static IUserRepository userRepository = new UserRepository();
[HttpGet]
public List<TableUser> GetAllUsers()
{
return userRepository.GetAll();
}
[HttpGet]
public HttpResponseMessage GetUser(int id)
{
TableUser user = userRepository.Get(id);
if (user == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "User Not found for the Given ID");
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, user);
}
}
[HttpPost]
public HttpResponseMessage PostUser(TableUser user)
{
user = userRepository.Add(user);
var response = Request.CreateResponse<TableUser>(HttpStatusCode.Created, user);
string uri = Url.Link("DefaultApi", new { id = user.UserId });
response.Headers.Location = new Uri(uri);
return response;
}
[HttpPut]
public HttpResponseMessage PutUser(int id, TableUser user)
{
user.UserId = id;
if (!userRepository.Update(user))
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Unable to Update the User for the Given ID");
}
else
{
return Request.CreateResponse(HttpStatusCode.OK);
}
}
[HttpDelete]
public HttpResponseMessage DeleteProduct(int id)
{
userRepository.Remove(id);
return new HttpResponseMessage(HttpStatusCode.NoContent);
}
}
}
</code></pre>
<p><strong>User.cs:</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebAPIv2.Models
{
public class User
{
public int UserId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
}
</code></pre>
<p><strong>IUserRepository.cs:</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebAPIv2.Models
{
interface IUserRepository
{
List<TableUser> GetAll();
TableUser Get(int id);
TableUser Add(TableUser user);
void Remove(int id);
bool Update(TableUser user);
}
}
</code></pre>
<p><strong>UserRepository.cs:</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebAPIv2.Models
{
public class UserRepository : IUserRepository
{
MastarsFriendsMVCDatabaseEntities userEntities;
public UserRepository()
{
userEntities = new MastarsFriendsMVCDatabaseEntities();
}
public List<TableUser> GetAll()
{
//throw new NotImplementedException();
return userEntities.TableUsers.ToList();
}
public TableUser Get(int id)
{
//throw new NotImplementedException();
var users = userEntities.TableUsers.Where(x => x.UserId == id);
if (users.Count() > 0)
{
return users.Single();
}
else
{
return null;
}
}
public TableUser Add(TableUser user)
{
//throw new NotImplementedException();
if (user == null)
{
throw new ArgumentNullException("item");
}
userEntities.TableUsers.Add(user);
userEntities.SaveChanges();
return user;
}
public void Remove(int id)
{
//throw new NotImplementedException();
TableUser user = Get(id);
if (user != null)
{
userEntities.TableUsers.Remove(user);
userEntities.SaveChanges();
}
}
public bool Update(TableUser user)
{
//throw new NotImplementedException();
if (user == null)
{
throw new ArgumentNullException("student");
}
TableUser userInDB = Get(user.UserId);
if (userInDB == null)
{
return false;
}
userEntities.TableUsers.Remove(userInDB);
userEntities.SaveChanges();
userEntities.TableUsers.Add(user);
userEntities.SaveChanges();
return true;
}
}
}
</code></pre>
<p><strong>WebApiConfig.cs:</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
namespace WebAPIv2
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
//config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
</code></pre>
<p><strong>index.html:</strong></p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>-->
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
</head>
<body>
<script>
$(document).ready(function() {
// jQuery.support.cors = true;
// $.ajax({
// url: "http://localhost:1176/api/user/1",
// headers: {"Accept": "application/json"},
// type: "GET",
// success: function(data) {
// alert(JSON.stringify(data));
// },
// error: function() {
// alert("Error");
// }
// });
// });
var user = {
UserName: "Disha",
Password: "disha123",
FirstName: "Disha",
LastName: "Vora",
Email: "[email protected]"
};
$.ajax({
url: 'http://localhost:1176/api/user/',
type: 'POST',
data: JSON.stringify(user),
crossDomain: true,
headers: {"Accept":"application/json" , "Content-Type":"application/json"},
success: function(data) {
alert('User added Successfully');
},
error: function() {
alert('User not Added');
}
});
});
</script>
</body>
</html>
</code></pre>
<p><strong>Web.config:</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301879
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings></appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
<httpRuntime targetFramework="4.5" />
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule" />
</modules>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Request-Headers:" value="*" />
<add name="Access-Control-Request-Method:" value="*" />
<add name="Access-Control-Allow-Methods" value="*" />
<!--<add name="Allow" value="*"/>-->
</customHeaders>
</httpProtocol>
<handlers>
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<directoryBrowse enabled="true" />
</system.webServer>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
<connectionStrings>
<add name="MastarsFriendsMVCDatabaseEntities" connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=WIN-WWU3DMLR6PX\PIXIELIT;initial catalog=MastarsFriendsMVCDatabase;persist security info=True;user id=sa;password=sa_12345;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
</code></pre> | 23,294,568 | 4 | 2 | null | 2014-04-25 12:54:26.337 UTC | 5 | 2018-12-22 15:33:52.27 UTC | 2014-04-25 12:58:54.9 UTC | null | 1,739,882 | null | 1,739,882 | null | 1 | 11 | c#|html|json|asp.net-web-api2 | 65,525 | <p>WebApi probably blocks the CORS request. To enable CORS on WebApi, use the Microsoft.AspNet.WebApi.Cors package. For further details, check <a href="http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api">http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api</a></p> |
1,657,684 | Creating a list of Folders in an ItemGroup using MSBuild | <p>I'm trying to build an ItemGroup in an MSBuild script which contains a list of folders directly below a given 'Root' folder. So - in this example...</p>
<pre><code>+ Root folder
---- Sub Folder 1
-------- Sub-Sub Folder 1
-------- Sub-Sub Folder 2
---- Sub Folder 2
---- Sub Folder 3
</code></pre>
<p>... I would want my ItemGroup to contain "Sub Folder 1", "Sub Folder 2" and "Sub Folder 3".</p>
<p>There may be a number of files at any point in the hierarchy, but I'm only interested in the folders.</p>
<p>Can anyone help!?</p> | 1,660,498 | 5 | 0 | null | 2009-11-01 17:07:36.423 UTC | 6 | 2013-02-07 23:09:19.827 UTC | 2011-05-03 12:15:28.413 UTC | null | 1,288 | null | 475 | null | 1 | 37 | msbuild | 27,054 | <pre><code><PropertyGroup>
<RootFolder>tmp</RootFolder>
</PropertyGroup>
<ItemGroup>
<AllFiles Include="$(RootFolder)\**\*"/>
<OnlyDirs Include="@(AllFiles->'%(Directory)')"/>
</ItemGroup>
</code></pre>
<p>@(OnlyDirs) might contain duplicates, so you could either use the RemoveDuplicatesTask :</p>
<pre><code><Target Name="foo">
<RemoveDuplicates Inputs="@(OnlyDirs)">
<Output TaskParameter="Filtered" ItemName="UniqueDirs"/>
</RemoveDuplicates>
</Target>
</code></pre>
<p>or use CreateItem with batching for %(AllFiles.Identity) or with msbuild 3.5:</p>
<pre><code><Target Name="foo">
<ItemGroup>
<UniqueDirs Include="%(AllFiles.Directory)"/>
</ItemGroup>
</Target>
</code></pre> |
2,174,419 | Ruby ternary operator without else | <p>Is there a ruby idiom for "If do-this," and "do-this" just as a simple command?</p>
<p>for example, I'm currently doing</p>
<pre><code>object.method ? a.action : nil
</code></pre>
<p>to leave the else clause empty, but I feel like there's probably a more idiomatic way of doing this that doesn't involve having to specify a nil at the end. (and alternatively, I feel like taking up multiple lines of code would be wasteful in this case.</p> | 2,174,433 | 5 | 1 | null | 2010-02-01 03:03:16.31 UTC | 23 | 2017-03-08 19:16:50.267 UTC | 2016-03-29 10:35:20.293 UTC | null | 1,127,485 | null | 124,537 | null | 1 | 83 | ruby|operators|conditional|conditional-operator | 54,820 | <pre><code>a.action if object.method?
</code></pre> |
2,012,589 | PHP & mySQL: Year 2038 Bug: What is it? How to solve it? | <p>I was thinking of using TIMESTAMP to store the date+time, but I read that there is a limitation of year 2038 on it. Instead of asking my question in bulk, I preferred to break it up into small parts so that it is easy for novice users to understand as well. So my question(s):</p>
<ol>
<li>What exactly is the Year 2038 problem?</li>
<li>Why does it occur and what happens when it occurs?</li>
<li>How do we solve it?</li>
<li>Are there any possible alternatives to using it, which do not pose a similar problem?</li>
<li>What can we do to the existing applications that use TIMESTAMP, to avoid the so-called problem, when it really occurs?</li>
</ol>
<p>Thanks in advance.</p> | 2,012,620 | 6 | 8 | null | 2010-01-06 11:36:22.243 UTC | 37 | 2022-07-28 07:26:52.82 UTC | 2010-01-06 11:45:09.433 UTC | null | 185,882 | null | 212,889 | null | 1 | 138 | php|mysql|year2038 | 47,413 | <p><em>I have marked this as a community wiki so feel free to edit at your leisure.</em></p>
<h2>What exactly is the Year 2038 problem?</h2>
<p>"The year 2038 problem (also known as Unix Millennium Bug, Y2K38 by analogy to the Y2K problem) may cause some computer software to fail before or in the year 2038. The problem affects all software and systems that store system time as a signed 32-bit integer, and interpret this number as the number of seconds since 00:00:00 UTC on January 1, 1970."</p>
<hr />
<h2>Why does it occur and what happens when it occurs?</h2>
<p>Times beyond <strong>03:14:07 UTC on Tuesday, 19 January 2038</strong> will 'wrap around' and be stored internally as a negative number, which these systems will interpret as a time in December 13, 1901 rather than in 2038. This is due to the fact that the number of seconds since the UNIX epoch (January 1 1970 00:00:00 GMT) will have exceeded a computer's maximum value for a 32-bit signed integer.</p>
<hr />
<h2>How do we solve it?</h2>
<ul>
<li>Use long data types (64 bits is sufficient)</li>
<li>For MySQL (or MariaDB), if you don't need the time information consider using the <code>DATE</code> column type. If you need higher accuracy, use <code>DATETIME</code> rather than <code>TIMESTAMP</code>. Beware that <code>DATETIME</code> columns do not store information about the timezone, so your application will have to know which timezone was used.</li>
<li><a href="http://en.wikipedia.org/wiki/Year_2038_problem#Solutions" rel="nofollow noreferrer">Other Possible solutions described on Wikipedia</a></li>
<li>Upgrade your Mysql to <a href="https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-28.html#mysqld-8-0-28-feature" rel="nofollow noreferrer">8.0.28</a> or higher</li>
</ul>
<hr />
<h2>Are there any possible alternatives to using it, which do not pose a similar problem?</h2>
<p>Try wherever possible to use large types for storing dates in databases: 64-bits is sufficient - a long long type in GNU C and POSIX/SuS, or <code>sprintf('%u'...)</code> in PHP or the BCmath extension.</p>
<hr />
<h2>What are some potentially breaking use cases even though we're not yet in 2038?</h2>
<p>So a MySQL <a href="http://dev.mysql.com/doc/refman/5.6/en/datetime.html" rel="nofollow noreferrer">DATETIME</a> has a range of 1000-9999, but TIMESTAMP only has a range of 1970-2038. If your system stores birthdates, future forward dates (e.g. 30 year mortgages), or similar, you're already going to run into this bug. Again, don't use TIMESTAMP if this is going to be a problem.</p>
<hr />
<h2>What can we do to the existing applications that use TIMESTAMP, to avoid the so-called problem, when it really occurs?</h2>
<p>Few PHP applications will still be around in 2038, though it's hard to foresee as the web hardly a legacy platform yet.</p>
<p>Here is a process for altering a database table column to convert <code>TIMESTAMP</code> to <code>DATETIME</code>. It starts with creating a temporary column:</p>
<pre><code># rename the old TIMESTAMP field
ALTER TABLE `myTable` CHANGE `myTimestamp` `temp_myTimestamp` int(11) NOT NULL;
# create a new DATETIME column of the same name as your old column
ALTER TABLE `myTable` ADD `myTimestamp` DATETIME NOT NULL;
# update all rows by populating your new DATETIME field
UPDATE `myTable` SET `myTimestamp` = FROM_UNIXTIME(temp_myTimestamp);
# remove the temporary column
ALTER TABLE `myTable` DROP `temp_myTimestamp`
</code></pre>
<hr />
<p><strong>Resources</strong></p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Year_2038_problem" rel="nofollow noreferrer">Year 2038 Problem (Wikipedia)</a></li>
<li><a href="http://readwrite.com/2008/03/13/the_internet_will_end_in_30_years/" rel="nofollow noreferrer">The Internet Will End in 30 Years</a></li>
</ul> |
1,728,475 | NSArray + remove item from array | <p>How to remove an item from NSArray.</p> | 1,728,505 | 7 | 0 | null | 2009-11-13 10:46:01.34 UTC | 5 | 2019-04-19 15:34:43.913 UTC | 2009-11-13 10:49:01.48 UTC | null | 21,234 | null | 178,369 | null | 1 | 47 | iphone|nsarray | 109,129 | <p>NSArray is not mutable, that is, you cannot modify it. You should take a look at <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html" rel="noreferrer">NSMutableArray</a>. Check out the "Removing Objects" section, you'll find there many functions that allow you to remove items:</p>
<pre><code>[anArray removeObjectAtIndex: index];
[anArray removeObject: item];
[anArray removeLastObject];
</code></pre> |
1,368,636 | Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy" | <p>I have a string that looks like this: "9/1/2009". I want to convert it to a DateTime object (using C#).</p>
<p>This works:</p>
<pre><code>DateTime.Parse("9/1/2009", new CultureInfo("en-US"));
</code></pre>
<p>But I don't understand why this doesn't work:</p>
<pre><code>DateTime.ParseExact("9/1/2009", "M/d/yyyy", null);
</code></pre>
<p>There's no word in the date (like "September"), and I know the specific format, so I'd rather use ParseExact (and I don't see why CultureInfo would be needed). But I keep getting the dreaded "String was not recognized as a valid DateTime" exception.</p>
<p>Thanks</p>
<p>A little follow up. Here are 3 approaches that work:</p>
<pre><code>DateTime.ParseExact("9/1/2009", "M'/'d'/'yyyy", null);
DateTime.ParseExact("9/1/2009", "M/d/yyyy", CultureInfo.InvariantCulture);
DateTime.Parse("9/1/2009", new CultureInfo("en-US"));
</code></pre>
<p>And here are 3 that don't work:</p>
<pre><code>DateTime.ParseExact("9/1/2009", "M/d/yyyy", CultureInfo.CurrentCulture);
DateTime.ParseExact("9/1/2009", "M/d/yyyy", new CultureInfo("en-US"));
DateTime.ParseExact("9/1/2009", "M/d/yyyy", null);
</code></pre>
<p>So, Parse() works with "en-US", but not ParseExact... Unexpected?</p> | 1,368,681 | 7 | 3 | null | 2009-09-02 16:07:49.173 UTC | 9 | 2015-05-21 07:58:29.71 UTC | 2009-09-02 16:51:49.68 UTC | null | 68,936 | null | 68,936 | null | 1 | 62 | .net|datetime|parsing|cultureinfo | 116,009 | <p>I suspect the problem is the slashes in the format string versus the ones in the data. That's a culture-sensitive date separator character in the format string, and the final argument being <code>null</code> means "use the current culture". If you <em>either</em> escape the slashes ("M'/'d'/'yyyy") <em>or</em> you specify <code>CultureInfo.InvariantCulture</code>, it will be okay.</p>
<p>If anyone's interested in reproducing this:</p>
<pre><code>// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M'/'d'/'yyyy",
new CultureInfo("de-DE"));
// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy",
new CultureInfo("en-US"));
// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy",
CultureInfo.InvariantCulture);
// Fails
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy",
new CultureInfo("de-DE"));
</code></pre> |
1,762,135 | accessing private variable from member function in PHP | <p>I have derived a class from <code>Exception</code>, basically like so:</p>
<pre><code>class MyException extends Exception {
private $_type;
public function type() {
return $this->_type; //line 74
}
public function __toString() {
include "sometemplate.php";
return "";
}
}
</code></pre>
<p>Then, I derived from <code>MyException</code> like so:</p>
<pre><code>class SpecialException extends MyException {
private $_type = "superspecial";
}
</code></pre>
<p>If I <code>throw new SpecialException("bla")</code> from a function, catch it, and go <code>echo $e</code>, then the <code>__toString</code> function should load a template, display that, and then not actually return anything to echo.</p>
<p>This is basically what's in the template file</p>
<pre><code><div class="<?php echo $this->type(); ?>class">
<p> <?php echo $this->message; ?> </p>
</div>
</code></pre>
<p>in my mind, this should definitely work. However, I get the following error when an exception is thrown and I try to display it:</p>
<blockquote>
<p><strong>Fatal error</strong>: Cannot access private property SpecialException::$_type in <strong>C:\path\to\exceptions.php</strong> on line <strong>74</strong></p>
</blockquote>
<p>Can anyone explain why I am breaking the rules here? Am I doing something horribly witty with this code? Is there a much more idiomatic way to handle this situation? The point of the <code>$_type</code> variable is (as shown) that I want a different div class to be used depending on the type of exception caught.</p> | 1,762,161 | 8 | 2 | null | 2009-11-19 09:53:19.573 UTC | 2 | 2021-02-04 10:55:04.013 UTC | 2009-11-19 10:21:35.553 UTC | null | 98,525 | null | 84,478 | null | 1 | 21 | php|oop|exception | 55,916 | <p>Name the variable protected:</p>
<pre><code>* Public: anyone either inside the class or outside can access them
* Private: only the specified class can access them. Even subclasses will be denied access.
* Protected: only the specified class and subclasses can access them
</code></pre> |
2,300,169 | how to change text in Android TextView | <p>I tried to do this</p>
<pre><code>@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t=new TextView(this);
t=(TextView)findViewById(R.id.TextView01);
t.setText("Step One: blast egg");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t.setText("Step Two: fry egg");
</code></pre>
<p>but for some reason, only the second text shows up when I run it. I think it might have something to do with the <code>Thread.sleep()</code> method blocking. So can someone show me how to implement a timer "asynchronously"?</p>
<p>Thanks.</p> | 2,301,284 | 8 | 1 | null | 2010-02-19 22:50:38.793 UTC | 39 | 2015-04-13 22:09:51.4 UTC | 2013-03-02 18:06:08.177 UTC | null | 1,278,949 | null | 270,811 | null | 1 | 92 | android|textview | 462,538 | <p>I just posted this answer in the android-discuss google group</p>
<p>If you are just trying to add text to the view so that it displays "Step One: blast egg Step Two: fry egg" Then consider using <code>t.appendText("Step Two: fry egg");</code> instead of <code>t.setText("Step Two: fry egg");</code></p>
<p>If you want to completely change what is in the <code>TextView</code> so that it says "Step One: blast egg" on startup and then it says "Step Two: fry egg" at a time later you can always use a </p>
<p>Runnable example sadboy gave</p>
<p>Good luck</p> |
1,785,744 | How do I seed a random class to avoid getting duplicate random values | <p>I have the following code inside a static method in a static class:</p>
<pre><code>Random r = new Random();
int randomNumber = r.Next(1,100);
</code></pre>
<p>I have this inside a loop and I keep getting the same <code>randomNumber</code>!</p>
<p>Any suggestions here?</p> | 1,785,752 | 8 | 4 | null | 2009-11-23 20:31:58.153 UTC | 44 | 2016-08-08 19:56:33.573 UTC | 2016-08-08 19:56:33.573 UTC | null | 157,770 | null | 4,653 | null | 1 | 140 | c#|random | 211,755 | <p>You should not create a new <code>Random</code> instance in a loop. Try something like:</p>
<pre><code>var rnd = new Random();
for(int i = 0; i < 100; ++i)
Console.WriteLine(rnd.Next(1, 100));
</code></pre>
<p>The sequence of random numbers generated by a single <code>Random</code> instance is supposed to be uniformly distributed. By creating a new <code>Random</code> instance for every random number in quick successions, you are likely to seed them with identical values and have them generate identical random numbers. Of course, in this case, the generated sequence will be far from uniform distribution.</p>
<p>For the sake of completeness, if you really need to reseed a <code>Random</code>, you'll create a new instance of <code>Random</code> with the new seed:</p>
<pre><code>rnd = new Random(newSeed);
</code></pre> |
1,459,739 | PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly? | <p>I did a lot of searching and also read the PHP <a href="http://php.net/reserved.variables.server" rel="noreferrer">$_SERVER docs</a>. Do I have this right regarding which to use for my PHP scripts for simple link definitions used throughout my site?</p>
<p><code>$_SERVER['SERVER_NAME']</code> is based on your web server's config file (Apache2 in my case), and varies depending on a few directives: (1) VirtualHost, (2) ServerName, (3) UseCanonicalName, etc.</p>
<p><code>$_SERVER['HTTP_HOST']</code> is based on the request from the client.</p>
<p>Therefore, it would seem to me that the proper one to use in order to make my scripts as compatible as possible would be <code>$_SERVER['HTTP_HOST']</code>. Is this assumption correct?</p>
<p><strong>Followup comments:</strong></p>
<p>I guess I got a little paranoid after reading this article and noting that some folks said "they wouldn't trust any of the <code>$_SERVER</code> vars":</p>
<ul>
<li><p><a href="http://markjaquith.wordpress.com/2009/09/21/php-server-vars-not-safe-in-forms-or-links/" rel="noreferrer">http://markjaquith.wordpress.com/2009/09/21/php-server-vars-not-safe-in-forms-or-links/</a></p></li>
<li><p><a href="http://php.net/manual/en/reserved.variables.server.php#89567" rel="noreferrer">http://php.net/manual/en/reserved.variables.server.php#89567</a> (comment: Vladimir Kornea 14-Mar-2009 01:06)</p></li>
</ul>
<p>Apparently the discussion is mainly about <code>$_SERVER['PHP_SELF']</code> and why you shouldn't use it in the form action attribute without proper escaping to prevent XSS attacks.</p>
<p>My conclusion about my original question above is that it is "safe" to use <code>$_SERVER['HTTP_HOST']</code> for all links on a site without having to worry about XSS attacks, even when used in forms.</p>
<p>Please correct me if I'm wrong.</p> | 1,459,794 | 9 | 0 | null | 2009-09-22 12:16:47.69 UTC | 56 | 2019-02-25 21:37:32.513 UTC | 2018-06-29 20:48:38.273 UTC | null | 142,233 | null | 142,233 | null | 1 | 188 | php|apache|security|owasp | 485,320 | <p>That’s probably everyone’s first thought. But it’s a little bit more difficult. See <a href="http://shiflett.org/blog/2006/mar/server-name-versus-http-host" rel="noreferrer">Chris Shiflett’s article <em><code>SERVER_NAME</code> Versus <code>HTTP_HOST</code></em></a>.</p>
<p>It seems that there is no silver bullet. Only when you <a href="http://httpd.apache.org/docs/2.2/mod/core.html#usecanonicalname" rel="noreferrer">force Apache to use the canonical name</a> you will always get the right server name with <code>SERVER_NAME</code>.</p>
<p>So you either go with that or you check the host name against a white list:</p>
<pre><code>$allowed_hosts = array('foo.example.com', 'bar.example.com');
if (!isset($_SERVER['HTTP_HOST']) || !in_array($_SERVER['HTTP_HOST'], $allowed_hosts)) {
header($_SERVER['SERVER_PROTOCOL'].' 400 Bad Request');
exit;
}
</code></pre> |
1,957,156 | How to add a custom button to the toolbar that calls a JavaScript function? | <p>I'd like to add a button to the toolbar that calls a JavaScript function like <code>Tada()</code>?</p>
<p>Any ideas on how to add this?</p> | 1,966,239 | 10 | 0 | null | 2009-12-24 07:06:27.71 UTC | 50 | 2019-12-31 08:56:34.507 UTC | 2015-03-23 11:58:06.977 UTC | null | 1,469,208 | null | 149,080 | null | 1 | 72 | javascript|ckeditor | 127,748 | <p>I am in the process of developing a number of custom Plugins for CKEditor and here's my survival pack of bookmarks:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/1139766/ckeditor-custom-plugins-button">A StackOverflow post linking to and talking about a plugins tutorial that got me started</a> (Tim Down already mentioned this)</li>
<li>A <a href="http://code.google.com/p/lajox/" rel="noreferrer">number of ready-made plugins for FCK and CKEditor</a> that may improve one's understanding of the system</li>
<li>The Blog of <a href="http://alfonsoml.blogspot.com/" rel="noreferrer">AlfonsoML</a>, one of the developers, lots of valuable stuff there, e.g. <a href="http://alfonsoml.blogspot.com/2009/12/plugin-localization-in-ckeditor-vs.html" rel="noreferrer">Plugin localization in CKEditor</a></li>
<li><a href="http://cksource.com/forums/viewtopic.php?f=11&t=16040" rel="noreferrer">Interaction between dialog buttons and a IFrame dialog</a>, with input from Garry Yao, one of the developers </li>
<li>The <a href="http://cksource.com/forums/" rel="noreferrer">forums</a> are not as bad as they look, there are some hidden gems there. Make sure you search there, well, if not first, then at least second or third. </li>
</ul>
<p>For your purpose, I would recommend look at one of the plugins in the <code>_source/plugins</code> directory, for example the "print" button. Adding a simple Javascript function is quite easy to achieve. You should be able to duplicate the print plugin (take the directory from _source into the actual plugins/ directory, worry about minification later), rename it, rename every mention of "print" within it, give the button a proper name you use later in your toolbar setup to include the button, and add your function.</p> |
1,710,935 | How do I find the PublicKeyToken for a particular dll? | <p>I need to recreate a provider in my web.config file that looks something like this:</p>
<pre><code><membership defaultProvider="AspNetSqlMemProvider">
<providers>
<clear/>
<add connectionStringName="TRAQDBConnectionString" applicationName="TRAQ" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="0"
name="AspNetSqlMemProvider"
type="System.Web.Security.SqlMembershipProvider, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"
/>
</providers>
</membership>
</code></pre>
<p>However, I get a runtime error saying this assembly cannot be loaded, and I think it is because I have the wrong PublicKeyToken. How do I look up the PublicKeyToken for my assembly?</p>
<p>Alternatively, am I going entirely the wrong way with this?</p> | 24,136,074 | 13 | 1 | null | 2009-11-10 20:23:35.26 UTC | 54 | 2022-05-31 15:00:37.943 UTC | 2016-05-30 08:07:25.11 UTC | null | 1,623,521 | null | 106,356 | null | 1 | 249 | .net|dll|.net-assembly|publickeytoken | 181,450 | <p>Using <strong>PowerShell</strong>, you can execute this statement:</p>
<pre><code>([system.reflection.assembly]::loadfile("C:\..\Full_Path\..\MyDLL.dll")).FullName
</code></pre>
<p>The output will provide the <em>Version</em>, <em>Culture</em> and <em>PublicKeyToken</em> as shown below:</p>
<pre><code>MyDLL, Version=1.0.0.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a
</code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.