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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7,493,781 | Explain the Differential Evolution method | <p>Can someone please explain the Differential Evolution method? The Wikipedia <a href="http://en.wikipedia.org/wiki/Differential_evolution#Algorithm" rel="noreferrer">definition</a> is extremely technical.</p>
<p>A dumbed-down explanation followed by a simple example would be appreciated :)</p> | 7,519,536 | 3 | 0 | null | 2011-09-21 02:02:56.077 UTC | 9 | 2017-12-24 21:40:45.903 UTC | 2015-11-03 21:08:50.59 UTC | null | 3,235,496 | null | 14,731 | null | 1 | 17 | evolutionary-algorithm|differential-evolution | 13,112 | <p>Here's a <strong>simplified</strong> description. DE is an optimisation technique which iteratively modifies a population of candidate solutions to make it converge to an optimum of your function. </p>
<p>You first initialise your candidate solutions randomly. Then at each iteration and for each candidate solution x you do the following:</p>
<ol>
<li>you produce a trial vector: v = a + ( b - c ) / 2, where a, b, c are three distinct candidate solutions picked randomly among your population.</li>
<li>you randomly swap vector components between x and v to produce v'. At least one component from v must be swapped.</li>
<li>you replace x in your population with v' only if it is a better candidate (i.e. it better optimise your function).</li>
</ol>
<p>(Note that the above algorithm is very simplified; don't code from it, find proper spec. elsewhere instead)</p>
<p>Unfortunately the Wikipedia article lacks illustrations. It is easier to understand with a graphical representation, you'll find some in these slides: <a href="http://www-personal.une.edu.au/~jvanderw/DE_1.pdf" rel="noreferrer">http://www-personal.une.edu.au/~jvanderw/DE_1.pdf</a> .</p>
<p>It is similar to genetic algorithm (GA) except that the candidate solutions are not considered as binary strings (chromosome) but (usually) as real vectors. One key aspect of DE is that the mutation step size (see step 1 for the mutation) is dynamic, that is, it adapts to the configuration of your population and will tend to zero when it converges. This makes DE less vulnerable to genetic drift than GA.</p> |
7,464,035 | How to tell ProGuard to keep everything in a particular package? | <p>My application has many activities and uses native library too. With the default ProGuard configuration which Eclipse generates ProGuard removes many things - OnClick methods, static members, callback methods which my native library uses... Is it there a simple way to instruct ProGuard to NOT remove anything from my package? Removing things saves only about 2.5% of the application size, but breaks my application completely. Configuring, testing and maintaining it class by class in ProGuard configuration would be a pain.</p> | 7,469,397 | 3 | 4 | null | 2011-09-18 19:52:57.577 UTC | 31 | 2021-04-28 22:50:45.12 UTC | 2015-10-17 17:45:32.647 UTC | null | 4,081,336 | null | 935,242 | null | 1 | 60 | android|proguard | 68,649 | <p>As final result I found that just keeping all class members is not enough for the correct work of my application, nor necessary. I addded to the settings file this:</p>
<pre><code>-keepclasseswithmembers class * {
void onClick*(...);
}
-keepclasseswithmembers class * {
*** *Callback(...);
}
</code></pre>
<p>The case with onClick* is for all methods which I address in android:onClick atribute in .xml layout files (I begin the names of all such methods with 'onClick').</p>
<p>The case with *Callback is for all callback methods which I call from my native code (through JNI). I place a suffix 'Callback' to the name of every such method.</p>
<p>Also I added few rows for some special cases with variables which I use from native code, like:</p>
<pre><code>-keep class com.myapp.mypackage.SomeMyClass {
*** position;
}
</code></pre>
<p>(for a varible with name 'position' in a class with name 'SomeMyClass' from package com.myapp.mypackage)</p>
<p>All this is because these onClick, callback etc. must not only be present but also kept with their original names. The other things ProGuard can optimize freely.</p>
<p>The case with the native methods is important also, but for it there was a declaration in the generated from Eclipse file:</p>
<pre><code>-keepclasseswithmembernames class * {
native <methods>;
}
</code></pre> |
7,369,647 | How do I get to the next line in the R command prompt without executing? | <p>The question is so simple I can't seem to find an answer.</p> | 7,369,659 | 4 | 2 | null | 2011-09-10 04:37:16.347 UTC | 1 | 2021-11-07 17:25:19.827 UTC | null | null | null | null | 546,427 | null | 1 | 3 | r | 41,259 | <p>Use'SHIFT-ENTER' to get to a new line in R without executing the command.</p> |
24,236,912 | How do I hide the status bar in a Swift iOS app? | <p>I'd like to remove the status bar at the top of the screen.</p>
<p>This does not work:</p>
<pre><code>func application
(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: NSDictionary?)
-> Bool
{
application.statusBarHidden = true
return true
}
</code></pre>
<p>I've also tried:</p>
<pre><code>func application
(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: NSDictionary?)
-> Bool
{
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
var controller = UIViewController()
application.statusBarHidden = true
controller.setNeedsStatusBarAppearanceUpdate()
var view = UIView(frame: CGRectMake(0, 0, 320, 568))
view.backgroundColor = UIColor.redColor()
controller.view = view
var label = UILabel(frame: CGRectMake(0, 0, 200, 21))
label.center = CGPointMake(160, 284)
label.textAlignment = NSTextAlignment.Center
label.text = "Hello World"
controller.view.addSubview(label)
self.window!.rootViewController = controller
self.window!.makeKeyAndVisible()
return true
}
</code></pre> | 24,236,943 | 27 | 1 | null | 2014-06-16 05:04:05.293 UTC | 55 | 2020-06-05 00:07:02.257 UTC | 2015-04-24 09:38:41.257 UTC | null | 1,055,664 | null | 336,892 | null | 1 | 215 | ios|iphone|ios7|swift | 166,161 | <p>You really should implement prefersStatusBarHidden on your view controller(s):</p>
<p><strong>Swift 3 and later</strong></p>
<pre><code>override var prefersStatusBarHidden: Bool {
return true
}
</code></pre> |
21,415,181 | Can I stop the "this website does not supply identity information" message | <p>I have a site which is completely on https: and works well, but, some of the images served are from other sources e.g. ebay, or Amazon.</p>
<p>This causes the browser to prompt a message: "<strong>this website does not supply identity information</strong>"</p>
<p>How can I avoid this? The images must be served from elsewhere sometimes.</p> | 21,428,120 | 5 | 3 | null | 2014-01-28 19:39:24.953 UTC | 9 | 2020-10-04 02:32:27.823 UTC | null | null | null | null | 973,552 | null | 1 | 28 | security|https | 80,946 | <p>Firefox shows the message</p>
<blockquote>
<p>"This website does not supply identity information."</p>
</blockquote>
<p>while hovering or clicking the favicon (Site Identity Button) when</p>
<ul>
<li>you requested a page over HTTP</li>
<li>you requested a page over HTTPS, but the page contains mixed passive content</li>
</ul>
<h3>HTTP</h3>
<p>HTTP connections generally don't supply any reliable identity information to the browser. That's normal. HTTP was designed to simply transmit data, not to secure the data it transmits.</p>
<p>On server side you could only avoid that message, if the server would start using a SSL certificate and the code of the page would be changed to exclusively use HTTPS requests.</p>
<p>To avoid the message on client side you could enter <code>about:config</code> in the address bar, confirm you'll be careful and set <code>browser.chrome.toolbar_tips = false</code>.</p>
<h3>HTTPS, mixed passive content</h3>
<p>When you request a page over HTTPS from a site which is using a SSL certificate, the site <em>does</em> supply identity information to the browser and normally the message wouldn't appear.</p>
<p>But if the requested page embeds at least one <code><img></code>, <code><video></code>, <code><audio></code> or <code><object></code> element which includes content over HTTP (which won't supply identity information), than you'll get a so-called <em>mixed passive content</em> <sup>*</sup> situation.</p>
<p>Firefox won't block mixed passive content by default, but only show said message to warn the user.</p>
<p>To avoid this on server side, you'd first need to identify which requests are producing mixed content.</p>
<p>With Firefox on Windows you can use <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>K</kbd> (Control-Option-K on Mac) to open the web console, deactivate the css, js and security filters, and press <kbd>F5</kbd> to reload the page, to show all the requests of the page.</p>
<p>Then fix your code for each line which is showing "mixed content", i.e. change the appropriate parts of your code to use <code>https://</code> or, depending on your case, <a href="http://www.paulirish.com/2010/the-protocol-relative-url/" rel="noreferrer">protocol-relative URLs</a>.</p>
<p>If the external site an element is requested from doesn't use a SSL certificate, the only chance to avoid the message would be to copy the external content over to your site so your code can refer to it locally via HTTPS.</p>
<hr>
<p><sub>* Firefox also knows <em>mixed <strong>active</strong> content</em>, which is blocked by default, but that's another story.
</sub></p> |
21,825,393 | How to use pipe within -exec in find | <p>Is there any way to use pipe within an -exec in find? I don't want grep to go through whole file, but only through first line of each file.</p>
<pre><code>find /path/to/dir -type f -print -exec grep yourstring {} \;
</code></pre>
<p>I tried to put the pipelines there with "cat" and "head -1", but it didn't work very well. I tried to use parenthesis somehow, but I didn't manage to work out how exactly to put them there.
I would be very thankful for your help. I know how to work it out other way, without using the find, but we tried to do it in school with the usage of find and pipeline, but couldn`t manage how to. </p>
<pre><code>find /path/to/dir -type f -print -exec cat {} | head -1 | grep yourstring \;
</code></pre>
<p>This is somehow how we tried to do it, but could't manage the parenthesis and wheter it is even possible. I tried to look through net, but couldn' t find any answers.</p> | 21,825,690 | 2 | 3 | null | 2014-02-17 09:36:26.803 UTC | 6 | 2015-04-19 16:01:29.673 UTC | null | null | null | null | 3,019,115 | null | 1 | 33 | unix|find|exec|pipe | 20,598 | <p>In order to be able to use a pipe, you need to execute a <em>shell</em> command, i.e. the command with the pipeline has to be a single command for <code>-exec</code>.</p>
<pre><code>find /path/to/dir -type f -print -exec sh -c "cat {} | head -1 | grep yourstring" \;
</code></pre>
<p>Note that the above is a <em>Useless Use of Cat</em>, that could be written as:</p>
<pre><code>find /path/to/dir -type f -print -exec sh -c "head -1 {} | grep yourstring" \;
</code></pre>
<hr>
<p>Another way to achieve what you want would be to say:</p>
<pre><code>find /path/to/dir -type f -print -exec awk 'NR==1 && /yourstring/' {} \;
</code></pre> |
2,242,042 | Array Merge (Union) | <p>I have two array I need to merge, and using the Union (|) operator is PAINFULLY slow.. are there any other ways to accomplish an array merge?</p>
<p>Also, the arrays are filled with objects, not strings. </p>
<p>An Example of the objects within the array </p>
<pre><code>#<Article
id: 1,
xml_document_id: 1,
source: "<article><domain>events.waikato.ac</domain><excerpt...",
created_at: "2010-02-11 01:32:46",
updated_at: "2010-02-11 01:41:28"
>
</code></pre>
<p>Where source is a short piece of XML.</p>
<p><strong>EDIT</strong></p>
<p>Sorry! By 'merge' I mean I need to not insert duplicates.</p>
<pre><code>A => [1, 2, 3, 4, 5]
B => [3, 4, 5, 6, 7]
A.magic_merge(B) #=> [1, 2, 3, 4, 5, 6, 7]
</code></pre>
<p>Understanding that the integers are actually Article objects, and the Union operator appears to take <em>forever</em></p> | 2,245,945 | 4 | 4 | null | 2010-02-11 03:22:55.31 UTC | 9 | 2010-02-12 13:57:29.227 UTC | 2010-02-11 11:24:08.61 UTC | null | 7,552 | null | 262,983 | null | 1 | 35 | ruby-on-rails|ruby|arrays | 51,568 | <p>Here's a script which benchmarks two merge techniques: using the pipe operator (<code>a1 | a2</code>), and using concatenate-and-uniq (<code>(a1 + a2).uniq</code>). Two additional benchmarks give the time of concatenate and uniq individually.</p>
<pre><code>require 'benchmark'
a1 = []; a2 = []
[a1, a2].each do |a|
1000000.times { a << rand(999999) }
end
puts "Merge with pipe:"
puts Benchmark.measure { a1 | a2 }
puts "Merge with concat and uniq:"
puts Benchmark.measure { (a1 + a2).uniq }
puts "Concat only:"
puts Benchmark.measure { a1 + a2 }
puts "Uniq only:"
b = a1 + a2
puts Benchmark.measure { b.uniq }
</code></pre>
<p>On my machine (Ubuntu Karmic, Ruby 1.8.7), I get output like this:</p>
<pre><code>Merge with pipe:
1.000000 0.030000 1.030000 ( 1.020562)
Merge with concat and uniq:
1.070000 0.000000 1.070000 ( 1.071448)
Concat only:
0.010000 0.000000 0.010000 ( 0.005888)
Uniq only:
0.980000 0.000000 0.980000 ( 0.981700)
</code></pre>
<p>Which shows that these two techniques are very similar in speed, and that <code>uniq</code> is the larger component of the operation. This makes sense intuitively, being O(n) (at best), whereas simple concatenation is O(1).</p>
<p>So, if you really want to speed this up, you need to look at how the <code><=></code> operator is implemented for the objects in your arrays. I believe that most of the time is being spent comparing objects to ensure inequality between any pair in the final array.</p> |
49,667,463 | Using alert message from other component in angular | <p>I googled several examples about using functions/variables from other components in Angular 4/5. They helped me a bit for understanding but I still couldn't figure out the solution to my problem.</p>
<p>I wanna call a standard JavaScript <strong>alert</strong> from another component.</p>
<p>I have a component, which has a variable like this:</p>
<p><strong>center.ts</strong></p>
<pre><code>export class CenterPage {
public message = new alert("Warning");
</code></pre>
<p><strong>center.html</strong></p>
<pre><code><products [message]="message"></products>
</code></pre>
<p>I'm using @Input to get the message in <strong>products.ts</strong></p>
<pre><code>export class ProductsComponent {
@Input() message;
</code></pre>
<p>Now I want to show the alert, when the user clicks on a button in <strong>product.html</strong></p>
<pre><code><button (click)="message"></button>
</code></pre>
<p>This seems to be wrong and I think this is not the right way how I'm trying to show the alert when the user clicks on the button.</p>
<p>How can I do this correctly?</p>
<p><strong>EDIT</strong></p>
<p>This is only one example. In the end I will have to call the same alert in several components. So I try to have only one function which I can call from all components so I won't have redundant code.</p> | 49,668,536 | 2 | 3 | null | 2018-04-05 08:20:50.673 UTC | 2 | 2018-04-05 09:15:11.513 UTC | 2018-04-05 08:28:41.683 UTC | null | 7,439,880 | null | 7,439,880 | null | 1 | 3 | angular|typescript|click|components|alert | 74,893 | <p><strong>You definitely have to use a service</strong> for such a functionality. You have to create a "service" folder in which you will create like a alert.service.ts file. in this file you will define the alert function you want to display in all your components.</p>
<p>Then you will import this service in the components which need it.</p>
<p>I suggest you to read this tuto from the angular documentation, which is really handy : <a href="https://angular.io/tutorial/toh-pt4" rel="nofollow noreferrer">https://angular.io/tutorial/toh-pt4</a></p> |
48,954,087 | Intellij IDEA complains cannot resolve spring boot properties but they work fine | <p><a href="https://i.stack.imgur.com/5Rcxm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5Rcxm.png" alt="enter image description here"></a></p>
<blockquote>
<p>Can not resolve configuration property '...</p>
</blockquote>
<p>I have no problem accessing my properties through the @Value annotation or through an autowired Evironment. But all of my own defined properties get this warning in IDEA. What should I be doing to get IDEA to recognize these and not bother me?</p> | 50,776,393 | 5 | 6 | null | 2018-02-23 18:23:45.927 UTC | 15 | 2021-11-24 14:03:43.347 UTC | null | null | null | null | 2,480,560 | null | 1 | 108 | spring|spring-boot|intellij-idea|application.properties | 71,640 | <p>In order for IntelliJ IDEA to know your Spring Boot properties, you can define <strong>Spring Boot configuration metadata</strong> in your project.</p>
<h3>Option 1:</h3>
<p>If you can use a <code>@ConfigurationProperties</code>-annotated class for your properties, you can add the Spring Boot configuration annotation processor to your classpath and IntelliJ IDEA will generate the configuration metadata for you in <code>target</code> or <code>out</code>:</p>
<p><strong>Maven:</strong></p>
<pre><code><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</code></pre>
<p><strong>Gradle:</strong></p>
<pre><code>implementation 'org.springframework.boot:spring-boot-configuration-processor'
</code></pre>
<h3>Option 2:</h3>
<p>Create the configuration metadata file yourself <code>src/main/resources/META-INF/spring-configuration-metadata.json</code>:</p>
<p>Content:</p>
<pre><code>{
"properties": [
{
"name": "myapp.someprop",
"type": "java.lang.String"
},
{
"name": "myapp.someintprop",
"type": "java.lang.Integer"
}
]
}
</code></pre>
<h3>Options 1 and 2:</h3>
<p>In the IntelliJ IDEA tool window of your build system (Maven/Gradle), click the "Refresh" button.</p>
<p>Select <code>Build > Rebuild Project</code> from the menu.</p>
<p>If the warning still appears, you can try to restart the IDE. Select <code>File > Invalidate Caches / Restart</code> and click on <code>Invalidate and Restart</code>.</p> |
7,363,119 | Android: How do I display an updating clock in a TextView | <p>have a clock I want to display in a TextView.</p>
<p>I would have thought there was a few nice functions to do this, but I couldn't find anything.
I ended up implementing my own way that uses a Handler. What I'm asking though, is there a better (more efficient) way to display a real time updating clock?</p>
<pre><code>private Runnable mUpdateClockTask = new Runnable() {
public void run() {
setTime();
mClockHandler.postDelayed(this, 1000);
}
};
</code></pre>
<p>That's my handler, which runs every second, and then my set time and date function is below</p>
<pre><code>TextView mClockView;
public void setTime() {
Calendar cal = Calendar.getInstance();
int minutes = cal.get(Calendar.MINUTE);
if (DateFormat.is24HourFormat(this)) {
int hours = cal.get(Calendar.HOUR_OF_DAY);
mClockView.setText((hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes));
}
else {
int hours = cal.get(Calendar.HOUR);
mClockView.setText(hours + ":" + (minutes < 10 ? "0" + minutes : minutes) + " " + new DateFormatSymbols().getAmPmStrings()[cal.get(Calendar.AM_PM)]);
}
}
</code></pre>
<p>Cheers</p> | 7,363,289 | 6 | 0 | null | 2011-09-09 14:22:52.76 UTC | 12 | 2020-08-14 11:06:00.9 UTC | null | null | null | null | 693,829 | null | 1 | 24 | android|timer|clock | 56,790 | <p>Remember: premature optimization is the root of all evil. So only optimize when you are sure (=have measured it) that your implementation is slow/inefficient.</p>
<p>That said, a more efficient method would probably be to record start time via <code>System.currentTimeMillis()</code> and then periodically check it and calculate difference in minutes. </p> |
7,192,101 | Writing an HTML Parser | <p>I am currently attempting (or planning to attempt) to write a simple (as possible) program to parse an html document into a tree.</p>
<p>After googling I have found many answers saying "don't do it it's been done" (or words to that effect); and references to examples of HTML parsers; and also a rather emphatic article on why one shouldn't use Regular expresions. However I haven't found any guides on the "right" way to write a parser. (This, by the way, is something I'm attempting more as a learning exersise than anything so I'd quite like to do it rather than use a premade one)</p>
<p>I believe I could make a working XML parser just by reading the document and adding the tags/text etc. to the tree, stepping up a level whenever I hit a close tag (again, simple, no fancy threading or efficiency required at this stage.). However, for HTML not all tags are closed.</p>
<p>So my question is this: what would you recommend as a way of dealing with this? The only idea I've had is to treat it in a similar way as the XML but have a list of tags that aren't necessarily closed each with conditions for closure (e.g. <p> ends on </p> or next <p> tag).</p>
<p>Has anyone any other (hopefully better) suggestions? Is there a better way of doing this altogether?</p> | 7,192,363 | 6 | 8 | null | 2011-08-25 14:26:50.493 UTC | 8 | 2020-10-20 13:02:14.633 UTC | 2011-08-25 14:42:45.133 UTC | null | 873,254 | null | 912,318 | null | 1 | 36 | html|parsing|html-parsing | 13,383 | <p>so, I'll try for an answer here - </p>
<p>basically, what makes "plain" html parsing (not talking about valid xhtml here) different from xml parsing are loads of rules like never-ending <code><img></code>tags, or, strictly speaking, the fact that even the sloppiest of all html markups will somewhat render in a browser.
You will need a validator along with the parser, to build your tree. But you'll have to decide on a standard for HTML you want to support, so that when you come across a weakness in the markup, you'll know it's an error and not just sloppy html.</p>
<p>know all the rules, build a validator, and then you'll be able to build a parser. that's Plan A.</p>
<p>Plan B would be, to allow for a certain error-resistance in your parser, which would render the validation step needless. For example, parse all the tags, and put them in a list, omitting any attributes, so that you can easily operate on the list, determining whether a tag is left open, or was never opened at all, to eventually get a "good" layout tree, which will be an approximate solution for sloppy layout, while being exact for correct layout.</p>
<p>hope that helped!</p> |
7,155,375 | How to set minimum height for a div? | <p>I have a page in which expanding content flows out of the holding div, the relevant CSS is below as well. Simply removing the <code>height:510px</code> line will allow the <code>div</code> to expand as needed. However, new users who have no content will not have any height and the page will look unblanced. How do I set a minimum height?</p>
<pre><code>.Bb1
{
width:680px;
height:510px;
background-color:#ffffff;
float:left;
border-right:3px solid #edefed;
border-radius: 10px;
}
</code></pre> | 7,155,387 | 6 | 0 | null | 2011-08-23 01:26:51.403 UTC | 10 | 2021-08-17 10:36:40.013 UTC | 2021-08-17 10:36:40.013 UTC | user656925 | 2,287,576 | user656925 | null | null | 1 | 47 | css | 96,177 | <p>CSS allows a "min-height" property. This can be used to set the minimum height of the div you're talking about.</p>
<pre><code>#div-id { min-height: 100px; }
</code></pre> |
7,442,760 | How are live tiles made in Windows 8? | <p>I've searched the samples, the developer site, the getting started and the enhancing <em>bla bla bla</em> pages.</p>
<p>Even using some search queries on Google, I can't seem any information on live tiles in Windows 8.</p>
<p>How do I create a live tile in Windows 8? What languages can be used for that? C#? XAML?</p> | 7,442,950 | 6 | 0 | null | 2011-09-16 09:38:05.81 UTC | 21 | 2013-02-25 20:38:32.88 UTC | null | null | null | null | 47,064 | null | 1 | 56 | c#|xaml|windows-8|live-tile | 36,931 | <p><a href="http://msdn.microsoft.com/en-us/library/windows/apps/br211386" rel="noreferrer">http://msdn.microsoft.com/en-us/library/windows/apps/br211386</a></p>
<p>You can use either C# or VB + XAML or HTML/JS or C++.</p>
<p>That was the big announcement at the BUILD conference and the whole point of WinRT (God I hope they actually are serious about pushing WinRT for more than a year).</p>
<p>Otherwise it would be back to the Silverlight/.Net uprising that we saw after the first preview. . .</p>
<p><strong>edit</strong></p>
<p>You'll first need to learn the terminology of the MetroUI. You can also find more info under Windows Phone 7.</p>
<p>The Live Tiles can send tile notifications. That's how the socialite tile does the facebook feed. The OS will <em>cycle</em> through tile notifications that you've declared. This is all in the basic Tile sample and the advanced Tile sample.</p>
<p><a href="http://code.msdn.microsoft.com/windowsapps/Windows-Developer-Preview-6b53adbb" rel="noreferrer">Here</a> is a link to all the samples from the BUILD event.</p>
<p>Start <a href="http://msdn.microsoft.com/en-us/library/windows/apps/" rel="noreferrer">here</a> for a step by step walkthrough of the platform. I would start there if the reference documentation is confusing.</p> |
7,076,186 | How do I purge a linux mail box with huge number of emails? | <p>I have setup some cron jobs and they send the crons result to an email. Now over the months I have accumulated a huge number of emails.</p>
<p>Now my question is how can I purge all those emails from my mailbox?</p> | 7,076,239 | 8 | 2 | null | 2011-08-16 09:33:53.847 UTC | 33 | 2016-05-30 11:31:27.257 UTC | 2015-06-09 20:42:48.98 UTC | null | 20,712 | null | 47,468 | null | 1 | 216 | email|purge | 256,357 | <p>You can simply delete the <code>/var/mail/username</code> file to delete all emails for a specific user. Also, emails that are outgoing but have not yet been sent will be stored in <code>/var/spool/mqueue</code>.</p> |
14,084,221 | How to make a table cell shrink width to fit only its contents? | <p>I want the table to have 100% width, but only one column from it should have a free width, like:</p>
<pre><code>| A | B | C |
</code></pre>
<p>so the width of A and B columns should match the width of their contents, but the width of C should go on until the table ends.</p>
<p>Ok I could specify the width of of A and B in pixels, but the problem is that the width of the contents of these columns is not fixed, so if I set a fixed width it wouldn't match the contents perfectly :(</p>
<p>PS: I'm not using actual table items, but a DL list wrapped in a div. The div has display:table, dl has display:table-row, and dt/dd display:table-cell ...</p> | 14,084,773 | 2 | 3 | null | 2012-12-29 17:35:29.963 UTC | 5 | 2022-08-23 14:40:23.433 UTC | 2018-12-17 16:55:05.073 UTC | null | 4,370,109 | null | 1,209,030 | null | 1 | 20 | html|css|css-tables | 39,466 | <p>If I understood you, you have tabular data but you want to present it in the browser using <code>div</code> elements (AFAIK tables and divs with display:table behaves mostly the same).</p>
<p>(here is a working jsfiddle: <a href="http://jsfiddle.net/roimergarcia/CWKRA/" rel="noreferrer">http://jsfiddle.net/roimergarcia/CWKRA/</a>)</p>
<p>The markup:
</p>
<pre><code><div class='theTable'>
<div class='theRow'>
<div class='theCell' >first</div>
<div class='theCell' >test</div>
<div class='theCell bigCell'>this is long</div>
</div>
<div class='theRow'>
<div class='theCell'>2nd</div>
<div class='theCell'>more test</div>
<div class='theCell'>it is still long</div>
</div>
</div>
</code></pre>
<p>And the CSS:
</p>
<pre><code>.theTable{
display:table;
width:95%; /* or whatever width for your table*/
}
.theRow{display:table-row}
.theCell{
display:table-cell;
padding: 0px 2px; /* just some padding, if needed*/
white-space: pre; /* this will avoid line breaks*/
}
.bigCell{
width:100%; /* this will shrink other cells */
}
</code></pre>
<p>The sad part is I couldn't do this one year ago, when I really needed it -_-! </p> |
29,106,702 | Blend overlapping images in python | <p>I am taking two images in python and overlapping the first image onto the second image. What I would like to do is blend the images where they overlap. Is there a way to do this in python other than a for loop?</p> | 29,108,632 | 2 | 4 | null | 2015-03-17 18:13:06.733 UTC | 8 | 2020-04-15 04:54:08.25 UTC | null | null | null | null | 4,585,247 | null | 1 | 17 | python|image-manipulation|color-blending | 41,750 | <p>PIL has a <a href="http://effbot.org/imagingbook/image.htm#tag-Image.blend" rel="noreferrer"><code>blend</code> function</a> which combines two RGB images with a fixed alpha:</p>
<pre><code>out = image1 * (1.0 - alpha) + image2 * alpha
</code></pre>
<p>However, to use <code>blend</code>, <code>image1</code> and <code>image2</code> must be the same size.
So to prepare your images you'll need to paste each of them into a new image of
the appropriate (combined) size.</p>
<p>Since blending with <code>alpha=0.5</code> averages the RGB values from both images equally,
we need to make two versions of the panorama -- one with img1 one top and one with img2 on top. Then regions with no overlap have RGB values which agree (so their averages will remain unchanged) and regions of overlap will get blended as desired.</p>
<hr>
<pre><code>import operator
from PIL import Image
from PIL import ImageDraw
# suppose img1 and img2 are your two images
img1 = Image.new('RGB', size=(100, 100), color=(255, 0, 0))
img2 = Image.new('RGB', size=(120, 130), color=(0, 255, 0))
# suppose img2 is to be shifted by `shift` amount
shift = (50, 60)
# compute the size of the panorama
nw, nh = map(max, map(operator.add, img2.size, shift), img1.size)
# paste img1 on top of img2
newimg1 = Image.new('RGBA', size=(nw, nh), color=(0, 0, 0, 0))
newimg1.paste(img2, shift)
newimg1.paste(img1, (0, 0))
# paste img2 on top of img1
newimg2 = Image.new('RGBA', size=(nw, nh), color=(0, 0, 0, 0))
newimg2.paste(img1, (0, 0))
newimg2.paste(img2, shift)
# blend with alpha=0.5
result = Image.blend(newimg1, newimg2, alpha=0.5)
</code></pre>
<hr>
<p>img1:</p>
<p><img src="https://i.stack.imgur.com/hvesb.png" alt="enter image description here"></p>
<p>img2:</p>
<p><img src="https://i.stack.imgur.com/MvxGL.png" alt="enter image description here"></p>
<p>result:</p>
<p><img src="https://i.stack.imgur.com/S5WoD.png" alt="enter image description here"></p>
<hr>
<p>If you have two RGBA images <a href="https://stackoverflow.com/q/3374878/190597">here is a way</a> to perform <a href="https://en.wikipedia.org/wiki/Alpha_compositing" rel="noreferrer">alpha compositing</a>. </p> |
29,847,709 | Run a .jar file using .sh file in unix | <p>I have a jar file <code>DirectoryScanner.jar</code> created in windows 7. I want to execute this jar on a unix server.
I ran the following command in putty and the jar run absolutely fine as expected:</p>
<pre><code>java -jar DirectoryScanner.jar
</code></pre>
<p>Now I want to create a .sh file on the unix server which on executing can run this jar. I created a file Report.sh in which I wrote following code to execute this jar:</p>
<pre><code>java -cp /home/applvis/Java/UAT/lib/DirectoryScanner.jar com.acc.directory.scanner.SDScanner
</code></pre>
<p>But when I execute this command in putty, it shows the following error:</p>
<pre><code>[applvis@bg6lnxebs1 UAT]$ . ./ReportGen.sh
Exception in thread "Main Thread" java.lang.NoClassDefFoundError: com/acc/directory/scanner/SDScanner
Caused by: java.lang.ClassNotFoundException: com.acc.directory.scanner.SDScanner
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Could not find the main class: com.acc.directory.scanner.SDScanner. Program will exit.
</code></pre>
<p>Can anyone tell me what exactly I'm doing wrong, or suggest some alternate command.</p>
<p>Both my jar and sh file are in different directories. Even if they are in same directory, I get this error.</p>
<p>Ps. I have many jar files to be executed one after the other. So rather than again and again writing the command to run each jar separartely on unix, I want to create an sh file which will contain the code to run all the jars one after the other. And it will be easier for me to just run the sh file. Hence I need the code to be written in sh file which can run my jars.</p> | 29,920,781 | 2 | 6 | null | 2015-04-24 12:35:37.043 UTC | 2 | 2015-04-28 13:21:32.607 UTC | 2015-04-27 06:09:28.99 UTC | null | 4,391,517 | null | 4,391,517 | null | 1 | 5 | java|bash|shell|unix|jar | 67,257 | <p>In your shell script change into the directory containing the jar files. Possibly not the best practice but I use this all the time to emulate a 'working directory' where scripts are started from. This way my shell script can be installed in a <code>scripts</code> directory and my Java can be installed in a <code>lib</code> directory. </p>
<p>Assuming your environment is the same when you execute the script as when you call the java from the command line. </p>
<pre><code>#!/bin/sh
cd /home/applvis/Java/UAT/lib
java -jar DirectoryScanner.jar
</code></pre> |
43,371,863 | Dagger 2.10 Android subcomponents and builders | <p>Using the new (in 2.10) dagger.android classes, I'm trying to inject things using a Subcomponent that depends on other Modules, and, therefore, has a Builder with setters for those modules. The documentation on <a href="https://google.github.io/dagger/android.html" rel="noreferrer">https://google.github.io/dagger/android.html</a> describes this, but is not clear on how to actually write and/or invoke those setters.</p>
<p>Quoting from the above link:</p>
<blockquote>
<p>AndroidInjection.inject() gets a DispatchingAndroidInjector from the Application and passes your activity to inject(Activity). The DispatchingAndroidInjector looks up the AndroidInjector.Factory for your activity’s class (which is YourActivitySubcomponent.Builder), creates the AndroidInjector (which is YourActivitySubcomponent), and passes your activity to inject(YourActivity).</p>
</blockquote>
<p>It seems to me that in order to be able to call the setters for the Builder, I need to get in there somewhere and ensure the Builder has all the necessary data? The problem I'm seeing is that at runtime, I get an <code>IllegalStateException: MODULE must be set</code>, when the generated builder for my Subcomponent is invoked by AndroidInjector.</p>
<p>The Subcomponent in question is in fact for a Fragment, not an Activity, but I'm not sure that should matter. Any ideas about how to do this?</p> | 43,429,833 | 2 | 2 | null | 2017-04-12 14:05:09.51 UTC | 21 | 2017-11-25 15:58:00.317 UTC | null | null | null | null | 1,659,929 | null | 1 | 17 | android|dagger-2 | 4,597 | <p>In short, you're supposed to <a href="https://github.com/google/dagger/blob/master/java/dagger/android/AndroidInjector.java#L79" rel="noreferrer">override the call to <code>seedInstance</code></a> on the Builder (which is an abstract class instead of an interface) to provide other modules you need.</p>
<p><em>edit</em>: Before you do, check and make sure that you really need to pass that Module. As <a href="https://stackoverflow.com/a/47487355/1426891">Damon added in a separate answer</a>, if you're making a specific Module for your Android class, you can rely on the automatic injection of that class to pull the configuration or instance out of the graph at that point. Favor his approach if it's easier just to eliminate the constructor parameters from your Module, which also may provide better performance as they avoid unnecessary instances and virtual method calls.</p>
<hr>
<p>First, <strong>dagger.android in 30 seconds:</strong> Rather than having each Activity or Fragment know about its parent, the Activity (or Fragment) calls <code>AndroidInjection.inject(this)</code>, which checks the Application for <code>HasActivityInjector</code> (or parent fragments, activity, and application for <code>HasFragmentInjector</code>). The idea is that you contribute a binding to a multibindings-created <code>Map<Class, AndroidInjector.Factory></code>, where the contributed bindings are <em>almost</em> always subcomponent builders you write that build object-specific subcomponents.</p>
<p>As you might tell from <code>AndroidInjection.inject(this)</code> and <code>AndroidInjector.Factory.create(T instance)</code>, you don't get a lot of opportunity to pass Activity-specific or Fragment-specific details to your Builder. Instead, the idea is that your subcomponent builder overrides the <code>seedInstance</code> implementation. As in the docs for <code>seedInstance</code>:</p>
<blockquote>
<p>Provides <code>instance</code> to be used in the binding graph of the built <code>AndroidInjector</code>. By default, this is used as a <code>BindsInstance</code> method, but it may be overridden to provide any modules which need a reference to the activity.</p>
<p>This should be the same instance that will be passed to <code>inject(Object)</code>.</p>
</blockquote>
<p>That'd look something like this:</p>
<pre><code>@Subcomponent(modules = {OneModule.class, TwoModule.class})
public interface YourActivitySubcomponent extends AndroidInjector<YourActivity> {
// inject(YourActivity) is inherited from AndroidInjector<YourActivity>
@Builder
public abstract class Builder extends AndroidInjector.Builder<YourActivity> {
// Here are your required module builders:
abstract Builder oneModule(OneModule module);
abstract Builder twoModule(TwoModule module);
// By overriding seedInstance, you don't let Dagger provide its
// normal @BindsInstance implementation, but you can supply the
// instance to modules or call your own BindsInstance:
@Override public void seedInstance(YourActivity activity) {
oneModule(new OneModule(activity));
twoModule(new TwoModule(activity.getTwoModuleParameter()));
}
}
}
</code></pre>
<p>The assumption here is that you need to wait for the <code>activity</code> instance for the modules. If not, then you also have the option of calling those when you bind the subcomponent:</p>
<pre><code>@Provides @IntoMap @ActivityKey(YourActivity.class)
AndroidInjector.Factory bindInjector(YourActivitySubcomponent.Builder builder) {
return builder
.oneModule(new OneModule(...))
.twoModule(new TwoModule(...));
}
</code></pre>
<p>...but if you can do that, then you could more-easily take care of those bindings by overriding those modules, implementing a zero-arg constructor that can supply the Module's constructor parameters, and letting Dagger create those as it does for any Modules with public zero-arg constructors.</p> |
9,227,328 | org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person] | <p>I'm trying to set up a small working sample of Hibernate that I found <a href="http://www.mastertheboss.com/hibernate/182-hibernate-tutorial.html" rel="noreferrer">here</a> However when I run the code I get the follwing error</p>
<pre><code>Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not insert: [com.sample.Person]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2345)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2852)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
at .....
Caused by: org.postgresql.util.PSQLException: ERROR: relation "person" does not exist
Position: 13
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:500)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:388)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:334)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:94)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:57)
... 23 more
</code></pre>
<p>But I already have a table by the name person in the database and here's my modified hibernate.cfg.xml
</p>
<p>
</p>
<pre><code> <!-- hibernate dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost/testDB</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.show.sql" ></property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- Automatic schema creation (begin) === -->
<property name="hibernate.hbm2ddl.auto">create</property>
<!-- Simple memory-only cache -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- ############################################ -->
<!-- # mapping files with external dependencies # -->
<!-- ############################################ -->
<mapping resource="com/sample/Person.hbm.xml" />
</session-factory>
</code></pre>
<p></p>
<p>It would be great if anyone could point out what Im doing wrong, as this is my first attempt at Hibernate.
Thanks!</p>
<p>EDIT: Person.hbm.xml
</p>
<p></p>
<p></p>
<pre><code><class name="com.sample.Person" table="person">
<id name="id" column="ID">
<generator class="native" />
</id>
<property name="name">
<column name="NAME" length="16" not-null="true" />
</property>
<property name="surname">
<column name="SURNAME" length="16" not-null="true" />
</property>
<property name="address">
<column name="ADDRESS" length="16" not-null="true" />
</property>
</class>
</code></pre>
<p></p>
<p>EDIT-II: Content of the log file (Postgresql.log) </p>
<pre><code> 2012-02-13 09:23:25 IST LOG: database system was shut down at 2012-02-10 18:14:57 IST
2012-02-13 09:23:25 IST FATAL: the database system is starting up
2012-02-13 09:23:33 IST LOG: database system is ready to accept connections
2012-02-13 09:23:38 IST LOG: autovacuum launcher started
2012-02-13 09:46:01 IST ERROR: syntax error at or near "auto_increment" at character 41
2012-02-13 09:46:01 IST STATEMENT: create table person (ID bigint not null auto_increment, NAME varchar(16) not null, SURNAME varchar(16) not null, ADDRESS varchar(16) not null, primary key (ID)) type=InnoDB
2012-02-13 09:46:01 IST ERROR: relation "person" does not exist at character 13
2012-02-13 09:46:01 IST STATEMENT: insert into person (NAME, SURNAME, ADDRESS) values ($1, $2, $3) RETURNING *
2012-02-13 09:46:01 IST LOG: could not receive data from client: No connection could be made because the target machine actively refused it.
2012-02-13 09:46:01 IST LOG: unexpected EOF on client connection
2012-02-13 09:48:15 IST ERROR: syntax error at or near "auto_increment" at character 41
2012-02-13 09:48:15 IST STATEMENT: create table person (ID bigint not null auto_increment, NAME varchar(16) not null, SURNAME varchar(16) not null, ADDRESS varchar(16) not null, primary key (ID)) type=InnoDB
2012-02-13 09:48:15 IST ERROR: relation "person" does not exist at character 13
2012-02-13 09:48:15 IST STATEMENT: insert into person (NAME, SURNAME, ADDRESS) values ($1, $2, $3) RETURNING *
2012-02-13 09:48:15 IST LOG: could not receive data from client: No connection could be made because the target machine actively refused it.
2012-02-13 09:48:15 IST LOG: unexpected EOF on client connection
</code></pre>
<p><strong>UPDATE</strong>: I just noticed something weird, I create the relation in the DB and then run this piece of code, only to see that the table gets deleted as in it just dissapears when I run this code; any idea why this happens? </p> | 9,257,574 | 9 | 1 | null | 2012-02-10 11:51:17.2 UTC | 4 | 2018-01-24 09:12:25.277 UTC | 2012-02-13 07:05:56.403 UTC | null | 919,858 | null | 919,858 | null | 1 | 6 | java|hibernate|orm|hibernate-mapping | 122,125 | <p>I solved the error by modifying the following property in hibernate.cfg.xml</p>
<pre><code> <property name="hibernate.hbm2ddl.auto">validate</property>
</code></pre>
<p>Earlier, the table was getting deleted each time I ran the program and now it doesnt, as hibernate only validates the schema and does not affect changes to it.</p> |
9,154,065 | How do I run CodeIgniter migrations? | <p>I know how to create them via <a href="http://codeigniter.com/user_guide/libraries/migration.html" rel="noreferrer">http://codeigniter.com/user_guide/libraries/migration.html</a></p>
<p>But once I've created my migration files, how do I run them?</p> | 9,189,334 | 7 | 1 | null | 2012-02-05 23:26:21.35 UTC | 14 | 2022-06-26 00:44:29.743 UTC | 2012-02-08 08:47:15.847 UTC | null | 250,470 | null | 239,879 | null | 1 | 49 | codeigniter|migration|codeigniter-2 | 52,753 | <p>I am not sure this is the right way to do it, But It works for me.</p>
<p>I created a controller named <code>migrate</code> <strong>(controllers/migrate.php)</strong>.</p>
<pre><code><?php defined("BASEPATH") or exit("No direct script access allowed");
class Migrate extends CI_Controller{
public function index($version){
$this->load->library("migration");
if(!$this->migration->version($version)){
show_error($this->migration->error_string());
}
}
}
</code></pre>
<p>Then from browser I will call this url to execute <code>index</code> action in <code>migrate</code> controller<br>
Eg : <strong>http://localhost/index.php/migrate/index/1</strong> </p> |
58,927,718 | Is there a better way to write nested if statements in python? | <p>Is there a more pythonic way to do nested if else statements than this one:</p>
<pre><code>def convert_what(numeral_sys_1, numeral_sys_2):
if numeral_sys_1 == numeral_sys_2:
return 0
elif numeral_sys_1 == "Hexadecimal":
if numeral_sys_2 == "Decimal":
return 1
elif numeral_sys_2 == "Binary":
return 2
elif numeral_sys_1 == "Decimal":
if numeral_sys_2 == "Hexadecimal":
return 4
elif numeral_sys_2 == "Binary":
return 6
elif numeral_sys_1 == "Binary":
if numeral_sys_2 == "Hexadecimal":
return 5
elif numeral_sys_2 == "Decimal":
return 3
else:
return 0
</code></pre>
<p>This script is a part of a simple converter.</p> | 58,985,114 | 13 | 3 | null | 2019-11-19 06:14:26.983 UTC | 6 | 2019-12-15 02:07:24.473 UTC | null | null | null | null | 4,772,772 | null | 1 | 37 | python|if-statement | 9,096 | <p>While @Aryerez and @SencerH.'s answers work, each possible value of <code>numeral_sys_1</code> has to be repeatedly written for each possible value of <code>numeral_sys_2</code> when listing the value pairs, making the data structure harder to maintain when the number of possible values increases. You can instead use a nested dict in place of your nested if statements instead:</p>
<pre><code>mapping = {
'Hexadecimal': {'Decimal': 1, 'Binary': 2},
'Binary': {'Decimal': 3, 'Hexadecimal': 5},
'Decimal': {'Hexadecimal': 4, 'Binary': 6}
}
def convert_what(numeral_sys_1, numeral_sys_2):
return mapping.get(numeral_sys_1, {}).get(numeral_sys_2, 0)
</code></pre>
<p>Alternatively, you can generate the pairs of values for the mapping with the <code>itertools.permutations</code> method, the order of which follows that of the input sequence:</p>
<pre><code>mapping = dict(zip(permutations(('Hexadecimal', 'Decimal', 'Binary'), r=2), (1, 2, 4, 6, 3, 5)))
def convert_what(numeral_sys_1, numeral_sys_2):
return mapping.get((numeral_sys_1, numeral_sys_2), 0)
</code></pre> |
32,986,780 | Applying bootstrap styles to django forms | <p>I want to use bootstrap to get a decent website design, unfortunately I don't know how style the form fields. I am talking about this:</p>
<pre><code><form class="form-horizontal" method="POST" action="."> {% csrf_token %}
{{ form.title.label }}
{{ form.title }}
</form>
</code></pre>
<p>How is one supposed to design this?? I tried this:</p>
<pre><code><form class="form-horizontal" method="POST" action="."> {% csrf_token %}
<div class="form-control">
{{ form.title.label }}
{{ form.title }}
</div>
</form>
</code></pre>
<p>This obviously didn't gave me the wanted results. </p>
<p>How can I apply bootstrap styles to django forms?</p> | 32,986,885 | 1 | 2 | null | 2015-10-07 07:58:41.26 UTC | 9 | 2015-10-07 08:11:39.317 UTC | 2015-10-07 08:11:39.317 UTC | null | 1,324,033 | null | 5,092,892 | null | 1 | 6 | django|django-forms|django-templates | 4,843 | <p>If you prefer not to use 3rd party tools then essentially you need to add attributes to your classes, I prefer to do this by having a base class that my model forms inherit from</p>
<pre><code>class BootstrapModelForm(ModelForm):
def __init__(self, *args, **kwargs):
super(BootstrapModelForm, self).__init__(*args, **kwargs)
for field in iter(self.fields):
self.fields[field].widget.attrs.update({
'class': 'form-control'
})
</code></pre>
<p>Can easily be adjusted... but as you see all my field widgets get the form-control css class applied</p>
<p>You can extend this for specific fields if you wish, here's an example of an inherited form having an attribute applied</p>
<pre><code>class MyForm(BootstrapModelForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs.update({'placeholder': 'Enter a name'})
</code></pre> |
19,352,976 | NPM modules won't install globally without sudo | <p><strong>I have just reinstalled Ubuntu 12.04 LTS, and before anything else i did these steps</strong>:</p>
<ol>
<li><p>Installed Node via package manager with the following script</p>
<pre><code>sudo apt-get update
sudo apt-get install python-software-properties python g++ make
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs
</code></pre></li>
<li><p>Tried to install yeoman, express, n, yeoman's generators globally and all of them returned the same error</p>
<blockquote>
<p>npm ERR! Error: EACCES, symlink '../lib/node_modules/n/bin/n'</p>
<p>npm ERR! { [Error: EACCES, symlink '../lib/node_modules/n/bin/n'] errno: 3, code: 'EACCES', path: '../lib/node_modules/n/bin/n' }</p>
<p>npm ERR! </p>
<p>npm ERR! Please try running this command again as root/Administrator.</p>
<p>npm ERR! System Linux 3.8.0-29-generic</p>
<p>npm ERR! command "/usr/bin/node" "/usr/bin/npm" "install" "-g" "-d" "n"</p>
<p>npm ERR! cwd /home/heberlz</p>
<p>npm ERR! node -v v0.10.20</p>
<p>npm ERR! npm -v 1.3.11</p>
<p>npm ERR! path ../lib/node_modules/n/bin/n</p>
<p>npm ERR! code EACCES</p>
<p>npm ERR! errno 3</p>
<p>npm ERR! stack Error: EACCES, symlink '../lib/node_modules/n/bin/n'</p>
<p>npm ERR! </p>
<p>npm ERR! Additional logging details can be found in:</p>
<p>npm ERR! /home/heberlz/npm-debug.log</p>
<p>npm ERR! not ok code 0</p>
</blockquote></li>
<li><p><strong>Reclaimed ownership of the following folders recursively</strong> ~/.npm, /usr/lib/node, /usr/lib/node_modules, and of the following symlinks /usr/bin/node, /usr/bin/nodejs <strong>with absolutely no success</strong></p></li>
</ol>
<p>I need to install yeoman and its generators without sudo not to be in trouble later on :(</p> | 21,712,034 | 16 | 3 | null | 2013-10-14 03:13:10.97 UTC | 79 | 2022-09-21 07:38:52.003 UTC | 2014-07-30 03:58:13.14 UTC | null | 283,366 | null | 2,334,176 | null | 1 | 139 | node.js|ubuntu|npm|yeoman|node-modules | 96,623 | <p>Ubuntu 12.04 and using Chris Lea's PPA for install the following works for me:</p>
<pre><code>npm config set prefix '~/.npm-packages'
</code></pre>
<p>and adding <code>$HOME/.npm-packages/bin</code> to <code>$PATH</code></p>
<p>Append to <code>.bashrc</code></p>
<pre><code>export PATH="$PATH:$HOME/.npm-packages/bin"
</code></pre>
<p>For more see <a href="https://stackoverflow.com/a/18277225">this answer</a> from @passy</p> |
24,676,877 | Should I return a Collection or a Stream? | <p>Suppose I have a method that returns a read-only view into a member list:</p>
<pre class="lang-java prettyprint-override"><code>class Team {
private List<Player> players = new ArrayList<>();
// ...
public List<Player> getPlayers() {
return Collections.unmodifiableList(players);
}
}
</code></pre>
<p>Further suppose that all the client does is iterate over the list once, immediately. Maybe to put the players into a JList or something. The client does <em>not</em> store a reference to the list for later inspection!</p>
<p>Given this common scenario, should I return a stream instead?</p>
<pre class="lang-java prettyprint-override"><code>public Stream<Player> getPlayers() {
return players.stream();
}
</code></pre>
<p>Or is returning a stream non-idiomatic in Java? Were streams designed to always be "terminated" inside the same expression they were created in?</p> | 24,679,745 | 9 | 2 | null | 2014-07-10 12:42:48.047 UTC | 72 | 2021-08-16 18:26:02.667 UTC | 2020-12-21 08:34:00.673 UTC | null | 252,000 | null | 252,000 | null | 1 | 182 | java|collections|java-8|encapsulation|java-stream | 51,591 | <p>The answer is, as always, "it depends". It depends on how big the returned collection will be. It depends on whether the result changes over time, and how important consistency of the returned result is. And it depends very much on how the user is likely to use the answer.</p>
<p>First, note that you can always get a <code>Collection</code> from a <code>Stream</code>, and vice versa:</p>
<pre><code>// If API returns Collection, convert with stream()
getFoo().stream()...
// If API returns Stream, use collect()
Collection<T> c = getFooStream().collect(toList());
</code></pre>
<p>So the question is, which is more useful to your callers.</p>
<p>If your result might be infinite, there's only one choice: <code>Stream</code>.</p>
<p>If your result might be very large, you probably prefer <code>Stream</code>, since there may not be any value in materializing it all at once, and doing so could create significant heap pressure.</p>
<p>If all the caller is going to do is iterate through it (search, filter, aggregate), you should prefer <code>Stream</code>, since <code>Stream</code> has these built-in already and there's no need to materialize a collection (especially if the user might not process the whole result.) This is a very common case.</p>
<p>Even if you know that the user will iterate it multiple times or otherwise keep it around, you still may want to return a <code>Stream</code> instead, for the simple fact that whatever <code>Collection</code> you choose to put it in (e.g., <code>ArrayList</code>) may not be the form they want, and then the caller has to copy it anyway. If you return a <code>Stream</code>, they can do <code>collect(toCollection(factory))</code> and get it in exactly the form they want.</p>
<p>The above "prefer <code>Stream</code>" cases mostly derive from the fact that <code>Stream</code> is more flexible; you can late-bind to how you use it without incurring the costs and constraints of materializing it to a <code>Collection</code>.</p>
<p>The one case where you must return a <code>Collection</code> is when there are strong consistency requirements, and you have to produce a consistent snapshot of a moving target. Then, you will want put the elements into a collection that will not change.</p>
<p>So I would say that most of the time, <code>Stream</code> is the right answer — it is more flexible, it doesn't impose usually-unnecessary materialization costs, and can be easily turned into the Collection of your choice if needed. But sometimes, you may have to return a <code>Collection</code> (say, due to strong consistency requirements), or you may want to return <code>Collection</code> because you know how the user will be using it and know this is the most convenient thing for them.</p>
<p>If you already have a suitable <code>Collection</code> "lying around", and it seems likely that your users would rather interact with it as a <code>Collection</code>, then it is a reasonable choice (though not the only one, and more brittle) to just return what you have.</p> |
35,131,312 | How to Unit Test React-Redux Connected Components? | <p>I am using Mocha, Chai, Karma, Sinon, Webpack for Unit tests.</p>
<p>I followed this link to configure my testing environment for React-Redux Code.</p>
<p><a href="https://medium.com/@scbarrus/how-to-get-test-coverage-on-react-with-karma-babel-and-webpack-c9273d805063#.7kcckz73r" rel="noreferrer">How to implement testing + code coverage on React with Karma, Babel, and Webpack</a></p>
<p>I can successfully test my action and reducers javascript code, but when it comes to testing my components it always throw some error.</p>
<pre><code>import React from 'react';
import TestUtils from 'react/lib/ReactTestUtils'; //I like using the Test Utils, but you can just use the DOM API instead.
import chai from 'chai';
// import sinon from 'sinon';
import spies from 'chai-spies';
chai.use(spies);
let should = chai.should()
, expect = chai.expect;
import { PhoneVerification } from '../PhoneVerification';
let fakeStore = {
'isFetching': false,
'usernameSettings': {
'errors': {},
'username': 'sahil',
'isEditable': false
},
'emailSettings': {
'email': '[email protected]',
'isEmailVerified': false,
'isEditable': false
},
'passwordSettings': {
'errors': {},
'password': 'showsomestarz',
'isEditable': false
},
'phoneSettings': {
'isEditable': false,
'errors': {},
'otp': null,
'isOTPSent': false,
'isOTPReSent': false,
'isShowMissedCallNumber': false,
'isShowMissedCallVerificationLink': false,
'missedCallNumber': null,
'timeLeftToVerify': null,
'_verifiedNumber': null,
'timers': [],
'phone': '',
'isPhoneVerified': false
}
}
function setup () {
console.log(PhoneVerification);
// PhoneVerification.componentDidMount = chai.spy();
let output = TestUtils.renderIntoDocument(<PhoneVerification {...fakeStore}/>);
return {
output
}
}
describe('PhoneVerificationComponent', () => {
it('should render properly', (done) => {
const { output } = setup();
expect(PhoneVerification.prototype.componentDidMount).to.have.been.called;
done();
})
});
</code></pre>
<p>This following error comes up with above code.</p>
<pre><code>FAILED TESTS:
PhoneVerificationComponent
✖ should render properly
Chrome 48.0.2564 (Mac OS X 10.11.3)
Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.
</code></pre>
<p>Tried switching from sinon spies to chai-spies.</p>
<p>How should I unit test my React-Redux Connected Components(Smart Components)? </p> | 35,578,985 | 5 | 4 | null | 2016-02-01 13:05:16.123 UTC | 17 | 2020-04-13 03:02:48.673 UTC | 2019-08-19 21:35:51.933 UTC | null | 12,216,735 | null | 5,867,305 | null | 1 | 55 | unit-testing|reactjs|mocha.js|sinon|redux | 42,099 | <p>A prettier way to do this, is to export both your plain component, and the component wrapped in connect. The named export would be the component, the default is the wrapped component:</p>
<pre><code>export class Sample extends Component {
render() {
let { verification } = this.props;
return (
<h3>This is my awesome component.</h3>
);
}
}
const select = (state) => {
return {
verification: state.verification
}
}
export default connect(select)(Sample);
</code></pre>
<p>In this way you can import normally in your app, but when it comes to testing you can import your named export using <code>import { Sample } from 'component'</code>.</p> |
1,100,739 | Quick way to grant Exec permissions to DB role for many stored procs | <p>Consider the scenario where a database has a SQL Database Role or Application Role. The task is to grant Execute permissions to <strong><em>n</em></strong> stored procedures.</p>
<p>When using SQL Management Studio, there's a nice screen to help apply permissions to objects for a Role.</p>
<p><a href="https://i.stack.imgur.com/hRALl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hRALl.png" alt="SQL Management Studio"></a>
</p>
<p>Here are the steps to apply permissions:</p>
<ul>
<li>select the object that you want to grant/deny permissions in the list of <em>Securables</em>. </li>
<li>navigate to the list of <em>Explicit Permissions</em> below. </li>
<li>select the Grant or Deny checkbox as appropriate.</li>
</ul>
<p>Repeat the above for <strong><em>n</em></strong> objects. Fire up some music to keep yourself entertained while doing this for 100+ objects! There's got to be a better way! It's a clickfest of major proportions.</p>
<p><strong>Question</strong>: </p>
<p>Is there a faster way to perform this task using SQL Server Management Studio 2005? Perhaps another GUI tool (preferably free)?</p>
<p>Any suggestions for creating T-SQL scripts to automatically perform this task? i.e. create a table of all stored procedure names, loop, and apply the exec permissions?</p> | 1,203,641 | 5 | 2 | null | 2009-07-08 21:55:35.56 UTC | 12 | 2019-03-27 17:59:57.227 UTC | 2019-03-27 17:59:57.227 UTC | user596075 | 4,751,173 | null | 23,199 | null | 1 | 24 | sql-server|sql-server-2005|tsql|ssms | 92,985 | <p>This should do it:</p>
<pre><code>CREATE PROC SProcs_GrantExecute(
@To AS NVARCHAR(255)
, @NameLike AS NVARCHAR(MAX)
, @SchemaLike as NVARCHAR(MAX) = N'dbo'
) AS
/*
Proc to Authorize a role for a whole bunch of SProcs at once
*/
DECLARE @sql as NVARCHAR(MAX)
SET @sql = ''
SELECT @sql = @sql + '
GRANT EXECUTE ON OBJECT::['+ROUTINE_SCHEMA+'].['+ROUTINE_NAME+'] TO '+@To+';'
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_NAME LIKE @NameLike
AND ROUTINE_SCHEMA LIKE @SchemaLike
PRINT @sql
EXEC(@sql)
</code></pre>
<p>This is Injectable as heck, so keep it for Admin use only.</p>
<hr>
<p>I just want to add that Remus's suggestion of using schemas is the preferred approach, where that is workable.</p> |
58,517 | Combining Enums | <p>Is there a way to combine Enums in VB.net?</p> | 58,527 | 5 | 0 | null | 2008-09-12 08:42:07.583 UTC | 8 | 2021-04-22 10:43:38.477 UTC | 2008-09-12 09:14:08.427 UTC | null | -1 | digiguru | 5,055 | null | 1 | 30 | .net|vb.net|enums | 22,345 | <p>I believe what you want is a flag type enum.</p>
<p>You need to add the Flags attribute to the top of the enum, and then you can combine enums with the 'Or' keyword.</p>
<p>Like this:</p>
<pre><code><Flags()> _
Enum CombinationEnums As Integer
HasButton = 1
TitleBar = 2
[ReadOnly] = 4
ETC = 8
End Enum
</code></pre>
<p><strong>Note:</strong> The numbers to the right are always twice as big (powers of 2) - this is needed to be able to separate the individual flags that have been set.</p>
<p>Combine the desired flags using the Or keyword:</p>
<pre><code>Dim settings As CombinationEnums
settings = CombinationEnums.TitleBar Or CombinationEnums.Readonly
</code></pre>
<p>This sets TitleBar and Readonly into the enum</p>
<p>To check what's been set:</p>
<pre><code>If (settings And CombinationEnums.TitleBar) = CombinationEnums.TitleBar Then
Window.TitleBar = True
End If
</code></pre> |
294,659 | Why did I get an error with my XmlSerializer? | <p>I made a couple of changes to my working application and started getting the following error at this line of code.</p>
<pre><code>Dim Deserializer As New Serialization.XmlSerializer(GetType(Groups))
</code></pre>
<p>And here is the error.</p>
<pre><code> BindingFailure was detected
Message: The assembly with display name 'FUSE.XmlSerializers' failed to load in the 'LoadFrom' binding context of the AppDomain with ID 1. The cause of the failure was: System.IO.FileNotFoundException: Could not load file or assembly 'FUSE.XmlSerializers, Version=8.11.16.1, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
File name: 'FUSE.XmlSerializers, Version=8.11.16.1, Culture=neutral, PublicKeyToken=null'
Message: The assembly with display name 'FUSE.XmlSerializers' failed to load in the 'LoadFrom' binding context of the AppDomain with ID 1. The cause of the failure was: System.IO.FileNotFoundException: Could not load file or assembly 'FUSE.XmlSerializers, Version=8.11.16.1, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
File name: 'FUSE.XmlSerializers, Version=8.11.16.1, Culture=neutral, PublicKeyToken=null'
=== Pre-bind state information ===
LOG: User = DOUG-VM\Doug
LOG: DisplayName = FUSE.XmlSerializers, Version=8.11.16.1, Culture=neutral, PublicKeyToken=null, processorArchitecture=MSIL
(Fully-specified)
LOG: Appbase = file:///E:/Laptop/Core Data/Data/Programming/Windows/DotNet/Work Projects/NOP/Official Apps/FUSE WPF/Fuse/bin/Debug/
LOG: Initial PrivatePath = NULL
Calling assembly : System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: E:\Laptop\Core Data\Data\Programming\Windows\DotNet\Work Projects\NOP\Official Apps\FUSE WPF\Fuse\bin\Debug\FUSE.vshost.exe.config
LOG: Using machine configuration file from C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///E:/Laptop/Core Data/Data/Programming/Windows/DotNet/Work Projects/NOP/Official Apps/FUSE WPF/Fuse/bin/Debug/FUSE.XmlSerializers.DLL.
LOG: Attempting download of new URL file:///E:/Laptop/Core Data/Data/Programming/Windows/DotNet/Work Projects/NOP/Official Apps/FUSE WPF/Fuse/bin/Debug/FUSE.XmlSerializers/FUSE.XmlSerializers.DLL.
LOG: Attempting download of new URL file:///E:/Laptop/Core Data/Data/Programming/Windows/DotNet/Work Projects/NOP/Official Apps/FUSE WPF/Fuse/bin/Debug/FUSE.XmlSerializers.EXE.
LOG: Attempting download of new URL file:///E:/Laptop/Core Data/Data/Programming/Windows/DotNet/Work Projects/NOP/Official Apps/FUSE WPF/Fuse/bin/Debug/FUSE.XmlSerializers/FUSE.XmlSerializers.EXE.
</code></pre>
<p>What's going on?</p> | 297,445 | 5 | 0 | null | 2008-11-17 00:54:59.213 UTC | 14 | 2014-12-31 15:12:24.34 UTC | 2013-11-13 18:18:34.71 UTC | Jay Bazuzi | 63,550 | Doug | 6,514 | null | 1 | 42 | wpf|system.xml | 46,069 | <p>The main reason this was happening was because I had a mismatch in the types I was trying to Serialize and Deserialize. I was Serializing ObservableCollection (of Group) and deserializing a business object - Groups which inherited ObservableCollection (of Group).</p>
<p>And this was also part of the problem...
From - <a href="http://social.msdn.microsoft.com/Forums/en-US/asmxandxml/thread/9f0c169f-c45e-4898-b2c4-f72c816d4b55/" rel="noreferrer">http://social.msdn.microsoft.com/Forums/en-US/asmxandxml/thread/9f0c169f-c45e-4898-b2c4-f72c816d4b55/</a></p>
<blockquote>
<p>This exception is a part of the
XmlSerializer's normal operation. It
is expected and will be caught and
handled inside of the Framework code.
Just ignore it and continue. If it
bothers you during debugging, set the
Visual Studio debugger to only stop on
unhandled exceptions instead of all
exceptions.</p>
</blockquote> |
230,588 | Problem sorting lists using delegates | <p>I am trying to sort a list using delegates but I am getting a signature match error. The compiler says I cannot convert from an 'anonymous method' </p>
<pre><code>List<MyType> myList = GetMyList();
myList.Sort( delegate (MyType t1, MyType t2) { return (t1.ID < t2.ID); } );
</code></pre>
<p>What am I missing?</p>
<p>Here are some references I found and they do it the same way.</p>
<p><a href="http://www.developerfusion.com/code/5513/sorting-and-searching-using-c-lists/" rel="noreferrer">Developer Fusion Reference</a> </p>
<p><a href="http://blogs.msdn.com/devdev/archive/2006/06/30/652802.aspx" rel="noreferrer">Microsoft Reference</a></p> | 230,620 | 6 | 0 | null | 2008-10-23 17:17:55.87 UTC | 6 | 2009-12-02 15:05:09.887 UTC | 2008-10-23 17:39:04.423 UTC | Jonathan Leffler | 15,168 | Maudite | 1,632 | null | 1 | 21 | c#|.net|closures | 38,817 | <p>I think you want:</p>
<pre><code>myList.Sort( delegate (MyType t1, MyType t2)
{ return (t1.ID.CompareTo(t2.ID)); }
);
</code></pre>
<p>To sort you need something other than "true/false", you need to know if its equal to, greater than, or less than.</p> |
93,770 | EEFileLoadException when using C# classes in C++(win32 app) | <p>For deployment reasons, I am trying to use IJW to wrap a C# assembly in C++ instead of using a COM Callable Wrapper. </p>
<p>I've done it on other projects, but on this one, I am getting an EEFileLoadException. Any help would be appreciated!</p>
<p>Managed C++ wrapper code (this is in a DLL):</p>
<pre><code>extern "C" __declspec(dllexport) IMyObject* CreateMyObject(void)
{
//this class references c# in the constructor
return new CMyWrapper( );
}
extern "C" __declspec(dllexport) void DeleteMyObject(IMyObject* pConfigFile)
{
delete pConfigFile;
}
extern "C" __declspec(dllexport) void TestFunction(void)
{
::MessageBox(NULL, _T("My Message Box"), _T("Test"), MB_OK);
}
</code></pre>
<p>Test Code (this is an EXE):</p>
<pre><code>typedef void* (*CreateObjectPtr)();
typedef void (*TestFunctionPtr)();
int _tmain testwrapper(int argc, TCHAR* argv[], TCHAR* envp[])
{
HMODULE hModule = ::LoadLibrary(_T("MyWrapper"));
_ASSERT(hModule != NULL);
PVOID pFunc1 = ::GetProcAddress(hModule, "TestFunction");
_ASSERT(pFunc1 != NULL);
TestFunctionPtr pTest = (TestFunctionPtr)pFunc1;
PVOID pFunc2 = ::GetProcAddress(hModule, "CreateMyObject");
_ASSERT(pFunc2 != NULL);
CreateObjectPtr pCreateObjectFunc = (CreateObjectPtr)pFunc2;
(*pTest)(); //this successfully pops up a message box
(*pCreateObjectFunc)(); //this tosses an EEFileLoadException
return 0;
}
</code></pre>
<p>For what it's worth, the Event Log reports the following:
.NET Runtime version 2.0.50727.143 -
Fatal Execution Engine Error (79F97075) (80131506)</p>
<p>Unfortunately, Microsoft has no information on that error.</p> | 96,651 | 6 | 2 | null | 2008-09-18 15:49:31.923 UTC | 8 | 2016-10-24 16:47:50.547 UTC | 2011-12-07 19:24:48.617 UTC | mwigdahl | 3,043 | Adam Tegen | 4,066 | null | 1 | 29 | c#|managed-c++ | 29,768 | <p>The problem was where the DLLs were located.</p>
<ul>
<li>c:\dlls\managed.dll</li>
<li>c:\dlls\wrapper.dll</li>
<li>c:\exe\my.exe</li>
</ul>
<p>I confirmed this by copying managed.dll into c:\exe and it worked without issue. Apparently, the CLR won't look for managed DLLs in the path of the unmanaged DLL and will only look for it where the executable is. (or in the GAC).</p>
<p>For reasons not worth going into, this is the structure I need, which meant that I needed to give the CLR a hand in located the managed dll. See code below:</p>
<p>AssemblyResolver.h:</p>
<pre><code>/// <summary>
/// Summary for AssemblyResolver
/// </summary>
public ref class AssemblyResolver
{
public:
static Assembly^ MyResolveEventHandler( Object^ sender, ResolveEventArgs^ args )
{
Console::WriteLine( "Resolving..." );
Assembly^ thisAssembly = Assembly::GetExecutingAssembly();
String^ thisPath = thisAssembly->Location;
String^ directory = Path::GetDirectoryName(thisPath);
String^ pathToManagedAssembly = Path::Combine(directory, "managed.dll");
Assembly^ newAssembly = Assembly::LoadFile(pathToManagedAssembly);
return newAssembly;
}
};
</code></pre>
<p>Wrapper.cpp:</p>
<pre><code>#include "AssemblyResolver.h"
extern "C" __declspec(dllexport) IMyObject* CreateMyObject(void)
{
try
{
AppDomain^ currentDomain = AppDomain::CurrentDomain;
currentDomain->AssemblyResolve += gcnew ResolveEventHandler( AssemblyResolver::MyResolveEventHandler );
return new CMyWrapper( );
}
catch(System::Exception^ e)
{
System::Console::WriteLine(e->Message);
return NULL;
}
}
</code></pre> |
258,757 | Escape a string in SQL Server so that it is safe to use in LIKE expression | <p>How do I escape a string in SQL Server's stored procedure so that it is safe to use in <code>LIKE</code> expression.</p>
<p>Suppose I have an <code>NVARCHAR</code> variable like so:</p>
<pre><code>declare @myString NVARCHAR(100);
</code></pre>
<p>And I want to use it in a <code>LIKE</code> expression:</p>
<pre><code>... WHERE ... LIKE '%' + @myString + '%';
</code></pre>
<p>How do I escape the string (more specifically, characters that are meaningful to <code>LIKE</code> pattern matching, e.g. <code>%</code> or <code>?</code>) in T-SQL, so that it is safe to use in this manner?</p>
<p>For example, given:</p>
<pre><code>@myString = 'aa%bb'
</code></pre>
<p>I want:</p>
<pre><code>WHERE ... LIKE '%' + @somehowEscapedMyString + '%'
</code></pre>
<p>to match <code>'aa%bb'</code>, <code>'caa%bbc'</code> but not <code>'aaxbb'</code> or <code>'caaxbb'</code>.</p> | 258,947 | 6 | 0 | null | 2008-11-03 14:24:10.633 UTC | 21 | 2019-07-07 15:39:46.807 UTC | 2015-04-22 14:45:56.133 UTC | NXC | 1,418,091 | Artur | null | null | 1 | 84 | sql-server|tsql|stored-procedures|sql-like | 204,265 | <p>To escape special characters in a LIKE expression you prefix them with an escape character. You get to choose which escape char to use with the ESCAPE keyword. (<a href="http://msdn.microsoft.com/en-us/library/ms179859.aspx" rel="noreferrer">MSDN Ref</a>)</p>
<p>For example this escapes the % symbol, using \ as the escape char:</p>
<pre><code>select * from table where myfield like '%15\% off%' ESCAPE '\'
</code></pre>
<p>If you don't know what characters will be in your string, and you don't want to treat them as wildcards, you can prefix all wildcard characters with an escape char, eg: </p>
<pre><code>set @myString = replace(
replace(
replace(
replace( @myString
, '\', '\\' )
, '%', '\%' )
, '_', '\_' )
, '[', '\[' )
</code></pre>
<p>(Note that you have to escape your escape char too, and make sure that's the inner <code>replace</code> so you don't escape the ones added from the other <code>replace</code> statements). Then you can use something like this: </p>
<pre><code>select * from table where myfield like '%' + @myString + '%' ESCAPE '\'
</code></pre>
<p>Also remember to allocate more space for your @myString variable as it will become longer with the string replacement.</p> |
2,775 | How to remove the time portion of a datetime value (SQL Server)? | <p>Here's what I use:</p>
<pre><code>SELECT CAST(FLOOR(CAST(getdate() as FLOAT)) as DATETIME)
</code></pre>
<p>I'm thinking there may be a better and more elegant way.</p>
<p>Requirements:</p>
<ul>
<li>It has to be as fast as possible (the less casting, the better).</li>
<li>The final result has to be a <code>datetime</code> type, not a string.</li>
</ul> | 3,696,991 | 6 | 0 | null | 2008-08-05 20:08:38.653 UTC | 33 | 2021-12-22 23:03:46.263 UTC | 2016-03-01 14:49:10.2 UTC | null | 5,903,382 | null | 434 | null | 1 | 86 | sql-server|datetime|date-conversion | 63,466 | <p><strong>SQL Server 2008 and up</strong></p>
<p>In SQL Server 2008 and up, of course the fastest way is <code>Convert(date, @date)</code>. This can be cast back to a <code>datetime</code> or <code>datetime2</code> if necessary.</p>
<p><strong>What Is Really Best In SQL Server 2005 and Older?</strong></p>
<p>I've seen inconsistent claims about what's fastest for truncating the time from a date in SQL Server, and some people even said they did testing, but my experience has been different. So let's do some more stringent testing and let everyone have the script so if I make any mistakes people can correct me.</p>
<p><strong>Float Conversions Are Not Accurate</strong></p>
<p>First, I would stay away from converting <code>datetime</code> to <code>float</code>, because it does not convert correctly. You may get away with doing the time-removal thing accurately, but I think it's a bad idea to use it because it implicitly communicates to developers that this is a safe operation and <strong>it is not</strong>. Take a look:</p>
<pre><code>declare @d datetime;
set @d = '2010-09-12 00:00:00.003';
select Convert(datetime, Convert(float, @d));
-- result: 2010-09-12 00:00:00.000 -- oops
</code></pre>
<p>This is not something we should be teaching people in our code or in our examples online.</p>
<p>Also, it is not even the fastest way!</p>
<p><strong>Proof – Performance Testing</strong></p>
<p>If you want to perform some tests yourself to see how the different methods really do stack up, then you'll need this setup script to run the tests farther down:</p>
<pre><code>create table AllDay (Tm datetime NOT NULL CONSTRAINT PK_AllDay PRIMARY KEY CLUSTERED);
declare @d datetime;
set @d = DateDiff(Day, 0, GetDate());
insert AllDay select @d;
while @@ROWCOUNT != 0
insert AllDay
select * from (
select Tm =
DateAdd(ms, (select Max(DateDiff(ms, @d, Tm)) from AllDay) + 3, Tm)
from AllDay
) X
where Tm < DateAdd(Day, 1, @d);
exec sp_spaceused AllDay; -- 25,920,000 rows
</code></pre>
<p>Please note that this creates a 427.57 MB table in your database and will take something like 15-30 minutes to run. If your database is small and set to 10% growth it will take longer than if you size big enough first.</p>
<p>Now for the actual performance testing script. Please note that it's purposeful to not return rows back to the client as this is crazy expensive on 26 million rows and would hide the performance differences between the methods.</p>
<p><strong>Performance Results</strong></p>
<pre><code>set statistics time on;
-- (All queries are the same on io: logical reads 54712)
GO
declare
@dd date,
@d datetime,
@di int,
@df float,
@dv varchar(10);
-- Round trip back to datetime
select @d = CONVERT(date, Tm) from AllDay; -- CPU time = 21234 ms, elapsed time = 22301 ms.
select @d = CAST(Tm - 0.50000004 AS int) from AllDay; -- CPU = 23031 ms, elapsed = 24091 ms.
select @d = DATEDIFF(DAY, 0, Tm) from AllDay; -- CPU = 23782 ms, elapsed = 24818 ms.
select @d = FLOOR(CAST(Tm as float)) from AllDay; -- CPU = 36891 ms, elapsed = 38414 ms.
select @d = CONVERT(VARCHAR(8), Tm, 112) from AllDay; -- CPU = 102984 ms, elapsed = 109897 ms.
select @d = CONVERT(CHAR(8), Tm, 112) from AllDay; -- CPU = 103390 ms, elapsed = 108236 ms.
select @d = CONVERT(VARCHAR(10), Tm, 101) from AllDay; -- CPU = 123375 ms, elapsed = 135179 ms.
-- Only to another type but not back
select @dd = Tm from AllDay; -- CPU time = 19891 ms, elapsed time = 20937 ms.
select @di = CAST(Tm - 0.50000004 AS int) from AllDay; -- CPU = 21453 ms, elapsed = 23079 ms.
select @di = DATEDIFF(DAY, 0, Tm) from AllDay; -- CPU = 23218 ms, elapsed = 24700 ms
select @df = FLOOR(CAST(Tm as float)) from AllDay; -- CPU = 29312 ms, elapsed = 31101 ms.
select @dv = CONVERT(VARCHAR(8), Tm, 112) from AllDay; -- CPU = 64016 ms, elapsed = 67815 ms.
select @dv = CONVERT(CHAR(8), Tm, 112) from AllDay; -- CPU = 64297 ms, elapsed = 67987 ms.
select @dv = CONVERT(VARCHAR(10), Tm, 101) from AllDay; -- CPU = 65609 ms, elapsed = 68173 ms.
GO
set statistics time off;
</code></pre>
<p><strong>Some Rambling Analysis</strong></p>
<p>Some notes about this. First of all, if just performing a GROUP BY or a comparison, there's no need to convert back to <code>datetime</code>. So you can save some CPU by avoiding that, unless you need the final value for display purposes. You can even GROUP BY the unconverted value and put the conversion only in the SELECT clause:</p>
<pre><code>select Convert(datetime, DateDiff(dd, 0, Tm))
from (select '2010-09-12 00:00:00.003') X (Tm)
group by DateDiff(dd, 0, Tm)
</code></pre>
<p>Also, see how the numeric conversions only take slightly more time to convert back to <code>datetime</code>, but the <code>varchar</code> conversion almost doubles? This reveals the portion of the CPU that is devoted to date calculation in the queries. There are parts of the CPU usage that don't involve date calculation, and this appears to be something close to 19875 ms in the above queries. Then the conversion takes some additional amount, so if there are two conversions, that amount is used up approximately twice.</p>
<p>More examination reveals that compared to <code>Convert(, 112)</code>, the <code>Convert(, 101)</code> query has some additional CPU expense (since it uses a longer <code>varchar</code>?), because the second conversion back to <code>date</code> doesn't cost as much as the initial conversion to <code>varchar</code>, but with <code>Convert(, 112)</code> it is closer to the same 20000 ms CPU base cost.</p>
<p>Here are those calculations on the CPU time that I used for the above analysis:</p>
<pre><code> method round single base
----------- ------ ------ -----
date 21324 19891 18458
int 23031 21453 19875
datediff 23782 23218 22654
float 36891 29312 21733
varchar-112 102984 64016 25048
varchar-101 123375 65609 7843
</code></pre>
<ul>
<li><p><em>round</em> is the CPU time for a round trip back to <code>datetime</code>.</p></li>
<li><p><em>single</em> is CPU time for a single conversion to the alternate data type (the one that has the side effect of removing the time portion).</p></li>
<li><p><em>base</em> is the calculation of subtracting from <code>single</code> the difference between the two invocations: <code>single - (round - single)</code>. It's a ballpark figure that assumes the conversion to and from that data type and <code>datetime</code> is approximately the same in either direction. It appears this assumption is not perfect but is close because the values are all close to 20000 ms with only one exception.</p></li>
</ul>
<p>One more interesting thing is that the base cost is nearly equal to the single <code>Convert(date)</code> method (which has to be almost 0 cost, as the server can internally extract the integer day portion right out of the first four bytes of the <code>datetime</code> data type).</p>
<p><strong>Conclusion</strong></p>
<p>So what it looks like is that the single-direction <code>varchar</code> conversion method takes about 1.8 μs and the single-direction <code>DateDiff</code> method takes about 0.18 μs. I'm basing this on the most conservative "base CPU" time in my testing of 18458 ms total for 25,920,000 rows, so 23218 ms / 25920000 = 0.18 μs. The apparent 10x improvement seems like a lot, but it is frankly pretty small until you are dealing with hundreds of thousands of rows (617k rows = 1 second savings).</p>
<p>Even given this small absolute improvement, in my opinion, the <code>DateAdd</code> method wins because it is the best combination of performance and clarity. The answer that requires a "magic number" of <code>0.50000004</code> is going to bite someone some day (five zeroes or six???), plus it's harder to understand.</p>
<p><strong>Additional Notes</strong></p>
<p>When I get some time I'm going to change <code>0.50000004</code> to <code>'12:00:00.003'</code> and see how it does. It is converted to the same <code>datetime</code> value and I find it much easier to remember.</p>
<p>For those interested, the above tests were run on a server where @@Version returns the following:</p>
<blockquote>
<p>Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86) Jul 9 2008 14:43:34 Copyright (c) 1988-2008 Microsoft Corporation Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 2)</p>
</blockquote> |
59,484,509 | Node had taints that the pod didn't tolerate error when deploying to Kubernetes cluster | <p>I am trying to deploy my microservices into Kubernetes cluster. My cluster having one master and one worker node. I created this cluster for my R&D of Kubernetes deployment. When I am trying to deploy I am getting the even error message like the following,</p>
<pre><code>Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Warning FailedScheduling <unknown> default-scheduler 0/2 nodes are available: 2 node(s) had taints that the pod didn't tolerate
</code></pre>
<p><strong>My attempt</strong></p>
<p>When I am exploring about the error, I found some comments in forums for restarting the docker in the node etc. So after that I restarted Docker. But still the error is the same.</p>
<p>When I tried the command <code>kubectl get nodes</code> it showing like that both nodes are master and both are <code>ready</code> state.</p>
<pre><code>NAME STATUS ROLES AGE VERSION
mildevkub020 Ready master 6d19h v1.17.0
mildevkub040 Ready master 6d19h v1.17.0
</code></pre>
<p>I did not found worker node here. I created one master (mildevkub020) and one worker node (mildev040) with one load balancer. And I followed the official documentation of Kubernetes from the following link,</p>
<p><a href="https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/high-availability/" rel="noreferrer">https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/high-availability/</a></p>
<p><strong>My question</strong></p>
<p>Is this error is because of the cluster problem? Because I am not finding the cluster worker node. Only master node.</p> | 59,486,329 | 10 | 1 | null | 2019-12-26 06:14:15.94 UTC | 7 | 2022-08-14 16:16:04.383 UTC | 2019-12-27 14:20:29.053 UTC | null | 472,495 | null | 8,655,052 | null | 1 | 45 | kubernetes | 104,181 | <p>You can run below command to remove the taint from master node and then you should be able to deploy your pod on that node</p>
<pre><code>kubectl taint nodes mildevkub020 node-role.kubernetes.io/master-
kubectl taint nodes mildevkub040 node-role.kubernetes.io/master-
</code></pre>
<p>Now regarding why its showing as master node check the command you ran to join the node with kubeadm. There are separate commands for master and worker node joining.</p> |
17,853,850 | Vagrant " VM not created." when trying to create box from existing VM | <p>I imported the precise32 box, then installed some packages and other data on the VM. My plan is to then repackage it into a box, to save on complicated provisioning when sharing. </p>
<p>However. </p>
<pre><code>vagrant package --base dev-vm --output /box/vm.box
</code></pre>
<p>Always returns </p>
<pre><code>[dev-vm] VM not created . Moving on
</code></pre>
<p>My directory structure is:</p>
<pre><code>-dev-vm
--.vagrant
--Logs
--box.ovf
--box-disk1.vmdk
--dev-vm_13345342.vbpx
--metadata.json
--Vagrantfile
</code></pre>
<p>Ive </p>
<pre><code> set VAGRANT_LOG=debug
</code></pre>
<p>Which shows no extra info on whats going on. </p>
<p>Windows 7 using Cygwin</p>
<p><strong>UPDATE:</strong></p>
<pre><code> export VAGRANT_LOG=debug
</code></pre>
<p>for Cygwin to set debug log.</p>
<p>I then get</p>
<pre><code> DEBUG subprocess: Waiting for process to exit. Remaining to timeout: 32000
DEBUG subprocess: Exit status: 0
INFO warden: Calling action: #<Vagrant::Action::Builtin::Call:0x2abb800>
INFO runner: Running action: #<Vagrant::Action::Builder:0x2695920>
INFO warden: Calling action: #<VagrantPlugins::ProviderVirtualBox::Action::Created:0x267c078>
INFO runner: Running action: #<Vagrant::Action::Warden:0x2ac6c48>
INFO warden: Calling action: #<VagrantPlugins::ProviderVirtualBox::Action::MessageNotCreated:0x2ac6c00>
INFO interface: info: VM not created. Moving on...
</code></pre> | 17,885,025 | 2 | 2 | null | 2013-07-25 09:17:24.21 UTC | 11 | 2017-09-24 20:16:40.793 UTC | 2013-07-25 09:25:38.747 UTC | null | 289,503 | null | 289,503 | null | 1 | 50 | virtual-machine|vagrant | 32,710 | <p>When you package a box, the box name has to be the specific machine name that you can get from VirtualBox (e.g. <code>lucid_1372711888</code>). Just execute following command in cmd:</p>
<pre><code>vboxmanage list vms
</code></pre>
<p>Notice that "vboxmanage" should prior be added to PATH variable. See <a href="https://serverfault.com/questions/365423/how-to-run-vboxmanage-exe">here</a> how to do that.</p>
<p>Also notice that virtual maschine name must not contain spaces. Otherwise it won't be recognized by "vagrant package" command. For instance:</p>
<pre><code>vagrant package --base win7_vbox_base --output win7_base.box #CORRECT
------------------------------------------------------------------------
vagrant package --base win7 vbox base --output win7_base.box #INCORRECT
</code></pre> |
18,103,117 | How to enable USB debugging in Android? | <p>How do you enable USB debugging in the Nexus 7 (first generation)?</p>
<p>Edit:
The accepted answer applies to other android devices also where Developer option is hidden .</p> | 18,103,158 | 3 | 0 | null | 2013-08-07 12:15:16.713 UTC | 11 | 2020-02-17 09:11:25.547 UTC | 2015-04-25 11:44:27.427 UTC | null | 786,337 | null | 786,337 | null | 1 | 81 | android | 88,498 | <p>Toggle on "USB Debugging" in the "Developer Options" area of Settings.</p>
<p>If you do not see "Developer Options", go into "About device" in Settings and tap on the "Build number" entry seven times, which will unlock "Developer Options".</p>
<p>As documented on Android Developers: <a href="https://developer.android.com/training/basics/firstapp/running-app.html" rel="noreferrer">https://developer.android.com/training/basics/firstapp/running-app.html</a></p> |
17,873,820 | Flask url_for() with multiple parameters | <h3>The Problem:</h3>
<p>I have an a input button in a form that when its submitted should redirect two parameters , <code>search_val</code> and <code>i</code>, to a <code>more_results()</code> function, (listed below), but I get a type error when wsgi builds.</p>
<p>The error is: <code>TypeError: more_results() takes exactly 2 arguments (1 given)</code></p>
<p>html:</p>
<pre><code> <form action="{{ url_for('more_results', past_val=search_val, ind=i ) }}" method=post>
<input id='next_hutch' type=submit value="Get the next Hunch!" name='action'>
</form>
</code></pre>
<p>flask function:</p>
<pre><code>@app.route('/results/more_<past_val>_hunches', methods=['POST'])
def more_results(past_val, ind):
if request.form["action"] == "Get the next Hunch!":
ind += 1
queried_resturants = hf.find_lunch(past_val) #method to generate a list
queried_resturants = queried_resturants[ind]
return render_template(
'show_entries.html',
queried_resturants=queried_resturants,
search_val=past_val,
i=ind
)
</code></pre>
<p>Any idea on how to get past the build error?</p>
<h3>What I've tried:</h3>
<p><a href="https://stackoverflow.com/questions/11124940/creating-link-to-an-url-of-flask-app-in-jinja2-template">Creating link to an url of Flask app in jinja2 template</a></p>
<p>for using multiple paramters with url_for()</p>
<p><a href="https://stackoverflow.com/questions/9023488/build-error-with-variables-and-url-for-in-flask?rq=1">Build error with variables and url_for in Flask</a></p>
<p>similar build erros</p>
<p>As side note, the purpose of the function is to iterate through a list when someone hits a "next page" button. I'm passing the variable <code>i</code> so I can have a reference to keep incrementing through the list. Is there a flask / jinja 2 method that would work better? I've looked into the cycling_list feature but it doesn't seem to able to be used to render a page and then re-render it with <code>cycling_list.next()</code>.</p> | 17,873,868 | 3 | 0 | null | 2013-07-26 05:46:51.607 UTC | 2 | 2022-07-15 12:57:18.203 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 2,259,303 | null | 1 | 18 | python|html|flask | 48,864 | <p>Your route doesn't specify how to fill in more than just the one <code>past_val</code> arg. Flask can't magically create a URL that will pass two arguments if you don't give it a two-argument pattern.</p> |
2,065,553 | Get all numbers that add up to a number | <p>I'm trying to find a way to display all the possible sets of X integers that add up to a given integer. for example to get all 2 integer sets that make 5 I would have:</p>
<pre><code>1, 4
2, 3
</code></pre>
<p>Or for 3 integers that make 6:</p>
<pre><code>1, 1, 4
1, 2, 3
2, 2, 2
</code></pre>
<p>I only need whole numbers not including 0 and it only needs to work on up to about 15 in a set and 30 max. number.</p>
<p>I'm not even sure if this has a term mathematically. It's similar to factorisation I guess?</p> | 2,074,693 | 5 | 3 | null | 2010-01-14 16:12:49.137 UTC | 10 | 2022-08-26 12:05:01.393 UTC | 2013-10-26 05:47:48.573 UTC | null | 321,731 | null | 111,002 | null | 1 | 24 | python|math | 23,203 | <p>Here is one way to solve this problem:</p>
<pre><code>def sum_to_n(n, size, limit=None):
"""Produce all lists of `size` positive integers in decreasing order
that add up to `n`."""
if size == 1:
yield [n]
return
if limit is None:
limit = n
start = (n + size - 1) // size
stop = min(limit, n - size + 1) + 1
for i in range(start, stop):
for tail in sum_to_n(n - i, size - 1, i):
yield [i] + tail
</code></pre>
<p>You can use it like this.</p>
<pre><code>for partition in sum_to_n(6, 3):
print partition
[2, 2, 2]
[3, 2, 1]
[4, 1, 1]
</code></pre> |
1,896,876 | What does the "$" character mean in Ruby? | <p>Been playing with Ruby on Rails for awhile and decided to take a look through the actual source. Grabbed the repo from GitHub and started looking around. Came across some code that I am not sure what it does or what it references. </p>
<p>I saw this code in actionmailer/test/abstract_unit.rb</p>
<pre><code>root = File.expand_path('../../..', __FILE__)
begin
require "#{root}/vendor/gems/environment"
rescue LoadError
$:.unshift("#{root}/activesupport/lib")
$:.unshift("#{root}/actionpack/lib")
end
lib = File.expand_path("#{File.dirname(__FILE__)}/../lib")
$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib)
require 'rubygems'
require 'test/unit'
require 'action_mailer'
require 'action_mailer/test_case'
</code></pre>
<p>Can someone tell me what the $: (a.k.a. "the bling") is referencing?</p> | 1,896,894 | 5 | 0 | null | 2009-12-13 15:53:56.767 UTC | 13 | 2022-01-12 16:50:53.923 UTC | 2022-01-12 16:50:53.923 UTC | null | 967,621 | null | 218,707 | null | 1 | 63 | ruby-on-rails|ruby|global-variables|dollar-sign|load-path | 36,586 | <p>$: is the global variable used for looking up external files.</p>
<p>From <a href="http://www.zenspider.com/Languages/Ruby/QuickRef.html#18" rel="noreferrer">http://www.zenspider.com/Languages/Ruby/QuickRef.html#18</a></p>
<blockquote>
<p>$: Load path for scripts and binary modules by load or require.</p>
</blockquote> |
1,635,497 | OrderBy descending in Lambda expression? | <p>I know in normal Linq grammar, <code>orderby xxx descending</code> is very easy, but how do I do this in Lambda expression?</p> | 1,635,506 | 6 | 0 | null | 2009-10-28 06:29:44.627 UTC | 35 | 2019-05-27 10:05:58.28 UTC | 2016-06-26 15:17:27.863 UTC | null | 2,371,323 | null | 164,168 | null | 1 | 260 | linq|lambda | 339,258 | <p>As Brannon says, it's <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.orderbydescending.aspx" rel="noreferrer"><code>OrderByDescending</code></a> and <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.thenbydescending.aspx" rel="noreferrer"><code>ThenByDescending</code></a>:</p>
<pre><code>var query = from person in people
orderby person.Name descending, person.Age descending
select person.Name;
</code></pre>
<p>is equivalent to:</p>
<pre><code>var query = people.OrderByDescending(person => person.Name)
.ThenByDescending(person => person.Age)
.Select(person => person.Name);
</code></pre> |
2,081,894 | Handling PUT/DELETE arguments in PHP | <p>I am working on my <a href="http://github.com/philsturgeon/codeigniter-restclient" rel="noreferrer">REST client library for CodeIgniter</a> and I am struggling to work out how to send PUT and DELETE arguments in PHP.</p>
<p>In a few places I have seen people using the options:</p>
<pre><code>$this->option(CURLOPT_PUT, TRUE);
$this->option(CURLOPT_POSTFIELDS, $params);
</code></pre>
<p>Annoyingly, this seems to do nothing. Is this the correct way to set PUT parameters?</p>
<p>If so, how do I set DELETE parameters?</p>
<p><em>$this->option() is part of my library, it simply builds up an array of CURLOPT_XX constants and sends them to curl_setopt_array() when the built up cURL request is executed.</em> </p>
<p>I am attempting to read PUT and DELETE parameters using the following code:</p>
<pre><code> case 'put':
// Set up out PUT variables
parse_str(file_get_contents('php://input'), $this->_put_args);
break;
case 'delete':
// Set up out PUT variables
parse_str(file_get_contents('php://input'), $this->_delete_args);
break;
</code></pre>
<p>There are two options here, I am approaching this in the wrong way or there is a bug somewhere in my libraries. If you could let me know if this should theoretically work I can just hammer away on debug until I solve it.</p>
<p>I dont want to waste any more time on an approach that is fundamentally wrong.</p> | 2,082,097 | 6 | 2 | null | 2010-01-17 17:26:02.57 UTC | 22 | 2014-08-15 14:52:57.843 UTC | 2011-11-01 00:53:25.637 UTC | null | 367,456 | null | 124,378 | null | 1 | 84 | php|rest|codeigniter|curl|http-headers | 75,200 | <p>Instead of using <code>CURLOPT_PUT = TRUE</code> use <code>CURLOPT_CUSTOMREQUEST = 'PUT'</code>
and <code>CURLOPT_CUSTOMREQUEST = 'DELETE'</code> then just set values with <code>CURLOPT_POSTFIELDS</code>.</p> |
2,218,111 | PHP Recursive Backup Script | <p>I wrote a basic content-management system for my website, including an administration panel. I understand basic file IO as well as copying via PHP, but my attempts at a backup script callable from the script have failed. I tried doing this:</p>
<pre><code>//... authentication, other functions
for(scandir($homedir) as $buffer){
if(is_dir($buffer)){
//Add $buffer to an array
}
else{
//Back up the file
}
}
for($founddirectories as $dir){
for(scandir($dir) as $b){
//Backup as above, adding to $founddirectories
}
}
</code></pre>
<p>But it did not seem to work.</p>
<p>I know that I can do this using FTP, but I want a completely server-side solution that can be accessed anywhere with sufficient authorization.</p> | 2,218,209 | 7 | 2 | null | 2010-02-07 20:02:40.153 UTC | 9 | 2014-04-01 13:48:13.36 UTC | null | null | null | null | 268,254 | null | 1 | 7 | php|backup | 8,984 | <p>Here is an alternative though: why don't you <a href="https://stackoverflow.com/questions/1334613/zip-a-directory-in-php/1334949#1334949">Zip the source directory instead</a>?</p>
<pre><code>function Zip($source, $destination)
{
if (extension_loaded('zip') === true)
{
if (file_exists($source) === true)
{
$zip = new ZipArchive();
if ($zip->open($destination, ZIPARCHIVE::CREATE) === true)
{
$source = realpath($source);
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file)
{
$file = realpath($file);
if (is_dir($file) === true)
{
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString(basename($source), file_get_contents($source));
}
}
return $zip->close();
}
}
return false;
}
</code></pre>
<p>You can even unzip it afterwards and archive the same effect, although I must say I prefer having my backups compressed in zip file format.</p> |
1,915,746 | In Perl, how can I find the index of a given value in an array? | <pre><code>$VAR1 = [
'830974',
'722065',
'722046',
'716963'
];
</code></pre>
<p>How can I calculate the array index for the value "722065"?</p> | 1,915,838 | 7 | 4 | null | 2009-12-16 16:14:06.34 UTC | 7 | 2014-07-11 16:02:13.957 UTC | 2009-12-16 17:52:29.56 UTC | null | 44,673 | null | 231,178 | null | 1 | 16 | perl|arrays | 41,570 | <p>The <code>firstidx</code> function from <a href="http://search.cpan.org/perldoc/List::MoreUtils" rel="noreferrer">List::MoreUtils</a> can help:</p>
<pre><code>use strict;
use warnings;
use List::MoreUtils qw(firstidx);
my @nums = ( '830974', '722065', '722046', '716963' );
printf "item with index %i in list is 722065\n", firstidx { $_ eq '722065' } @nums;
__END__
</code></pre>
<pre>
item with index 1 in list is 722065
</pre> |
1,494,800 | WITH statement in Java | <p>In VB.NET there is the WITH command that lets you omit an object name and only access the methods and properties needed. For example:</p>
<pre><code>With foo
.bar()
.reset(true)
myVar = .getName()
End With
</code></pre>
<p>Is there any such syntax within Java?</p>
<p>Thanks!</p> | 1,494,809 | 8 | 1 | null | 2009-09-29 20:38:27.9 UTC | 6 | 2019-09-04 13:24:36.24 UTC | null | null | null | null | 93,953 | null | 1 | 36 | java|vb.net|syntax|syntactic-sugar | 29,535 | <p>No. The best you can do, when the expression is overly long, is to assign it to a local variable with a short name, and use <code>{...}</code> to create a scope:</p>
<pre><code>{
TypeOfFoo it = foo; // foo could be any lengthy expression
it.bar();
it.reset(true);
myvar = it.getName();
}
</code></pre> |
2,307,437 | C# application doesn't run on another computer | <p>I complied my C# windows forms application on Visual Studio 2008 with configuration "Release". When I try to run it on another computer, no windows are shown at all. Complied on Windows 7, another computer has windows xp installed.
What can it be?</p>
<p><strong>Added</strong>:
I didn't create any installer. Another machine has .net framework 3.0, not 3.5 installed, but simple hello world application works just fine. I tried to copy the program to another folder on my computer - no changes.</p> | 2,307,853 | 9 | 12 | null | 2010-02-21 20:50:52.43 UTC | 1 | 2020-05-09 04:21:49.543 UTC | 2010-02-21 21:14:47.06 UTC | null | 187,644 | null | 187,644 | null | 1 | 4 | c#|deployment|winforms | 42,007 | <p>Double check on the .NET version, if you built a release against .NET 3.5, and the other machine does not have .NET 3.5, that must be installed I'm afraid, not alone that, don't forget the Service Pack 1 as well. Have a look at this SO <a href="https://stackoverflow.com/questions/2238696/is-there-a-way-to-determine-the-net-framework-version-from-the-command-line/2238861#2238861">thread</a> here to determine the .NET version that is installed, run it on the computer that 'appears to be broken' to see what version...</p> |
1,490,745 | Why is Perl the best choice for most string manipulation tasks? | <p>I've heard that Perl is the go-to language for string manipulation (and line noise ;). Can someone provide examples and comparisons with other language(s) to show me why?</p> | 1,490,787 | 11 | 7 | null | 2009-09-29 05:41:00.883 UTC | 4 | 2014-02-15 07:04:24.333 UTC | 2009-09-29 23:24:31.153 UTC | null | 2,766,176 | null | 117,069 | null | 1 | 28 | perl|string|programming-languages|comparison | 21,338 | <p>It is very subjective, so I wouldn't say that Perl is the best choice, but it is certainly a valid choice for string manipulation. Other alternatives are Tcl, Python, AWK, etc.</p>
<p>I like Perl's capabilities because it has excellent support (better than POSIX as pointed out in the comment) for fast regexs and the implicit variables makes it easy to do basic string crunching with very little code. </p>
<p>If you have a *nix background a lot of what you already know will apply to Perl as well, which makes it fairly easy to pick up for a lot of people. </p> |
2,155,737 | Remove CSS class from element with JavaScript (no jQuery) | <p>Could anyone let me know how to remove a class on an element using JavaScript only?
Please do not give me an answer with jQuery as I can't use it, and I don't know anything about it.</p> | 2,156,090 | 11 | 6 | null | 2010-01-28 15:43:04.287 UTC | 109 | 2022-06-17 20:25:24.54 UTC | 2012-10-04 08:59:47.71 UTC | null | 58,792 | null | 207,847 | null | 1 | 692 | javascript|html|css | 910,964 | <p>The right and standard way to do it is using <code>classList</code>. It is now <a href="http://caniuse.com/#search=classList" rel="noreferrer">widely supported in the latest version of most modern browsers</a>:</p>
<pre><code>ELEMENT.classList.remove("CLASS_NAME");
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>remove.onclick = () => {
const el = document.querySelector('#el');
el.classList.remove("red");
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.red {
background: red
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='el' class="red"> Test</div>
<button id='remove'>Remove Class</button></code></pre>
</div>
</div>
</p>
<p>Documentation: <a href="https://developer.mozilla.org/en/DOM/element.classList" rel="noreferrer">https://developer.mozilla.org/en/DOM/element.classList</a></p> |
18,149,882 | Run As JUnit not appearing in Eclipse - using JUnit4 | <p>I'm trying to write JUnit4 tests for my web app, and they had been working fine previously. However, now when I try to run the tests by right clicking the class file -> Run As -> JUnit Test I don't see that option. I think it could be because a colleague committed some Eclipse settings/property files on accident that messed with mine. I'm using Eclipse Helios on a Mac running 10.6.X.</p>
<p>I noticed that the icons on the test classes changed from the "filled" J to a "bubble" J and I'm not sure if that is signifying some kind of problem:</p>
<p><img src="https://i.stack.imgur.com/4EhaB.png" alt="enter image description here"></p>
<p>I've double checked and made sure that JUnit4 is on my Build Path, and I've gone to the Eclipse -> Preferences -> JUnit pane and verified there are JUnit4 imports being used.</p>
<p>My test classes look like this:</p>
<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration( { "classpath*:/resources/action-test-appconfig.xml" })
@Transactional
public class UserControllerTest extends BaseStrutsTestCase<UserController> {
/**
* Tests the ability of a user to change their login username
* @throws Exception
*/
@Test
public void testChangeLogin() throws Exception {
</code></pre>
<p>Any thoughts and suggestions are appreciated.</p> | 18,149,985 | 4 | 0 | null | 2013-08-09 15:05:59.97 UTC | null | 2015-03-31 06:23:40.69 UTC | null | null | null | null | 2,432,532 | null | 1 | 6 | java|eclipse|unit-testing|junit|junit4 | 42,118 | <p>The problem is with the way you are trying to access and run java files in eclipse. You should be observing this empty 'J' icons on your java files. It is a classpath problem, when you click, you are actually accessing the file from the classpath.</p>
<p>To view the Java file, you have to add a reference to your project in the classpath and move it to the top of the classpath list.</p>
<p>Once you do that, then you should be able to run your junits.</p> |
18,125,294 | Hibernate 4 javax/transaction/SystemException error | <p>I am trying to get Hibernate 4.3 to work with my MySQL database. I am already able to use the Hibernate Code Generation tool in Eclipse and I am also able to connect to the database using the Hibernate Configurations tool.</p>
<p>However when I try to run code in my Main class that queries the database I get the following error:</p>
<pre><code>Exception in thread "main" java.lang.NoClassDefFoundError: javax/transaction/SystemException
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at org.jboss.logging.Logger.getMessageLogger(Logger.java:2248)
at org.jboss.logging.Logger.getMessageLogger(Logger.java:2214)
at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:184)
at be.comp.permanenties.HibernateUtil.<clinit>(HibernateUtil.java:15)
at be.comp.dao.balie.ZitdagenDAOMySQL.findByMaCode(ZitdagenDAOMySQL.java:31)
at be.comp.permanenties.Main.main(Main.java:19)
Caused by: java.lang.ClassNotFoundException: javax.transaction.SystemException
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 8 more
</code></pre>
<p>The code in my HibernateUtil.java file is:</p>
<pre><code>import org.apache.commons.lang3.SystemUtils;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateUtil {
private static final SessionFactory sessionFactoryBalie = new Configuration().configure("mysql_balie.cfg.xml").buildSessionFactory();
public static SessionFactory getSessionFactoryBalie() {
return sessionFactoryBalie;
}
}
</code></pre>
<p>The mysq_balie.cfg.xml file looks like:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- Development -->
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/balie?autoReconnect=true&amp;useUnicode=true&amp;characterEncoding=iso-8859-1</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.default_catalog">db</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="hibernate.connection.pool_size">1</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- <property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>-->
<!-- Disable the second-level cache -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="hibernate.show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- List of XML mapping files -->
<mapping resource="be/comp/model/balie/Zitdagen.hbm.xml"/>
</session-factory>
</code></pre>
<p></p>
<p>I am unable to figure out where the error might be. All help is welcome. Thanks.</p> | 18,125,386 | 4 | 0 | null | 2013-08-08 11:51:52.18 UTC | 3 | 2021-10-01 20:55:00.697 UTC | null | null | null | null | 1,401,657 | null | 1 | 28 | hibernate | 57,597 | <p>you are missing jta.jar<br/>
with maven add this dep:</p>
<pre><code> <dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
</code></pre>
<p>or download from maven repository and add to your CLASSPATH</p> |
17,901,588 | New repo with copied history of only currently tracked files | <p>Our current repo has tens of thousands of commits and a fresh clone transfers nearly a gig of data (there are lots of jar files that have since been deleted in the history). We'd like to cut this size down by making a new repo that keeps the full history for just the files that are currently active in the repo, or possibly just modify the current repo to clear the deleted file history. But I'm not sure how to do this in a practical manor. </p>
<p>I've tried the script in <a href="https://stackoverflow.com/questions/10676128/remove-deleted-files-from-git-history">Remove deleted files from git history</a>:</p>
<pre><code>for del in `cat deleted.txt`
do
git filter-branch --index-filter "git rm --cached --ignore-unmatch $del" --prune-empty -- --all
# The following seems to be necessary every time
# because otherwise git won't overwrite refs/original
git reset --hard
git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d
git reflog expire --expire=now --all
git gc --aggressive --prune=now
done;
</code></pre>
<p>But given that we have tens of thousands of deleted files in the history and tens of thousands of commits, running the script would take an eternity. I started running this for just ONE deleted file 2 hours ago and the filter-branch command is still running, it's going through each of the 40,000+ commits one at a time, and this is on a new Macbook pro with an SSD drive. </p>
<p>I've also read the page <a href="https://help.github.com/articles/remove-sensitive-data" rel="noreferrer">https://help.github.com/articles/remove-sensitive-data</a> but this only works for removing single files. </p>
<p>Has anyone been able to do this? I really want to preserve history of currently tracked files, I'm not sure if the space savings benefit would be worth creating a new repo if we can't keep the history. </p> | 17,909,526 | 5 | 11 | null | 2013-07-27 19:22:23.657 UTC | 33 | 2021-09-22 07:48:57.537 UTC | 2017-05-23 12:10:47.957 UTC | null | -1 | null | 1,010,025 | null | 1 | 34 | git | 5,165 | <h2>Delete everything and restore what you want</h2>
<p>Rather than delete this-list-of-files one at a time, do the almost-opposite: delete everything and just restore the files you want to keep.</p>
<p>Like so:</p>
<pre><code># for unix
$ git checkout master
$ git ls-files > keep-these.txt
$ git filter-branch --force --index-filter \
"git rm --ignore-unmatch --cached -qr . ; \
cat $PWD/keep-these.txt | tr '\n' '\0' | xargs -d '\0' git reset -q \$GIT_COMMIT --" \
--prune-empty --tag-name-filter cat -- --all
</code></pre>
<pre><code># for macOS
$ git checkout master
$ git ls-files > keep-these.txt
$ git filter-branch --force --index-filter \
"git rm --ignore-unmatch --cached -qr . ; \
cat $PWD/keep-these.txt | tr '\n' '\0' | xargs -0 git reset -q \$GIT_COMMIT --" \
--prune-empty --tag-name-filter cat -- --all
</code></pre>
<p>It may be faster to execute.</p>
<h3>Cleanup steps</h3>
<p>Once the whole process has finished, <em>then</em> cleanup:</p>
<pre><code>$ rm -rf .git/refs/original/
$ git reflog expire --expire=now --all
$ git gc --prune=now
# optional extra gc. Slow and may not further-reduce the repo size
$ git gc --aggressive --prune=now
</code></pre>
<p>Comparing the repository size before and after, should indicate a sizable
reduction, and of course only commits that touch the kept files, plus merge
commits - even if empty (<a href="https://www.kernel.org/pub/software/scm/git/docs/git-filter-branch.html" rel="nofollow noreferrer">because that's how --prune-empty works</a>), will be in the history.</p>
<h3>$GIT_COMMIT?</h3>
<p>The use of <code>$GIT_COMMIT</code> seems to have caused some confusion, <a href="https://www.kernel.org/pub/software/scm/git/docs/git-filter-branch.html" rel="nofollow noreferrer">from the git filter-branch documentation</a> (emphasis added):</p>
<blockquote>
<p>The argument is always evaluated in the shell context using the eval command (with the notable exception of the commit filter, for technical reasons). Prior to that, <strong>the $GIT_COMMIT environment variable will be set to contain the id of the commit being rewritten</strong>.</p>
</blockquote>
<p>That means <code>git filter-branch</code> will provide the variable at run time, it's not provided by you before hand. This can be demonstrated if there's any doubt using this no-op filter branch command:</p>
<pre><code>$ git filter-branch --index-filter "echo current commit is \$GIT_COMMIT"
Rewrite d832800a85be9ef4ee6fda2fe4b3b6715c8bb860 (1/xxxxx)current commit is d832800a85be9ef4ee6fda2fe4b3b6715c8bb860
Rewrite cd86555549ac17aeaa28abecaf450b49ce5ae663 (2/xxxxx)current commit is cd86555549ac17aeaa28abecaf450b49ce5ae663
...
</code></pre> |
17,713,412 | CORS POST Requests not working - OPTIONS (Bad Request) - The origin is not allowed | <p>I'm having a lot of trouble getting a cross domain POST request to hit an Api controller in the latest beta 2 release.</p>
<p>Chrome (and other browsers) spit out:</p>
<pre><code>OPTIONS http://api.hybridwebapp.com/api/values 400 (Bad Request)
POST http://api.hybridwebapp.com/api/values 404 (Not Found)
</code></pre>
<p>It may be related to <a href="https://aspnetwebstack.codeplex.com/workitem/954" rel="noreferrer">this issue</a> but I have applied that workaround and several other fixes such as web.config <a href="https://stackoverflow.com/questions/12521499/cors-support-for-put-and-delete-with-asp-net-web-api">additions here</a> </p>
<p>I've been banging my head with this for a while so I created a solution to reproduce the problem exactly.</p>
<p>Load the web app there will be 2 buttons one for GET one for POST and the response will appear next to the button. GET works. Cannot get POST to return successfully.</p>
<p><img src="https://i.stack.imgur.com/VBsBf.png" alt="enter image description here"></p>
<p>I'm able to get a hint at the cause from Fiddler but it makes no sense because if you look at the response it DOES include the domain in the Access-Controll-Allow-Origin header:</p>
<p><img src="https://i.stack.imgur.com/nCMwC.png" alt="enter image description here"></p>
<p>There is a folder in the solution called "ConfigurationScreenshots" with a few screenshots of the IIS configuration (website bindings) and Project properties configurations to make it as easy as possible to help me :)</p>
<p>EDIT: Don't forget to add this entry to host file (%SystemRoot%\system32\drivers\etc):</p>
<pre><code> 127.0.0.1 hybridwebapp.com api.hybridwebapp.com
</code></pre>
<p>**STATUS: ** It seems that some browsers like Chrome allow me to proceed with the POST regardless of the error message in the OPTIONS response (while others like Firefox don't). But I don't consider that solved.</p>
<p>Look at the Fidler screenshots of the OPTIONS request it has </p>
<p>Access-Control-Allow-Origin: <a href="http://hybridwebapp.com" rel="noreferrer">http://hybridwebapp.com</a></p>
<p>And yet the error:</p>
<p>The origin <a href="http://hybridwebapp.com" rel="noreferrer">http://hybridwebapp.com</a> is not allowed</p>
<p>That is completely contradictory it's as if it's ignoring the header.</p> | 17,800,055 | 5 | 8 | null | 2013-07-18 02:16:15.57 UTC | 9 | 2016-07-05 12:47:07.013 UTC | 2017-05-23 11:47:11.987 UTC | null | -1 | null | 1,267,778 | null | 1 | 28 | asp.net|asp.net-web-api|cors | 57,205 | <p>Ok I got past this. This has got to be the strangest issue I've ever encountered. Here's how to "solve" it:</p>
<ol>
<li>Continue on with life as usual until <em>suddenly out of no where</em> OPTIONS requests to this domain begin returning 200 OK (instead of 400 Bad Request) and POST never happens (or at least seems like it doesn't because the browser swallows it) </li>
<li>Realize that Fiddler's OPTIONS response mysteriously contains duplicates for "Access-Control-Allow-XXX". </li>
<li>Try removing the following statement from you web.config even though you clearly remember trying that to fix the previous issue and it not working:</li>
</ol>
<p>Remove this:</p>
<pre><code> <httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
<add name="Access-Control-Allow-Origin" value="http://mydomain.com" />
<add name="Access-Control-Allow-Headers" value="Accept, Content-Type, Origin" />
<add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</code></pre>
<p>Because you already have this:</p>
<pre><code> var enableCorsAttribute = new EnableCorsAttribute("http://mydomain.com",
"Origin, Content-Type, Accept",
"GET, PUT, POST, DELETE, OPTIONS");
config.EnableCors(enableCorsAttribute);
</code></pre>
<p>Moral: You only need one.</p> |
17,772,534 | PHP Difference between array() and [] | <p>I'm writing a PHP app and I want to make sure it will work with no errors.</p>
<p>The original code:</p>
<pre><code><?php
$data = array('name' => 'test',
'id' => 'theID');
echo form_input($data);
?>
</code></pre>
<p>Would the following work with no errors or is not recommended for some reason?</p>
<pre><code><?= form_input(['name' => 'test', 'id' => 'theID']); ?>
</code></pre>
<p>Are there any difference?</p>
<p>I've looked again the data about <code>array()</code> and the short array method with square brackets <code>[]</code> in PHP.net but I'm not sure.</p>
<p>And also, is the short php tag <code><?= ?></code> fine for echoing? Is there any version issue? (provided is enabled in php.ini)</p> | 17,772,560 | 5 | 5 | null | 2013-07-21 12:51:45.48 UTC | 16 | 2022-04-12 20:10:31.817 UTC | 2017-10-20 17:51:08.073 UTC | null | 1,995,006 | null | 1,995,006 | null | 1 | 178 | php|arrays|syntax|square-bracket | 102,804 | <p>Following <code>[]</code> is supported in PHP >= 5.4:</p>
<pre><code>['name' => 'test', 'id' => 'theID']
</code></pre>
<p>This is a short syntax only and in <strong>PHP < 5.4 it won't work</strong>.</p> |
6,740,134 | Case Statement in SQL using Like | <p>Hello I have a SQL statement</p>
<pre><code>INSERT INTO Foundation.TaxLiability.EmpowerSystemCalendarCode
SELECT SystemTax.SystemTaxID,
EmpowerCalendarCode.CalendarCodeID
,CASE WHEN EmpowerCalendarCode.CalendarName LIKE '%Monthly%' THEN 3
WHEN EmpowerCalendarCode.CalendarName LIKE '%Annual%' THEN 2
WHEN EmpowerCalendarCode.CalendarName LIKE '%Quarterly%' THEN 4
ELSE 0
END
FROM Foundation.Common.SystemTax SystemTax, Foundation.TaxLiability.EmpowerCalendarCode EmpowerCalendarCode
WHERE SystemTax.EmpowerTaxCode = EmpowerCalendarCode.LongAgencyCode and SystemTax.EmpowerTaxType = EmpowerCalendarCode.EmpowerTaxType
</code></pre>
<p>Even though CalendarName has values like Quarterly (EOM) I still end up getting 0. Any ideas and suggestions!</p> | 6,740,207 | 3 | 6 | null | 2011-07-18 22:21:13.067 UTC | 4 | 2019-03-19 16:23:07.617 UTC | null | null | null | null | 424,294 | null | 1 | 10 | sql|sql-server-2008 | 95,064 | <p>For one, I would update your SQL to this so you are using a <code>JOIN</code> on your <code>SELECT</code> statement instead of placing this in a <code>WHERE</code> clause. </p>
<pre><code>INSERT INTO Foundation.TaxLiability.EmpowerSystemCalendarCode
SELECT SystemTax.SystemTaxID,
EmpowerCalendarCode.CalendarCodeID
,CASE WHEN EmpowerCalendarCode.CalendarName LIKE '%Monthly%' THEN 3
WHEN EmpowerCalendarCode.CalendarName LIKE '%Annual%' THEN 2
WHEN EmpowerCalendarCode.CalendarName LIKE '%Quarterly%' THEN 4
ELSE 0
END
FROM Foundation.Common.SystemTax SystemTax
INNER JOIN Foundation.TaxLiability.EmpowerCalendarCode EmpowerCalendarCode
ON SystemTax.EmpowerTaxCode = EmpowerCalendarCode.LongAgencyCode
AND SystemTax.EmpowerTaxType = EmpowerCalendarCode.EmpowerTaxType
</code></pre>
<p>two, what happens if you remove the <code>INSERT INTO</code>?</p> |
6,633,536 | CSS rotation with respect to a reference point | <p>How to rotate an element with respect to a defined point i.e. defined <code>x</code> & <code>y</code> coordinate in <strong>CSS</strong> (webkit)?</p>
<p>Normally rotation make element's center point as reference.</p> | 6,633,676 | 3 | 0 | null | 2011-07-09 08:01:54.667 UTC | 7 | 2022-08-04 07:14:04.593 UTC | 2014-06-26 22:39:07.38 UTC | null | 502,381 | null | 690,854 | null | 1 | 31 | css|rotation | 37,391 | <p>You could use transform-origin.
It defines the point to rotate around from the upper left corner of the element.</p>
<pre><code>transform-origin: 0% 0%
</code></pre>
<p>This would rotate around the upper left corner.</p>
<p>For other options look here: <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/transform-origin" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/CSS/transform-origin</a></p>
<p>for the safer side if this link not available then here are a couple of more options</p>
<pre><code>transform-origin: center; // one of the keywords left, center, right, top, and bottom
transform-origin: top left; // same way can use two keywords
transform-origin: 50px 50px; // specific x-offset | y-offset
transform-origin: bottom right 60px; // third part is for 3D transform : z-offset
</code></pre>
<p>As far as I know there isn't an option to rotate around a fixed point (although this would be handy).</p> |
45,823,734 | Visual Studio Code formatting for "{ }" | <p>I'm on Ubuntu. C++ in Visual Studio Code automatically lints like</p>
<pre><code>if (condition == true)
{
DoStuff();
}
</code></pre>
<p>Instead I want to do :</p>
<pre><code>if (condition == true) {
DoStuff();
}
</code></pre>
<p>How do I do that?</p>
<p>I've already installed the <strong>C/C++</strong> extension from the marketplace.</p> | 50,489,812 | 6 | 11 | null | 2017-08-22 17:31:42.16 UTC | 52 | 2021-11-18 15:42:15.973 UTC | 2020-12-02 04:57:40.39 UTC | null | 5,536,005 | null | 5,536,005 | null | 1 | 128 | c++|ubuntu|visual-studio-code|lint | 73,286 | <p>base on @Chris Drew's answer</p>
<ol>
<li>Go Preferences -> Settings</li>
<li>Search for C_Cpp.clang_format_fallbackStyle</li>
<li>Click Edit, Copy to Settings</li>
<li>Change from "Visual Studio" to <code>"{ BasedOnStyle: Google, IndentWidth: 4 }"</code></li>
</ol>
<p>e.g.</p>
<ul>
<li><code>"C_Cpp.clang_format_fallbackStyle": "{ BasedOnStyle: Google, IndentWidth: 4, ColumnLimit: 0}"
</code></li>
<li>btw <code>ColumnLimit: 0</code> is helpful too, because google limit will break your code to next line when you do not need it.</li>
</ul>
<p>If you want more:</p>
<ul>
<li>check <a href="https://clang.llvm.org/docs/ClangFormatStyleOptions.html" rel="noreferrer">https://clang.llvm.org/docs/ClangFormatStyleOptions.html</a></li>
<li>customize your functionality to "C_Cpp.clang_format_fallbackStyle" for your loved favor.</li>
</ul>
<p>More detail:</p>
<p>English: <a href="https://medium.com/@zamhuang/vscode-how-to-customize-c-s-coding-style-in-vscode-ad16d87e93bf" rel="noreferrer">https://medium.com/@zamhuang/vscode-how-to-customize-c-s-coding-style-in-vscode-ad16d87e93bf</a></p>
<p>Taiwan: <a href="https://medium.com/@zamhuang/vscode-%E5%A6%82%E4%BD%95%E5%9C%A8-vscode-%E4%B8%8A%E8%87%AA%E5%AE%9A%E7%BE%A9-c-%E7%9A%84-coding-style-c8eb199c57ce" rel="noreferrer">https://medium.com/@zamhuang/vscode-%E5%A6%82%E4%BD%95%E5%9C%A8-vscode-%E4%B8%8A%E8%87%AA%E5%AE%9A%E7%BE%A9-c-%E7%9A%84-coding-style-c8eb199c57ce</a></p> |
23,927,047 | Button Animate like ios game center button | <p>I am trying to make my buttons animate like buttons in ios game center. they seem to wobble and float about the screen like a bubble. I've tried moving my buttons randomly on the screen, make them move in a constant cirular path at the same time but it's not the same effect.</p>
<p>I need a wobble kind of effect. any ideas are appreciated</p> | 23,933,975 | 1 | 4 | null | 2014-05-29 06:25:44.73 UTC | 12 | 2014-05-30 10:18:34.83 UTC | null | null | null | null | 1,235,151 | null | 1 | 6 | ios|animation|button|game-center | 4,098 | <p>Combining a few <code>CAKeyframeAnimations</code> will give you the result. You need one for the position to follow a circle, and one for each scale (x/y) which are timed a bit different to achieve the wobble-effect. Check out the example:</p>
<pre><code> UIView * view = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 50, 50)];
view.backgroundColor = [UIColor redColor];
view.layer.cornerRadius = view.frame.size.width/2;
[self.view addSubview:view];
//create an animation to follow a circular path
CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
//interpolate the movement to be more smooth
pathAnimation.calculationMode = kCAAnimationPaced;
//apply transformation at the end of animation (not really needed since it runs forever)
pathAnimation.fillMode = kCAFillModeForwards;
pathAnimation.removedOnCompletion = NO;
//run forever
pathAnimation.repeatCount = INFINITY;
//no ease in/out to have the same speed along the path
pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
pathAnimation.duration = 5.0;
//The circle to follow will be inside the circleContainer frame.
//it should be a frame around the center of your view to animate.
//do not make it to large, a width/height of 3-4 will be enough.
CGMutablePathRef curvedPath = CGPathCreateMutable();
CGRect circleContainer = CGRectInset(view.frame, 23, 23);
CGPathAddEllipseInRect(curvedPath, NULL, circleContainer);
//add the path to the animation
pathAnimation.path = curvedPath;
//release path
CGPathRelease(curvedPath);
//add animation to the view's layer
[view.layer addAnimation:pathAnimation forKey:@"myCircleAnimation"];
//create an animation to scale the width of the view
CAKeyframeAnimation *scaleX = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale.x"];
//set the duration
scaleX.duration = 1;
//it starts from scale factor 1, scales to 1.05 and back to 1
scaleX.values = @[@1.0, @1.05, @1.0];
//time percentage when the values above will be reached.
//i.e. 1.05 will be reached just as half the duration has passed.
scaleX.keyTimes = @[@0.0, @0.5, @1.0];
//keep repeating
scaleX.repeatCount = INFINITY;
//play animation backwards on repeat (not really needed since it scales back to 1)
scaleX.autoreverses = YES;
//ease in/out animation for more natural look
scaleX.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
//add the animation to the view's layer
[view.layer addAnimation:scaleX forKey:@"scaleXAnimation"];
//create the height-scale animation just like the width one above
//but slightly increased duration so they will not animate synchronously
CAKeyframeAnimation *scaleY = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale.y"];
scaleY.duration = 1.5;
scaleY.values = @[@1.0, @1.05, @1.0];
scaleY.keyTimes = @[@0.0, @0.5, @1.0];
scaleY.repeatCount = INFINITY;
scaleY.autoreverses = YES;
scaleX.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[view.layer addAnimation:scaleY forKey:@"scaleYAnimation"];
</code></pre> |
18,687,877 | Nodejs application Error: bind EADDRINUSE when use pm2 deploy | <p>Express application deploy with <a href="https://github.com/Unitech/pm2" rel="noreferrer">pm2</a></p>
<p>database is mongodb </p>
<p>when run app with command: </p>
<p><code>NODE_ENV=production pm2 start app.js -i max</code></p>
<p>aften has Error: bind EADDRINUSE, this is logs, when error, </p>
<pre><code>[app err (l0)] js:1073:26
[app err (l1)] at Object.30:1 (cluster.js:587:5)
[app err (l2)] at handleResponse (cluster.js:171:41)
[app err (l3)] at respond (cluster.js:192:5)
[app err (l4)] at handleMessage (cluster.js:202:5)
[app err (l5)] at process.EventEmitter.emit (events.js:117:20)
[app err (l6)] at handleMessage (child_process.js:318:10)
[app err (l7)] at child_process.js:392:7
[app err (l8)] at process.handleConversion.net.Native.got (child_process.js:91:7)Error: bind EADDRINUSE
[app err (l9)] at errnoException (net.js:901:11)
[app err (l10)] at net.js:1073:26
[app err (l11)] at Object.31:1 (cluster.js:587:5)
[app err (l12)] at handleResponse (cluster.js:171:41)
[app err (l13)] at respond (cluster.js:192:5)
[app err (l14)] at handleMessage (cluster.js:202:5)
[app err (l15)] at process.EventEmitter.emit (events.js:117:20)
[app err (l16)] at handleMessage (child_process.js:318:10)
[app err (l17)] at child_process.js:392:7
[app err (l18)] at process.handleConversion.net.Native.got (child_process.js:91:7)
</code></pre>
<p>This causes app is slow, How to solve this problem, thanks very much </p> | 18,687,960 | 2 | 0 | null | 2013-09-08 19:40:01.667 UTC | 6 | 2017-05-04 08:43:36.163 UTC | null | null | null | null | 869,142 | null | 1 | 26 | node.js|mongodb|deployment|express|cluster-computing | 40,560 | <p>I don't know the port used by your application. It depends on your code. In this example, I will assume the port is <code>3000</code>.</p>
<p>You need to verify if the port is already took on your system. To do that:</p>
<ul>
<li>On linux: <code>sudo netstat -nltp | grep 3000</code></li>
<li>On OSX: <code>sudo lsof -i -P | grep 3000</code></li>
</ul>
<p>If you have a result, you need to kill the process (<code>kill <pid></code>).</p>
<p>You should check if <code>pm2 list</code> returns 0 process. In addition, when you do a <code>pm2 stopAll</code>, the socket is not released. Don't forget to do a <code>pm2 kill</code> to be sure the daemon is killed.</p>
<pre><code>$ pm2 kill
Daemon killed
</code></pre> |
18,401,035 | Twitter bootstrap 3 - create a custom glyphicon and add to glyphicon "font" | <p>I am running twitter bootstrap3, and I am extremely happy with the new way it handles the icon as fonts. However: I need some custom icons; I need to make them myself, and ideally integrate it into the existing font. I have searched with no luck. I am well familiar with illustrator, vector graphics etc, but how to integrate?</p>
<p>Worst case scenario, I will make images the traditional way, but hope there is a better solution.</p>
<hr>
<p><strong>How do I integrate a custom glyphicon with the existing (bootstrap 3) glyphicon font?</strong> </p> | 18,410,804 | 2 | 0 | null | 2013-08-23 10:51:38.703 UTC | 35 | 2018-08-10 02:18:12.14 UTC | 2018-08-10 02:18:12.14 UTC | null | 7,508,418 | null | 318,704 | null | 1 | 63 | fonts|icons|twitter-bootstrap-3|glyphicons | 88,693 | <p>This process might be one option. </p>
<p>You could use the <a href="http://icomoon.io/app/">IcoMoon App</a>. Their <a href="http://icomoon.io/app/#library">library</a> includes FontAwesome which would get you off to a quick start, or you download glyphicon, and upload the fontawesome-webfont.svg </p>
<p>For your custom icons, create SVGs, upload them to IcoMoon and add them to the FontAwesome / Glyphicon set.</p>
<p>When you are finished export the font set and load it as you would any icon font. </p>
<p>Good luck! </p>
<p><strong>UPDATE</strong></p>
<p>If your imported SVG file icons seem misaligned after importing into the iconmoom.app, first check how they actually look when used on a web page. It seems to me that the preview may not always be perfect. Alternatively, there is an edit icon in the iconmoon.app tool bar which lets you move and resize.</p> |
15,666,856 | Calling Oracle stored procedures with MyBatis | <p>I am in the process of moving our database over to Oracle from SQL Server 2008 but cannot get MyBatis to work.</p>
<p>Given the following example:</p>
<p><strong>UserMapper.xml</strong> (example)</p>
<pre><code><resultMap type="User" id="UserResult">
<id property="userId" column="userId"/>
<result property="firstName" column="firstName"/>
<result property="lastName" column="lastName"/>
</resultMap>
<select id="getUsers" statementType="CALLABLE" resultMap="UserResult">
{CALL GetUsers()}
</select>
</code></pre>
<p><strong>UserDAO.java</strong></p>
<pre><code>public interface UserDAO {
public List<User> getUsers();
}
</code></pre>
<p><strong>SQL Server procedure</strong></p>
<pre><code>CREATE PROCEDURE [dbo].[GetUsers]
AS
BEGIN
SET NOCOUNT ON;
SELECT userId, firstName, lastName
FROM Users
END
</code></pre>
<p>...works in SQL Server 2008. Can someone please explain to me how to call the Oracle procedure (that has the same name and columns as the SQL Server procedure above) from the UserMapper.xml and populate my User class with an Oracle cursor?</p>
<p>This is what I tried:</p>
<pre><code><resultMap type="User" id="UserResult">
<id property="userId" column="userId"/>
<result property="firstName" column="firstName"/>
<result property="lastName" column="lastName"/>
</resultMap>
<select id="getUsers" statementType="CALLABLE" resultMap="UserResult">
{CALL GetUsers(#{resultSet,mode=OUT,jdbcType=CURSOR,resultMap=UserResult})}
</select>
</code></pre>
<p>and I get this error:</p>
<pre><code>Caused by: org.apache.ibatis.reflection.ReflectionException:
Could not set property 'resultSet' of 'class java.lang.Class'
with value 'oracle.jdbc.driver.OracleResultSetImpl@476d05dc'
Cause: org.apache.ibatis.reflection.ReflectionException:
There is no setter for property named 'resultSet' in 'class java.lang.Class'
</code></pre> | 15,667,106 | 4 | 0 | null | 2013-03-27 18:40:39.183 UTC | 2 | 2021-12-30 18:27:22.53 UTC | 2021-12-30 18:27:22.53 UTC | null | 4,294,399 | null | 1,200,195 | null | 1 | 6 | java|oracle|mybatis|ibatis|database-cursor | 46,699 | <p>Result map looks like this: </p>
<pre><code><resultMap id="UserResult" type="User">
<id property="userId" column="userId"/>
<result property="firstName" column="firstName"/>
<result property="lastName" column="lastName"/>
</resultMap>
</code></pre>
<p>In your select statement, change the parameter type to java.util.Map.</p>
<pre><code><select id="getUsers" statementType="CALLABLE" parameterType="java.util.Map">
{call GetUsers(#{users, jdbcType=CURSOR, javaType=java.sql.ResultSet, mode=OUT, resultMap=UserResult})}
</select>
</code></pre>
<p>Your mapper interface looks like this, it looks like you are currently calling this the DAO. The way I've done it in the past is to make a mapper interface that gets injected into the DAO and the DAO is what calls the methods on the mapper. Here's an example mapper interface:</p>
<pre><code>public interface UserMapper {
public Object getUsers(Map<String, Object> params);
}
</code></pre>
<p>That mapper class would then get injected into a DAO class and make the call like this:</p>
<pre><code>public List<User> getUsers() {
Map<String, Object> params = new HashMap<String, Object>();
ResultSet rs = null;
params.put("users", rs);
userMapper.getUsers(params);
return ((ArrayList<User>)params.get("users"));
}
</code></pre> |
18,914,156 | How to call a phone number from ios app? | <p>I'm trying to call a phone number from ios app using:
It's not working, although the method gets called:</p>
<pre><code>-(IBAction)callPhone:(id)sender {
NSString *phoneCallNum = [NSString stringWithFormat:@"tel://%@",listingPhoneNumber ];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneCallNum]];
NSLog(@"phone btn touch %@", phoneCallNum);
}
</code></pre>
<p><code>NSLog</code> output: phone btn touch tel://+39 0668806972</p> | 18,914,346 | 5 | 3 | null | 2013-09-20 10:09:24.667 UTC | 8 | 2021-07-18 08:21:11.85 UTC | 2013-09-20 10:27:47.623 UTC | null | 2,547,064 | null | 2,588,945 | null | 1 | 27 | ios|objective-c | 52,543 | <p>your code is correct. did you check in real device. this function will not work in simulator.</p>
<p>try this also,</p>
<pre><code>NSString *phNo = @"+919876543210";
NSURL *phoneUrl = [NSURL URLWithString:[NSString stringWithFormat:@"telprompt:%@",phNo]];
if ([[UIApplication sharedApplication] canOpenURL:phoneUrl]) {
[[UIApplication sharedApplication] openURL:phoneUrl];
} else
{
calert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Call facility is not available!!!" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
[calert show];
}
</code></pre>
<p>** Swift 3 version**</p>
<pre><code>if let url = URL(string: "telprompt:\(phoneNumber)") {
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(call, options: []) { result in
// do something with result
}
}
}
</code></pre> |
60,855,852 | How to scroll List programmatically in SwiftUI? | <p>It looks like in current tools/system, just released Xcode 11.4 / iOS 13.4, there will be no SwiftUI-native support for "scroll-to" feature in <code>List</code>. So even if they, Apple, will provide it in next <em>major</em> released, I will need backward support for iOS 13.x.</p>
<p>So how would I do it in most simple & light way? </p>
<ul>
<li>scroll List to end</li>
<li>scroll List to top</li>
<li>and others</li>
</ul>
<p>(I don't like wrapping full <code>UITableView</code> infrastructure into <code>UIViewRepresentable/UIViewControllerRepresentable</code> as was proposed earlier on SO).</p> | 60,855,853 | 9 | 1 | null | 2020-03-25 19:14:34.467 UTC | 21 | 2022-08-27 08:41:33.14 UTC | 2020-05-14 15:31:37.783 UTC | null | 1,033,581 | null | 12,299,030 | null | 1 | 40 | ios|swift|swiftui | 31,560 | <p><strong>SWIFTUI 2.0</strong></p>
<p>Here is possible alternate solution in Xcode 12 / iOS 14 (SwiftUI 2.0) that can be used in same scenario when controls for scrolling is outside of scrolling area (because SwiftUI2 <code>ScrollViewReader</code> can be used only <em>inside</em> <code>ScrollView</code>)</p>
<p><em>Note: Row content design is out of consideration scope</em></p>
<p>Tested with Xcode 12b / iOS 14</p>
<p><a href="https://i.stack.imgur.com/NZYrv.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NZYrv.gif" alt="demo2" /></a></p>
<pre><code>class ScrollToModel: ObservableObject {
enum Action {
case end
case top
}
@Published var direction: Action? = nil
}
struct ContentView: View {
@StateObject var vm = ScrollToModel()
let items = (0..<200).map { $0 }
var body: some View {
VStack {
HStack {
Button(action: { vm.direction = .top }) { // < here
Image(systemName: "arrow.up.to.line")
.padding(.horizontal)
}
Button(action: { vm.direction = .end }) { // << here
Image(systemName: "arrow.down.to.line")
.padding(.horizontal)
}
}
Divider()
ScrollViewReader { sp in
ScrollView {
LazyVStack {
ForEach(items, id: \.self) { item in
VStack(alignment: .leading) {
Text("Item \(item)").id(item)
Divider()
}.frame(maxWidth: .infinity).padding(.horizontal)
}
}.onReceive(vm.$direction) { action in
guard !items.isEmpty else { return }
withAnimation {
switch action {
case .top:
sp.scrollTo(items.first!, anchor: .top)
case .end:
sp.scrollTo(items.last!, anchor: .bottom)
default:
return
}
}
}
}
}
}
}
}
</code></pre>
<p><strong>SWIFTUI 1.0+</strong></p>
<p>Here is simplified variant of approach that works, looks appropriate, and takes a couple of screens code.</p>
<p>Tested with Xcode 11.2+ / iOS 13.2+ (also with Xcode 12b / iOS 14)</p>
<p><strong>Demo of usage:</strong></p>
<pre><code>struct ContentView: View {
private let scrollingProxy = ListScrollingProxy() // proxy helper
var body: some View {
VStack {
HStack {
Button(action: { self.scrollingProxy.scrollTo(.top) }) { // < here
Image(systemName: "arrow.up.to.line")
.padding(.horizontal)
}
Button(action: { self.scrollingProxy.scrollTo(.end) }) { // << here
Image(systemName: "arrow.down.to.line")
.padding(.horizontal)
}
}
Divider()
List {
ForEach(0 ..< 200) { i in
Text("Item \(i)")
.background(
ListScrollingHelper(proxy: self.scrollingProxy) // injection
)
}
}
}
}
}
</code></pre>
<p><img src="https://i.stack.imgur.com/mzFYb.gif" alt="demo" /></p>
<p><strong>Solution:</strong></p>
<p>Light view representable being injected into <code>List</code> gives access to UIKit's view hierarchy. As <code>List</code> reuses rows there are no more values then fit rows into screen.</p>
<pre><code>struct ListScrollingHelper: UIViewRepresentable {
let proxy: ListScrollingProxy // reference type
func makeUIView(context: Context) -> UIView {
return UIView() // managed by SwiftUI, no overloads
}
func updateUIView(_ uiView: UIView, context: Context) {
proxy.catchScrollView(for: uiView) // here UIView is in view hierarchy
}
}
</code></pre>
<p>Simple proxy that finds enclosing <code>UIScrollView</code> (needed to do once) and then redirects needed "scroll-to" actions to that stored scrollview</p>
<pre><code>class ListScrollingProxy {
enum Action {
case end
case top
case point(point: CGPoint) // << bonus !!
}
private var scrollView: UIScrollView?
func catchScrollView(for view: UIView) {
if nil == scrollView {
scrollView = view.enclosingScrollView()
}
}
func scrollTo(_ action: Action) {
if let scroller = scrollView {
var rect = CGRect(origin: .zero, size: CGSize(width: 1, height: 1))
switch action {
case .end:
rect.origin.y = scroller.contentSize.height +
scroller.contentInset.bottom + scroller.contentInset.top - 1
case .point(let point):
rect.origin.y = point.y
default: {
// default goes to top
}()
}
scroller.scrollRectToVisible(rect, animated: true)
}
}
}
extension UIView {
func enclosingScrollView() -> UIScrollView? {
var next: UIView? = self
repeat {
next = next?.superview
if let scrollview = next as? UIScrollView {
return scrollview
}
} while next != nil
return nil
}
}
</code></pre> |
40,230,473 | How to serve up images in Angular2? | <p>I am trying to put the relative path to one of my images in my assets folder in an image src tag in my Angular2 app. I set a variable in my component to 'fullImagePath' and used that in my template. I have tried many different possible paths, but just cannot seem to get my image up. Is there some special path in Angular2 that is always relative to a static folder like in Django ?</p>
<p>Component</p>
<pre><code>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hero',
templateUrl: './hero.component.html',
styleUrls: ['./hero.component.css']
})
export class HeroComponent implements OnInit {
fullImagePath: string;
constructor() {
this.fullImagePath = '../../assets/images/therealdealportfoliohero.jpg'
}
ngOnInit() {
}
}
</code></pre>
<p>I also put the picture into the same folder as this component, so since the template, and css in the same folder is working I'm not sure why a similar relative path to the image is not working. This is the same component with the image in the same folder.</p>
<pre><code>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hero',
templateUrl: './hero.component.html',
styleUrls: ['./hero.component.css']
})
export class HeroComponent implements OnInit {
fullImagePath: string;
constructor() {
this.fullImagePath = './therealdealportfoliohero.jpg'
}
ngOnInit() {
}
}
</code></pre>
<p>html</p>
<pre><code><div class="row">
<div class="col-xs-12">
<img [src]="fullImagePath">
</div>
</div>
</code></pre>
<p>app tree * I left out the node modules folder to save space</p>
<pre><code>├── README.md
├── angular-cli.json
├── e2e
│ ├── app.e2e-spec.ts
│ ├── app.po.ts
│ └── tsconfig.json
├── karma.conf.js
├── package.json
├── protractor.conf.js
├── src
│ ├── app
│ │ ├── app.component.css
│ │ ├── app.component.html
│ │ ├── app.component.spec.ts
│ │ ├── app.component.ts
│ │ ├── app.module.ts
│ │ ├── hero
│ │ │ ├── hero.component.css
│ │ │ ├── hero.component.html
│ │ │ ├── hero.component.spec.ts
│ │ │ ├── hero.component.ts
│ │ │ └── portheropng.png
│ │ ├── index.ts
│ │ └── shared
│ │ └── index.ts
│ ├── assets
│ │ └── images
│ │ └── therealdealportfoliohero.jpg
│ ├── environments
│ │ ├── environment.dev.ts
│ │ ├── environment.prod.ts
│ │ └── environment.ts
│ ├── favicon.ico
│ ├── index.html
│ ├── main.ts
│ ├── polyfills.ts
│ ├── styles.css
│ ├── test.ts
│ ├── tsconfig.json
│ └── typings.d.ts
└── tslint.json
</code></pre> | 42,660,412 | 7 | 4 | null | 2016-10-25 02:32:28.597 UTC | 22 | 2021-10-07 00:01:18.27 UTC | 2018-03-06 23:04:19.98 UTC | user7776077 | null | null | 5,159,043 | null | 1 | 84 | html|angular|image|typescript|path | 164,722 | <p>Angular only points to <code>src/assets</code> folder, nothing else is public to access via url so you should use full path</p>
<pre><code> this.fullImagePath = '/assets/images/therealdealportfoliohero.jpg'
</code></pre>
<p>Or</p>
<pre><code> this.fullImagePath = 'assets/images/therealdealportfoliohero.jpg'
</code></pre>
<p>This will only work if the base href tag is set with <code>/</code></p>
<p>You can also add other folders for data in <code>angular/cli</code>.
All you need to modify is <code>angular-cli.json</code></p>
<pre><code>"assets": [
"assets",
"img",
"favicon.ico",
".htaccess"
]
</code></pre>
<p>Note in edit :
Dist command will try to find all attachments from assets so it is also important to keep the images and any files you want to access via url inside assets, like mock json data files should also be in assets.</p> |
27,593,029 | C compile : collect2: error: ld returned 1 exit status | <p>I tried to search for that bug online but all the posts are for C++.</p>
<p>This is the message:</p>
<pre><code>test1.o: In function `ReadDictionary':
/home/johnny/Desktop/haggai/test1.c:13: undefined reference to `CreateDictionary'
collect2: error: ld returned 1 exit status
make: *** [test1] Error 1
</code></pre>
<p>super simple code and can't understand what's the problem</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "dict.h"
#include "hash.h"
pHash ReadDictionary() {
/* This function reads a dictionary line by line from the standard input. */
pHash dictionary;
char entryLine[100] = "";
char *word, *translation;
dictionary = CreateDictionary();
while (scanf("%s", entryLine) == 1) { // Not EOF
word = strtok(entryLine, "=");
translation = strtok(NULL, "=");
AddTranslation(dictionary, word, translation);
}
return dictionary;
}
int main() {
pHash dicti;
...
</code></pre>
<p>now this is the header dict.h</p>
<pre><code>#ifndef _DICT_H_
#define _DICT_H_
#include "hash.h"
pHash CreateDictionary();
...
#endif
</code></pre>
<p>and here is the dict.c</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hash.h"
#include "dict.h"
pHash CreateDectionary()
{
pHash newDict;
newDict= HashCreate(650, HashWord, PrintEntry, CompareWords, GetEntryKey, DestroyEntry);
return newDict;
}
</code></pre>
<p>and if you wanna check hash.h</p>
<pre><code>#ifndef _HASH_H_
#define _HASH_H_
//type defintions//
typedef enum {FAIL = 0, SUCCESS} Result;
typedef enum {SAME = 0, DIFFERENT} CompResult;
typedef struct _Hash Hash, *pHash;
typedef void* pElement;
typedef void* pKey;
//function types//
typedef int (*HashFunc) (pKey key, int size);
typedef Result (*PrintFunc) (pElement element);
typedef CompResult (*CompareFunc) (pKey key1, pKey key2);
typedef pKey (*GetKeyFunc) (pElement element);
typedef void (*DestroyFunc)(pElement element);
...
//interface functions//
#endif
</code></pre>
<p>Maybe it will be easier if I give you the files here?</p>
<p>Any way, I will be happy for tips on how to understand the problem</p> | 27,593,367 | 10 | 3 | null | 2014-12-21 19:39:37.077 UTC | 11 | 2022-06-17 11:40:37.69 UTC | 2020-10-22 20:42:28.577 UTC | null | 6,388,243 | null | 3,678,933 | null | 1 | 18 | c|compilation|linker | 331,424 | <p>Your problem is the typo in the function CreateD<strong>e</strong>ctionary().You should change it to CreateD<strong>i</strong>ctionary().
collect2: error: ld returned 1 exit status is the same problem in both C and C++, usually it means that you have unresolved symbols. In your case is the typo that i mentioned before.</p> |
51,263,438 | How to solve "Unable to find git in your PATH" on Flutter? | <p>I've just tried to install Flutter on Linux and when I try to run a flutter command (flutter doctor), I'm getting</p>
<pre><code>Error: Unable to find git in your PATH.
</code></pre>
<p>How can I solve this?</p> | 51,263,641 | 12 | 4 | null | 2018-07-10 10:56:15.2 UTC | 5 | 2021-11-21 04:38:56.597 UTC | 2021-02-25 18:08:02.433 UTC | null | 4,764,353 | null | 4,764,353 | null | 1 | 29 | git|flutter|flutter-dependencies|flutter-test | 103,863 | <p>Install it using following command.</p>
<p><code>sudo apt-get install git</code></p> |
581,074 | Begin Lua-scripting | <p>I'm at a stage where I am forced to learn Lua, so do you have any suggestions on how I do this? I don't have a lot of experience with any other scripting languages than PHP.</p>
<p>So, some suggestions on "head start Lua"-pages?</p>
<p><strong>EDIT</strong></p>
<p>As an addition to the wonderful tutorial pages, could you please suggest any "programs" I could make that will help me learn Lua? Imagine I would want to learn Pointers in C++, I'd make a Linked List. I want to touch the basics in Lua but meanwhile be open to pretty advanced stuff.</p> | 581,080 | 7 | 6 | null | 2009-02-24 09:26:09.07 UTC | 15 | 2014-04-14 21:54:08.967 UTC | 2013-07-25 01:21:42.157 UTC | Filip Ekberg | 1,009,479 | Filip Ekberg | 39,106 | null | 1 | 19 | scripting|lua | 13,086 | <p>First of all work your way through the <a href="http://www.lua.org/pil/" rel="nofollow noreferrer">Programming in Lua</a>, it should take you a day or two to get the gist of Lua.</p>
<p>However I can tell you right away on your first time through ignore coroutines and metatables, they are very powerful, but take a while to grasp. First learn the syntax, scoping (same as PHP luckily for you) and the standard libraries.</p>
<p>After that go back to coroutines and metatables, read them try them and by the third time through you might get it. Unless you have a very good CS background these are complex topics</p>
<p><strong>Edit:</strong> The book is free online == website. Besides it is the best tutorial out there on Lua, everyone learns Lua with it.</p>
<p><strong>Also:</strong> If you're purpose is Lua for World of Warcraft (probably not but just in case) you can check out <a href="http://wow.gamegate2k.com/viewwow/wowuiscriptingtutorial" rel="nofollow noreferrer">this tutorial</a></p>
<p><strong>And:</strong> Here is a <a href="http://www.stackprinter.com/export?question=89523&service=stackoverflow" rel="nofollow noreferrer">tips and tricks</a> thread on StackOverflow, might help give you some ideas of what to expect from Lua</p>
<p><strong>Suggested Programs/Exercises:</strong> </p>
<p>Since you're initially looking at Lua for web development try to understand and improve the <a href="http://www.lua.org/pil/10.1.html" rel="nofollow noreferrer">Data Description</a> example in PIL. It'll give you a few good ideas and a nice feel for the power or Lua. </p>
<p>Then you might want to try out playing with the <a href="http://www.lua.org/pil/11.html" rel="nofollow noreferrer">Data Structures</a> chapter, although Lua has a single complex data-type, the Table, that chapter will show you Lua-like ways to make a table do anything you need. </p>
<p>Finally once you begin to grok metatables you should design a class system (yes with Lua you decide how your class system works). I'm sure everyone that knows Lua has made a dozen class systems, a good chapter to get you started on a class system is <a href="http://www.lua.org/pil/16.html" rel="nofollow noreferrer">Object-Oriented Programming</a></p>
<p>And if you got time and know C or something like that (C# and Java included) try extending an application with Lua, but that'll take a week or two to do</p> |
462,390 | How to stretch in width a WPF user control to its window? | <p>I have a Window with my user control and I would like to make usercontrol width equals window width. How to do that?</p>
<p>The user control is a horizontal menu and contains a grid with three columns:</p>
<pre><code><ColumnDefinition Name="LeftSideMenu" Width="433"/>
<ColumnDefinition Name="Middle" Width="*"/>
<ColumnDefinition Name="RightSideMenu" Width="90"/>
</code></pre>
<p>That is the reason I want the window width, to stretch the user control to 100% width, with the second column relative.</p>
<p>EDIT:</p>
<p>I am using a grid, there is the code for Window:</p>
<pre><code><Window x:Class="TCI.Indexer.UI.Operacao"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tci="clr-namespace:TCI.Indexer.UI.Controles"
Title=" " MinHeight="550" MinWidth="675" Loaded="Load" ResizeMode="NoResize" WindowStyle="None" WindowStartupLocation="CenterScreen" WindowState="Maximized" Focusable="True"
x:Name="windowOperacao">
<Canvas x:Name="canv">
<Grid>
<tci:Status x:Name="ucStatus"/> <!-- the control which I want to stretch in width -->
</Grid>
</Canvas>
</Window>
</code></pre> | 462,499 | 7 | 0 | null | 2009-01-20 18:05:26.15 UTC | 10 | 2017-03-22 02:20:22.517 UTC | 2009-01-20 18:30:53.26 UTC | Victor Rodrigues | 21,668 | Victor Rodrigues | 21,668 | null | 1 | 46 | c#|.net|wpf|xaml|wpf-controls | 166,089 | <p>You need to make sure your usercontrol hasn't set it's width in the usercontrol's xaml file. Just delete the Width="..." from it and you're good to go!</p>
<p><strong>EDIT:</strong> This is the code I tested it with:</p>
<p><em>SOUserAnswerTest.xaml:</em></p>
<pre><code><UserControl x:Class="WpfApplication1.SOAnswerTest"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Name="LeftSideMenu" Width="100"/>
<ColumnDefinition Name="Middle" Width="*"/>
<ColumnDefinition Name="RightSideMenu" Width="90"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0">a</TextBlock>
<TextBlock Grid.Column="1">b</TextBlock>
<TextBlock Grid.Column="2">c</TextBlock>
</Grid>
</UserControl>
</code></pre>
<p><em>Window1.xaml:</em></p>
<pre><code><Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="Window1" Height="300" Width="415">
<Grid>
<local:SOAnswerTest Grid.Column="0" Grid.Row="5" Grid.ColumnSpan="2"/>
</Grid>
</Window>
</code></pre> |
1,075,074 | Opinions on NetCDF vs HDF5 for storing scientific data? | <p>Anyone out there have enough experience w/ NetCDF and HDF5 to give some pluses / minuses about them as a way of storing scientific data? </p>
<p>I've used HDF5 and would like to read/write via Java but the interface is essentially a wrapper around the C libraries, which I have found confusing, so NetCDF seems intriguing but I know almost nothing about it.</p>
<p><strong>edit:</strong> my application is "only" for datalogging, so that I get a file that has a self-describing format. Important features for me are being able to add arbitrary metadata, having fast write access for appending to byte arrays, and having single-writer / multiple-reader concurrency (strongly preferred but not a must-have. NetCDF docs say they have SWMR but don't say whether they support any mechanism for ensuring that two writers can't open the same file at once with disastrous results). I like the hierarchical aspect of HDF5 (in particular I <strong>love</strong> the directed-acyclic-graph hierarchy, much more flexible than a "regular" filesystem-like hierarchy), am reading the NetCDF docs now... if it only allows one dataset per file then it probably won't work for me. :(</p>
<p><strong>update</strong> — looks like <a href="http://www.unidata.ucar.edu/software/netcdf-java/" rel="noreferrer">NetCDF-Java</a> reads from netCDF-4 files but only writes from netCDF-3 files which don't support hierarchical groups. darn.</p>
<p><strong>update 2009-Jul-14</strong>: I am starting to get really upset with HDF5 in Java. The library available isn't that great and it has some major stumbling blocks that have to do with Java's abstraction layers (compound data types). A great file format for C but looks like I just lose. >:(</p> | 1,131,013 | 7 | 3 | null | 2009-07-02 15:29:11.693 UTC | 21 | 2013-10-11 00:41:16.467 UTC | 2012-01-14 15:50:20.98 UTC | null | 254,477 | null | 44,330 | null | 1 | 74 | hdf5|netcdf | 25,651 | <p>I strongly suggest you HDF5 instead of NetCDF. NetCDF is flat, and it gets very dirty after a while if you are not able to classify stuff. Of course classification is also a matter of debate, but at least you have this flexibility.</p>
<p>We performed an accurate evaluation of HDF5 vs. NetCDF when I wrote Q5Cost, and the final result was for HDF5 hands down.</p> |
1,097,467 | Why should I use int instead of a byte or short in C# | <p>I have found a few threads in regards to this issue. Most people appear to favor using int in their c# code accross the board even if a byte or smallint would handle the data unless it is a mobile app. I don't understand why. Doesn't it make more sense to define your C# datatype as the same datatype that would be in your data storage solution?</p>
<p>My Premise:
If I am using a typed dataset, Linq2SQL classes, POCO, one way or another I will run into compiler datatype conversion issues if I don't keep my datatypes in sync across my tiers. I don't really like doing System.Convert all the time just because it was easier to use int accross the board in c# code. I have always used whatever the smallest datatype is needed to handle the data in the database as well as in code, to keep my interface to the database clean. So I would bet 75% of my C# code is using byte or short as opposed to int, because that is what is in the database. </p>
<p>Possibilities:
Does this mean that most people who just use int for everything in code also use the int datatype for their sql storage datatypes and could care less about the overall size of their database, or do they do system.convert in code wherever applicable?</p>
<p>Why I care: I have worked on my own forever and I just want to be familiar with best practices and standard coding conventions.</p> | 1,148,505 | 7 | 2 | null | 2009-07-08 11:28:48.17 UTC | 32 | 2021-08-22 09:28:10.037 UTC | 2009-07-18 20:14:23.677 UTC | null | 133,544 | null | 133,544 | null | 1 | 78 | c#|asp.net|sql-server|types | 27,384 | <p>Performance-wise, an int is faster in almost all cases. The CPU is designed to work efficiently with 32-bit values.</p>
<p>Shorter values are complicated to deal with. To read a single byte, say, the CPU has to read the 32-bit block that contains it, and then mask out the upper 24 bits.</p>
<p>To write a byte, it has to read the destination 32-bit block, overwrite the lower 8 bits with the desired byte value, and write the entire 32-bit block back again.</p>
<p>Space-wise, of course, you save a few bytes by using smaller datatypes. So if you're building a table with a few million rows, then shorter datatypes may be worth considering. (And the same might be good reason why you should use smaller datatypes in your database)</p>
<p>And correctness-wise, an int doesn't overflow easily. What if you <em>think</em> your value is going to fit within a byte, and then at some point in the future some harmless-looking change to the code means larger values get stored into it?</p>
<p>Those are some of the reasons why int should be your default datatype for all integral data. Only use byte if you actually want to store machine bytes. Only use shorts if you're dealing with a file format or protocol or similar that actually specifies 16-bit integer values. If you're just dealing with integers in general, make them ints.</p> |
124,764 | Are Mutexes needed in javascript? | <p>I have seen this link: <a href="http://www.developer.com/lang/jscript/article.php/3592016" rel="noreferrer">Implementing Mutual Exclusion in JavaScript</a>.
On the other hand, I have read that there are no threads in javascript, but what exactly does that mean? </p>
<p>When events occur, where in the code can they interrupt?</p>
<p>And if there are no threads in JS, do I need to use mutexes in JS or not?</p>
<p>Specifically, I am wondering about the effects of using functions called by <code>setTimeout()</code> and <code>XmlHttpRequest</code>'s <code>onreadystatechange</code> on globally accessible variables. </p> | 124,832 | 7 | 0 | null | 2008-09-24 00:40:43.03 UTC | 24 | 2018-02-08 17:35:31.217 UTC | null | null | null | Ovesh | 3,751 | null | 1 | 117 | javascript|multithreading|mutex | 72,530 | <p>Javascript is defined as a <i>reentrant</i> language which means there is no threading exposed to the user, there may be threads in the implementation. Functions like <code>setTimeout()</code> and asynchronous callbacks need to wait for the script engine to sleep before they're able to run.</p>
<p>That means that everything that happens in an event must be finished before the next event will be processed.</p>
<p>That being said, you may need a mutex if your code does something where it expects a value not to change between when the asynchronous event was fired and when the callback was called.</p>
<p>For example if you have a data structure where you click one button and it sends an XmlHttpRequest which calls a callback the changes the data structure in a destructive way, and you have another button that changes the same data structure directly, between when the event was fired and when the call back was executed the user could have clicked and updated the data structure before the callback which could then lose the value.</p>
<p>While you could create a race condition like that it's very easy to prevent that in your code since each function will be atomic. It would be a lot of work and take some odd coding patterns to create the race condition in fact.</p> |
1,090,815 | How to clone a Date object? | <p>Assigning a <code>Date</code> variable to another one will copy the reference to the same instance. This means that changing one will change the other.</p>
<p>How can I actually clone or copy a <code>Date</code> instance?</p> | 1,090,817 | 7 | 0 | null | 2009-07-07 07:22:42.46 UTC | 66 | 2022-05-24 13:15:36.743 UTC | 2019-07-11 22:25:28.63 UTC | null | 3,345,644 | null | 131,055 | null | 1 | 659 | javascript | 259,983 | <p>Use the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date" rel="noreferrer">Date</a> object's <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/getTime" rel="noreferrer"><code>getTime()</code></a> method, which returns the number of milliseconds since 1 January 1970 00:00:00 UTC (<a href="http://en.wikipedia.org/wiki/Unix_time" rel="noreferrer">epoch time</a>):</p>
<pre><code>var date = new Date();
var copiedDate = new Date(date.getTime());
</code></pre>
<p>In Safari 4, you can also write:</p>
<pre><code>var date = new Date();
var copiedDate = new Date(date);
</code></pre>
<p>...but I'm not sure whether this works in other browsers. (It seems to work in IE8).</p> |
1,303,021 | Shortest hash in python to name cache files | <p>What is the shortest hash (in filename-usable form, like a hexdigest) available in python? My application wants to save <em>cache files</em> for some objects. The objects must have unique repr() so they are used to 'seed' the filename. I want to produce a possibly unique filename for each object (not that many). They should not collide, but if they do my app will simply lack cache for that object (and will have to reindex that object's data, a minor cost for the application).</p>
<p>So, if there is one collision we lose one cache file, but it is the collected savings of caching all objects makes the application startup much faster, so it does not matter much.</p>
<p>Right now I'm actually using abs(hash(repr(obj))); that's right, the string hash! Haven't found any collisions yet, but I would like to have a better hash function. hashlib.md5 is available in the python library, but the hexdigest is really long if put in a filename. Alternatives, with reasonable collision resistance?</p>
<p>Edit:
Use case is like this:
The data loader gets a new instance of a data-carrying object. Unique types have unique repr. so if a cache file for <code>hash(repr(obj))</code> exists, I unpickle that cache file and replace obj with the unpickled object. If there was a collision and the cache was a false match I notice. So if we don't have cache or have a false match, I instead init obj (reloading its data).</p>
<p><strong>Conclusions (?)</strong></p>
<p>The <code>str</code> hash in python may be good enough, I was only worried about its collision resistance. But if I can hash <code>2**16</code> objects with it, it's going to be more than good enough.</p>
<p>I found out how to take a hex hash (from any hash source) and store it compactly with base64:</p>
<pre><code># 'h' is a string of hex digits
bytes = "".join(chr(int(h[i:i+2], 16)) for i in xrange(0, len(h), 2))
hashstr = base64.urlsafe_b64encode(bytes).rstrip("=")
</code></pre> | 1,303,619 | 8 | 4 | null | 2009-08-19 22:43:51.517 UTC | 12 | 2009-08-20 11:16:16.667 UTC | 2009-08-20 11:16:16.667 UTC | null | 137,317 | null | 137,317 | null | 1 | 19 | python|hash | 13,229 | <p>The <a href="http://en.wikipedia.org/wiki/Birthday_paradox#Cast_as_a_collision_problem" rel="noreferrer">birthday paradox</a> applies: given a good hash function, the expected number of hashes before a collision occurs is about sqrt(N), where N is the number of different values that the hash function can take. (The wikipedia entry I've pointed to gives the exact formula). So, for example, if you want to use no more than 32 bits, your collision worries are serious for around 64K objects (i.e., <code>2**16</code> objects -- the square root of the <code>2**32</code> different values your hash function can take). How many objects do you expect to have, as an order of magnitude?</p>
<p>Since you mention that a collision is a minor annoyance, I recommend you aim for a hash length that's roughly the square of the number of objects you'll have, or a bit less but not MUCH less than that.</p>
<p>You want to make a filename - is that on a case-sensitive filesystem, as typical on Unix, or do you have to cater for case-insensitive systems too? This matters because you aim for short filenames, but the number of bits per character you can use to represent your hash as a filename changes dramatically on case-sensive vs insensitive systems.</p>
<p>On a case-sensitive system, you can use the standard library's <code>base64</code> module (I recommend the "urlsafe" version of the encoding, i.e. <a href="http://docs.python.org/library/base64.html#base64.urlsafe_b64encode" rel="noreferrer">this</a> function, as avoiding '/' characters that could be present in plain base64 is important in Unix filenames). This gives you 6 usable bits per character, much better than the 4 bits/char in hex.</p>
<p>Even on a case-insensitive system, you can still do better than hex -- use base64.b32encode and get 5 bits per character.</p>
<p>These functions take and return strings; use the <code>struct</code> module to turn numbers into strings if your chosen hash function generates numbers.</p>
<p>If you do have a few tens of thousands of objects I think you'll be fine with builtin hash (32 bits, so 6-7 characters depending on your chosen encoding). For a million objects you'd want 40 bits or so (7 or 8 characters) -- you can fold (xor, don't truncate;-) a sha256 down to a long with a reasonable number of bits, say 128 or so, and use the <code>%</code> operator to cut it further to your desired length before encoding.</p> |
11,060 | How should I unit test a code-generator? | <p>This is a difficult and open-ended question I know, but I thought I'd throw it to the floor and see if anyone had any interesting suggestions.</p>
<p>I have developed a code-generator that takes our python interface to our C++ code (generated via SWIG) and generates code needed to expose this as WebServices. When I developed this code I did it using TDD, but I've found my tests to be brittle as hell. Because each test essentially wanted to verify that for a given bit of input code (which happens to be a C++ header) I'd get a given bit of outputted code I wrote a small engine that reads test definitions from XML input files and generates test cases from these expectations.</p>
<p>The problem is I dread going in to modify the code at all. That and the fact that the unit tests themselves are a: complex, and b: brittle.</p>
<p>So I'm trying to think of alternative approaches to this problem, and it strikes me I'm perhaps tackling it the wrong way. Maybe I need to focus more on the outcome, IE: does the code I generate actually run and do what I want it to, rather than, does the code look the way I want it to.</p>
<p>Has anyone got any experiences of something similar to this they would care to share?</p> | 11,074 | 8 | 3 | null | 2008-08-14 13:59:21.533 UTC | 5 | 2015-07-20 04:10:25.057 UTC | 2008-08-23 19:52:34.193 UTC | Chris Fournier | 2,134 | JKP | 912 | null | 1 | 29 | c++|python|unit-testing|code-generation|swig | 7,656 | <p>I started writing up a summary of my experience with my own code generator, then went back and re-read your question and found you had already touched upon the same issues yourself, focus on the execution results instead of the code layout/look.</p>
<p>Problem is, this is hard to test, the generated code might not be suited to actually run in the environment of the unit test system, and how do you encode the expected results?</p>
<p>I've found that you need to break down the code generator into smaller pieces and unit test those. Unit testing a full code generator is more like integration testing than unit testing if you ask me.</p> |
895,786 | how to get the cookies from a php curl into a variable | <p>So some guy at some other company thought it would be awesome if instead of using soap or xml-rpc or rest or any other reasonable communication protocol he just embedded all of his response as cookies in the header.</p>
<p>I need to pull these cookies out as hopefully an array from this curl response. If I have to waste a bunch of my life writing a parser for this I will be very unhappy.</p>
<p>Does anyone know how this can simply be done, preferably without writing anything to a file?</p>
<p>I will be very grateful if anyone can help me out with this.</p> | 895,858 | 8 | 0 | null | 2009-05-21 23:31:11.773 UTC | 40 | 2019-04-22 08:33:11.683 UTC | null | null | null | null | 20,895 | null | 1 | 142 | php|cookies|curl | 207,671 | <pre><code>$ch = curl_init('http://www.google.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// get headers too with this line
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
// get cookie
// multi-cookie variant contributed by @Combuster in comments
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);
$cookies = array();
foreach($matches[1] as $item) {
parse_str($item, $cookie);
$cookies = array_merge($cookies, $cookie);
}
var_dump($cookies);
</code></pre> |
626,671 | Java: How to remove elements from a list while iterating over/adding to it | <p>This question is a more special case of the problem described (and solved) in <a href="https://stackoverflow.com/questions/223918/java-efficient-equivalent-to-removing-while-iterating-a-collection">this question</a>.</p>
<p>I have two methods, stopAndRemove(ServerObject server) and a close() method. The later should close all servers and remove them from the server list. The list is defined as</p>
<pre><code>List<ServerObject> server.
</code></pre>
<p>I do not want to have almost the same code from stopAndRemove in closeCurrentlyOpen, so I want to do something like:</p>
<pre><code>public void closeCurrentlyOpen() {
for(ServerObject server : this.servers) {
stopAndRemove(server)
}
}
</code></pre>
<p>This won't work, as this will cause a ConcurrentModificationException. I tried to make a copy of the list </p>
<pre><code>List<ServerObject> copyList = new ArrayList<ServerObject>(this.servers);
</code></pre>
<p>and use that as the list for the foreach-loop. But then it might be possible that an other thread appends a Server to the servers list while I am iterating over copyList but closeCurrentlyOpen is supposed to result in an emtpy list.
As the addServerToList method is synchronized to the servers-list, doing this</p>
<pre><code>public void closeCurrentlyOpen() {
synchronized(this.servers) {
for(ServerObject server : this.servers) {
stopAndRemove(server)
}
}
}
</code></pre>
<p>will solve the problem with modifications. But then I can not synchronize the code in the stopAndRemove method which is necessary if it is directly called.</p>
<p>I seems to me that the design of this three methods probably needs a workover.
Ideas anybody?</p> | 626,689 | 9 | 0 | null | 2009-03-09 15:22:57.357 UTC | 2 | 2013-05-29 18:21:57.737 UTC | 2017-05-23 12:30:28.077 UTC | null | -1 | Arvodan | 5,751 | null | 1 | 17 | java|algorithm|collections|list | 61,288 | <p>Split off a method stop() from stopAndRemove(). Then write the loop with an explicit iterator, do the stop and then iterator.remove().</p>
<p>"and" in a method name is a code smell.</p> |
483,977 | Find unadded files in Team Foundation Server | <p>We're using team foundation server for our source control. I frequently put files into my project (under source control) and forget to "add" them as far as TFS is concerned. There are also cases where TFS doesn't pick up new files (copy and paste a file in your project).</p>
<p>Is there a way I can list all of the files that have not been marked as "add" so that I can verify that all of the intended check-ins take place?</p>
<p>This is driving me crazy! We don't have continuous integration set up yet for this project, and I keep missing files. I don't find out until someone asks me where the file in.</p>
<p>In Subversion, this was dead simple.</p>
<p>I know one solution is to checkout a second copy, but that's not really an optimal workaround.</p> | 487,077 | 9 | 1 | null | 2009-01-27 16:04:44.103 UTC | 6 | 2021-01-04 12:05:15.787 UTC | null | null | null | SuperJason | 23,837 | null | 1 | 40 | version-control|tfs | 22,713 | <p>You might want to make sure you have the latest version of the TFS client installed (<a href="http://www.microsoft.com/downloads/details.aspx?familyid=9e40a5b6-da41-43a2-a06d-3cee196bfe3d" rel="noreferrer">VS 2008 SP1</a>) as that makes it much easier to work with files. Also, take a look at the <a href="http://msdn.microsoft.com/en-us/tfs2008/bb980963.aspx" rel="noreferrer">TFS Power Tools</a> - especially the tfpt online command.</p>
<p>The tfpt command line has a bunch of handy TFS utilities. Once you install the TFS power tools, type "tfpt help" at a Visual Studio 2008 Command Prompt to get a list. If you do "tfpt online /r" in the root of your solution it will detect the files that are writeable in your local file system and pend adds or edits for them. You might want to limit the command so that it only looks for source files - "tfpt online /r *.cs" for example.</p> |
1,266,792 | How to change the default Netbeans 7 project directory? | <p>This is only a minor annoyance but if I can figure this out I'll be very happy.</p>
<p>Is it possible to change the default project directory in Netbeans 7? I don't know if it's relevant but I have the PHP Netbeans distro.</p>
<p>Thanks!</p> | 8,037,739 | 10 | 0 | null | 2009-08-12 15:07:13.243 UTC | 5 | 2016-02-18 09:03:15.953 UTC | 2015-04-27 15:07:15.12 UTC | null | 143,145 | null | 143,145 | null | 1 | 27 | php|netbeans | 64,103 | <p>In new netbeans 7 search file: <strong>D:\Users\YourWindowsUserName\.netbeans\7.0\config\Preferences\org\netbeans\modules\projectui.properties</strong></p>
<p>Delete: *<em>RecentProjectsDisplayNames.</em>*8, *<em>RecentProjectsIcons.</em>*8, *<em>recentProjectsURLs.</em>*8 for cleaning recent projects.</p>
<p>Change <strong>projectsFolder</strong> for default projects folder when creating new one</p>
<p>To find out the location of the projectui.properties file for the latest versions of NetBeans for various operating systems:</p>
<p><a href="http://wiki.netbeans.org/FaqWhatIsUserdir">http://wiki.netbeans.org/FaqWhatIsUserdir</a></p> |
544,463 | How would you keep secret data secret in an iPhone application? | <p>Let's say I need to access a web service from an iPhone app. This web service requires clients to digitally sign HTTP requests in order to prove that the app "knows" a shared secret; a client key. The request signature is stored in a HTTP header and the request is simply sent over HTTP (not HTTPS). </p>
<p>This key must stay secret at all times yet needs to be used by the iPhone app.</p>
<p>So, how would you securely store this key given that you've always been told to never store anything sensitive on the client side?</p>
<p>The average user (99% of users) will happily just use the application. There will be somebody (an enemy?) who wants that secret client key so as to do the service or client key owner harm by way of impersonation. Such a person might jailbreak their phone, get access to the binary, run 'strings' or a hex editor and poke around. Thus, just storing the key in the source code is a terrible idea. </p>
<p>Another idea is storing the key in code not a string literal but in a NSMutableArray that's created from byte literals. </p>
<p>One can use the Keychain but since an iPhone app never has to supply a password to store things in the Keychain, I'm wary that someone with access to the app's sandbox can and will be able to simply look at or trivially decode items therein. </p>
<p>EDIT - so I read this about the Keychain: "In iPhone OS, an application always has access to its own keychain items and does not have access to any other application’s items. The system generates its own password for the keychain, and stores the key on the device in such a way that it is not accessible to any application."</p>
<p>So perhaps this is the best place to store the key.... If so, how do I ship with the key pre-entered into the app's keychain? Is that possible? Else, how could you add the key on first launch without the key being in the source code? Hmm..</p>
<p>EDIT - Filed bug report # 6584858 at <a href="http://bugreport.apple.com" rel="noreferrer">http://bugreport.apple.com</a></p>
<p>Thanks.</p> | 1,683,274 | 10 | 2 | null | 2009-02-13 02:02:20.597 UTC | 32 | 2014-12-23 20:33:51.493 UTC | 2009-02-13 19:13:36.543 UTC | Brian Hammond | 28,287 | 2pence | 28,287 | null | 1 | 38 | iphone|security|cryptography | 7,726 | <p>The simple answer is that as things stand today it's just not possible to keep secrets on the iPhone. A jailbroken iPhone is just a general-purpose computer that fits in your hand. There's no trusted platform hardware that you can access. The user can spoof anything you can imagine using to uniquely identify a given device. The user can inject code into your process to do things like inspect the keychain. (Search for MobileSubstrate to see what I mean.) Sorry, you're screwed.</p>
<p>One ray of light in this situation is in app purchase receipts. If you sell an item in your app using in app purchase you get a receipt that's crypto signed and can be verified with Apple on demand. Even though you can't keep the receipt secret it <em>can</em> be traced (by Apple, not you) to a specific purchase, which might discourage pirates from sharing them. You can also throttle access to your server on a per-receipt basis to prevent your server resources from being drained by pirates.</p> |
684,648 | A clear, layman's explanation of the difference between | and || in c#? | <p>Ok, so I've read about this a number of times, but I'm yet to hear a clear, easy to understand (and memorable) way to learn the difference between:</p>
<pre><code>if (x | y)
</code></pre>
<p>and </p>
<pre><code>if (x || y)
</code></pre>
<p>..within the context of C#. Can anyone please help me learn this basic truth, and how C# specifically, treats them differently (because they seem to do the same thing). If the difference a given piece of code has between them is irrelevant, which should I default to as a best-practise?</p> | 684,659 | 11 | 0 | null | 2009-03-26 05:43:56.09 UTC | 15 | 2018-08-12 03:35:50.867 UTC | 2014-01-25 17:01:41.913 UTC | John Feminella | 578,411 | Ash | 11,194 | null | 1 | 44 | c#|bitwise-operators|logical-operators | 8,724 | <p><code>||</code> is the <em>logical-or</em> operator. See <strong><a href="http://msdn.microsoft.com/en-us/library/aa691310(VS.71).aspx" rel="noreferrer">here</a></strong>. It evaluates to <code>true</code> if at least one of the operands is true. You can only use it with boolean operands; it is an error to use it with integer operands.</p>
<pre><code>// Example
var one = true || bar(); // result is true; bar() is never called
var two = true | bar(); // result is true; bar() is always called
</code></pre>
<p><code>|</code> is the <em>or</em> operator. See <strong><a href="http://msdn.microsoft.com/en-us/library/kxszd0kx(VS.71).aspx" rel="noreferrer">here</a></strong>. If applied to boolean types, it evaluates to <code>true</code> if at least one of the operands is true. If applied to integer types, it evaluates to another number. This number has each of its bits set to 1 if at least one of the operands has a corresponding bit set.</p>
<pre><code>// Example
var a = 0x10;
var b = 0x01;
var c = a | b; // 0x11 == 17
var d = a || b; // Compile error; can't apply || to integers
var e = 0x11 == c; // True
</code></pre>
<p>For boolean operands, <code>a || b</code> is <em>identical</em> to <code>a | b</code>, with the single exception that <code>b</code> is not evaluated if <code>a</code> is true. For this reason, <code>||</code> is said to be "short-circuiting".</p>
<blockquote>
<p>If the difference a given piece of code has between them is irrelevant, which should I default to as a best-practise?</p>
</blockquote>
<p>As noted, the difference isn't irrelevant, so this question is partially moot. As for a "best practice", there isn't one: you simply use whichever operator is the correct one to use. In general, people favor <code>||</code> over <code>|</code> for boolean operands since you can be sure it won't produce unnecessary side effects.</p> |
836,167 | Does a foreign key automatically create an index? | <p>I've been told that if I foreign key two tables, that SQL Server will create something akin to an index in the child table. I have a hard time believing this to be true, but can't find much out there related specifically to this.</p>
<p>My real reason for asking this is because we're experiencing some very slow response time in a delete statement against a table that has probably 15 related tables. I've asked our database guy and he says that if there is a foreign key on the fields, then it acts like an index. What is your experience with this? Should I add indexes on all foreign key fields or are they just unnecessary overhead?</p> | 836,176 | 11 | 10 | null | 2009-05-07 18:06:18.063 UTC | 75 | 2022-02-18 10:16:30.573 UTC | 2019-03-15 18:19:37.957 UTC | null | 792,066 | null | 1,380 | null | 1 | 438 | sql-server | 152,328 | <p>A foreign key is a constraint, a relationship between two tables - that has nothing to do with an index per se.</p>
<p>But it is a known fact that it makes a lot of sense to index all the columns that are part of any foreign key relationship, because through a FK-relationship, you'll often need to lookup a relating table and extract certain rows based on a single value or a range of values.</p>
<p>So it makes good sense to index any columns involved in a FK, but a FK per se is not an index.</p>
<p>Check out Kimberly Tripp's excellent article <a href="https://www.sqlskills.com/blogs/kimberly/when-did-sql-server-stop-putting-indexes-on-foreign-key-columns/" rel="noreferrer">"When did SQL Server stop putting indexes on Foreign Key columns?"</a>.</p> |
1,146,416 | How to parse an ISO-8601 duration in Objective C? | <p>I'm looking for an easy way to parse a string that contains an ISO-8601 <strong>duration</strong> in Objective C. The result should be something usable like a <code>NSTimeInterval</code>.</p>
<p>An example of an ISO-8601 duration: <code>P1DT13H24M17S</code>, which means 1 day, 13 hours, 24 minutes and 17 seconds.</p> | 1,146,552 | 12 | 0 | null | 2009-07-18 01:32:06.58 UTC | 9 | 2020-04-16 05:47:04.17 UTC | 2009-07-18 06:49:09.6 UTC | null | 459 | null | 44,014 | null | 1 | 14 | iphone|objective-c|datetime|iso8601|nstimeinterval | 8,068 | <p>If you know exactly which fields you'll be getting, you can use one invocation of <code>sscanf()</code>:</p>
<pre><code>const char *stringToParse = ...;
int days, hours, minutes, seconds;
NSTimeInterval interval;
if(sscanf(stringToParse, "P%dDT%dH%dM%sS", &days, &hours, &minutes, &seconds) == 4)
interval = ((days * 24 + hours) * 60 + minutes) * 60 + seconds;
else
; // handle error, parsing failed
</code></pre>
<p>If any of the fields might be omitted, you'll need to be a little smarter in your parsing, e.g.:</p>
<pre><code>const char *stringToParse = ...;
int days = 0, hours = 0, minutes = 0, seconds = 0;
const char *ptr = stringToParse;
while(*ptr)
{
if(*ptr == 'P' || *ptr == 'T')
{
ptr++;
continue;
}
int value, charsRead;
char type;
if(sscanf(ptr, "%d%c%n", &value, &type, &charsRead) != 2)
; // handle parse error
if(type == 'D')
days = value;
else if(type == 'H')
hours = value;
else if(type == 'M')
minutes = value;
else if(type == 'S')
seconds = value;
else
; // handle invalid type
ptr += charsRead;
}
NSTimeInterval interval = ((days * 24 + hours) * 60 + minutes) * 60 + seconds;
</code></pre> |
530,519 | std::mktime and timezone info | <p>I'm trying to convert a time info I reveive as a UTC string to a timestamp using <code>std::mktime</code> in C++. My problem is that in <code><ctime></code> / <code><time.h></code> there is no function to convert to UTC; mktime will only return the timestamp as local time.</p>
<p>So I need to figure out the timezone offset and take it into account, but I can't find a platform-independent way that doesn't involve porting the whole code to <code>boost::date_time</code>. Is there some easy solution which I have overlooked?</p> | 530,557 | 12 | 1 | null | 2009-02-09 23:22:13.01 UTC | 5 | 2021-03-12 17:21:02.9 UTC | 2011-09-29 09:24:52.673 UTC | null | 560,648 | VolkA | 25,472 | null | 1 | 41 | c++ | 65,034 | <p>mktime assumes that the date value is in the local time zone. Thus you can change the timezone environment variable beforehand (setenv) and get the UTC timezone.</p>
<p><a href="https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/tzset?view=msvc-160" rel="nofollow noreferrer">Windows tzset</a></p>
<p>Can also try looking at various home-made <a href="http://www.koders.com/c/fidB1A0A680FBCF84DDC534E66371053D726A5546EB.aspx?s=md5" rel="nofollow noreferrer">utc-mktimes, mktime-utcs, etc.</a></p> |
292,095 | Polling the keyboard (detect a keypress) in python | <p>How can I poll the keyboard from a console python app? Specifically, I would like to do something akin to this in the midst of a lot of other I/O activities (socket selects, serial port access, etc.):</p>
<pre><code>while True:
# doing amazing pythonic embedded stuff
# ...
# periodically do a non-blocking check to see if
# we are being told to do something else
x = keyboard.read(1000, timeout = 0)
if len(x):
# ok, some key got pressed
# do something
</code></pre>
<p>What is the correct pythonic way to do this on Windows? Also, portability to Linux wouldn't be bad, though it's not required.</p> | 292,770 | 12 | 2 | null | 2008-11-15 03:29:09.777 UTC | 23 | 2022-02-07 12:03:53.913 UTC | 2022-02-07 12:01:43.503 UTC | null | 4,298,200 | null | 33,263 | null | 1 | 75 | python|console|keyboard|blocking|nonblocking | 150,369 | <p>The standard approach is to use the <a href="https://docs.python.org/2/library/select.html" rel="noreferrer">select</a> module.</p>
<p>However, this doesn't work on Windows. For that, you can use the <a href="https://docs.python.org/2/library/msvcrt.html#console-i-o" rel="noreferrer">msvcrt</a> module's keyboard polling.</p>
<p>Often, this is done with multiple threads -- one per device being "watched" plus the background processes that might need to be interrupted by the device.</p> |
713,247 | What is the best way to programmatically detect porn images? | <p>Akismet does an amazing job at detecting spam comments. But comments are not the only form of spam these days. What if I wanted something like akismet to automatically detect porn images on a social networking site which allows users to upload their pics, avatars, etc?</p>
<p>There are already a few image based search engines as well as face recognition stuff available so I am assuming it wouldn't be rocket science and it could be done. However, I have no clue regarding how that stuff works and how I should go about it if I want to develop it from scratch.</p>
<p>How should I get started?</p>
<p>Is there any open source project for this going on?</p> | 713,414 | 25 | 9 | null | 2009-04-03 09:39:51.557 UTC | 117 | 2017-08-02 16:15:53.11 UTC | 2017-08-02 16:15:53.11 UTC | Rich B | 189,134 | Raj | 83,027 | null | 1 | 120 | spam-prevention | 112,406 | <p>This was written in 2000, not sure if the state of the art in porn detection has advanced at all, but I doubt it.</p>
<p><a href="http://www.dansdata.com/pornsweeper.htm" rel="noreferrer">http://www.dansdata.com/pornsweeper.htm</a></p>
<blockquote>
<p>PORNsweeper seems to have some ability to distinguish pictures of people from pictures of things that aren't people, as long as the pictures are in colour. It is less successful at distinguishing dirty pictures of people from clean ones.</p>
<p>With the default, medium sensitivity, if Human Resources sends around a picture of the new chap in Accounts, you've got about a 50% chance of getting it. If your sister sends you a picture of her six-month-old, it's similarly likely to be detained.</p>
<p>It's only fair to point out amusing errors, like calling the Mona Lisa porn, if they're representative of the behaviour of the software. If the makers admit that their algorithmic image recogniser will drop the ball 15% of the time, then making fun of it when it does exactly that is silly.</p>
<p>But PORNsweeper only seems to live up to its stated specifications in one department - detection of actual porn. <strong>It's half-way decent at detecting porn, but it's bad at detecting clean pictures. And I wouldn't be surprised if no major leaps were made in this area in the near future.</strong></p>
</blockquote> |
1,000,900 | How to keep a Python script output window open? | <p>I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?</p> | 1,000,968 | 26 | 5 | null | 2009-06-16 11:31:16.737 UTC | 44 | 2022-08-14 12:16:58.627 UTC | null | null | null | null | 121,858 | null | 1 | 221 | python|windows | 401,577 | <p>You have a few options:</p>
<ol>
<li><p>Run the program from an already-open terminal. Open a command prompt and type:</p>
<pre><code>python myscript.py
</code></pre>
<p>For that to work you need the python executable in your path. Just check on <a href="https://superuser.com/questions/284342/what-are-path-and-other-environment-variables-and-how-can-i-set-or-use-them">how to edit environment variables</a> on Windows, and add <code>C:\PYTHON26</code> (or whatever directory you installed python to).</p>
<p>When the program ends, it'll drop you back to the <strong>cmd</strong> prompt instead of closing the window.</p></li>
<li><p>Add code to wait at the end of your script. For Python2, adding ...</p>
<pre><code>raw_input()
</code></pre>
<p>... at the end of the script makes it wait for the <kbd>Enter</kbd> key. That method is annoying because you have to modify the script, and have to remember removing it when you're done. Specially annoying when testing other people's scripts. For Python3, use <code>input()</code>.</p></li>
<li><p>Use an editor that pauses for you. Some editors prepared for python will automatically pause for you after execution. Other editors allow you to configure the command line it uses to run your program. I find it particularly useful to configure it as "<code>python -i myscript.py</code>" when running. That drops you to a python shell after the end of the program, with the program environment loaded, so you may further play with the variables and call functions and methods.</p></li>
</ol> |
351,409 | How to append something to an array? | <p>How do I append an object (such as a string or number) to an array in JavaScript? </p> | 351,421 | 30 | 0 | 2008-12-09 00:23:17.973 UTC | 2008-12-09 00:20:05.937 UTC | 432 | 2022-03-29 21:09:18.293 UTC | 2017-09-10 19:21:27.333 UTC | interstar | 7,848,065 | interstar | 8,482 | null | 1 | 2,891 | javascript|arrays|append | 4,657,190 | <p>Use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push" rel="noreferrer"><code>Array.prototype.push</code></a> method to append values to the end of an array:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// initialize array
var arr = [
"Hi",
"Hello",
"Bonjour"
];
// append new value to the array
arr.push("Hola");
console.log(arr);</code></pre>
</div>
</div>
</p>
<hr />
<p>You can use the <code>push()</code> function to append more than one value to an array in a single call:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// initialize array
var arr = ["Hi", "Hello", "Bonjour", "Hola"];
// append multiple values to the array
arr.push("Salut", "Hey");
// display all values
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}</code></pre>
</div>
</div>
</p>
<hr />
<p><strong>Update</strong></p>
<p>If you want to add the items of one array to another array, you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat" rel="noreferrer"><code>firstArray.concat(secondArray)</code></a>:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = [
"apple",
"banana",
"cherry"
];
// Do not forget to assign the result as, unlike push, concat does not change the existing array
arr = arr.concat([
"dragonfruit",
"elderberry",
"fig"
]);
console.log(arr);</code></pre>
</div>
</div>
</p>
<p><strong>Update</strong></p>
<p>Just an addition to this answer if you want to prepend any value to the start of an array (i.e. first index) then you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift" rel="noreferrer"><code>Array.prototype.unshift</code></a> for this purpose.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = [1, 2, 3];
arr.unshift(0);
console.log(arr);</code></pre>
</div>
</div>
</p>
<p>It also supports appending multiple values at once just like <code>push</code>.</p>
<hr />
<p><strong>Update</strong></p>
<p>Another way with <em><strong>ES6</strong></em> syntax is to return a new array with the <em><strong><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax" rel="noreferrer">spread syntax</a></strong></em>. This leaves the original array unchanged, but returns a new array with new items appended, compliant with the spirit of functional programming.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const arr = [
"Hi",
"Hello",
"Bonjour",
];
const newArr = [
...arr,
"Salut",
];
console.log(newArr);</code></pre>
</div>
</div>
</p> |
6,631,257 | How to log properly http requests with Spring MVC | <p>Hello I've been trying to figure out generic way to log http requests in my application, so far no luck, here is how I handle the logging right now i.e:</p>
<pre><code>@RequestMapping(value="register", method = RequestMethod.POST)
@ResponseBody
public String register(@RequestParam(value="param1",required=false) String param1, @RequestParam("param2") String param2, @RequestParam("param3") String param3, HttpServletRequest request){
long start = System.currentTimeMillis();
logger.info("!--REQUEST START--!");
logger.info("Request URL: " + request.getRequestURL().toString());
List<String> requestParameterNames = Collections.list((Enumeration<String>)request.getParameterNames());
logger.info("Parameter number: " + requestParameterNames.size());
for (String parameterName : requestParameterNames){
logger.info("Parameter name: " + parameterName + " - Parameter value: " + request.getParameter(parameterName));
}
//Some processing logic, call to the various services/methods with different parameters, response is always String(Json)
String response = service.callSomeServiceMethods(param1,param2,param3);
logger.info("Response is: " + response);
long end = System.currentTimeMillis();
logger.info("Requested completed in: " + (end-start) + "ms");
logger.info("!--REQUEST END--!");
return response;
}
</code></pre>
<p>So what I do right now for different controllers/methods is copy everything from beginning of the inside of the method until the processing logic which differs from method to method and then copy everything from below of that as showed in above template.</p>
<p>It is kind of messy, and there is a lot of code repetition(which I don't like). But I need to log everything.</p>
<p>Does anyone have more experience with this kinds of logging, can anyone shed some light on this?</p> | 6,631,285 | 6 | 1 | null | 2011-07-08 22:33:40.553 UTC | 20 | 2017-08-22 19:03:21.783 UTC | 2015-01-12 15:48:09.027 UTC | null | 3,270,595 | null | 282,383 | null | 1 | 41 | java|spring|logging|spring-mvc | 51,460 | <p>Use an <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-handlermapping-interceptor" rel="noreferrer">interceptor</a>:</p>
<ul>
<li>extend <code>HandlerInterceptorAdapter</code> and override <code>preHandle</code></li>
<li>define it with <code><mvc:interceptors></code> in <code>dispatcher-servlet.xml</code></li>
</ul>
<p>It will run for every request.</p> |
6,852,213 | Can Jackson be configured to trim leading/trailing whitespace from all string properties? | <p>Example JSON (note that the string has trailing spaces): </p>
<pre><code>{ "aNumber": 0, "aString": "string " }
</code></pre>
<p>Ideally, the deserialised instance would have an <strong>aString</strong> property with a value of <strong>"string"</strong> (i.e. without trailing spaces). This seems like something that is probably supported but I can't find it (e.g. in <em>DeserializationConfig.Feature</em>).</p>
<p>We're using Spring MVC 3.x so a Spring-based solution would also be fine.</p>
<p>I tried configuring Spring's WebDataBinder based on a suggestion in a <a href="http://forum.springsource.org/archive/index.php/t-102013.html" rel="noreferrer">forum post</a> but it does not seem to work when using a Jackson message converter:</p>
<pre><code>@InitBinder
public void initBinder( WebDataBinder binder )
{
binder.registerCustomEditor( String.class, new StringTrimmerEditor( " \t\r\n\f", true ) );
}
</code></pre> | 6,989,290 | 6 | 3 | null | 2011-07-27 22:54:55.493 UTC | 13 | 2020-04-03 16:52:41.607 UTC | null | null | null | null | 786,999 | null | 1 | 61 | java|json|spring-mvc|jackson | 52,016 | <p>With a <a href="https://fasterxml.github.io/jackson-databind/javadoc/2.3.0/com/fasterxml/jackson/databind/annotation/JsonDeserialize.html" rel="noreferrer">custom deserializer</a>, you could do the following:</p>
<pre><code> <your bean>
@JsonDeserialize(using=WhiteSpaceRemovalSerializer.class)
public void setAString(String aString) {
// body
}
<somewhere>
public class WhiteSpaceRemovalDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser jp, DeserializationContext ctxt) {
// This is where you can deserialize your value the way you want.
// Don't know if the following expression is correct, this is just an idea.
return jp.getCurrentToken().asText().trim();
}
}
</code></pre>
<p>This solution does imply that this bean attribute will always be serialized this way, and you will have to annotate every attribute that you want to be deserialized this way.</p> |
45,660,139 | How exactly do partial registers on Haswell/Skylake perform? Writing AL seems to have a false dependency on RAX, and AH is inconsistent | <p>This loop runs at one iteration per 3 cycles on Intel Conroe/Merom, bottlenecked on <code>imul</code> throughput as expected. But on Haswell/Skylake, it runs at one iteration per 11 cycles, apparently because <code>setnz al</code> has a dependency on the last <code>imul</code>.</p>
<pre><code>; synthetic micro-benchmark to test partial-register renaming
mov ecx, 1000000000
.loop: ; do{
imul eax, eax ; a dep chain with high latency but also high throughput
imul eax, eax
imul eax, eax
dec ecx ; set ZF, independent of old ZF. (Use sub ecx,1 on Silvermont/KNL or P4)
setnz al ; ****** Does this depend on RAX as well as ZF?
movzx eax, al
jnz .loop ; }while(ecx);
</code></pre>
<p>If <code>setnz al</code> depends on <code>rax</code>, the 3ximul/setcc/movzx sequence forms a loop-carried dependency chain. If not, each <code>setcc</code>/<code>movzx</code>/3x<code>imul</code> chain is independent, forked off from the <code>dec</code> that updates the loop counter. The 11c per iteration measured on HSW/SKL is perfectly explained by a latency bottleneck: 3x3c(imul) + 1c(read-modify-write by setcc) + 1c(movzx within the same register).</p>
<hr>
<p><strong>Off topic: avoiding these (intentional) bottlenecks</strong></p>
<p>I was going for understandable / predictable behaviour to isolate partial-reg stuff, not optimal performance.</p>
<p>For example, <code>xor</code>-zero / set-flags / <code>setcc</code> is better anyway (in this case, <code>xor eax,eax</code> / <code>dec ecx</code> / <code>setnz al</code>). That breaks the dep on eax on all CPUs (except early P6-family like PII and PIII), still avoids partial-register merging penalties, and saves 1c of <code>movzx</code> latency. It also uses one fewer ALU uop on CPUs that <a href="https://stackoverflow.com/questions/33666617/what-is-the-best-way-to-set-a-register-to-zero-in-x86-assembly-xor-mov-or-and/33668295#33668295">handle xor-zeroing in the register-rename stage</a>. See that link for more about using xor-zeroing with <code>setcc</code>.</p>
<p>Note that AMD, Intel Silvermont/KNL, and P4, don't do partial-register renaming at all. It's only a feature in Intel P6-family CPUs and its descendant, Intel Sandybridge-family, but seems to be getting phased out.</p>
<p>gcc unfortunately does tend to use <code>cmp</code> / <code>setcc al</code> / <code>movzx eax,al</code> where it could have used <code>xor</code> instead of <code>movzx</code> <a href="https://gcc.godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(j:1,source:'//+gcc+uses+xor/cmp/setcc+in+a+simple+case%0Aint+boolean(int+a)+%7B+return+a!!%3D5%3B+%7D%0A%0A%0A//+When+things+get+complex+enough,+gcc+uses+setcc/movzx.%0A//+But+fortunately+into+a+register+that+was+already+part+of+the+same+dep+chain%0A//+clang+uses+R8%0Aunsigned+int+countmatch(unsigned+int+arr%5B%5D,+unsigned+int+key)%0A%7B%0A++++unsigned+count+%3D+0%3B%0A++++for+(int+i%3D0%3B+i%3C1024+%3B+i%2B%2B)+%7B%0A++++++++//+changing+%60key%60+to+%607%60+doesn!'t+get+gcc+to+use+xor/cmp/setcc:+It!'s+not+trying+to+avoid+REX+prefixes,+maybe+just+some+register-pressure+threshold%0A++++++++count+%2B%3D+((arr%5Bi%5D+%26+key)+!!%3D+5)%3B%0A++++%7D%0A++++return+count%3B%0A%7D%0A%0A//+we+can+even+convince+gcc+and+clang+to+do+%0A//+%22dangerous%22+things+with+partial+registers%0A//+by+combining+boolean+conditions%0Aunsigned+int+doubletmatch(unsigned+int+arr%5B%5D,+unsigned+int+key)%0A%7B%0A++++unsigned+count+%3D+0%3B%0A++++for+(int+i%3D0%3B+i%3C1024+%3B+i%2B%2B)+%7B%0A++++++++//+gcc+uses+a+32-bit+OR+to+combine+setcc+results+even+with+-march%3Dcore2%0A++++++++//+causing+a+partial-register+stall.++(Even+with+old+gcc)%0A++++++++count+%2B%3D+(arr%5Bi%5D+%3D%3D+key)+%7C+(arr%5Bi%5D+%3D%3D+~key)%3B%0A++++++++//+clang+-m32+uses+dl+and+dh,+which+is+also+problematic%0A++++%7D%0A++++return+count%3B%0A%7D%0A%0A%0A//+compilers+don!'t+spend+an+instruction+breaking+the+dep+on+the+setcc+destination,%0A//+even+with+-march%3Dbdver2+(Piledriver)+where+it!'s+known+to+have+one.%0A//+This+doesn!'t+usually+come+up,+since+trivial+functions+usually+inline.%0Achar+narrow_boolean(int+a)+%7B+return+a!!%3D5%3B+%7D%0A%0A%0A%23if+0%0A//+gcc+uses+setcc/movzx+for+these,+but+only+in+32-bit+mode.%0A//+I+think+because+of+the+extra+work+of+loading+args+from+the+stack%0A//+In+this+case+there!'s+no+actual+register+pressure,%0A//+because+the+pointers+are+dead+by+the+time+we+need+them.%0Aint+foo(unsigned+int+%26a,+unsigned+int+%26b)+%7B%0A++++return+a+%2B+(a!!%3Db)%3B%0A%7D%0A%0Aextern+int+extfunc(unsigned)%3B%0Aunsigned+int+bar(unsigned+int+a,+unsigned+int+b)+%7B%0A++++a+*%3D+b%3B%0A++++b+*%3D+a%3B%0A++++a+*%3D+b%3B%0A++++b+*%3D+a%3B%0A++++//int+r+%3D+extfunc(a)%3B%0A++++return+a+%2B+(a!!%3Db)%3B%0A%7D%0A%23endif'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:37.151279838941626,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:g71,filters:(b:'0',commentOnly:'0',directives:'0',intel:'0'),options:'-Wall+-O3++-mtune%3Dhaswell+-fno-tree-vectorize',source:1),l:'5',n:'0',o:'x86-64+gcc+7.1+(Editor+%231,+Compiler+%231)',t:'0')),k:30.12953615077989,l:'4',m:100,n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:clang400,filters:(___0:(),b:'0',commentOnly:'0',directives:'0',intel:'0',jquery:'3.2.1',length:1,prevObject:(___0:(sizzle1502600537666:(undefined:(legend:!(1590,0,'1')))),length:1,prevObject:(___0:(jQuery321081933210614779781:(display:''),sizzle1502600537666:(undefined:(legend:!(1590,0,'1')))),length:1))),options:'-Wall+-O3+-mtune%3Dhaswell++-fno-tree-vectorize+-fno-unroll-loops',source:1),l:'5',n:'0',o:'x86-64+clang+4.0.0+(Editor+%231,+Compiler+%232)',t:'0')),k:32.7191840102785,l:'4',n:'0',o:'',s:0,t:'0')),l:'2',m:100,n:'0',o:'',t:'0')),version:4" rel="noreferrer">(Godbolt compiler-explorer example)</a>, while clang uses xor-zero/cmp/setcc unless you combine multiple boolean conditions like <code>count += (a==b) | (a==~b)</code>.</p>
<p>The xor/dec/setnz version runs at 3.0c per iteration on Skylake, Haswell, and Core2 (bottlenecked on <code>imul</code> throughput). <code>xor</code>-zeroing breaks the dependency on the old value of <code>eax</code> on all out-of-order CPUs other than PPro/PII/PIII/early-Pentium-M (where it still avoids partial-register merging penalties but doesn't break the dep). <a href="http://agner.org/optimize/" rel="noreferrer">Agner Fog's microarch guide describes this</a>. Replacing the xor-zeroing with <code>mov eax,0</code> slows it down to one per 4.78 cycles on Core2: <a href="https://stackoverflow.com/questions/7031671/why-are-mov-ah-bh-and-mov-al-bl-together-much-faster-than-single-instruction-mo/35175245#35175245">2-3c stall (in the front-end?) to insert a partial-reg merging uop</a> when <code>imul</code> reads <code>eax</code> after <code>setnz al</code>.</p>
<p>Also, I used <code>movzx eax, al</code> which defeats mov-elimination, just like <code>mov rax,rax</code> does. (IvB, HSW, and SKL can rename <code>movzx eax, bl</code> with 0 latency, but Core2 can't). This makes everything equal across Core2 / SKL, except for the partial-register behaviour.</p>
<hr>
<p>The Core2 behaviour is consistent with <a href="http://agner.org/optimize/" rel="noreferrer">Agner Fog's microarch guide</a>, but the HSW/SKL behaviour isn't. From section 11.10 for Skylake, and same for previous Intel uarches:</p>
<blockquote>
<p>Different parts of a general purpose register can be stored in different temporary registers in order to remove false dependences.</p>
</blockquote>
<p>He unfortunately doesn't have time to do detailed testing for every new uarch to re-test assumptions, so this change in behaviour slipped through the cracks.</p>
<p>Agner does describe a merging uop being inserted (without stalling) for high8 registers (AH/BH/CH/DH) on Sandybridge through Skylake, and for low8/low16 on SnB. (I've unfortunately been spreading mis-information in the past, and saying that Haswell can merge AH for free. I skimmed Agner's Haswell section too quickly, and didn't notice the later paragraph about high8 registers. Let me know if you see my wrong comments on other posts, so I can delete them or add a correction. I will try to at least find and edit my answers where I've said this.)</p>
<hr>
<p>My actual questions: <strong>How <em>exactly</em> do partial registers really behave on Skylake?</strong></p>
<p><strong>Is everything the same from IvyBridge to Skylake, including the high8 extra latency?</strong></p>
<p><a href="https://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf#page=129" rel="noreferrer">Intel's optimization manual</a> is not specific about which CPUs have false dependencies for what (although it does mention that some CPUs have them), and leaves out things like reading AH/BH/CH/DH (high8 registers) adding extra latency even when they haven't been modified.</p>
<p>If there's any P6-family (Core2/Nehalem) behaviour that Agner Fog's microarch guide doesn't describe, that would be interesting too, but I should probably limit the scope of this question to just Skylake or Sandybridge-family.</p>
<hr>
<p><strong>My Skylake test data</strong>, from putting <code>%rep 4</code> short sequences inside a small <code>dec ebp/jnz</code> loop that runs 100M or 1G iterations. I measured cycles with Linux <code>perf</code> the same way as <a href="https://stackoverflow.com/questions/44169342/can-x86s-mov-really-be-free-why-cant-i-reproduce-this-at-all/44193770#44193770">in my answer here</a>, on the same hardware (desktop Skylake i7 6700k).</p>
<p>Unless otherwise noted, each instruction runs as 1 fused-domain uop, using an ALU execution port. (Measured with <a href="https://github.com/andikleen/pmu-tools" rel="noreferrer"><code>ocperf.py stat -e ...,uops_issued.any,uops_executed.thread</code></a>). This detects (absence of) mov-elimination and extra merging uops.</p>
<p>The "4 per cycle" cases are an extrapolation to the infinitely-unrolled case. Loop overhead takes up some of the front-end bandwidth, but anything better than 1 per cycle is an indication that register-renaming avoided the <a href="https://en.wikipedia.org/wiki/Register_renaming#Data_hazards" rel="noreferrer">write-after-write output dependency</a>, and that the uop isn't handled internally as a read-modify-write.</p>
<p><strong>Writing to AH only</strong>: prevents the loop from executing from the loopback buffer (aka the Loop Stream Detector (LSD)). Counts for <code>lsd.uops</code> are exactly 0 on HSW, and tiny on SKL (around 1.8k) and don't scale with the loop iteration count. Probably those counts are from some kernel code. When loops do run from the LSD, <code>lsd.uops ~= uops_issued</code> to within measurement noise. Some loops alternate between LSD or no-LSD (e.g when they might not fit into the uop cache if decode starts in the wrong place), but I didn't run into that while testing this.</p>
<ul>
<li>repeated <code>mov ah, bh</code> and/or <code>mov ah, bl</code> runs at 4 per cycle. It takes an ALU uop, so it's not eliminated like <code>mov eax, ebx</code> is.</li>
<li>repeated <code>mov ah, [rsi]</code> runs at 2 per cycle (load throughput bottleneck).</li>
<li>repeated <code>mov ah, 123</code> runs at 1 per cycle. (A <a href="https://stackoverflow.com/questions/33666617/what-is-the-best-way-to-set-a-register-to-zero-in-x86-assembly-xor-mov-or-and/33668295#33668295">dep-breaking <code>xor eax,eax</code></a> inside the loop removes the bottleneck.)</li>
<li><p>repeated <code>setz ah</code> or <code>setc ah</code> runs at 1 per cycle. (A dep-breaking <code>xor eax,eax</code> lets it bottleneck on p06 throughput for <code>setcc</code> and the loop branch.)</p>
<p><strong>Why does writing <code>ah</code> with an instruction that would normally use an ALU execution unit have a false dependency on the old value, while <code>mov r8, r/m8</code> doesn't (for reg or memory src)?</strong> (And what about <code>mov r/m8, r8</code>? Surely it doesn't matter which of the two opcodes you use for reg-reg moves?)</p></li>
<li><p>repeated <code>add ah, 123</code> runs at 1 per cycle, as expected.</p></li>
<li>repeated <code>add dh, cl</code> runs at 1 per cycle.</li>
<li>repeated <code>add dh, dh</code> runs at 1 per cycle.</li>
<li>repeated <code>add dh, ch</code> runs at 0.5 per cycle. Reading [ABCD]H is special when they're "clean" (in this case, RCX is not recently modified at all).</li>
</ul>
<p><strong>Terminology</strong>: All of these leave AH (or DH) "<strong>dirty</strong>", i.e. in need of merging (with a merging uop) when the rest of the register is read (or in some other cases). i.e. that AH is renamed separately from RAX, if I'm understanding this correctly. "<strong>clean</strong>" is the opposite. There are many ways to clean a dirty register, the simplest being <code>inc eax</code> or <code>mov eax, esi</code>.</p>
<p><strong>Writing to AL only</strong>: These loops do run from the LSD: <code>uops_issue.any</code> ~= <code>lsd.uops</code>.</p>
<ul>
<li>repeated <code>mov al, bl</code> runs at 1 per cycle. An occasional dep-breaking <code>xor eax,eax</code> per group lets OOO execution bottleneck on uop throughput, not latency.</li>
<li>repeated <code>mov al, [rsi]</code> runs at 1 per cycle, as a micro-fused ALU+load uop. (uops_issued=4G + loop overhead, uops_executed=8G + loop overhead).
A dep-breaking <code>xor eax,eax</code> before a group of 4 lets it bottleneck on 2 loads per clock.</li>
<li>repeated <code>mov al, 123</code> runs at 1 per cycle.</li>
<li>repeated <code>mov al, bh</code> runs at 0.5 per cycle. (1 per 2 cycles). Reading [ABCD]H is special.</li>
<li><code>xor eax,eax</code> + 6x <code>mov al,bh</code> + <code>dec ebp/jnz</code>: 2c per iter, bottleneck on 4 uops per clock for the front-end.</li>
<li>repeated <code>add dl, ch</code> runs at 0.5 per cycle. (1 per 2 cycles). Reading [ABCD]H apparently creates extra latency for <code>dl</code>.</li>
<li>repeated <code>add dl, cl</code> runs at 1 per cycle.</li>
</ul>
<p>I think a write to a low-8 reg behaves as a RMW blend into the full reg, like <code>add eax, 123</code> would be, but it doesn't trigger a merge if <code>ah</code> is dirty. So (other than ignoring <code>AH</code> merging) it behaves the same as on CPUs that don't do partial-reg renaming at all. It seems <code>AL</code> is never renamed separately from <code>RAX</code>?</p>
<ul>
<li><code>inc al</code>/<code>inc ah</code> pairs can run in parallel.</li>
<li><code>mov ecx, eax</code> inserts a merging uop if <code>ah</code> is "dirty", but the actual <code>mov</code> is renamed. This is what <a href="http://agner.org/optimize/" rel="noreferrer">Agner Fog describes</a> for IvyBridge and later.</li>
<li>repeated <code>movzx eax, ah</code> runs at one per 2 cycles. (Reading high-8 registers after writing full regs has extra latency.)</li>
<li><code>movzx ecx, al</code> has zero latency and doesn't take an execution port on HSW and SKL. (Like what Agner Fog describes for IvyBridge, but he says HSW doesn't rename movzx).</li>
<li><p><code>movzx ecx, cl</code> has 1c latency and takes an execution port. (<a href="https://stackoverflow.com/questions/44169342/can-x86s-mov-really-be-free-why-cant-i-reproduce-this-at-all/44193770#44193770">mov-elimination never works for the <code>same,same</code> case</a>, only between different architectural registers.)</p>
<p>A loop that inserts a merging uop every iteration can't run from the LSD (loop buffer)?</p></li>
</ul>
<p>I don't think there's anything special about AL/AH/RAX vs. B*, C*, DL/DH/RDX. I have tested some with partial regs in other registers (even though I'm mostly showing <code>AL</code>/<code>AH</code> for consistency), and have never noticed any difference.</p>
<p><strong>How can we explain all of these observations with a sensible model of how the microarch works internally?</strong></p>
<hr>
<p>Related: Partial <strong>flag</strong> issues are different from partial <strong>register</strong> issues. See <a href="https://stackoverflow.com/questions/36510095/inc-instruction-vs-add-1-does-it-matter/36510865#36510865">INC instruction vs ADD 1: Does it matter?</a> for some super-weird stuff with <code>shr r32,cl</code> (and even <code>shr r32,2</code> on Core2/Nehalem: don't read flags from a shift other than by 1).</p>
<p>See also <a href="https://stackoverflow.com/questions/32084204/problems-with-adc-sbb-and-inc-dec-in-tight-loops-on-some-cpus">Problems with ADC/SBB and INC/DEC in tight loops on some CPUs</a> for partial-flag stuff in <code>adc</code> loops.</p> | 45,660,140 | 2 | 3 | null | 2017-08-13 12:05:33.373 UTC | 8 | 2019-10-10 02:19:36.907 UTC | 2017-08-21 15:52:45.093 UTC | null | 224,132 | null | 224,132 | null | 1 | 46 | assembly|x86|intel|cpu-architecture|micro-optimization | 3,304 | <p>Other answers welcome to address Sandybridge and IvyBridge in more detail.
I don't have access to that hardware.</p>
<hr>
<p>I haven't found any partial-reg behaviour differences between HSW and SKL.
On Haswell and Skylake, everything I've tested so far supports this model:</p>
<p><strong>AL is never renamed separately from RAX</strong> (or r15b from r15). So if you never touch the high8 registers (AH/BH/CH/DH), everything behaves exactly like on a CPU with no partial-reg renaming (e.g. AMD).</p>
<p>Write-only access to AL merges into RAX, with a dependency on RAX. For loads into AL, this is a micro-fused ALU+load uop that executes on p0156, which is one of the strongest pieces of evidence that it's truly merging on every write, and not just doing some fancy double-bookkeeping as Agner speculated.</p>
<p>Agner (and Intel) say Sandybridge can require a merging uop for AL, so it probably is renamed separately from RAX. For SnB, <a href="https://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf#page=129" rel="noreferrer">Intel's optimization manual (section 3.5.2.4 Partial Register Stalls)</a> says </p>
<blockquote>
<p>SnB (not necessarily later uarches) inserts a merging uop in the following cases:</p>
<ul>
<li><p>After a write to one of the registers AH, BH, CH or DH and before a
following read of the 2-, 4- or 8-byte form of the same register. In
these cases a merge micro-op is inserted. <strong>The insertion consumes a
full allocation cycle in which other micro-ops cannot be allocated.</strong> </p></li>
<li><p>After a micro-op with a destination register of 1 or 2 bytes, which is
not a source of the instruction (or the register's bigger form), and
before a following read of a 2-,4- or 8-byte form of the same
register. In these cases <strong>the merge micro-op is part of the flow</strong>.</p></li>
</ul>
</blockquote>
<p>I think they're saying that on SnB, <code>add al,bl</code> will RMW the full RAX instead of renaming it separately, because one of the source registers is (part of) RAX. My guess is that this doesn't apply for a load like <code>mov al, [rbx + rax]</code>; <code>rax</code> in an addressing mode probably doesn't count as a source.</p>
<p>I haven't tested whether high8 merging uops still have to issue/rename on their own on HSW/SKL. That would make the front-end impact equivalent to 4 uops (since that's the issue/rename pipeline width).</p>
<ul>
<li>There is no way to break a dependency involving AL without writing EAX/RAX. <code>xor al,al</code> doesn't help, and neither does <code>mov al, 0</code>.</li>
<li><strong><code>movzx ebx, al</code> has <a href="https://stackoverflow.com/questions/44169342/can-x86s-mov-really-be-free-why-cant-i-reproduce-this-at-all/44193770#44193770">zero latency (renamed)</a>, and needs no execution unit.</strong> (i.e. mov-elimination works on HSW and SKL). <strong>It triggers merging of AH if it's dirty</strong>, which I guess is necessary for it to work without an ALU. It's probably not a coincidence that Intel dropped low8 renaming in the same uarch that introduced mov-elimination. (Agner Fog's micro-arch guide has a mistake here, saying that zero-extended moves are not eliminated on HSW or SKL, only IvB.)</li>
<li><code>movzx eax, al</code> is <em>not</em> eliminated at rename. mov-elimination on Intel never works for same,same. <code>mov rax,rax</code> isn't eliminated either, even though it doesn't have to zero-extend anything. (Although there'd be no point to giving it special hardware support, because it's just a no-op, unlike <code>mov eax,eax</code>). Anyway, prefer moving between two separate architectural registers when zero-extending, whether it's with a 32-bit <code>mov</code> or an 8-bit <code>movzx</code>.</li>
<li><code>movzx eax, bx</code> is <em>not</em> eliminated at rename on HSW or SKL. It has 1c latency and uses an ALU uop. Intel's optimization manual only mentions zero-latency for 8-bit movzx (and points out that <code>movzx r32, high8</code> is never renamed).</li>
</ul>
<hr>
<h3>High-8 regs can be renamed separately from the rest of the register, and do need merging uops.</h3>
<ul>
<li>Write-only access to <code>ah</code> with <code>mov ah, reg8</code> or <code>mov ah, [mem8]</code> do rename AH, with no dependency on the old value. These are both instructions that wouldn't normally need an ALU uop for the 32-bit version. (But <code>mov ah, bl</code> is <em>not</em> eliminated; it does need a p0156 ALU uop so that might be a coincidence).</li>
<li>a RMW of AH (like <code>inc ah</code>) dirties it.</li>
<li><p><code>setcc ah</code> depends on the old <code>ah</code>, but still dirties it. I think <code>mov ah, imm8</code> is the same, but haven't tested as many corner cases.</p>
<p>(Unexplained: a loop involving <code>setcc ah</code> can sometimes run from the LSD, see the <code>rcr</code> loop at the end of this post. Maybe as long as <code>ah</code> is clean at the <em>end</em> of the loop, it can use the LSD?).</p>
<p>If <code>ah</code> is dirty, <code>setcc ah</code> merges into the renamed <code>ah</code>, rather than forcing a merge into <code>rax</code>. e.g. <code>%rep 4</code> (<code>inc al</code> / <code>test ebx,ebx</code> / <code>setcc ah</code> / <code>inc al</code> / <code>inc ah</code>) generates no merging uops, and only runs in about 8.7c (latency of 8 <code>inc al</code> slowed down by resource conflicts from the uops for <code>ah</code>. Also the <code>inc ah</code> / <code>setcc ah</code> dep chain).</p>
<p>I think what's going on here is that <code>setcc r8</code> is always implemented as a read-modify-write. Intel probably decided that it wasn't worth having a write-only <code>setcc</code> uop to optimize the <code>setcc ah</code> case, since it's very rare for compiler-generated code to <code>setcc ah</code>. (But see the godbolt link in the question: clang4.0 with <code>-m32</code> will do so.)</p></li>
<li><p>reading AX, EAX, or RAX triggers a merge uop (which takes up front-end issue/rename bandwidth). Probably the RAT (Register Allocation Table) tracks the high-8-dirty state for the architectural R[ABCD]X, and even after a write to AH retires, the AH data is stored in a separate physical register from RAX. Even with 256 NOPs between writing AH and reading EAX, there is an extra merging uop. (ROB size=224 on SKL, so this guarantees that the <code>mov ah, 123</code> was retired). Detected with uops_issued/executed perf counters, which clearly show the difference.</p></li>
<li><p>Read-modify-write of AL (e.g. <code>inc al</code>) merges for free, as part of the ALU uop. (Only tested with a few simple uops, like <code>add</code>/<code>inc</code>, not <code>div r8</code> or <code>mul r8</code>). Again, no merging uop is triggered even if AH is dirty.</p></li>
<li><p>Write-only to EAX/RAX (like <code>lea eax, [rsi + rcx]</code> or <a href="https://stackoverflow.com/questions/33666617/what-is-the-best-way-to-set-a-register-to-zero-in-x86-assembly-xor-mov-or-and"><code>xor eax,eax</code></a>) clears the AH-dirty state (no merging uop).</p></li>
<li>Write-only to AX (<code>mov ax, 1</code>) triggers a merge of AH first. I guess instead of special-casing this, it runs like any other RMW of AX/RAX. (TODO: test <code>mov ax, bx</code>, although that shouldn't be special because it's not renamed.)</li>
<li><code>xor ah,ah</code> has 1c latency, is not dep-breaking, and still needs an execution port.</li>
<li>Read and/or write of AL does not force a merge, so AH can stay dirty (and be used independently in a separate dep chain). (e.g. <code>add ah, cl</code> / <code>add al, dl</code> can run at 1 per clock (bottlenecked on add latency).</li>
</ul>
<hr>
<p><strong>Making AH dirty prevents a loop from running from the LSD</strong> (the loop-buffer), even when there are no merging uops. The LSD is when the CPU recycles uops in the queue that feeds the issue/rename stage. (Called the IDQ).</p>
<p>Inserting merging uops is a bit like inserting stack-sync uops for the stack-engine. Intel's optimization manual says that SnB's LSD can't run loops with mismatched <code>push</code>/<code>pop</code>, which makes sense, but it implies that it <em>can</em> run loops with balanced <code>push</code>/<code>pop</code>. That's not what I'm seeing on SKL: even balanced <code>push</code>/<code>pop</code> prevents running from the LSD (e.g. <code>push rax</code> / <code>pop rdx</code> / <code>times 6 imul rax, rdx</code>. (There may be a real difference between SnB's LSD and HSW/SKL: <a href="https://stackoverflow.com/questions/39311872/is-performance-reduced-when-executing-loops-whose-uop-count-is-not-a-multiple-of">SnB may just "lock down" the uops in the IDQ instead of repeating them multiple times, so a 5-uop loop takes 2 cycles to issue instead of 1.25</a>.) Anyway, it appears that HSW/SKL can't use the LSD when a high-8 register is dirty, or when it contains stack-engine uops.</p>
<p>This behaviour may be related to a <a href="https://hothardware.com/news/critical-flaw-in-intel-skylake-and-kaby-lake-hyperthreading-discovered-requiring-bios-microcode-fix" rel="noreferrer">an erratum in SKL</a>:</p>
<blockquote>
<p><a href="https://www3.intel.com/content/dam/www/public/us/en/documents/specification-updates/desktop-6th-gen-core-family-spec-update.pdf" rel="noreferrer">SKL150: Short Loops Which Use AH/BH/CH/DH Registers May Cause Unpredictable System Behaviour</a></p>
<p>Problem: Under complex micro-architectural conditions, short loops of less than 64 instruction that use AH, BH, CH, or DH registers as well as their corresponding wider registers (e.g. RAX, EAX, or AX for AH) may cause unpredictable system behaviour. This can only happen when both logical processors on the same physical processor are active.</p>
</blockquote>
<p>This may also be related to Intel's optimization manual statement that SnB at least has to issue/rename an AH-merge uop in a cycle by itself. That's a weird difference for the front-end.</p>
<p>My Linux kernel log says <code>microcode: sig=0x506e3, pf=0x2, revision=0x84</code>.
Arch Linux's <code>intel-ucode</code> package just provides the update, <a href="https://wiki.archlinux.org/index.php/microcode#Enabling_Intel_microcode_updates" rel="noreferrer">you have to edit config files to actually have it loaded</a>. So <strong>my Skylake testing was on an i7-6700k with microcode revision 0x84, which <a href="https://lists.debian.org/debian-devel/2017/06/msg00308.html" rel="noreferrer">doesn't include the fix for SKL150</a></strong>. It matches the Haswell behaviour in every case I tested, IIRC. (e.g. both Haswell and my SKL can run the <code>setne ah</code> / <code>add ah,ah</code> / <code>rcr ebx,1</code> / <code>mov eax,ebx</code> loop from the LSD). I have HT enabled (which is a pre-condition for SKL150 to manifest), but I was testing on a mostly-idle system so my thread had the core to itself.</p>
<p>With updated microcode, the LSD is completely disabled for everything all the time, not just when partial registers are active. <code>lsd.uops</code> is always exactly zero, including for real programs not synthetic loops. Hardware bugs (rather than microcode bugs) often require disabling a whole feature to fix. This is why SKL-avx512 (SKX) is <a href="https://en.wikichip.org/wiki/intel/microarchitectures/skylake_(client)#.C2.B5OP-Fusion_.26_LSD" rel="noreferrer">reported to not have a loopback buffer</a>. Fortunately this is not a performance problem: SKL's increased uop-cache throughput over Broadwell can almost always keep up with issue/rename.</p>
<hr>
<h2>Extra AH/BH/CH/DH latency:</h2>
<ul>
<li>Reading AH when it's not dirty (renamed separately) adds an extra cycle of latency for both operands. e.g. <code>add bl, ah</code> has a latency of 2c from input BL to output BL, so it can add latency to the critical path even if RAX and AH are not part of it. (I've seen this kind of extra latency for the other operand before, with vector latency on Skylake, where an int/float delay "pollutes" a register forever. TODO: write that up.)</li>
</ul>
<p>This means unpacking bytes with <code>movzx ecx, al</code> / <code>movzx edx, ah</code> has extra latency vs. <code>movzx</code>/<code>shr eax,8</code>/<code>movzx</code>, but still better throughput.</p>
<ul>
<li><p>Reading AH when it <em>is</em> dirty doesn't add any latency. (<code>add ah,ah</code> or <code>add ah,dh</code>/<code>add dh,ah</code> have 1c latency per add). I haven't done a lot of testing to confirm this in many corner-cases.</p>
<p><strong>Hypothesis: a dirty high8 value is stored in the bottom of a physical register</strong>. Reading a clean high8 requires a shift to extract bits [15:8], but reading a dirty high8 can just take bits [7:0] of a physical register like a normal 8-bit register read.</p></li>
</ul>
<p>Extra latency doesn't mean reduced throughput. This program can run at 1 iter per 2 clocks, even though all the <code>add</code> instructions have 2c latency (from reading DH, which is not modified.)</p>
<pre><code>global _start
_start:
mov ebp, 100000000
.loop:
add ah, dh
add bh, dh
add ch, dh
add al, dh
add bl, dh
add cl, dh
add dl, dh
dec ebp
jnz .loop
xor edi,edi
mov eax,231 ; __NR_exit_group from /usr/include/asm/unistd_64.h
syscall ; sys_exit_group(0)
</code></pre>
<p></p>
<pre><code> Performance counter stats for './testloop':
48.943652 task-clock (msec) # 0.997 CPUs utilized
1 context-switches # 0.020 K/sec
0 cpu-migrations # 0.000 K/sec
3 page-faults # 0.061 K/sec
200,314,806 cycles # 4.093 GHz
100,024,930 branches # 2043.675 M/sec
900,136,527 instructions # 4.49 insn per cycle
800,219,617 uops_issued_any # 16349.814 M/sec
800,219,014 uops_executed_thread # 16349.802 M/sec
1,903 lsd_uops # 0.039 M/sec
0.049107358 seconds time elapsed
</code></pre>
<hr>
<p><strong>Some interesting test loop bodies</strong>:</p>
<pre><code>%if 1
imul eax,eax
mov dh, al
inc dh
inc dh
inc dh
; add al, dl
mov cl,dl
movzx eax,cl
%endif
Runs at ~2.35c per iteration on both HSW and SKL. reading `dl` has no dep on the `inc dh` result. But using `movzx eax, dl` instead of `mov cl,dl` / `movzx eax,cl` causes a partial-register merge, and creates a loop-carried dep chain. (8c per iteration).
%if 1
imul eax, eax
imul eax, eax
imul eax, eax
imul eax, eax
imul eax, eax ; off the critical path unless there's a false dep
%if 1
test ebx, ebx ; independent of the imul results
;mov ah, 123 ; dependent on RAX
;mov eax,0 ; breaks the RAX dependency
setz ah ; dependent on RAX
%else
mov ah, bl ; dep-breaking
%endif
add ah, ah
;; ;inc eax
; sbb eax,eax
rcr ebx, 1 ; dep on add ah,ah via CF
mov eax,ebx ; clear AH-dirty
;; mov [rdi], ah
;; movzx eax, byte [rdi] ; clear AH-dirty, and remove dep on old value of RAX
;; add ebx, eax ; make the dep chain through AH loop-carried
%endif
</code></pre>
<p></p>
<p>The setcc version (with the <code>%if 1</code>) has 20c loop-carried latency, and runs from the LSD even though it has <code>setcc ah</code> and <code>add ah,ah</code>.</p>
<pre><code>00000000004000e0 <_start.loop>:
4000e0: 0f af c0 imul eax,eax
4000e3: 0f af c0 imul eax,eax
4000e6: 0f af c0 imul eax,eax
4000e9: 0f af c0 imul eax,eax
4000ec: 0f af c0 imul eax,eax
4000ef: 85 db test ebx,ebx
4000f1: 0f 94 d4 sete ah
4000f4: 00 e4 add ah,ah
4000f6: d1 db rcr ebx,1
4000f8: 89 d8 mov eax,ebx
4000fa: ff cd dec ebp
4000fc: 75 e2 jne 4000e0 <_start.loop>
Performance counter stats for './testloop' (4 runs):
4565.851575 task-clock (msec) # 1.000 CPUs utilized ( +- 0.08% )
4 context-switches # 0.001 K/sec ( +- 5.88% )
0 cpu-migrations # 0.000 K/sec
3 page-faults # 0.001 K/sec
20,007,739,240 cycles # 4.382 GHz ( +- 0.00% )
1,001,181,788 branches # 219.276 M/sec ( +- 0.00% )
12,006,455,028 instructions # 0.60 insn per cycle ( +- 0.00% )
13,009,415,501 uops_issued_any # 2849.286 M/sec ( +- 0.00% )
12,009,592,328 uops_executed_thread # 2630.307 M/sec ( +- 0.00% )
13,055,852,774 lsd_uops # 2859.456 M/sec ( +- 0.29% )
4.565914158 seconds time elapsed ( +- 0.08% )
</code></pre>
<p>Unexplained: it runs from the LSD, even though it makes AH dirty. (At least I think it does. TODO: try adding some instructions that do something with <code>eax</code> before the <code>mov eax,ebx</code> clears it.)</p>
<p>But with <code>mov ah, bl</code>, it runs in 5.0c per iteration (<code>imul</code> throughput bottleneck) on both HSW/SKL. (The commented-out store/reload works, too, but SKL has faster store-forwarding than HSW, and it's <a href="https://stackoverflow.com/questions/45442458/loop-with-function-call-faster-than-an-empty-loop/45529487#45529487">variable-latency</a>...)</p>
<pre><code> # mov ah, bl version
5,009,785,393 cycles # 4.289 GHz ( +- 0.08% )
1,000,315,930 branches # 856.373 M/sec ( +- 0.00% )
11,001,728,338 instructions # 2.20 insn per cycle ( +- 0.00% )
12,003,003,708 uops_issued_any # 10275.807 M/sec ( +- 0.00% )
11,002,974,066 uops_executed_thread # 9419.678 M/sec ( +- 0.00% )
1,806 lsd_uops # 0.002 M/sec ( +- 3.88% )
1.168238322 seconds time elapsed ( +- 0.33% )
</code></pre>
<p>Notice that it doesn't run from the LSD anymore.</p> |
15,923,062 | How to URL encode a URL in JSP / JSTL? | <p>I want to create an encoded <a href="http://en.wikipedia.org/wiki/Uniform_resource_locator" rel="noreferrer">URL</a> for my site. Say for example, for this URL: "<a href="http://google.com/index.html" rel="noreferrer">http://google.com/index.html</a>"</p>
<p>I want to give this URL to the client by URL encoding it. </p> | 15,926,416 | 3 | 1 | null | 2013-04-10 10:17:02.35 UTC | 6 | 2019-05-13 14:18:09.31 UTC | 2019-05-13 14:18:09.31 UTC | null | 880,619 | null | 2,223,817 | null | 1 | 21 | java|html|jsp | 50,901 | <p>Since you are using JSP, I would stick to <a href="https://stackoverflow.com/tags/jstl/info">JSTL</a> and <a href="https://stackoverflow.com/questions/2188706/how-to-avoid-using-scriptlets-in-my-jsp-page">not use scriptlets</a>. You could use the JSTL tag <a href="http://docs.oracle.com/javaee/1.4/tutorial/doc/JSTL4.html" rel="noreferrer"><code><c:url /></code> in combination with <code><c:param /></code></a>:</p>
<pre><code><c:url value="/yourClient" var="url">
<c:param name="yourParamName" value="http://google.com/index.html" />
</c:url>
<a href="${url}">Link to your client</a>
</code></pre>
<p>This will result in:</p>
<pre><code><a href="/yourClient?yourParamName=http%3a%2f%2fgoogle.com%2findex.html">Link to your client</a>
</code></pre> |
15,527,614 | send track informations via A2DP/AVRCP | <p>I'm trying to send track informations via A2DP/AVRCP. Right now, music is perfectly streamed, but on the "receiver" (ie: car audio), the "track informations screen" is blank (which is not the case using popular players out there).
Any idea ?</p> | 15,870,883 | 5 | 0 | null | 2013-03-20 15:20:33 UTC | 19 | 2017-02-09 20:50:21.317 UTC | 2013-03-20 15:36:04.877 UTC | null | 1,058,339 | null | 1,058,339 | null | 1 | 27 | android|bluetooth|a2dp|avrcp | 24,178 | <p>This code worked for me:</p>
<pre><code>private static final String AVRCP_PLAYSTATE_CHANGED = "com.android.music.playstatechanged";
private static final String AVRCP_META_CHANGED = "com.android.music.metachanged";
private void bluetoothNotifyChange(String what) {
Intent i = new Intent(what);
i.putExtra("id", Long.valueOf(getAudioId()));
i.putExtra("artist", getArtistName());
i.putExtra("album",getAlbumName());
i.putExtra("track", getTrackName());
i.putExtra("playing", isPlaying());
i.putExtra("ListSize", getQueue());
i.putExtra("duration", duration());
i.putExtra("position", position());
sendBroadcast(i);
}
</code></pre>
<p>Call bluetoothNotifyChange with the appropriate intent (defined above) depending on your playback status: pause/playing/metadata changed.</p> |
10,492,480 | Starting QTimer In A QThread | <p>I am trying to start a QTimer in a specific thread. However, the timer does not seem to execute and nothing is printing out. Is it something to do with the timer, the slot or the thread?</p>
<p>main.cpp</p>
<pre><code> #include "MyThread.h"
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
MyThread t;
t.start();
while(1);
}
</code></pre>
<p>MyThread.h</p>
<pre><code> #ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QTimer>
#include <QThread>
#include <iostream>
class MyThread : public QThread {
Q_OBJECT
public:
MyThread();
public slots:
void doIt();
protected:
void run();
};
#endif /* MYTHREAD_H */
</code></pre>
<p>MyThread.cpp</p>
<pre><code> #include "MyThread.h"
using namespace std;
MyThread::MyThread() {
moveToThread(this);
}
void MyThread::run() {
QTimer* timer = new QTimer(this);
timer->setInterval(1);
timer->connect(timer, SIGNAL(timeout()), this, SLOT(doIt()));
timer->start();
}
void MyThread::doIt(){
cout << "it works";
}
</code></pre> | 10,493,492 | 6 | 4 | null | 2012-05-08 04:16:21.867 UTC | 7 | 2018-04-23 19:30:25.747 UTC | 2017-11-02 13:17:25.13 UTC | null | 8,724,882 | null | 1,363,460 | null | 1 | 15 | c++|multithreading|qt|timer|qthread | 48,668 | <p>As I commented (further information in the link) you are doing it wrong :</p>
<ol>
<li>You are mixing the object holding thread data with another object (responsible of <code>doIt()</code>). They should be separated.</li>
<li>There is no need to subclass <code>QThread</code> in your case. Worse, you are overriding the <code>run</code> method without any consideration of what it was doing.</li>
</ol>
<p>This portion of code should be enough</p>
<pre><code>QThread* somethread = new QThread(this);
QTimer* timer = new QTimer(0); //parent must be null
timer->setInterval(1);
timer->moveToThread(somethread);
//connect what you want
somethread->start();
</code></pre>
<p>Now (Qt version >= 4.7) by default <code>QThread</code> starts a event loop in his <code>run()</code> method. In order to run inside a thread, you just need to move the object. <a href="http://qt-project.org/doc/qt-4.8/QThread.html" rel="noreferrer">Read the doc...</a></p> |
25,306,870 | How do I make RecyclerView update its layout? | <p>I have a <code>RecyclerView</code> with a bunch of custom views which may change height after a while, because they contain <code>ImageView</code>s which load their image asynchronously. The <code>RecyclerView</code> does not pick up on this layout change, although I call <code>forceLayout</code> on the <code>ImageView</code>, and the <code>RecyclerView</code> is initialized with <code>setHasFixedSize(false)</code>. All container-parents of the <code>ImageView</code> have set <code>android:layout_height="wrap_content"</code>.</p>
<p>How can I make the <code>RecyclerView</code> update its layout? With good'ol <code>ListView</code> this was not a problem. </p> | 35,629,713 | 5 | 4 | null | 2014-08-14 11:23:23.11 UTC | 4 | 2016-07-30 18:47:38.797 UTC | 2016-07-30 18:41:46.743 UTC | null | 596,013 | null | 507,339 | null | 1 | 37 | android|android-recyclerview | 48,760 | <p>Google has finally fixed this in <a href="http://android-developers.blogspot.no/2016/02/android-support-library-232.html">support library v23.2</a>. Issue is fixed by updating this line in <code>build.gradle</code> after updating your support repository with the SDK Manager:</p>
<pre><code>compile 'com.android.support:recyclerview-v7:23.2.0'
</code></pre> |
25,174,784 | How to create a directory and sub directory structure with java? | <p>Hello there I want to create the directories and sub directories with the java.
My directory structure is starts from the current application directory, Means in current projects directory which looks like following...</p>
<pre><code>Images
|
|+ Background
|
|+ Foreground
|
|+Necklace
|+Earrings
|+Etc...
</code></pre>
<p>I know how to create directory but I need to create sub directory I tried with following code what should be next steps ?</p>
<pre><code>File file = new File("Images");
file.mkdir();
</code></pre> | 25,174,825 | 5 | 4 | null | 2014-08-07 05:26:43.923 UTC | 8 | 2019-09-01 16:03:02.697 UTC | 2014-09-26 06:40:28.21 UTC | null | 3,510,195 | null | 3,510,195 | null | 1 | 27 | java | 84,148 | <p>You can use <a href="http://docs.oracle.com/javase/7/docs/api/java/io/File.html#mkdir()">File.mkdir()</a> or <a href="http://docs.oracle.com/javase/7/docs/api/java/io/File.html#mkdirs()">File.mkdirs()</a> to create a directory. Between the two, the latter method is more tolerant and will create all intermediate directories as needed. Also, since I see that you use "\\" in your question, I would suggest using <a href="http://docs.oracle.com/javase/7/docs/api/java/io/File.html#separator">File.separator</a> for a portable path separator string.</p> |
37,862,030 | Is there an operation for not less than or not greater than in python? | <p>Consider a following snippet:</p>
<pre><code>a = 0
if a == 0 or a > 0:
print(a)
</code></pre>
<p>Essentially, I want to do something when <code>a</code> is not negative. If instead of this, I had wanted to do something when <code>a</code> is not <code>0</code>, I would have simply written:</p>
<pre><code>if a != 0 :
</code></pre>
<p>In the same spirit, I tried :</p>
<pre><code>if a !< 0 :
</code></pre>
<p>assuming the consistency of the Python where user starts guessing the correct implementations once he/she gets used to the language. I was surprised to see that this particular operation does not exist in Python! My question is that why such simple thing has not been implemented in Python and is there another way in which it has been implemented. Any feedback is highly appreciated. Thank you</p> | 37,862,059 | 7 | 7 | null | 2016-06-16 14:25:38.707 UTC | 4 | 2022-02-11 08:08:32.773 UTC | null | null | null | null | 2,396,502 | null | 1 | 6 | python|comparison-operators | 79,901 | <p>Instead of <code>a == 0 or a > 0</code> you could just use <code>a >= 0</code>.</p>
<p><a href="https://docs.python.org/library/stdtypes.html#comparisons" rel="noreferrer">https://docs.python.org/library/stdtypes.html#comparisons</a></p> |
13,584,719 | iOS Link Binary with library for debug only | <p>I have a bit of a problem with setting different configuration for my project. I have two versions of the same static library. One has logging enabled, the other doesn't. </p>
<p>I am using two different xcconfig files for Debug vs. Release. In these files I specify the library and header search paths for the two variants of the static lib. So far so good. </p>
<p>However, in my build settings I can't see a way to conditionally link the actual library. I.e use the debug variant for Debug and the release for Release. </p>
<p>Any ideas? </p> | 13,585,189 | 1 | 1 | null | 2012-11-27 12:55:44.313 UTC | 9 | 2012-11-27 13:28:12.797 UTC | null | null | null | null | 1,031,474 | null | 1 | 13 | iphone|objective-c|ios|xcode | 6,032 | <p>You need to link the library using the "Other Linker Flags" build setting, rather than the standard "Link Binary With Libraries" UI. The build setting can be changed depending on the configuration:</p>
<p><img src="https://i.stack.imgur.com/e8oSl.png" alt="enter image description here"></p>
<p>Click the triangle and you can give different values for Debug/Release. You will need to use the <code>-l</code> flag. For example, for a filename of <code>libMyLib.a</code> use the flag <code>-lMyLib</code>. You may need to edit the "Library Search Paths" to search the appropriate location.</p>
<p>If the filenames for the debug and release version are the same and you don't want to change them, put them into their own <code>lib/Debug</code> and <code>lib/Release</code> directories respectively. Then edit the "Library Search Paths" build setting adding either <code>"$SRCROOT/lib/Debug"</code> or <code>"$SRCROOT/lib/Release"</code> for the appropriate configuration.</p> |
13,555,021 | Supervised Latent Dirichlet Allocation for Document Classification? | <p>I have a bunch of already human-classified documents in some groups. </p>
<p>Is there a modified version of lda which I can use to train a model and then later classify unknown documents with it?</p> | 13,562,862 | 3 | 0 | null | 2012-11-25 20:12:20.14 UTC | 11 | 2021-03-04 06:50:13.04 UTC | null | null | null | null | 1,260,229 | null | 1 | 14 | machine-learning|nlp|classification|document-classification|lda | 17,138 | <p>For what it's worth, LDA as a classifier is going to be fairly weak because it's a generative model, and classification is a discriminative problem. There is a variant of LDA called <a href="http://www.cs.columbia.edu/%7Eblei/papers/BleiMcAuliffe2007.pdf" rel="nofollow noreferrer">supervised LDA</a> which uses a more discriminative criterion to form the topics (you can get source for this in various places), and there's also a paper with a <a href="http://people.ee.duke.edu/%7Elcarin/MedLDA.pdf" rel="nofollow noreferrer">max margin</a> formulation that I don't know the status of source-code-wise. I would avoid the Labelled LDA formulation unless you're sure that's what you want, because it makes a strong assumption about the correspondence between topics and categories in the classification problem.</p>
<p>However, it's worth pointing out that none of these methods use the topic model directly to do the classification. Instead, they take documents, and instead of using word-based features use the posterior over the topics (the vector that results from inference for the document) as its feature representation before feeding it to a classifier, usually a Linear SVM. This gets you a topic model based dimensionality reduction, followed by a strong discriminative classifier, which is probably what you're after. This pipeline is available
in most languages using popular toolkits.</p> |
13,655,541 | WCF service attribute to log method calls and exceptions | <p>I have a requirement to log each method call in a WCF service, and any exceptions thrown. This has led to a lot of redundant code, because each method needs to include boilerplate similar to this:</p>
<pre><code>[OperationContract]
public ResultBase<int> Add(int x, int y)
{
var parameters = new object[] { x, y }
MyInfrastructure.LogStart("Add", parameters);
try
{
// actual method body goes here
}
catch (Exception ex)
{
MyInfrastructure.LogError("Add", parameters, ex);
return new ResultBase<int>("Oops, the request failed", ex);
}
MyInfrastructure.LogEnd("Add", parameters);
}
</code></pre>
<p>Is there a way I can encapsulate all this logic into an attribute <code>MyServiceLoggingBehaviorAttribute</code>, which I could apply to the service class (or methods) like this:</p>
<pre><code>[ServiceContract]
[MyServiceLoggingBehavior]
public class MyService
{
}
</code></pre>
<hr/>
<p><strong>Note #1</strong> </p>
<p>I realize that this can be done using <a href="https://stackoverflow.com/questions/4133569/how-to-log-method-calls-on-targets-marked-with-an-attribute">Aspect-oriented programming</a>, but in C# the only way to do this is to modify bytecode, which requires the use of a third-party product like PostSharp. I would like to avoid using commercial libraries.</p>
<p><strong>Note #2</strong></p>
<p>Note that Silverlight applications are the primary consumers of the service.</p>
<p><strong>Note #3</strong></p>
<p><a href="https://stackoverflow.com/questions/1178256/log-wcf-service-calls-with-parameter-information">WCF trace logging</a> is a good option in some cases, but it doesn't work here because, as noted above, I need to inspect, and in the case of an exception change, the return value.</p> | 13,655,542 | 2 | 5 | null | 2012-12-01 01:44:09.343 UTC | 11 | 2018-01-15 06:36:34.627 UTC | 2017-05-23 12:17:55.067 UTC | null | -1 | null | 1,001,985 | null | 1 | 17 | c#|wcf|logging|custom-attributes|aop | 14,855 | <p>Yes, it is possible to encapsulate this kind of logging, using the <a href="http://msdn.microsoft.com/en-us/magazine/cc163302.aspx" rel="noreferrer">extensibility points built into WCF</a>. There are actually multiple possible approaches. The one I'm describing here adds an <code>IServiceBehavior</code>, which uses a custom <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.ioperationinvoker.aspx" rel="noreferrer"><code>IOperationInvoker</code></a>, and does not require any web.config modifications.</p>
<p>There are three parts to this.</p>
<ol>
<li>Create an implementation of <code>IOperationInvoker</code>, which wraps the method invocation in the required logging and error-handling.</li>
<li>Create an implementation of <code>IOperationBehavior</code> that applies the invoker from step 1.</li>
<li>Create an <code>IServiceBehavior</code>, which inherits from <code>Attribute</code>, and applies the behavior from step 2.</li>
</ol>
<h3>Step 1 - IOperationInvoker</h3>
<p>The crux of <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.ioperationinvoker.aspx" rel="noreferrer">IOperationInvoker</a> is the <code>Invoke</code> method. My class wraps the base invoker in a try-catch block:</p>
<pre><code>public class LoggingOperationInvoker : IOperationInvoker
{
IOperationInvoker _baseInvoker;
string _operationName;
public LoggingOperationInvoker(IOperationInvoker baseInvoker, DispatchOperation operation)
{
_baseInvoker = baseInvoker;
_operationName = operation.Name;
}
// (TODO stub implementations)
public object Invoke(object instance, object[] inputs, out object[] outputs)
{
MyInfrastructure.LogStart(_operationName, inputs);
try
{
return _baseInvoker.Invoke(instance, inputs, out outputs);
}
catch (Exception ex)
{
MyInfrastructure.LogError(_operationName, inputs, ex);
return null;
}
MyInfrastructure.LogEnd("Add", parameters);
}
}
</code></pre>
<h3>Step 2 - IOperationBehavior</h3>
<p>The implementation of <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.description.ioperationbehavior.aspx" rel="noreferrer">IOperationBehavior</a> simply applies the custom dispatcher to the operation.</p>
<pre><code>public class LoggingOperationBehavior : IOperationBehavior
{
public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
{
dispatchOperation.Invoker = new LoggingOperationInvoker(dispatchOperation.Invoker, dispatchOperation);
}
// (TODO stub implementations)
}
</code></pre>
<h3>Step 3 - IServiceBehavior</h3>
<p>This implementation of <code>IServiceBehavior</code> applies the operation behavior to the service; it should inherit from <code>Attribute</code> so that it can be applied as an attribute to the WCF service class. The implementation for this is standard.</p>
<pre><code>public class ServiceLoggingBehavior : Attribute, IServiceBehavior
{
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
foreach (ServiceEndpoint endpoint in serviceDescription.Endpoints)
{
foreach (OperationDescription operation in endpoint.Contract.Operations)
{
IOperationBehavior behavior = new LoggingOperationBehavior();
operation.Behaviors.Add(behavior);
}
}
}
}
</code></pre> |
13,247,984 | How to insert code into wordpress | <p>In many wordpress blogs, we are seeing the code like below.
<img src="https://i.stack.imgur.com/fNa09.png" alt="enter image description here" /></p>
<p>Now I want to put my code also like this? How to do it? is it belongs to any thrid party tool or is it in built comes with wordpress? When I copy and paste the code into blog it looking ugly. Please give me suggestion to make my blog more readable.
Thank you</p> | 13,269,912 | 6 | 0 | null | 2012-11-06 09:23:16.963 UTC | 15 | 2022-01-07 22:15:27.467 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 526,095 | null | 1 | 34 | wordpress | 39,089 | <p><em>If you are running your blog on Wordpress.com</em>, you just include the following lines before your code.</p>
<pre><code>[sourcecode language="csharp"]
//your code comes here
[/sourcecode]
</code></pre>
<p>Wordpress.com gives us the facility to avoid worrying about code highlighting. If your code is in between these blocks then it will automatically render as per the language you specified. It can support many languages.</p>
<p>Some of them are..</p>
<p>html</p>
<p>javascript </p>
<p>java </p>
<p>javafx </p>
<p>matlab (keywords only) </p>
<p>objc </p>
<p>perl </p>
<p>php</p>
<p><em>If you have a self-hosted site, or one hosted on wordpress.org</em>, you should should use the SyntaxHighlighter plugin: <a href="http://wordpress.org/plugins/syntaxhighlighter" rel="noreferrer">wordpress.org/plugins/syntaxhighlighter</a>. </p>
<p>This is the plugin the WordPress team sourced to create this functionality on wordpress.com</p>
<p>For more information see this <a href="http://en.support.wordpress.com/code/posting-source-code/" rel="noreferrer">link</a></p> |
13,275,144 | How to make xib compatible with both iphone 5 and iphone 4 devices | <p>I am trying to layout my xib so that layout fits in both iphone 5 (4 inches retina) and 3.5 devices. </p>
<p>Because I have to support IOS-5 I cannot use autolayout. I have to use springs and Struts.</p>
<p>I tried everything in interface-builder. But either my view is going beyond the bottom of iphone-3.5-inch or not filling completely the iphone-4-inch-retina. </p>
<p>Can someone give a hint how to actually make an xib compatible to both the devices?</p>
<p>For more clarity I am adding screenshots:</p>
<p>When I set size 3.5 in attribute inspector:
<img src="https://i.stack.imgur.com/RusNY.png" alt="When I set size in attribute inspector to 3.5"></p>
<p>it looks in iphone-5. There is a space below the buttons:
<img src="https://i.stack.imgur.com/UXwqx.png" alt="And this is how it looks in simulator for 3.5 inch device"></p>
<p>If I set size 4 inch in interface builder. You can see that bottom buttons are not visible in iphone-4.
<img src="https://i.stack.imgur.com/m2TO7.png" alt="If I set size 3.5 inch in interface builder"></p>
<p>So you will ask what are the settings I am using. Here are they:</p>
<p><img src="https://i.stack.imgur.com/qHQR9.png" alt="enter image description here">
<img src="https://i.stack.imgur.com/5yJ37.png" alt="enter image description here">
<img src="https://i.stack.imgur.com/cTZ8A.png" alt="enter image description here"></p> | 13,283,851 | 14 | 5 | null | 2012-11-07 17:39:40.167 UTC | 31 | 2017-10-20 12:41:56.283 UTC | 2013-06-10 17:07:33.967 UTC | null | 739,711 | null | 739,711 | null | 1 | 45 | iphone|xcode|interface-builder | 51,586 | <ol>
<li><p>You add new category for UIviewController and add this code in .h file </p>
<pre><code> - (id)initWithNibNameforIphone4:(NSString *)nibNameOrNil4 NibNameforIphone5:(NSString *)nibNameOrNil5 NibNameforIpad:(NSString *)nibNameOrNilpad bundle:(NSBundle *)nibBundleOrNil;
</code></pre></li>
<li><p>Add this code in your .m file </p>
<pre><code> - (id)initWithNibNameforIphone4:(NSString *)nibNameOrNil4 NibNameforIphone5:(NSString *)nibNameOrNil5 NibNameforIpad:(NSString *)nibNameOrNilpad bundle:(NSBundle *)nibBundleOrNil
{
if (self = [super init])
{
self = [self initWithNibName:[self CheckDeviceIphone4:nibNameOrNil4 Iphone5:nibNameOrNil5 Ipad:nibNameOrNilpad] bundle:nibBundleOrNil];
}
return self;
}
-(NSString *)CheckDeviceIphone4:(NSString *)iphone4 Iphone5:(NSString *)iphone5 Ipad:(NSString *)ipad {
return ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) ? ipad :([[UIScreen mainScreen] bounds].size.height == 568) ? iphone5 :iphone4;
}
</code></pre></li>
<li><p>Open YouProject-Prefix.pch file and import your category here </p></li>
<li><p>now you just use this in all over project like this </p>
<pre><code> self.firstView=[[firstView alloc]initWithNibNameforIphone4:@"firstView4" NibNameforIphone5:@"firstView" NibNameforIpad:@"firstViewIpad" bundle:[NSBundle mainBundle]];
</code></pre>
<p>thanks and any question then comment and dont forget to upvote :-)</p></li>
</ol>
<p>\</p> |
24,001,147 | python bind socket.error: [Errno 13] Permission denied | <p>I have a python script which gets packets from a remote machine and writes them
(os.write(self.tun_fd.fileno(), ''.join(packet))) to a tun interface gr3:</p>
<pre><code>Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
inet addr:10.0.0.6 P-t-P:10.0.0.8 Mask:255.255.255.255
UP POINTOPOINT RUNNING NOARP MULTICAST MTU:1500 Metric:1
RX packets:61 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:500
RX bytes:5124 (5.0 KiB) TX bytes:0 (0.0 b)
</code></pre>
<p>I would like to receive those packets via a separate pong script as follows:</p>
<pre><code>import threading, os, sys, fcntl, struct, socket
from fcntl import ioctl
from packet import Packet
HOST = '10.0.0.6'
PORT = 111
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
else: print data
conn.sendall(data)
conn.close()
</code></pre>
<p>I got this error :</p>
<pre><code>s.bind((HOST, PORT))
File "<string>", line 1, in bind
socket.error: [Errno 13] Permission denied
</code></pre> | 24,001,186 | 2 | 3 | null | 2014-06-02 18:40:54.987 UTC | 8 | 2020-09-21 13:53:41.803 UTC | null | null | null | null | 2,705,283 | null | 1 | 29 | python|tunnel | 75,689 | <p>You can't bind to port numbers lower than 1024 as a unprivileged user. </p>
<p>So you should either:</p>
<ul>
<li>Use a port number larger than 1024 (recommended)</li>
<li>Or run the script as a privileged user</li>
</ul>
<p>Harder, but more secure solution if it's really necessary to accept from 111:</p>
<ul>
<li>Run the as unprivileged on a higher port, and forward port 111 to it externally. </li>
</ul> |
28,722,276 | SQL SELECT TOP 1 FOR EACH GROUP | <p>I have had a look through the other questions and can't quite find what i'm looking for I have an SQL Database and in it a table called InventoryAllocations. In the table I have multiple entries for DocumentID's and want to retrieve the last entry for each unique DocumentID. I can retrieve just one by doing</p>
<pre><code>SELECT top(1) [UID]
,[RecordStatusID]
,[CreatedDate]
,[CreatedTime]
,[CreatedByID]
,[OperationType]
,[InventoryLocationID]
,[DocumentTypeID]
,[DocumentID]
,[SOJPersonnelID]
,[InventorySerialisedItemID]
,[TransactionQty]
,[TransactionInventoryStatusID]
,[Completed]
,[CreatedByType]
,[RecordTimeStamp]
FROM [CPData].[dbo].[InventoryAllocations]
order by DocumentID desc
</code></pre>
<p>but I want it to bring back a list containing all the unique DocumentID's.I hope you can help. Many Thanks Hannah x</p> | 28,727,802 | 4 | 5 | null | 2015-02-25 14:58:59.423 UTC | 9 | 2020-11-27 17:58:48.34 UTC | 2015-02-25 15:06:45.74 UTC | null | 1,231,866 | null | 4,606,152 | null | 1 | 21 | sql|sql-server|greatest-n-per-group | 69,032 | <pre><code>SELECT TOP 1 WITH TIES
[UID]
,[RecordStatusID]
,[CreatedDate]
,[CreatedTime]
,[CreatedByID]
,[OperationType]
,[InventoryLocationID]
,[DocumentTypeID]
,[DocumentID]
,[SOJPersonnelID]
,[InventorySerialisedItemID]
,[TransactionQty]
,[TransactionInventoryStatusID]
,[Completed]
,[CreatedByType]
,[RecordTimeStamp]
FROM
[CPData].[dbo].[InventoryAllocations]
ORDER BY
ROW_NUMBER() OVER(PARTITION BY DocumentID ORDER BY [RecordTimeStamp] DESC);
</code></pre>
<p><code>TOP 1</code> works with <code>WITH TIES</code> here.</p>
<p><code>WITH TIES</code> means that when <code>ORDER BY = 1</code>, then <code>SELECT</code> takes this record (because of <code>TOP 1</code>) and all others that have <code>ORDER BY = 1</code> (because of <code>WITH TIES</code>).</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.