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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6,232,288 | Opening a browser link through notification isn't working | <p>My problem is the following:</p>
<p>I'm posting a notification to the notifications bar, and i've put a URI link in the intent being sent with it. As soon as i click on the notification i get a dialog what i want to do, but it's showing rubbish like Application info, Barcode scanner, Call dialog. instead of Browser.</p>
<p>I present my code:</p>
<pre><code> Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
PendingIntent contentIntent = PendingIntent.getActivity(contexta, 0, notificationIntent, 0);
notificationIntent.setData(Uri.parse("http://www.google.com"));
notification.setLatestEventInfo(contexta, contentTitle, contentText, contentIntent);
mNotificationManager.notify(970970, notification);
</code></pre>
<p>So i'm probably not thinking in the right direction.
Should i perhaps insert an intent and have a handler in my own application create a new intent for the browser instead?
But that would be strange, why does android not handle my initial intent correctly then.</p>
<p>As always,
Any and all help is greatly appreciated.</p>
<p>Thanks,
Rohan.</p> | 6,232,652 | 2 | 0 | null | 2011-06-03 20:25:43.5 UTC | 6 | 2016-03-30 12:53:13.387 UTC | 2013-08-27 08:26:18.96 UTC | null | 956,975 | null | 530,543 | null | 1 | 28 | android | 31,715 | <p>I think the problem is you're setting the data to "notificationIntent" after you give it to PendingIntent.</p>
<p>Try this:</p>
<pre><code> Intent notificationIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
PendingIntent contentIntent = PendingIntent.getActivity(contexta, 0, notificationIntent, 0);
notification.setLatestEventInfo(contexta, contentTitle, contentText, contentIntent);
mNotificationManager.notify(970970, notification);
</code></pre>
<p>Or try this:</p>
<pre><code> Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setData(Uri.parse("http://www.google.com"));
PendingIntent contentIntent = PendingIntent.getActivity(contexta, 0, notificationIntent, 0);
notification.setLatestEventInfo(contexta, contentTitle, contentText, contentIntent);
mNotificationManager.notify(970970, notification);
</code></pre> |
5,745,001 | XAML Combine styles going beyond BasedOn? | <p>Is there any way to combine mutliple styles in XAML to make a new style that has all of the desired settings?</p>
<p>For example (pseudo code);</p>
<pre><code><Style x:key="A">
...
</Style>
<Style x:key="B">
...
</Style>
<Style x:key="Combined">
<IncludeStyle Name="A"/>
<IncludeStyle Name="B"/>
... other properties.
</Style>
</code></pre>
<p>I know that there is a <code>BasedOn</code> property for styles, but that feature will only take you so far. I am really just looking for an easy way (in XAML) to create these 'combined' styles. But like I said before, I doubt it exists, unless anyone has heard of such a thing??</p> | 7,502,874 | 2 | 1 | null | 2011-04-21 13:49:35.1 UTC | 20 | 2021-08-16 17:32:06.043 UTC | 2021-08-16 17:28:31.3 UTC | null | 3,195,477 | null | 472,614 | null | 1 | 54 | wpf|xaml|styles | 20,949 | <p>You can make a custom markup extensions that will merge styles properties and triggers into a single style. All you need to do is add a <code>MarkupExtension</code>-derived class to your namespace with the <code>MarkupExtensionReturnType</code> attribute defined and you're off and running.</p>
<p>Here is an extension that will allow you to merge styles using a "css-like" syntax.</p>
<p><strong>MultiStyleExtension.cs</strong></p>
<pre class="lang-cs prettyprint-override"><code>[MarkupExtensionReturnType(typeof(Style))]
public class MultiStyleExtension : MarkupExtension
{
private string[] resourceKeys;
/// <summary>
/// Public constructor.
/// </summary>
/// <param name="inputResourceKeys">The constructor input should be a string consisting of one or more style names separated by spaces.</param>
public MultiStyleExtension(string inputResourceKeys)
{
if (inputResourceKeys == null)
throw new ArgumentNullException("inputResourceKeys");
this.resourceKeys = inputResourceKeys.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (this.resourceKeys.Length == 0)
throw new ArgumentException("No input resource keys specified.");
}
/// <summary>
/// Returns a style that merges all styles with the keys specified in the constructor.
/// </summary>
/// <param name="serviceProvider">The service provider for this markup extension.</param>
/// <returns>A style that merges all styles with the keys specified in the constructor.</returns>
public override object ProvideValue(IServiceProvider serviceProvider)
{
Style resultStyle = new Style();
foreach (string currentResourceKey in resourceKeys)
{
object key = currentResourceKey;
if (currentResourceKey == ".")
{
IProvideValueTarget service = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));
key = service.TargetObject.GetType();
}
Style currentStyle = new StaticResourceExtension(key).ProvideValue(serviceProvider) as Style;
if (currentStyle == null)
throw new InvalidOperationException("Could not find style with resource key " + currentResourceKey + ".");
resultStyle.Merge(currentStyle);
}
return resultStyle;
}
}
public static class MultiStyleMethods
{
/// <summary>
/// Merges the two styles passed as parameters. The first style will be modified to include any
/// information present in the second. If there are collisions, the second style takes priority.
/// </summary>
/// <param name="style1">First style to merge, which will be modified to include information from the second one.</param>
/// <param name="style2">Second style to merge.</param>
public static void Merge(this Style style1, Style style2)
{
if(style1 == null)
throw new ArgumentNullException("style1");
if(style2 == null)
throw new ArgumentNullException("style2");
if(style1.TargetType.IsAssignableFrom(style2.TargetType))
style1.TargetType = style2.TargetType;
if(style2.BasedOn != null)
Merge(style1, style2.BasedOn);
foreach(SetterBase currentSetter in style2.Setters)
style1.Setters.Add(currentSetter);
foreach(TriggerBase currentTrigger in style2.Triggers)
style1.Triggers.Add(currentTrigger);
// This code is only needed when using DynamicResources.
foreach(object key in style2.Resources.Keys)
style1.Resources[key] = style2.Resources[key];
}
}
</code></pre>
<p><strong>Your example would then be solved by going:</strong></p>
<pre class="lang-xml prettyprint-override"><code><Style x:key="Combined" BasedOn="{local:MultiStyle A B}">
... other properties.
</Style>
</code></pre>
<p>We have defined a new style named "Combined" by merging two other styles "A" and "B" within the built-in <code>BasedOn</code> attribute (used for style inheritance). We can optionally add other properties to the new "Combined" style as per usual.</p>
<p><strong>Other Examples</strong>:</p>
<p>Here, we define 4 button styles, and can use them in various combinations with little repetition:</p>
<pre class="lang-xml prettyprint-override"><code><Window.Resources>
<Style TargetType="Button" x:Key="ButtonStyle">
<Setter Property="Width" Value="120" />
<Setter Property="Height" Value="25" />
<Setter Property="FontSize" Value="12" />
</Style>
<Style TargetType="Button" x:Key="GreenButtonStyle">
<Setter Property="Foreground" Value="Green" />
</Style>
<Style TargetType="Button" x:Key="RedButtonStyle">
<Setter Property="Foreground" Value="Red" />
</Style>
<Style TargetType="Button" x:Key="BoldButtonStyle">
<Setter Property="FontWeight" Value="Bold" />
</Style>
</Window.Resources>
<Button Style="{local:MultiStyle ButtonStyle GreenButtonStyle}" Content="Green Button" />
<Button Style="{local:MultiStyle ButtonStyle RedButtonStyle}" Content="Red Button" />
<Button Style="{local:MultiStyle ButtonStyle GreenButtonStyle BoldButtonStyle}" Content="green, bold button" />
<Button Style="{local:MultiStyle ButtonStyle RedButtonStyle BoldButtonStyle}" Content="red, bold button" />
</code></pre>
<p>You can even use the "<code>.</code>" syntax to merge the "current" default style for a type (context-dependent) with some additional styles:</p>
<pre class="lang-xml prettyprint-override"><code><Button Style="{local:MultiStyle . GreenButtonStyle BoldButtonStyle}"/>
</code></pre>
<p>The above will merge the default style for <code>TargetType="{x:Type Button}"</code> with the two supplemental styles.</p>
<p><strong>Credit</strong></p>
<p>I found the original idea for the <code>MultiStyleExtension</code> at <a href="https://web.archive.org/web/20120103082937/http://bea.stollnitz.com/blog/?p=384" rel="nofollow noreferrer">bea.stollnitz.com</a> and modified it to support the "<code>.</code>" notation to reference the current style.</p> |
19,820,718 | How to make Visual Studio use the native amd64 toolchain | <p>How can I get Visual Studio 2012 to use the native amd64 toolchain, rather than the default x86_amd64 cross-compiler?</p>
<p>I am building a large library that causes the linker to run out of memory when doing whole program optimization and link-time code generation.</p>
<p>I found two older posts (<a href="https://stackoverflow.com/questions/10731090/how-to-enable-native-64-bit-compiler-in-visual-studio">here</a> and <a href="https://stackoverflow.com/questions/14188380/how-to-make-visual-studio-2012-call-the-the-native-64-bit-visual-c-compiler-in">here</a>) asking this same question, but no answers yet. Microsoft provides documentation on how to specify the toolchain <a href="http://msdn.microsoft.com/en-us/library/x4d2c09s%28v=vs.110%29.aspx" rel="noreferrer">on the command line</a>, but not in the IDE.</p> | 23,793,055 | 5 | 0 | null | 2013-11-06 19:11:50.2 UTC | 20 | 2019-05-28 07:36:37.267 UTC | 2017-05-23 11:47:05.107 UTC | null | -1 | null | 1,789,618 | null | 1 | 35 | c++|visual-studio|compilation|64-bit | 26,304 | <p>You need to set the environment variable "_IsNativeEnvironment" to "true" prior to starting Visual Studio 2012 IDE:</p>
<pre><code>set _IsNativeEnvironment=true
start "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe" your_solution.sln
</code></pre>
<p>For Visual Studio 2013, the name of the environment variable is different:</p>
<pre><code>set PreferredToolArchitecture=x64
sbm start "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe" your_solution.sln
</code></pre>
<p>Beware that this technique does not work if the version of the IDE does not match the version of the toolchain. That is, if you use VS2013 IDE configured to run VS2012 compiler, you are out of luck. But such combination is uncommon.</p>
<p>Here are some links for further information:</p>
<p><a href="https://connect.microsoft.com/VisualStudio/feedback/details/800059/isnativeenvironment-true-no-longer-works-on-visual-studio-2013-rc">difference between VS12 and VS13</a></p>
<p><a href="http://blogs.msdn.com/b/vcblog/archive/2013/10/30/the-visual-c-linker-best-practices-developer-iteration.aspx">how to embed PreferredToolArchitecture into the project in VS13</a></p> |
34,202,997 | How to aggregate values into collection after groupBy? | <p>I have a dataframe with schema as such:</p>
<pre><code>[visitorId: string, trackingIds: array<string>, emailIds: array<string>]
</code></pre>
<p>Looking for a way to group (or maybe rollup?) this dataframe by visitorid where the trackingIds and emailIds columns would append together. So for example if my initial df looks like:</p>
<pre><code>visitorId |trackingIds|emailIds
+-----------+------------+--------
|a158| [666b] | [12]
|7g21| [c0b5] | [45]
|7g21| [c0b4] | [87]
|a158| [666b, 777c]| []
</code></pre>
<p>I would like my output df to look like this</p>
<pre><code>visitorId |trackingIds|emailIds
+-----------+------------+--------
|a158| [666b,666b,777c]| [12,'']
|7g21| [c0b5,c0b4] | [45, 87]
</code></pre>
<p>Attempting to use <code>groupBy</code> and <code>agg</code> operators but not have much luck.</p> | 34,204,640 | 3 | 0 | null | 2015-12-10 13:20:31 UTC | 23 | 2019-02-11 15:23:58.667 UTC | 2017-03-07 18:20:20.697 UTC | null | 1,305,344 | null | 5,659,347 | null | 1 | 65 | scala|apache-spark|apache-spark-sql | 79,536 | <p><strong>Spark >= 2.4</strong></p>
<p>You can replace <code>flatten</code> <code>udf</code> with built-in <a href="https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.functions$@flatten(e:org.apache.spark.sql.Column):org.apache.spark.sql.Column" rel="noreferrer"><code>flatten</code> function</a></p>
<pre class="lang-scala prettyprint-override"><code>import org.apache.spark.sql.functions.flatten
</code></pre>
<p>leaving the rest as-is.</p>
<p><strong>Spark >= 2.0, < 2.4</strong></p>
<p>It is possible but quite expensive. Using data you've provided:</p>
<pre><code>case class Record(
visitorId: String, trackingIds: Array[String], emailIds: Array[String])
val df = Seq(
Record("a158", Array("666b"), Array("12")),
Record("7g21", Array("c0b5"), Array("45")),
Record("7g21", Array("c0b4"), Array("87")),
Record("a158", Array("666b", "777c"), Array.empty[String])).toDF
</code></pre>
<p>and a helper function:</p>
<pre><code>import org.apache.spark.sql.functions.udf
val flatten = udf((xs: Seq[Seq[String]]) => xs.flatten)
</code></pre>
<p>we can fill the blanks with placeholders:</p>
<pre><code>import org.apache.spark.sql.functions.{array, lit, when}
val dfWithPlaceholders = df.withColumn(
"emailIds",
when(size($"emailIds") === 0, array(lit(""))).otherwise($"emailIds"))
</code></pre>
<p><code>collect_lists</code> and <code>flatten</code>:</p>
<pre><code>import org.apache.spark.sql.functions.{array, collect_list}
val emailIds = flatten(collect_list($"emailIds")).alias("emailIds")
val trackingIds = flatten(collect_list($"trackingIds")).alias("trackingIds")
df
.groupBy($"visitorId")
.agg(trackingIds, emailIds)
// +---------+------------------+--------+
// |visitorId| trackingIds|emailIds|
// +---------+------------------+--------+
// | a158|[666b, 666b, 777c]| [12, ]|
// | 7g21| [c0b5, c0b4]|[45, 87]|
// +---------+------------------+--------+
</code></pre>
<p>With statically typed <code>Dataset</code>:</p>
<pre><code>df.as[Record]
.groupByKey(_.visitorId)
.mapGroups { case (key, vs) =>
vs.map(v => (v.trackingIds, v.emailIds)).toArray.unzip match {
case (trackingIds, emailIds) =>
Record(key, trackingIds.flatten, emailIds.flatten)
}}
// +---------+------------------+--------+
// |visitorId| trackingIds|emailIds|
// +---------+------------------+--------+
// | a158|[666b, 666b, 777c]| [12, ]|
// | 7g21| [c0b5, c0b4]|[45, 87]|
// +---------+------------------+--------+
</code></pre>
<p><strong>Spark 1.x</strong></p>
<p>You can convert to RDD and group</p>
<pre><code>import org.apache.spark.sql.Row
dfWithPlaceholders.rdd
.map {
case Row(id: String,
trcks: Seq[String @ unchecked],
emails: Seq[String @ unchecked]) => (id, (trcks, emails))
}
.groupByKey
.map {case (key, vs) => vs.toArray.unzip match {
case (trackingIds, emailIds) =>
Record(key, trackingIds.flatten, emailIds.flatten)
}}
.toDF
// +---------+------------------+--------+
// |visitorId| trackingIds|emailIds|
// +---------+------------------+--------+
// | 7g21| [c0b5, c0b4]|[45, 87]|
// | a158|[666b, 666b, 777c]| [12, ]|
// +---------+------------------+--------+
</code></pre> |
37,141,516 | Laravel 5.2 pluck() multiple attributes from Eloquent Model Collection | <p>Laravel 5.2 has pretty nice Helpers, I would like to use them to do following:</p>
<p>I have Eloquent Model Collection:</p>
<pre><code>$lesson->users(); // returns Eloquent collection of 3 users
</code></pre>
<p><code>pluck()</code> function would be useful, but it can get just single parameter. However I want to get output with <strong>two parameters</strong>, <code>id</code> and <code>name</code>, like this:</p>
<pre><code>[
1=>['id'=>10,'name'=>'Michael Dook'],
2=>['id'=>16,'name'=>'Henry Babcock'],
3=>['id'=>19,'name'=>'Joe Nedd']
]
</code></pre>
<p>Is there any elegant solution for this?</p> | 55,449,823 | 9 | 0 | null | 2016-05-10 14:31:43.563 UTC | 4 | 2021-09-28 11:07:30.39 UTC | null | null | null | null | 4,322,159 | null | 1 | 22 | laravel-5.2|helpers|laravel-collection | 46,240 | <p>Laravel: 5.7</p>
<p><strong>if method is returning relation</strong></p>
<p>use <code>get()</code> </p>
<p>e.g</p>
<pre><code>$lesson = Lesson::find(1);
$lesson->users()->get(['id', 'name']);
</code></pre>
<hr>
<p><strong>on collections</strong></p>
<p>use <code>only()</code> </p>
<pre><code>$user = collect(['id' => 1, 'name' => 'Foo', 'role' => 'A']);
$user->only(['id', 'name']);
</code></pre>
<p>multiple arrays</p>
<pre><code>$users = collect([
['id' => 1, 'name' => 'Foo', 'role' => 'A'],
['id' => 2, 'name' => 'Bar', 'role' => 'B'];
]);
$result = $users->map(function($user){
return Arr::only($user, ['id', 'name']);
});
var_dump($result);
</code></pre> |
47,042,201 | docker view directory within container | <p>I'm trying to copy some files from my docker container to my localhost, I read the documentation that the way to do this is</p>
<pre><code>docker cp 'container':path/to/file dest/path
</code></pre>
<p>But this requires I know the path and directory within the container that I want to get to, how can I view the container's directory? I tried docker diff and docker inspect but these don't show me the container's file directory</p> | 47,042,259 | 2 | 0 | null | 2017-10-31 18:23:50.54 UTC | 1 | 2020-10-24 13:05:15.183 UTC | null | null | null | null | 5,021,627 | null | 1 | 18 | docker|docker-container|docker-copy | 38,072 | <p>You'll first need to know the name of the instance running?</p>
<pre><code>$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
36029... image/image ... 1 sec.. Up.. ... some-container
</code></pre>
<p>Now, get inside the container and look for what you need. Assuming the container name is, <strong>some-image.</strong></p>
<pre><code>$ docker exec -it some-container /bin/bash
root@1f3420c939:/var/www/html#
</code></pre>
<p>If you already know the folder:</p>
<pre><code>docker exec -it some-container ls /path/to/file
</code></pre>
<hr />
<p>EDIT:</p>
<p>as noted by @Konrad Botor it's possible to use also the container id instead of the container name and more importantly not all images have <code>bash</code> installed (alpine is the most popular image not using it).</p>
<p>Here's an example with alpine:</p>
<pre class="lang-sh prettyprint-override"><code>docker run -d \
--rm \
--name my_alpine_container \
alpine \
sleep 3600
CONTAINER_ID=$( docker ps -q my_alpine_container )
# to "enter" the container:
docker exec -it $CONTAINER_ID sh
</code></pre> |
30,005,331 | Java- how to clear graphics from a JPanel | <p>I'm creating a simple program where I draw a black oval where I click with my mouse. However I want a new oval to appear and the old one to disappear. How would I go about doing this? I've messed around with the removeAll() method inserted into my mousePressed method, however it isn't working for me. Is the removeAll() method even suitable for this? Or should I use something else? Sorry if the answer is obvious, but I am still new to this and trying to learn. Any advice would be immensely appreciated. Thanks. </p>
<pre><code>import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PaintPractice extends JPanel implements MouseListener {
Random rand = new Random();
int x = rand.nextInt(450);
int y = rand.nextInt(450);
public PaintPractice(){
super();
addMouseListener(this);
}
public static void main(String[] args){
JFrame frame = new JFrame();
PaintPractice panel = new PaintPractice();
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(panel);
}
public void paint(Graphics g){
g.setColor(Color.BLACK);
g.fillOval(x, y, 50, 50);
}
@Override
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
removeAll();
repaint();
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
}
</code></pre> | 30,005,776 | 5 | 1 | null | 2015-05-02 17:28:37.163 UTC | 0 | 2021-01-06 16:43:25.357 UTC | 2015-05-03 05:37:52.227 UTC | null | 418,556 | null | 4,857,246 | null | 1 | 6 | java|swing|jpanel|java-2d | 40,868 | <p>Immediate solution it to Just call <code>super.paint(g)</code> in the <code>paint(Graphics g)</code> method.</p>
<pre><code>public void paint(Graphics g){
super.paint(g);
g.setColor(Color.BLACK);
g.fillOval(x, y, 50, 50);
}
</code></pre>
<h1>The Paint Mechanism and why Should i override <code>paintComponent()</code> instead of overriding <code>paint()</code>:</h1>
<p>Javadoc explains <a href="http://docs.oracle.com/javase/tutorial/uiswing/painting/closer.html" rel="nofollow">the Paint Mechanism</a>:</p>
<blockquote>
<p>By now you know that the paintComponent method is where all of your
painting code should be placed. It is true that this method will be
invoked when it is time to paint, but painting actually begins higher
up the class heirarchy, with the paint method (defined by
java.awt.Component.) This method will be executed by the painting
subsystem whenever you component needs to be rendered. Its signature
is:</p>
<ul>
<li>public void paint(Graphics g)</li>
</ul>
<p>javax.swing.JComponent extends this class and further factors the
paint method into three separate methods, which are invoked in the
following order:</p>
<ul>
<li>protected void paintComponent(Graphics g)</li>
<li>protected void paintBorder(Graphics g)</li>
<li>protected void paintChildren(Graphics g)</li>
</ul>
<p>The API does nothing to prevent your code from overriding paintBorder
and paintChildren, <strong>but generally speaking, there is no reason for you
to do so. For all practical purposes paintComponent will be the only
method that you will ever need to override</strong>.</p>
</blockquote>
<p>This is why your <code>PaintPractice</code> code should invoke <code>super.paintComponent(g)</code> instead.</p>
<pre><code>public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillOval(x, y, 50, 50);
}
</code></pre>
<p>Also you don't need to call <code>removeAll()</code> in the <code>mousePressed(MouseEvent e)</code> method.</p>
<pre><code> @Override
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
</code></pre> |
25,803,923 | Check if a range of cells has any number bigger or smaller than 0 | <p>Is there a way to identify in column L if any of the cells between C and K contain a number greater or smaller than zero? </p>
<p>If yes it should return TRUE if not it should return FALSE. So in the example picture rows number 4 and 6 should return FALSE and rows number 1,2,5 should return TRUE. </p>
<p><img src="https://i.stack.imgur.com/SZg4T.png" alt="SO25803923 question example"></p> | 25,804,111 | 5 | 0 | null | 2014-09-12 08:29:15.917 UTC | 0 | 2015-06-28 10:13:38.403 UTC | 2014-09-12 08:52:13.733 UTC | null | 1,505,120 | null | 2,480,410 | null | 1 | 2 | excel|count|excel-formula | 42,952 | <p>In L2 you could use a formula like this:</p>
<pre><code>=IF(OR(C2<>0;D2<>0;E2<>0;F2<>0;G2<>0;H2<>0;I2<>0;J2<>0;K2<>0);TRUE;FALSE)
</code></pre>
<p>and then just drag it down. </p>
<p>It will Return TRUE if there is a Value uneven 0 otherwise it will return FALSE.</p> |
25,552,321 | OR and AND Operators in Elasticsearch query | <p>I have few json document with the following format :-</p>
<pre><code> _source: {
userId: "A1A1",
customerId: "C1",
component: "comp_1",
timestamp: 1408986553,
}
</code></pre>
<p>I want to query the document based on the following :-</p>
<pre><code>(( userId == currentUserId) OR ( customerId== currentCustomerId) OR (currentRole ==ADMIN) ) AND component= currentComponent)
</code></pre>
<p>I tried using the SearchSourceBuilder and QueryBuilders.matchQuery, but I wasnt able to put multiple sub queries with AND and OR operators.</p>
<pre><code>SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("userId",userId)).sort("timestamp", SortOrder.DESC).size(count);
</code></pre>
<p>How we query elasticsearch using OR and AND operators?</p> | 25,552,608 | 2 | 0 | null | 2014-08-28 15:13:33.523 UTC | 3 | 2021-09-23 09:30:32.073 UTC | 2021-01-04 23:01:33.74 UTC | null | 2,370,483 | null | 1,938,998 | null | 1 | 21 | java|elasticsearch|elasticsearch-jest | 39,626 | <p>I think in this case the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html" rel="noreferrer">Bool query</a> is the best shot.</p>
<p>Something like :</p>
<pre><code>{
"bool" : {
"must" : { "term" : { "component" : "comp_1" } },
"should" : [
{ "term" : { "userId" : "A1A1" } },
{ "term" : { "customerId" : "C1" } },
{ "term" : { "currentRole" : "ADMIN" } }
],
"minimum_should_match" : 1
}
}
</code></pre>
<p>Which gives in Java:</p>
<pre><code>QueryBuilder qb = QueryBuilders
.boolQuery()
.must(termQuery("component", currentComponent))
.should(termQuery("userId", currentUserId))
.should(termQuery("customerId", currentCustomerId))
.should(termQuery("currentRole", ADMIN))
.minimumNumberShouldMatch(1)
</code></pre>
<p>The <code>must</code> parts are <code>AND</code>s, the <code>should</code> parts are more or less <code>OR</code>s, except that you can specify a minimum number of <code>should</code>s to match (using <code>minimum_should_match</code>), this minimum being 1 by default I think (but you could set it to 0, meaning that a document matching no <code>should</code> condition would be returned as well).</p>
<p>If you want to do more complex queries involving nested <code>AND</code>s and <code>OR</code>s, simply nest other bool queries inside <code>must</code> or <code>should</code> parts.</p>
<p>Also, as you're looking for exact values (ids and so on), maybe you can use <a href="http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/term-vs-full-text.html" rel="noreferrer">term queries instead of match queries</a>, which spare you the analysis phase (if those fields are analyzed at all, which doesn't necessarily make sense for ids). If they are analyzed, you still can do that, but only if you know exactly how your terms are stored (<a href="https://www.found.no/foundation/beginner-troubleshooting/#why-isnt-my-search-returning-what-i-expect" rel="noreferrer">standard analyzer stores them lower cased for instance</a>).</p> |
48,572,831 | How to access the type arguments of typing.Generic? | <p>The <a href="https://docs.python.org/3/library/typing.html" rel="noreferrer"><code>typing</code></a> module provides a base class for generic type hints: The <a href="https://docs.python.org/3/library/typing.html#typing.Generic" rel="noreferrer"><code>typing.Generic</code></a> class.</p>
<p>Subclasses of <code>Generic</code> accept type arguments in square brackets, for example:</p>
<pre><code>list_of_ints = typing.List[int]
str_to_bool_dict = typing.Dict[str, bool]
</code></pre>
<hr>
<p>My question is, how can I access these type arguments?</p>
<p>That is, given <code>str_to_bool_dict</code> as input, how can I get <code>str</code> and <code>bool</code> as output?</p>
<p>Basically I'm looking for a function such that</p>
<pre><code>>>> magic_function(str_to_bool_dict)
(<class 'str'>, <class 'bool'>)
</code></pre> | 50,101,934 | 5 | 1 | null | 2018-02-01 22:31:34.553 UTC | 8 | 2021-09-20 16:20:47.61 UTC | null | null | null | null | 1,222,951 | null | 1 | 55 | python|generics | 27,048 | <h2>Python >= 3.8</h2>
<p>As of Python3.8 there is <code>typing.get_args</code>:</p>
<pre><code>print( get_args( List[int] ) ) # (<class 'int'>,)
</code></pre>
<p><a href="https://www.python.org/dev/peps/pep-0560/" rel="noreferrer">PEP-560</a> also provides <code>__orig_bases__[n]</code>, which allows us the arguments of the <em>n</em>th generic base:</p>
<pre><code>from typing import TypeVar, Generic, get_args
T = TypeVar( "T" )
class Base( Generic[T] ):
pass
class Derived( Base[int] ):
pass
print( get_args( Derived.__orig_bases__[0] ) ) # (<class 'int'>,)
</code></pre>
<hr />
<h2>Python >= 3.6</h2>
<p>As of Python 3.6. there is a public <code>__args__</code> and (<code>__parameters__</code>) field.
For instance:</p>
<pre><code>print( typing.List[int].__args__ )
</code></pre>
<p>This contains the generic parameters (i.e. <code>int</code>), whilst <code>__parameters__</code> contains the generic itself (i.e. <code>~T</code>).</p>
<hr />
<h2>Python < 3.6</h2>
<p>Use <a href="https://github.com/ilevkivskyi/typing_inspect" rel="noreferrer">typing_inspect.getargs</a></p>
<hr />
<h2>Some considerations</h2>
<p><code>typing</code> follows <a href="https://www.python.org/dev/peps/pep-0008/" rel="noreferrer">PEP8</a>. Both PEP8 and <code>typing</code> are coauthored by Guido van Rossum. A double leading and trailing underscore is defined in as: <em>"“magic” objects or attributes that live in <strong>user-controlled namespaces</strong>"</em>.</p>
<p>The dunders are also commented in-line; from the official repository for <a href="https://github.com/python/typing" rel="noreferrer">typing</a> we
can see:</p>
<ul>
<li><em>"<code>__args__</code> is a tuple of all arguments used in subscripting, e.g., <code>Dict[T, int].__args__ == (T, int)</code>".</em></li>
</ul>
<p>However, the <a href="https://github.com/python/typing/issues/480" rel="noreferrer">authors also note</a>:</p>
<ul>
<li><em>"The typing module has provisional status, so it is not covered by the high standards of backward compatibility (although we try to keep it as much as possible), this is especially true for (yet undocumented) dunder attributes like <code>__union_params__</code>. If you want to work with typing types in runtime context, then you may be interested in the <code>typing_inspect</code> project (part of which may end up in typing later)."</em></li>
</ul>
<p>I general, whatever you do with <code>typing</code> will need to be kept up-to-date for the time being. If you need forward compatible changes, I'd recommend writing your own annotation classes.</p> |
48,449,107 | How to exclude files ending in '.spec.ts' in tsconfig.json | <p>I'm trying to include some files in my tsconfig.json, but it's including files I don't want to be included. From a repo (with uncompiled source) I'm trying to include files that end in <code>.ts</code>, <em>except</em> for ones that end in <code>.spec.ts</code>.</p>
<p>The following includes the files I want, but doesn't successfully exclude the files I don't want.</p>
<pre><code> "include": ["node_modules/dashboard/**/*.ts"],
"exclude": ["node_modules/dashboard/**/*.spec.ts"],
</code></pre>
<p>(Then) new to Unix <strong>glob</strong> patterns/strings, I need ones to match and exclude the files correctly, and then how to add them to the config.</p> | 48,449,206 | 3 | 2 | null | 2018-01-25 17:53:54.12 UTC | 2 | 2021-07-29 22:49:57.283 UTC | 2021-07-29 22:49:57.283 UTC | null | 1,253,298 | null | 1,253,298 | null | 1 | 29 | javascript|angular|typescript | 30,872 | <p>The <a href="https://www.typescriptlang.org/docs/handbook/tsconfig-json.html" rel="noreferrer">TypeScript handbook has a good write up on tsconfig file</a>.</p>
<p>The example in the handbook is:</p>
<pre><code>"exclude": [
"node_modules",
"**/*.spec.ts"
]
</code></pre>
<p>Note the use of <code>**</code> for any folder, and <code>*</code> (a single asterisk) for the file name wildcard.</p>
<p>You don't usually need to be any more specific, as I imagine you would want to exclude "all spec files", not just files in a particular sub-directory.</p>
<h1>When This Won't Work</h1>
<p>There are cases when this won't work.</p>
<ol>
<li>If you have also include the file in both include and exclude sections - include wins</li>
<li>If you are importing the excluded file into an included file.</li>
<li>If you are using an old version of the compiler (early versions of tsconfig didn't allow the wildcards)</li>
<li>You are compiling using <code>tsc app.ts</code> (or pass other arguments) - your tsconfig is ignored when you do this</li>
</ol> |
43,297,589 | Merge two data frames based on common column values in Pandas | <p>How to get merged data frame from two data frames having common column value such that only those rows make merged data frame having common value in a particular column. </p>
<p>I have 5000 rows of <code>df1</code> as format : -</p>
<pre><code> director_name actor_1_name actor_2_name actor_3_name movie_title
0 James Cameron CCH Pounder Joel David Moore Wes Studi Avatar
1 Gore Verbinski Johnny Depp Orlando Bloom Jack Davenport Pirates
of the Caribbean: At World's End
2 Sam Mendes Christoph Waltz Rory Kinnear Stephanie Sigman Spectre
</code></pre>
<p>and 10000 rows of <code>df2</code> as</p>
<pre><code>movieId genres movie_title
1 Adventure|Animation|Children|Comedy|Fantasy Toy Story
2 Adventure|Children|Fantasy Jumanji
3 Comedy|Romance Grumpier Old Men
4 Comedy|Drama|Romance Waiting to Exhale
</code></pre>
<p>A common column 'movie_title' have common values and based on them, I want to get all rows where 'movie_title' is same. Other rows to be deleted.</p>
<p>Any help/suggestion would be appreciated. </p>
<p>Note: I already tried </p>
<pre><code>pd.merge(dfinal, df1, on='movie_title')
</code></pre>
<p>and output comes like one row </p>
<pre><code>director_name actor_1_name actor_2_name actor_3_name movie_title movieId title genres
</code></pre>
<p>and on how ="outer"/"left", "right", I tried all and didn't get any row after dropping NaN although many common coloumn do exist.</p> | 47,640,804 | 3 | 0 | null | 2017-04-08 16:32:34.823 UTC | 25 | 2022-03-19 03:46:23.347 UTC | 2017-04-08 16:47:24.003 UTC | null | 5,661,594 | null | 5,661,594 | null | 1 | 92 | pandas|dataframe | 179,622 | <p>We can merge two Data frames in several ways. Most common way in python is using merge operation in Pandas.</p>
<pre><code>import pandas
dfinal = df1.merge(df2, on="movie_title", how = 'inner')
</code></pre>
<p>For merging based on columns of different dataframe, you may specify left and right common column names specially in case of ambiguity of two different names of same column, lets say - <code>'movie_title'</code> as <code>'movie_name'</code>.</p>
<pre><code>dfinal = df1.merge(df2, how='inner', left_on='movie_title', right_on='movie_name')
</code></pre>
<p>If you want to be even more specific, you may read the documentation of pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="noreferrer"><code>merge</code></a> operation. </p> |
8,411,495 | Controller to Return an Error Message Instead of a View? | <p>I'm fairly new to ASP.NET MVC and am not sure how best to handle the following situation.</p>
<p>A method in my controller needs to load some data based on an ID argument. Under normal circumstances, this ID argument will be set to a valid ID of an entity within my database. I construct some data and place it in ViewBag, which the view uses to render the page.</p>
<p>However, I would like some basic error handling just in case the ID argument is <em>not</em> valid. Although I could write a bunch of error handling code in the view, it would be much simpler not to display the view if there is a major misuse or malfunction of the site.</p>
<p>Is there a way the controller could simply return a "Item not found" string or something like that, and display that rather than the normal view? Or perhaps someone can suggest a better idea?</p> | 8,411,525 | 4 | 0 | null | 2011-12-07 06:54:28.02 UTC | 2 | 2016-07-07 21:58:46.27 UTC | null | null | null | null | 522,663 | null | 1 | 11 | asp.net-mvc | 50,336 | <pre><code>if (itemId == null)
{
return Content("Item not found");
}
</code></pre>
<p>Or if you want to return an HTTP 404 instead:</p>
<pre><code>throw new HttpException(404, "Item Not Found");
</code></pre> |
8,678,362 | wait until wifi connected on android | <p>I have a small program that trying to connect to a wifi network.
It enables the wifi on the device then if it's the first time that is connect to the certain networkss It loads the device wifi in order to select and add the password for connection.
Until I add the password in order to connect the program should not be finished.
How can I add something to wait until I get from the wifi manager that is connected?
I try sleep but it freeze the application and am not getting the wifi pop up menu to connect?
are there any other ways?</p> | 8,679,706 | 1 | 0 | null | 2011-12-30 10:11:13.39 UTC | 10 | 2016-11-29 07:15:26.593 UTC | 2011-12-30 10:55:19.027 UTC | null | 633,239 | null | 1,041,204 | null | 1 | 17 | java|android|wifi | 19,291 | <p>I have found the solution for your problem a month ago, just use Thread put method isConnected() in it. <br>In this case, I use WifiExplorerActivity to display all wifi network and allow user connect to it.</p>
<pre><code> Thread t = new Thread() {
@Override
public void run() {
try {
//check if connected!
while (!isConnected(WifiExplorerActivity.this)) {
//Wait to connect
Thread.sleep(1000);
}
Intent i = new Intent(WifiExplorerActivity.this, MainActivity.class);
startActivity(i);
} catch (Exception e) {
}
}
};
t.start();
</code></pre>
<p>And this is function to check wifi has connected or not:</p>
<pre><code> public static boolean isConnected(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = null;
if (connectivityManager != null) {
networkInfo = connectivityManager.getActiveNetworkInfo();
}
return networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED;
}
</code></pre>
<p>Finally, make sure your Androidmanifest.xml look like this:</p>
<pre><code> <activity android:name=".WifiExplorerActivity" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</activity>
</code></pre>
<p>Also, you can use ProgressDialog to wait connect. See <a href="http://developer.android.com/guide/topics/ui/dialogs.html" rel="noreferrer">http://developer.android.com/guide/topics/ui/dialogs.html</a></p> |
8,528,681 | Where is the socket.io client library? | <p>As far as I have seen, there is no explanation as to where we are to locate the client side script for <code>socket.io</code> if <code>node.js</code> is not used as the web server. I've found a whole directory of client side files, but I need them in a combined version (like it's served when using node.js webs servers). Any ideas?</p> | 8,529,264 | 8 | 0 | null | 2011-12-16 01:07:53.027 UTC | 8 | 2017-06-02 08:33:18.87 UTC | 2015-03-06 09:31:03.453 UTC | null | 858,775 | null | 858,775 | null | 1 | 76 | node.js|client|socket.io | 39,734 | <p>socket.io.js is what you're going to put into your client-side html. Something like:</p>
<pre><code><script type="text/javascript" src="socket.io.js"></script>
</code></pre>
<p>my script is located:</p>
<pre><code>/usr/local/lib/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js
</code></pre>
<p>copy that file to where you want your server to serve it.</p> |
30,560,470 | context in nested serializers django rest framework | <p>If i have a nested serializer:</p>
<pre><code>class ChildSerializer(ModelSerializer):
class Meta:
fields = ('c_name', )
model = Child
class ParentSerializer(ModelSerializer):
child = ChildSerializer(many=True, read_only=True)
class Meta:
model = Parent
fields = ('p_name', 'child')
</code></pre>
<p>And i want to access the context in the nested serializer, how can i do that? As far as i can tell, context isn't passed to the Child. </p>
<p>I want to be able to implement a permission model per user on fields, for that i overridden the get_fields() method of the ModelSerializer:</p>
<pre><code>def get_fields(self):
fields = super().get_fields()
....
for f in fields:
if has_rights(self.context['request'].user, f, "read"):
ret_val[f] = fields[f]
....
return ret_val
</code></pre>
<p>Which works for regular serializers, but the context, and thus the request and user are not available when the nested child is passed to get_fields(). How do i access the context when the serializer is nested?</p> | 30,568,323 | 7 | 0 | null | 2015-05-31 17:33:46.327 UTC | 2 | 2022-04-07 10:00:23.547 UTC | null | null | null | null | 10,617,218 | null | 1 | 48 | django|python-3.x|serialization|django-rest-framework | 16,004 | <p>Ok i found a working solution. I replaced the ChildSerializer assignment in the Parent class with a SerializerMethodField which adds the context. This is then passed to the get_fields method in my CustomModelSerializer:</p>
<pre><code>class ChildSerializer(CustomModelSerializer):
class Meta:
fields = ('c_name', )
model = Child
class ParentSerializer(CustomModelSerializer):
child = serializers.SerializerMethodField('get_child_serializer')
class Meta:
model = Parent
fields = ('p_name', 'child')
def get_child_serializer(self, obj):
serializer_context = {'request': self.context.get('request') }
children = Child.objects.all().filter(parent=obj)
serializer = ChildSerializer(children, many=True, context=serializer_context)
return serializer.data
</code></pre>
<p>and in my CustomModelSerializer:</p>
<pre><code>class CustomModelSerializer(rest_serializer_classes.HyperlinkedModelSerializer):
def __init__(self, *args, **kwargs):
"""
Make sure a user is coupled to the serializer (needed for permissions)
"""
super().__init__(*args, **kwargs)
if not self.context:
self._context = getattr(self.Meta, 'context', {})
try:
self.user = self.context['request'].user
except KeyError:
self.user = None
def get_fields(self):
ret = OrderedDict()
if not self.user:
print("No user associated with object")
return ret
fields = super().get_fields()
# Bypass permission if superuser
if self.user.is_superuser:
return fields
for f in fields:
if has_right(self.user, self.Meta.model.__name__.lower(), f, "read"):
ret[f] = fields[f]
return ret
</code></pre>
<p>This seems to work fine, and fields of the child are discarded in the serializer when i either revoke read-rights on <em>Child.c_name</em> or on <em>Parent.child</em></p> |
534,511 | JavaScript/jQuery - offsetLeft and offsetTop | <p>When hovering over a span I would like to get the offsetLeft and offsetTop values so I can make something hover near it. When I do this I get 0 for both values. </p>
<p>What is a better way to tackle this? I am using jQuery. </p>
<p>Assume I am starting with (looped by server-side scripting):</p>
<pre><code><span onmouseover="hoverNearMe(this.offsetLeft,this.offsetTop);">some username</span><br />
</code></pre>
<p><strong>FINAL THOUGHTS:</strong><br>
I'm giving the the answer rep out based on "code leverage"/DRY.
The longer function you could use over and over in your own js library.
The second short answer however is 100% correct too.</p> | 534,526 | 3 | 0 | null | 2009-02-10 22:30:17.77 UTC | 7 | 2013-10-16 17:38:05.373 UTC | 2013-10-16 17:38:05.373 UTC | Bruno Tyndall | 246,246 | Bruno Tyndall | 36,590 | null | 1 | 4 | javascript|jquery | 43,574 | <p>I think you should be able to do this:</p>
<p><strong>HTML</strong></p>
<pre><code><span class="get-close-to">some username</span><br />
</code></pre>
<p><strong>jQuery</strong></p>
<pre><code>jQuery('.get-close-to').hover(function() {
var offset = jQuery(this).css('offset');
alert( 'Left: ' + offset.left + '\nTop: ' + offset.top );
});
</code></pre> |
743,549 | How to put image in a picture box from Bitmap | <p>Is it possible to load a picture from memory (<code>byte[]</code> or <code>stream</code> or <code>Bitmap</code>) without saving it to disk?</p>
<p>This is the code I use to turn the <code>byte[]</code> array into a <code>Bitmap</code>:</p>
<pre><code>unsafe
{
fixed (byte* ptr = Misc.ConvertFromUInt32Array(image))
{
Bitmap bmp = new Bitmap(200, 64, 800, PixelFormat.Format32bppRgb, new IntPtr(ptr));
bmp.RotateFlip(RotateFlipType.Rotate180FlipX);
bmp.MakeTransparent(Color.Black);
bmp.Save("test.bmp");
}
}
</code></pre>
<p>Instead of using <code>Bmp.save()</code>, can I put the <code>Bitmap</code> in the picture box on my form?</p> | 743,590 | 3 | 0 | null | 2009-04-13 10:30:20.123 UTC | 2 | 2017-07-30 19:30:42.463 UTC | 2017-07-30 19:30:42.463 UTC | null | 493,729 | null | 81,800 | null | 1 | 24 | c#|bitmap|image | 93,839 | <p>Have you tried this?</p>
<pre><code>pictureBox.Image = bmp;
</code></pre> |
750,765 | Concurrency in a GIT repo on a network shared folder | <p>I want to have a bare git repository stored on a (windows) network share. I use linux, and have the said network share mounted with CIFS. My coleague uses windows xp, and has the network share automounted (from ActiveDirectory, somehow) as a network drive.</p>
<p>I wonder if I can use the repo from both computers, without concurrency problems. </p>
<p>I've already tested, and on my end I can clone ok, but I'm afraid of what might happen if we both access the same repo (push/pull), at the same time.</p>
<p>In the git FAQ there is a reference about using network file systems (and some problems with SMBFS), but I am not sure if there is any file locking done by the network/server/windows/linux - i'm quite sure there isn't.</p>
<p>So, has anyone used a git repo on a network share, without a server, and without problems?</p>
<p>Thank you,<br/>
Alex</p>
<p>PS: I want to avoid using an http server (or the git-daemon), because I do not have access to the server with the shares. Also, I know we can just push/pull from one to another, but we are required to have the code/repo on the share for back-up reasons.</p>
<p><b>Update:</b><br /><br />
My worries are not about the possibility of a network failure. Even so, we would have the required branches locally, and we'll be able to compile our sources.</p>
<p>But, we usually commit quite often, and need to rebase/merge often. From my point of view, the best option would be to have a central repo on the share (so the backups are assured), and we would both clone from that one, and use it to rebase.</p>
<p>But, due to the fact we are doing this often, I am afraid about <b>file/repo corruption</b>, if it happens that we both push/pull at the same time. Normally, we could <i>yell</i> at each other each time we access the remote repo :), but it would be better to have it secured by the computers/network.</p>
<p>And, it is possible that GIT has an internal mechanism to do this (since someone can push to one of your repos, while you work on it), but I haven't found anything conclusive yet.</p>
<p><b>Update 2:</b><br /><br />
The repo on the share drive would be a <b>bare</b> repo, not containing a working copy.</p> | 751,026 | 3 | 3 | null | 2009-04-15 08:21:38.403 UTC | 14 | 2009-11-10 17:20:28.053 UTC | 2009-04-15 09:50:33.853 UTC | null | 73,593 | null | 73,593 | null | 1 | 52 | windows|linux|git|concurrency|network-share | 14,637 | <p>Git requires minimal file locking, which I believe is the main cause of problems when using this kind of shared resource over a network file system. The reason it can get away with this is that most of the files in a Git repo--- all the ones that form the object database--- are named as a digest of their content, and immutable once created. So there the problem of two clients trying to use the same file for different content doesn't come up.</p>
<p>The other part of the object database is trickier-- the refs are stored in files under the "refs" directory (or in "packed-refs") and these do change: although the <code>refs/*</code> files are small and always rewritten rather than being edited. In this case, Git writes the new ref to a temporary ".lock" file and then renames it over the target file. If the filesystem respects <code>O_EXCL</code> semantics, that's safe. Even if not, the worst that could happen would be a race overwriting a ref file. Although this would be annoying to encounter, it should not cause corruption as such: it just might be the case that you push to the shared repo, and that push looks like it succeeded whereas in fact someone else's did. But this could be sorted out simply by pulling (merging in the other guy's commits) and pushing again.</p>
<p>In summary, I don't think that repo corruption is too much of a problem here--- it's true that things can go a bit wrong due to locking problems, but the design of the Git repo will minimise the damage.</p>
<p>(Disclaimer: this all sounds good in theory, but I've not done any concurrent hammering of a repo to test it out, and only share them over NFS not CIFS)</p> |
1,072,784 | How can I convert a Java Iterable to a Scala Iterable? | <p>Is there an easy way to convert a </p>
<pre><code>java.lang.Iterable[_]
</code></pre>
<p>to a</p>
<pre><code>Scala.Iterable[_]
</code></pre>
<p>? </p> | 8,087,609 | 3 | 0 | null | 2009-07-02 06:24:44.827 UTC | 16 | 2019-06-30 10:38:01.277 UTC | 2013-06-22 12:10:35.43 UTC | null | 298,389 | null | 61,298 | null | 1 | 59 | scala|scala-java-interop | 23,021 | <p>In Scala 2.8 this became much much easier, and there are two ways to achieve it. One that's sort of explicit (although it <em>uses</em> implicits):</p>
<pre><code>import scala.collection.JavaConverters._
val myJavaIterable = someExpr()
val myScalaIterable = myJavaIterable.asScala
</code></pre>
<p><em>EDIT:</em> Since I wrote this, the Scala community has arrived at a broad consensus that <code>JavaConverters</code> is good, and <code>JavaConversions</code> is bad, because of the potential for spooky-action-at-a-distance. So don't use <code>JavaConversions</code> at all!</p>
<hr>
<p><strike>And one that's more like an implicit implicit: :)</p>
<pre><code>import scala.collection.JavaConversions._
val myJavaIterable = someExpr()
for (magicValue <- myJavaIterable) yield doStuffWith(magicValue)
</code></pre>
<p></strike></p> |
22,332,031 | Composer: The requested PHP extension ext-intl * is missing from your system | <p>I am trying to use <code>composer.json</code> file. but, when I am trying to run command '<code>composer install</code>' in my <code>path/project/</code>, I am getting an error:</p>
<p><img src="https://i.stack.imgur.com/RyHbc.jpg" alt="enter image description here"></p>
<p>I have already configured my <code>wamp</code> for '<code>extension=php_intl.dll</code>' and copied all <code>icu*.dll</code> in '<code>D:\wamp\bin\apache\apache2.2.22\bin</code>' from '<code>D:\wamp\bin\php\php5.3.13</code>' and it's showing in <code>phpinfo()</code>:</p>
<p><img src="https://i.stack.imgur.com/H0QPs.jpg" alt="enter image description here"></p>
<p>without copy <code>icu*.dll</code> also works and showing in <code>phpinfo()</code>;</p>
<p>Kindly, let me know if I have <strong><code>intl</code></strong> install on my <strong><code>wamp</code></strong> and <strong><code>composer install</code></strong> on my pc then why I am getting this error. really, it is so annoying.</p>
<p>Here is my details:</p>
<ol>
<li>OS: windows 7 (64)</li>
<li>PHP: 5.3.13</li>
<li>Apache:2.2.22</li>
<li>Composer: installed by executable file</li>
<li>Pear: installed (latest)</li>
<li>PHPUnit: installed (latest)</li>
</ol>
<p>My <strong><code>composer.json</code></strong> is as below:</p>
<pre><code>{
"name" : "sebastian/money",
"description" : "Value Object that represents a monetary value (using a currency's smallest unit)",
"keywords" : ["money"],
"homepage" : "http://www.github.com/sebastianbergmann/money",
"license" : "BSD-3-Clause",
"authors" : [{
"name" : "Sebastian Bergmann",
"email" : "[email protected]"
}
],
"require" : {
"php" : ">=5.3.3",
"ext-intl" : "*"
},
"require-dev" : {
"phpunit/phpunit" : "~4.0"
},
"autoload" : {
"classmap" : [
"src/"
]
},
"extra" : {
"branch-alias" : {
"dev-master" : "1.3.x-dev"
}
}
}
</code></pre>
<p>Let me know if any other details is required..</p>
<p>Any feedback/help would be highly appreciated. </p> | 22,345,369 | 11 | 0 | null | 2014-03-11 17:22:02.947 UTC | 20 | 2022-08-09 15:32:46.827 UTC | null | null | null | null | 584,262 | null | 1 | 108 | composer-php | 270,700 | <p>PHP uses a different php.ini for command line php than for the web/apache php. So you see the intl extension in phpinfo() in the browser, but if you run <code>php -m</code> in the command line you might see that the list of extensions there does not include intl.</p>
<p>You can check using <code>php -i</code> on top of the output it should tell you where the ini file is loaded from. Make sure you enable the intl extension in that ini file and you should be good to go.</p>
<p>For php.ini 5.6 version (check version using php -v)</p>
<pre><code>;extension=php_intl.dll
; remove semicolon
extension=php_intl.dll
</code></pre>
<p>For php.ini 7.* version</p>
<pre><code>;extension=intl
; remove semicolon
extension=intl
</code></pre> |
22,294,128 | How can I Get Google Map Api v3 key? | <p>I'm trying to get the Google Maps API v3 key. I read a lot of tutorials all are about Google Map API V3 but when go to Google API console and in services I did not get this API. However, Google Map javascript API V3 is lies there but it gives the client ID not the API key.</p>
<p><img src="https://i.stack.imgur.com/e1v62.png" alt="enter image description here"></p>
<p>Kindly guide me how can i get it?</p> | 22,294,670 | 2 | 0 | null | 2014-03-10 07:14:58.543 UTC | 3 | 2017-06-13 05:37:49.32 UTC | 2014-03-10 09:47:41.22 UTC | null | 492,335 | null | 1,017,742 | null | 1 | 11 | google-maps-api-3 | 87,485 | <p>Have you seen <a href="https://developers.google.com/maps/documentation/javascript/tutorial" rel="nofollow noreferrer">this link</a> ?</p>
<blockquote>
<ul>
<li>Visit the APIs Console at <a href="https://code.google.com/apis/console" rel="nofollow noreferrer">https://code.google.com/apis/console</a> and log in with your Google Account.</li>
<li>Click the Services link from the left-hand menu.</li>
<li>Activate the Google Maps API v3 service.</li>
<li>Click the API Access link from the left-hand menu. Your API key is available from the API Access page, in the Simple API Access section. Maps API applications use the Key for browser apps.</li>
</ul>
</blockquote>
<p>Then you have to use it in your webpages with </p>
<pre><code><script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</code></pre>
<p></p>
<p>And replace <code>YOUR_API_KEY</code> by the API key you just generated.
Here, <code>initMap</code> is the name of the method executed once GoogleMaps is fully loaded ; you can remove or rename this parameter depending what you need</p>
<p>Do you experience any issue with this step-by-step ? It worked for me.</p> |
6,759,399 | Rails i18n: How to know what is the current language? | <p>I am aware of how i18n/l10n is usually done in Rails3, and I chose to have a single ERB file that calls <code>t(...)</code> for localization. But for a particular part I need something special:</p>
<p>I need to display a string whose <b>localization is coming from an external database</b>.</p>
<p>So how can I know the current language, to call the external database with an <code>en</code> or <code>ja</code> parameter?</p>
<p>Something like $LANG in UNIX. Preferably accessible from view or controller.</p> | 6,759,450 | 1 | 0 | null | 2011-07-20 09:01:08.167 UTC | 7 | 2011-07-20 09:05:43.247 UTC | null | null | null | null | 226,958 | null | 1 | 59 | ruby-on-rails-3|internationalization | 32,027 | <pre><code>I18n.locale # Get and set the current locale
</code></pre> |
28,703,093 | What exactly is the difference between Web API and REST API in MVC? | <p>I have a little understanding on REST API. As per my knowledge it is used to work with HTTP services (GET, POST, PUT, DELETE).</p>
<p>When I add a Web API controller it provides me some basic methods like :</p>
<pre><code> public class Default1Controller : ApiController
{
// GET api/default1
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/default1/5
public string Get(int id)
{
return "value";
}
// POST api/default1
public void Post([FromBody]string value)
{
}
// PUT api/default1/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/default1/5
public void Delete(int id)
{
}
}
</code></pre>
<p>So my question is: what's the difference between a Web API and a REST API?</p>
<p>By the definition of REST, the above code is REST based so what's a normal Web API in MVC? I'm a bit confused as some people say you use a Web API with REST?</p>
<p>Kindly provide a better understanding of them both.</p> | 41,898,108 | 2 | 1 | null | 2015-02-24 18:07:47.033 UTC | 36 | 2022-01-11 14:31:39.11 UTC | 2021-05-04 20:15:07.397 UTC | null | 16,299 | null | 4,136,094 | null | 1 | 58 | c#|asp.net-web-api|model-view-controller|rest | 144,624 | <p>I have been there, like so many of us. There are so many confusing words like Web API, REST, RESTful, HTTP, SOAP, WCF, Web Services... and many more around this topic. But I am going to give brief explanation of only those which you have asked.</p>
<h2>REST</h2>
<p>It is neither an API nor a framework. It is just an architectural concept. You can find more details <a href="https://en.wikipedia.org/wiki/Representational_state_transfer" rel="noreferrer">here</a> or tutorials here <a href="https://restfulapi.net/" rel="noreferrer">https://restfulapi.net/</a></p>
<h2>RESTful</h2>
<p>I have not come across any formal definition of RESTful anywhere. I believe it is just another buzzword for APIs to say if they comply with <a href="https://www.rfc-editor.org/rfc/rfc7231" rel="noreferrer">REST specifications</a>.</p>
<p>EDIT: There is another trending open source initiative <a href="https://www.openapis.org/" rel="noreferrer">OpenAPI Specification (OAS)</a> (formerly known as Swagger) to standardise REST APIs.</p>
<h2>Web API</h2>
<p>It in an open source framework for writing HTTP APIs. These APIs can be RESTful or not. Most HTTP APIs we write are not RESTful. This framework implements HTTP protocol specification and hence you hear terms like URIs, request/response headers, caching, versioning, various content types(formats).</p>
<p>Note: I have not used the term Web Services deliberately because it is a confusing term to use. Some people use this as a generic concept, I preferred to call them HTTP APIs. There is an actual framework named 'Web Services' by Microsoft like Web API. However it implements another protocol called SOAP.</p> |
28,506,907 | How to make matplotlib show all x coordinates? | <p>For example in the following code:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
N = 10
x = [1,2,3,4,5,6,7,8,9,10]
y = np.random.rand(N)
plt.scatter(x, y)
plt.show()
</code></pre>
<p>I get the following plot</p>
<p><img src="https://i.stack.imgur.com/ayvse.png" alt="enter image description here"></p>
<p>as you can see, in the x axis only the even values appear. How to force matplotlib to show all values, that is 1 2 3 4 5 6 7 8 9 10?</p> | 28,506,982 | 1 | 2 | null | 2015-02-13 19:07:11.453 UTC | 2 | 2019-06-06 19:19:37.883 UTC | null | null | null | null | 4,038,196 | null | 1 | 37 | python|matplotlib | 80,418 | <p>Use <code>plt.xticks(x)</code>. See <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xticks" rel="noreferrer">the documentation</a>.</p>
<p>Note that using only the input values for ticks will usually be confusing to a viewer. It makes more sense to use evenly spaced ticks.</p> |
42,773,714 | Is async await truly non-blocking in the browser? | <p>I have been playing around with the feature in an SPA using TypeScript and native Promises, and I notice that even if I refactor a long-running function into an async function returning a promise, the UI is still unresponsive.</p>
<p>So my questions are:</p>
<ul>
<li><p>How exactly does the new async/await feature help avoid blocking the UI in the browser? Are there any special extra steps one needs to take when using async/await to actually get a responsive UI?</p></li>
<li><p>Can someone create a fiddle to demonstrate the how async/await helps to make the UI responsive?</p></li>
<li><p>How does async/await relate to prior async features such as setTimeout and XmlHttpRequest?</p></li>
</ul> | 42,800,542 | 5 | 2 | null | 2017-03-13 21:26:31.037 UTC | 32 | 2021-07-09 02:34:46.133 UTC | 2017-03-16 06:18:55.61 UTC | null | 218,196 | null | 761,861 | null | 1 | 64 | javascript|user-interface|asynchronous|async-await|ecmascript-2017 | 40,025 | <p><code>await p</code> schedules execution of the rest of your function when promise <code>p</code> resolves. That's all.</p>
<p><code>async</code> lets you use <code>await</code>. That's (almost) all it does (It also wraps your result in a promise).</p>
<p>Together they make non-blocking code read like simpler blocking code. They don't unblock code.</p>
<p>For a responsive UI, offload CPU-intensive work to a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API" rel="noreferrer">worker</a> thread, and pass messages to it:</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>async function brutePrime(n) {
function work({data}) {
while (true) {
let d = 2;
for (; d < data; d++) {
if (data % d == 0) break;
}
if (d == data) return self.postMessage(data);
data++;
}
}
let b = new Blob(["onmessage =" + work.toString()], {type: "text/javascript"});
let worker = new Worker(URL.createObjectURL(b));
worker.postMessage(n);
return await new Promise(resolve => worker.onmessage = e => resolve(e.data));
}
(async () => {
let n = 700000000;
for (let i = 0; i < 10; i++) {
console.log(n = await brutePrime(n + 1));
}
})().catch(e => console.log(e));</code></pre>
</div>
</div>
</p> |
6,238,074 | How the right associative of null coalescing operator behaves? | <blockquote>
<p>null coalescing operator is right associative, which means an expression of the form </p>
<p><strong>first ?? second ??third</strong> </p>
<p>is evaluated as </p>
<p><strong>first ?? (second ?? third)</strong></p>
</blockquote>
<p>Based on the above rule, I think the following translation is not correct.</p>
<p><strong>From:</strong></p>
<pre><code>Address contact = user.ContactAddress;
if (contact == null)
{
contact = order.ShippingAddress;
if (contact == null)
{
contact = user.BillingAddress;
}
}
</code></pre>
<p><strong>To:</strong></p>
<pre><code>Address contact = user.ContactAddress ??
order.ShippingAddress ??
user.BillingAddress;
</code></pre>
<p>Instead, I think the following is right one (Please correct me if I am wrong)</p>
<pre><code>Address contact = (user.ContactAddress ?? order.ShippingAddress) ??
user.BillingAddress;
</code></pre> | 6,238,365 | 4 | 1 | null | 2011-06-04 16:53:25.36 UTC | 8 | 2019-05-12 15:47:26.067 UTC | null | null | null | null | 391,104 | null | 1 | 31 | c# | 3,042 | <p>The spec is actually self-contradictory on this one.</p>
<p>Section 7.13 of the C# 4 spec states:</p>
<blockquote>
<p>The null coalescing operator is right-associative, meaning that operations are grouped from right to left. For example, an expression of the form <code>a ?? b ?? c</code> is evaluated as <code>a ?? (b ?? c)</code>.</p>
</blockquote>
<p>On the other hand, as has been pointed out, 7.3.1 claims that:</p>
<blockquote>
<p>Except for the assignment operators, all binary operators are left-associative</p>
</blockquote>
<p>I entirely agree that for simple cases it doesn't matter how you do the grouping... but there <em>may</em> be cases where it really matters due to implicit type conversions doing interesting things if the operands have different types.</p>
<p>I'll consider it further, ping Mads and Eric, and add an erratum for the relevant section of C# in Depth (which inspired this question).</p>
<p>EDIT: Okay, I've now got an example where it <em>does</em> matter... and the null coalescing operator is definitely <em>right</em>-associative, at least in the MS C# 4 compiler. Code:</p>
<pre><code>using System;
public struct Foo
{
public static implicit operator Bar(Foo input)
{
Console.WriteLine("Foo to Bar");
return new Bar();
}
public static implicit operator Baz(Foo input)
{
Console.WriteLine("Foo to Baz");
return new Baz();
}
}
public struct Bar
{
public static implicit operator Baz(Bar input)
{
Console.WriteLine("Bar to Baz");
return new Baz();
}
}
public struct Baz
{
}
class Test
{
static void Main()
{
Foo? x = new Foo();
Bar? y = new Bar();
Baz? z = new Baz();
Console.WriteLine("Unbracketed:");
Baz? a = x ?? y ?? z;
Console.WriteLine("Grouped to the left:");
Baz? b = (x ?? y) ?? z;
Console.WriteLine("Grouped to the right:");
Baz? c = x ?? (y ?? z);
}
}
</code></pre>
<p>Output:</p>
<pre><code>Unbracketed:
Foo to Baz
Grouped to the left:
Foo to Bar
Foo to Bar
Bar to Baz
Grouped to the right:
Foo to Baz
</code></pre>
<p>In other words,</p>
<pre><code>x ?? y ?? z
</code></pre>
<p>behaves the same as</p>
<pre><code>x ?? (y ?? z)
</code></pre>
<p>but <em>not</em> the same as</p>
<pre><code>(x ?? y) ?? z
</code></pre>
<p>I'm not currently sure why there are <em>two</em> conversions from Foo to Bar when using <code>(x ?? y) ?? z</code> - I need to check that out more carefully...</p>
<p>EDIT: I now have <a href="https://stackoverflow.com/questions/6256847">another question</a> to cover the double conversion...</p> |
5,612,201 | Haskell library for 2D drawing | <p>I basically want to create a full screen window and draw text on it in different colors and sizes (and also update the screen). I've used pygame for this in python and I'm looking for a similar library (should be fairly easy to use).</p>
<p>+1 if it handles input too...</p> | 5,613,257 | 4 | 7 | null | 2011-04-10 13:56:04.087 UTC | 33 | 2017-07-24 16:56:55.917 UTC | 2011-04-16 19:17:02.03 UTC | null | 83,805 | null | 71,976 | null | 1 | 40 | graphics|haskell|sdl | 22,335 | <p>If you're looking for a specialized game library, you have a number of options that you can find <a href="http://www.haskell.org/haskellwiki/Applications_and_libraries/Games" rel="noreferrer">here</a>. <a href="http://hackage.haskell.org/package/FunGEn" rel="noreferrer">FunGEn</a> is probably your best option out of those libraries. However, your question seems to suggest a game library would be a bit overkill, if all you're looking to do is draw text and receive input. In that case, you might opt for something simpler like <a href="http://www.haskell.org/haskellwiki/Opengl" rel="noreferrer">HOpenGL</a> or <a href="http://www.haskell.org/haskellwiki/SDL" rel="noreferrer">hsSDL</a>. There are also several other libraries listed <a href="http://www.haskell.org/haskellwiki/Applications_and_libraries/Graphics" rel="noreferrer">here</a>.</p>
<p>Edit: After a bit more research, you might do well using <a href="http://hackage.haskell.org/package/haskgame" rel="noreferrer">haskgame</a>. I've never used it myself, but it looks like it's got a few functions <a href="http://hackage.haskell.org/packages/archive/haskgame/0.0.6/doc/html/Graphics-UI-HaskGame-Font.html" rel="noreferrer">here</a> that do exactly what you're looking for.</p> |
2,187,484 | Why is the ELF execution entry point virtual address of the form 0x80xxxxx and not zero 0x0? | <p>When executed, program will start running from virtual address 0x80482c0. This address doesn't point to our <code>main()</code> procedure, but to a procedure named <code>_start</code> which is created by the linker.</p>
<p>My Google research so far just led me to some (vague) historical speculations like this:</p>
<blockquote>
<p>There is folklore that 0x08048000 once was STACK_TOP (that is, the stack grew downwards from near 0x08048000 towards 0) on a port of *NIX to i386 that was promulgated by a group from Santa Cruz, California. This was when 128MB of RAM was expensive, and 4GB of RAM was unthinkable.</p>
</blockquote>
<p>Can anyone confirm/deny this?</p> | 2,187,753 | 2 | 2 | null | 2010-02-02 20:33:57.533 UTC | 17 | 2020-12-28 09:29:47.103 UTC | 2017-08-30 13:34:38.95 UTC | null | 1,685,157 | null | 264,704 | null | 1 | 26 | point|elf|virtual-address-space | 15,120 | <p>As Mads pointed out, in order to catch most accesses through null pointers, Unix-like systems tend to make the page at address zero "unmapped". Thus, accesses immediately trigger a CPU exception, in other words a segfault. This is quite better than letting the application go rogue. The exception vector table, however, can be at any address, at least on x86 processors (there is a special register for that, loaded with the <code>lidt</code> opcode).</p>
<p>The starting point address is part of a set of conventions which describe how memory is laid out. The linker, when it produces an executable binary, must know these conventions, so they are not likely to change. Basically, for Linux, the memory layout conventions are inherited from the very first versions of Linux, in the early 90's. A process must have access to several areas:</p>
<ul>
<li>The code must be in a range which includes the starting point.</li>
<li>There must be a stack.</li>
<li>There must be a heap, with a limit which is increased with the <code>brk()</code> and <code>sbrk()</code> system calls.</li>
<li>There must be some room for <code>mmap()</code> system calls, including shared library loading.</li>
</ul>
<p>Nowadays, the heap, where <code>malloc()</code> goes, is backed by <code>mmap()</code> calls which obtain chunks of memory at whatever address the kernel sees fit. But in older times, Linux was like previous Unix-like systems, and its heap required a big area in one uninterrupted chunk, which could grow towards increasing addresses. So whatever was the convention, it had to stuff code and stack towards low addresses, and give every chunk of the address space after a given point to the heap.</p>
<p>But there is also the stack, which is usually quite small but could grow quite dramatically in some occasions. The stack grows down, and when the stack is full, we really want the process to predictably crash rather than overwriting some data. So there had to be a wide area for the stack, with, at the low end of that area, an unmapped page. And lo! There is an unmapped page at address zero, to catch null pointer dereferences. Hence it was defined that the stack would get the first 128 MB of address space, except for the first page. This means that the code had to go after those 128 MB, at an address similar to 0x080xxxxx.</p>
<p>As Michael points out, "losing" 128 MB of address space was no big deal because the address space was very large with regards to what could be actually used. At that time, the Linux kernel was limiting the address space for a single process to 1 GB, over a maximum of 4 GB allowed by the hardware, and that was not considered to be a big issue.</p> |
2,044,565 | Volatile Struct Semantics | <p>Is it sufficient to declare an instance of a structure-typed variable as volatile (if its fields are accessed in re-entrant code), or must one declare specific fields of the structure as volatile?</p>
<p>Phrased differently, what are the semantic differences (if any) between:</p>
<pre><code>typdef struct {
uint8_t bar;
} foo_t;
volatile foo_t foo_inst;
</code></pre>
<p>and </p>
<pre><code>typedef struct{
volatile uint8_t bar;
} foo_t;
foo_t foo_inst;
</code></pre>
<p>I recognize that declaring a pointer-typed variable as volatile (e.g. volatile uint8_t * foo) merely informs the compiler that the address pointed-to by foo may change, while making no statement about the values pointed to by foo. It is unclear to me whether an analogy holds for structure-typed variables.</p> | 2,044,608 | 2 | 1 | null | 2010-01-11 20:05:04.16 UTC | 21 | 2016-01-07 19:10:29.02 UTC | null | null | null | null | 212,215 | null | 1 | 83 | c|struct|volatile | 41,224 | <p>In your example, the two are the same. But the issues revolve around pointers.</p>
<p>First off, <code>volatile uint8_t *foo;</code> tells the compiler the memory being pointed to is volatile. If you want to mark the pointer itself as volatile, you would need to do <code>uint8_t * volatile foo;</code></p>
<p>And that is where you get to the main differences between marking the struct as volatile vs marking individual fields. If you had:</p>
<pre><code>typedef struct
{
uint8_t *field;
} foo;
volatile foo f;
</code></pre>
<p>That would act like:</p>
<pre><code>typedef struct
{
uint8_t * volatile field;
} foo;
</code></pre>
<p>and not like:</p>
<pre><code>typedef struct
{
volatile uint8_t *field;
} foo;
</code></pre> |
5,736,417 | Ruby Dropped in Netbeans 7,How to Use it in Netbeans7? | <p>In Netbeans 7, Ruby support was dropped:</p>
<blockquote>
<p>Although our Ruby support has
historically been well received, based
on existing low usage trends we are
unable to justify the continued
allocation of resources to support the
feature.</p>
</blockquote>
<p>How can I use it in Netbeans 7?</p> | 5,742,626 | 6 | 1 | null | 2011-04-20 20:46:23.397 UTC | 12 | 2013-07-08 07:17:41.233 UTC | 2013-02-23 08:07:15.523 UTC | null | 140,934 | null | 140,934 | null | 1 | 31 | ruby|netbeans|netbeans-7 | 18,107 | <p>I followed the steps described in this blog post - <a href="http://blog.enebo.com/2011/02/installing-ruby-support-in-netbeans-70.html" rel="noreferrer">http://blog.enebo.com/2011/02/installing-ruby-support-in-netbeans-70.html</a> and it works. Enjoy</p>
<blockquote>
<p>Click Tools -> Plugins Click on <br>
'Settings' tab Click on 'Add' button<br>
to get Update Center Customizer popup<br>
Set name to 'Beta 1' Set URL: to
'<a href="http://updates.netbeans.org/netbeans/updates/7.0/uc/beta/stable/catalog.xml.gz" rel="noreferrer">http://updates.netbeans.org/netbeans/updates/7.0/uc/beta/stable/catalog.xml.gz</a>'<br>
Press 'OK' Click to 'Available<br>
Plugins' Click 'Reload Catalog' Choose<br>
'Ruby and Rails' Pat yourself on the
back</p>
</blockquote>
<p>Edit: now ruby on rails plugin can be found directly at "Tools">"Plugins">"Available Plugins">"Ruby And Rails" (if you don't find this plugin at the provided path you should download and install the latest netbeans ide)</p>
<p>Reedit: if you need Ruby On Rails support for Netbeans 7.1 check <a href="http://blog.enebo.com/2012/01/workaround-for-ruby-support-on-netbeans.html" rel="noreferrer">http://blog.enebo.com/2012/01/workaround-for-ruby-support-on-netbeans.html</a></p> |
6,130,712 | Pointer to Array of Pointers | <p>I have an array of int pointers <code>int* arr[MAX];</code> and I want to store its address in another variable. How do I define a pointer to an array of pointers? i.e.:</p>
<pre><code>int* arr[MAX];
int (what here?) val = &arr;
</code></pre> | 6,130,783 | 7 | 0 | null | 2011-05-25 20:45:14.667 UTC | 10 | 2020-05-24 16:42:47.723 UTC | 2011-05-25 20:59:17.41 UTC | null | 367,322 | null | 367,322 | null | 1 | 20 | c|arrays|pointers | 74,993 | <p>Should just be:</p>
<pre><code>int* array[SIZE];
int** val = array;
</code></pre>
<p>There's no need to use an address-of operator on <code>array</code> since arrays decay into implicit pointers on the right-hand side of the assignment operator.</p> |
5,774,808 | s3cmd failed too many times | <p>I used to be a happy s3cmd user. However recently when I try to transfer a large zip file (~7Gig) to Amazon S3, I am getting this error:</p>
<pre><code>$> s3cmd put thefile.tgz s3://thebucket/thefile.tgz
....
20480 of 7563176329 0% in 1s 14.97 kB/s failed
WARNING: Upload failed: /thefile.tgz ([Errno 32] Broken pipe)
WARNING: Retrying on lower speed (throttle=1.25)
WARNING: Waiting 15 sec...
thefile.tgz -> s3://thebucket/thefile.tgz [1 of 1]
8192 of 7563176329 0% in 1s 5.57 kB/s failed
ERROR: Upload of 'thefile.tgz' failed too many times. Skipping that file.
</code></pre>
<p>I am using the latest <a href="http://s3tools.org/repositories#note-deb" rel="noreferrer">s3cmd on Ubuntu</a>.</p>
<p>Why is it so? and how can I solve it? If it is unresolvable, what alternative tool can I use?</p> | 8,405,712 | 15 | 2 | null | 2011-04-25 03:05:05.11 UTC | 19 | 2016-10-05 07:00:20.473 UTC | null | null | null | null | 517,235 | null | 1 | 51 | file-upload|ubuntu|amazon-s3|backup | 33,092 | <p>In my case the reason of the failure was the server's time being ahead of the S3 time. Since I used GMT+4 in my server (located in US East) and I was using Amazon's US East storage facility. </p>
<p>After adjusting my server to the US East time, the problem was gone. </p> |
5,771,758 | Invalid gemspec because of the date format in specification | <p>When I include a gem that I made, thanks to Bundler (version 1.0.12), in a Gemfile and then I try to bundle or to rake just like that:</p>
<p><code>$ rake</code></p>
<p>I've got this error message:</p>
<pre><code>Invalid gemspec in [/Users/zagzag/.rvm/gems/ruby-1.9.2-p180@foobar/specifications/myplugin-1.0.0.gemspec]: invalid date format in specification: "2011-04-21 00:00:00.000000000Z"
</code></pre>
<p>I'm on the last Mac OS X (10.6.4), with:</p>
<pre><code>$ ruby -v
ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-darwin10.4.0]
</code></pre>
<p>and:</p>
<pre><code>$ gem -v
Invalid gemspec in [/Users/zagzag/.rvm/gems/ruby-1.9.2-p180@foobar/specifications/myplugin-1.0.0.gemspec]: invalid date format in specification: "2011-04-21 00:00:00.000000000Z"
1.7.2
</code></pre>
<p>I really don't see how to solve this issue. Thanks for any ideas.</p> | 7,125,033 | 15 | 2 | null | 2011-04-24 16:31:28.47 UTC | 43 | 2016-06-14 09:50:22.767 UTC | 2012-03-15 22:38:01.48 UTC | null | 136 | null | 326,039 | null | 1 | 89 | rubygems|bundler|ruby-1.9|ruby-1.9.2 | 37,736 | <p>Here is the way I fix the "invalid date format in specification" error:</p>
<p>1.) Go to the specifications folder located at:</p>
<p><code>/usr/local/lib/ruby/gems/1.8/specifications/</code></p>
<p>2.) Find the spec that is causing the problem.</p>
<p>3.) Change <code>s.date = %q{2011-05-21 00:00:00.000000000Z}</code> to <code>s.date = %q{2011-05-21}</code></p>
<p>That's a WIN for me! Good Luck</p> |
55,760,343 | Error: JavaFX runtime components are missing - JavaFX 11 and OpenJDK 11 and Eclipse IDE | <p>I have this classical issue: Using JavaFX 11 with OpenJDK 11 together with Eclipse IDE.</p>
<pre><code>Error: JavaFX runtime components are missing, and are required to run this application
</code></pre>
<p>I have OpenJDK 11.0.2</p>
<pre><code>dell@dell-pc:~$ java -version
openjdk version "11.0.2" 2019-01-15
OpenJDK Runtime Environment 18.9 (build 11.0.2+9)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)
dell@dell-pc:~$
</code></pre>
<p>And I also have <code>JavaFX 11 SDK</code>. By the way! I'm using Lubuntu Linux 18.10 if you wonder.
<a href="https://i.stack.imgur.com/OWv6S.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OWv6S.png" alt="enter image description here"></a></p>
<p>Then I have included the <code>.jar</code> files from the <code>JavaFX 11 SDK</code> in Eclipse IDE into a library package.</p>
<p><a href="https://i.stack.imgur.com/w94bE.png" rel="noreferrer"><img src="https://i.stack.imgur.com/w94bE.png" alt="enter image description here"></a></p>
<p>Then I have included this library package into my <code>JAdaptiveMPC</code> project.
<a href="https://i.stack.imgur.com/9Guqu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9Guqu.png" alt="enter image description here"></a></p>
<p>I get no error in my code syntax, but still, I cannot compile my project.
<a href="https://i.stack.imgur.com/Tr0x7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Tr0x7.png" alt="enter image description here"></a></p>
<p>Do you know why? I got the same error if I import all those <code>.jar</code> files from Maven instead of download the <code>JavaFX SDK</code> and import it into a library.</p>
<pre><code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Control</groupId>
<artifactId>JAdaptiveMPC</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx</artifactId>
<version>13-ea+5</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-base</artifactId>
<version>13-ea+5</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>13-ea+5</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-graphics</artifactId>
<version>13-ea+5</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-swing</artifactId>
<version>13-ea+5</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-web</artifactId>
<version>13-ea+5</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-media</artifactId>
<version>13-ea+5</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>13-ea+5</version>
</dependency>
</dependencies>
</project>
</code></pre>
<p><strong>Continue</strong></p>
<p>I have added this in the <code>Run Configuration</code></p>
<p><a href="https://i.stack.imgur.com/gj2gM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gj2gM.png" alt="enter image description here"></a></p>
<p>And then I try to run
<a href="https://i.stack.imgur.com/Kul20.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Kul20.png" alt="enter image description here"></a></p>
<p>Still errors.</p> | 55,760,756 | 4 | 5 | null | 2019-04-19 10:21:42.12 UTC | 1 | 2021-11-19 22:21:20.793 UTC | 2019-04-19 10:56:19.803 UTC | null | 1,008,405 | null | 1,008,405 | null | 1 | 15 | java|eclipse|javafx|javafx-11|gluon-desktop | 48,449 | <p>Your problem is not compiling the project, but running it.
Since your <code>main</code> is defined in your <code>Application</code>-extension, running the project will require JavaFX in your module path on startup.</p>
<p>So either outsource your <code>main</code> into a class different from your <code>Application</code> or add the JavaFX modules with VM arguments:</p>
<pre><code>--module-path="<javafx-root>\lib" --add-modules="javafx.base,javafx.controls,..."
</code></pre>
<p>See <a href="https://github.com/javafxports/openjdk-jfx/issues/236#issuecomment-426583174" rel="noreferrer">this</a> for some more info.</p> |
39,247,993 | Android TV RecyclerView focus interaction | <p>I'm currently using a regular <code>RecyclerView</code> with <code>GridLayoutManager</code>with different <code>spanCount</code> depeding on the <code>viewType</code> for an Android TV app. All is working decent but I have 2 issues:</p>
<ol>
<li>If you long press the dpad down to scroll fast between the items sometimes the focus is lost to a view that isn't a child of the RecyclerView.</li>
<li>How can I tell the <code>RecyclerView</code> to keep the current focused view in the center of the grid?</li>
</ol>
<p>It seems that the issues listed are fixed by using the <code>VerticalGridView</code> from <code>LeanBack</code> library but the <code>LayoutManger</code> that it uses is internal and doesn't support <code>spanCount</code>.</p> | 45,917,400 | 3 | 2 | null | 2016-08-31 11:09:16.12 UTC | 3 | 2018-12-13 10:31:19.4 UTC | null | null | null | null | 923,582 | null | 1 | 33 | android|android-recyclerview|android-tv | 15,230 | <p>Recycler view works fine with android TV.Possible solutions you can include are:</p>
<p>1.add focusable and focusableInTouchode to view.Add focusListner through the code and request focus each time when the view is clicked.</p>
<p>2.To keep Recycler View focused item in the centre you have to override layout manager just like this example.</p>
<p><a href="https://stackoverflow.com/questions/38416146/recyclerview-smoothscroll-to-position-in-the-center-android">RecyclerView smoothScroll to position in the center. android</a></p>
<p>or</p>
<p>use layoutManager.scrollToPositionWithOffset(position,offset) where position-focused view position and offset is the recycler view width/2.</p> |
5,272,408 | Does Linux use self-map for page directory and page tables? | <p>I'm just asking this question because I'm curious how the Linux kernel works. According to <a href="http://i-web.i.u-tokyo.ac.jp/edu/training/ss/lecture/new-documents/Lectures/02-VirtualMemory/VirtualMemory.ppt" rel="nofollow">http://i-web.i.u-tokyo.ac.jp/edu/training/ss/lecture/new-documents/Lectures/02-VirtualMemory/VirtualMemory.ppt</a> Windows uses special entries in its page directory and page tables named self-map in order to be able to manipulate page directory/tables content from kernel virtual address space. If anyone is familiar with Linux memory management, please tell me if Linux kernel handle this problem in a similar or different way. Thanks.</p> | 5,274,478 | 1 | 0 | null | 2011-03-11 11:38:21.753 UTC | 9 | 2021-03-19 13:19:12.223 UTC | null | null | null | null | 635,404 | null | 1 | 3 | memory-management|operating-system|linux-kernel|paging | 5,162 | <p>Yes, in Linux also page tables are mapped to address space. But paging data structures in some of the architectures may use physical addresses. So it not fixed in Linux. But you can access the table easily.</p>
<p>Here is the kernel code to access the page table</p>
<pre><code>struct mm_struct *mm = current->mm;
pgd = pgd_offset(mm, address);
pmd = pmd_offset(pgd, address);
pte = *pte_offset_map(pmd, address);
</code></pre>
<p>To understand more about Linux memory management <a href="http://linux-mm.org/VirtualMemory" rel="nofollow noreferrer">see this</a></p>
<p>Cr3 register on IA32 stores the page table base pointer (pgd pointer), which stores physical address. This is <a href="http://analyze-v.com/?p=410" rel="nofollow noreferrer">true even for Windows</a> (as it is a feature of the x86 processor, not of the OS).</p>
<p>Read <a href="http://www.stanford.edu/%7Estinson/paper_notes/fundamental/mem_mgmt/ia32_pts.txt" rel="nofollow noreferrer">this article</a> to understand IA32 paging.</p>
<p>Edit2:
<a href="http://lxr.linux.no/linux+v2.6.37.3/include/linux/sched.h#L1182" rel="nofollow noreferrer">Task struct</a> contains a <a href="http://lxr.linux.no/linux+v2.6.37.3/include/linux/mm_types.h#L222" rel="nofollow noreferrer">mm_struct</a> instance related to Memory management of that task (so a process), this <code>mm_struct</code> has a <code>pgd_t * pgd</code>. <a href="http://lxr.linux.no/linux+v2.6.37.3/arch/x86/include/asm/processor.h#L190" rel="nofollow noreferrer">load_cr3</a> loads a physical address of page directory table in <code>cr3</code> register but it takes the virtual address of pgt. So <code>mm_struct</code> contains the virtual address of <code>pgt</code>.</p>
<p>Since page tables are in kernel space and kernel virtual memory is mapped directly to ram it's just easy macro.</p> |
4,954,258 | What is the name of the path helper for a sign_in page in Devise? | <p>I couldn't really find this in the documentation. Only thing I've found is a <code>after_sign_in_path_for</code> method. What I want though is something like <code>sign_in_path_for(:account)</code> so that I wouldn't have to hardcode "/account/sign_in" path in. Any ideas if Devise has this kind of thing?</p> | 4,954,283 | 1 | 0 | null | 2011-02-10 06:57:51.923 UTC | 2 | 2011-02-10 07:01:56.433 UTC | null | null | null | null | 34,134 | null | 1 | 32 | ruby-on-rails|devise | 13,130 | <p>this depends on the scope, if yours is 'account' then</p>
<pre><code>new_account_session_path
</code></pre>
<p>you can see all the routes that devise creates doing a </p>
<pre><code>$ rake routes
</code></pre> |
5,108,359 | How do I define a template function within a template class outside of the class definition? | <p>Given:</p>
<pre><code>template <class T>
class Foo
{
public:
template <class U>
void bar();
};
</code></pre>
<p>How do I implement bar outside of the class definition while still having access to both template parameters T and U?</p> | 5,108,395 | 1 | 0 | null | 2011-02-24 17:39:06.077 UTC | 12 | 2011-02-24 17:46:01.19 UTC | null | null | null | null | 129,963 | null | 1 | 45 | c++|templates | 7,486 | <p>IIRC:</p>
<pre><code>template<class T> template <class U>
void Foo<T>::bar() { ...
</code></pre> |
5,011,632 | Should a 502 HTTP status code be used if a proxy receives no response at all? | <p>According to the RFC:</p>
<blockquote>
<p><strong>10.5.3 502 Bad Gateway</strong><br/>
The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request.</p>
</blockquote>
<p>Can <em>invalid response</em> also mean no response at all (e.g. connection refused)?</p> | 5,011,662 | 1 | 0 | null | 2011-02-16 01:35:57.38 UTC | 9 | 2020-03-25 16:06:39.803 UTC | 2020-03-25 16:06:39.803 UTC | null | 28,324 | null | 575,007 | null | 1 | 92 | http|client|http-status-codes|status | 240,950 | <p>Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.</p>
<p>For more information about the network errors </p>
<p><a href="https://en.wikipedia.org/wiki/List_of_HTTP_status_codes">https://en.wikipedia.org/wiki/List_of_HTTP_status_codes</a></p> |
25,127,738 | Cannot run ionic. receives "No command 'ionic' found" | <p>I want to start using the ionic framework, but unfortunately I'm already failing on the first step.</p>
<p>I am running Ubuntu 13.04 and I have node v0.10.25 installed.
I've installed ionic, at described in their docs:</p>
<pre><code>sudo npm install -g cordova
sudo npm install -g ionic
</code></pre>
<p>The installation went well, no errors or warnings, but after the installation I type </p>
<pre><code>ionic
</code></pre>
<p>and I get the error:</p>
<pre><code>No command 'ionic' found, did you mean:
Command 'ionice' from package 'util-linux' (main)
Command 'sonic' from package 'sonic' (universe)
ionic: command not found
</code></pre>
<p>I'm pretty new to ubuntu so I might have something not configured correctly, but I can't find what.</p>
<p>Thanks</p> | 25,146,556 | 13 | 1 | null | 2014-08-04 21:20:00.143 UTC | 11 | 2021-10-14 20:35:53.153 UTC | null | null | null | null | 1,119,268 | null | 1 | 29 | node.js|ubuntu|ionic-framework | 60,192 | <p>Well, I found it finally.</p>
<p>The ionic installation was at /home/guy/npm/bin/ionic, not at /usr/bin/ionic at it should be.</p>
<p>Solved it with:</p>
<pre><code>sudo ln -s /home/guy/npm/bin/ionic /usr/bin/ionic
</code></pre> |
24,587,414 | How to update a claim in ASP.NET Identity? | <p>I'm using OWIN authentication for my MVC5 project.
This is my <code>SignInAsync</code></p>
<pre><code> private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
var AccountNo = "101";
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
identity.AddClaim(new Claim(ClaimTypes.UserData, AccountNo));
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent, RedirectUri="Account/Index"}, identity);
}
</code></pre>
<p>As you can see, i added <code>AccountNo</code> into the Claims list.</p>
<p>Now, how can I update this Claim at some point in my application? So far, i have this:</p>
<pre><code> public string AccountNo
{
get
{
var CP = ClaimsPrincipal.Current.Identities.First();
var Account= CP.Claims.FirstOrDefault(p => p.Type == ClaimTypes.UserData);
return Account.Value;
}
set
{
var CP = ClaimsPrincipal.Current.Identities.First();
var AccountNo= CP.Claims.FirstOrDefault(p => p.Type == ClaimTypes.UserData).Value;
CP.RemoveClaim(new Claim(ClaimTypes.UserData,AccountNo));
CP.AddClaim(new Claim(ClaimTypes.UserData, value));
}
}
</code></pre>
<p>when i try to remove the claim, I get this exception:</p>
<blockquote>
<p>The Claim
'http://schemas.microsoft.com/ws/2008/06/identity/claims/userdata:
101' was not able to be removed. It is either not part of this
Identity or it is a claim that is owned by the Principal that contains
this Identity. For example, the Principal will own the claim when
creating a GenericPrincipal with roles. The roles will be exposed
through the Identity that is passed in the constructor, but not
actually owned by the Identity. Similar logic exists for a
RolePrincipal.</p>
</blockquote>
<p>How does one remove and update the Claim?</p> | 32,112,002 | 16 | 1 | null | 2014-07-05 14:28:57.073 UTC | 43 | 2022-09-03 15:33:38.863 UTC | 2021-08-20 15:49:24.67 UTC | null | 285,795 | null | 1,155,282 | null | 1 | 111 | c#|asp.net|asp.net-mvc|asp.net-mvc-4|asp.net-web-api | 137,357 | <p>I created a Extension method to Add/Update/Read Claims based on a given ClaimsIdentity</p>
<pre><code>namespace Foobar.Common.Extensions
{
public static class Extensions
{
public static void AddUpdateClaim(this IPrincipal currentPrincipal, string key, string value)
{
var identity = currentPrincipal.Identity as ClaimsIdentity;
if (identity == null)
return;
// check for existing claim and remove it
var existingClaim = identity.FindFirst(key);
if (existingClaim != null)
identity.RemoveClaim(existingClaim);
// add new claim
identity.AddClaim(new Claim(key, value));
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(identity), new AuthenticationProperties() { IsPersistent = true });
}
public static string GetClaimValue(this IPrincipal currentPrincipal, string key)
{
var identity = currentPrincipal.Identity as ClaimsIdentity;
if (identity == null)
return null;
var claim = identity.Claims.FirstOrDefault(c => c.Type == key);
// ?. prevents a exception if claim is null.
return claim?.Value;
}
}
}
</code></pre>
<p>and then to use it</p>
<pre><code>using Foobar.Common.Extensions;
namespace Foobar.Web.Main.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
// add/updating claims
User.AddUpdateClaim("key1", "value1");
User.AddUpdateClaim("key2", "value2");
User.AddUpdateClaim("key3", "value3");
}
public ActionResult Details()
{
// reading a claim
var key2 = User.GetClaimValue("key2");
}
}
}
</code></pre> |
24,901,645 | Oracle 11g: ORA-00604: error occurred at recursive SQL level 1 | <p>I executed the script below and it works:</p>
<pre><code>BEGIN
FOR cur_rec IN (SELECT object_name, object_type
FROM user_objects
WHERE object_type IN
('TABLE',
'VIEW',
'PACKAGE',
'PROCEDURE',
'FUNCTION',
'SEQUENCE'
))
LOOP
BEGIN
IF cur_rec.object_type = 'TABLE'
THEN
EXECUTE IMMEDIATE 'DROP '
|| cur_rec.object_type
|| ' "'
|| cur_rec.object_name
|| '" CASCADE CONSTRAINTS';
ELSE
EXECUTE IMMEDIATE 'DROP '
|| cur_rec.object_type
|| ' "'
|| cur_rec.object_name
|| '"';
END IF;
EXCEPTION
WHEN OTHERS
THEN
DBMS_OUTPUT.put_line ( 'FAILED: DROP '
|| cur_rec.object_type
|| ' "'
|| cur_rec.object_name
|| '"'
);
END;
END LOOP;
END;
/
</code></pre>
<p>But the problem is, after this, I cant grant, create or drop etc. in my database even I'm using a sysdba user.</p>
<p>I am getting the error:</p>
<blockquote>
<p>ORA-00604: error occurred at recursive SQL level 1
ORA-00942: table or view does not exist</p>
</blockquote>
<p>Please help. Thanks.</p> | 24,904,848 | 1 | 2 | null | 2014-07-23 04:04:32.39 UTC | 1 | 2014-07-23 07:58:11.037 UTC | 2014-07-23 04:28:00.54 UTC | null | 1,726,069 | null | 1,891,785 | null | 1 | 2 | sql|oracle11g | 60,423 | <p>One possible cause for the recursive SQL error is triggers. You might have run into this scenario:</p>
<ul>
<li>you have a trigger that fires for every DDL statement</li>
<li>this trigger tries to insert records into some kind of audit/log table</li>
<li>you audit/log table was dropped by your cleanup script</li>
</ul>
<p>To get a list of all triggers, you can use</p>
<pre><code>select * from dba_triggers
where trigger_type not in ('BEFORE EACH ROW','AFTER EACH ROW')
</code></pre>
<p>(you can exclude row-level triggers because they conceptually belong to the table and would have been automatically dropped when you dropped the table). After you've identified the offending trigger, you can either disable or drop it.</p> |
21,869,223 | create folder in laravel | <p>I have problem let user create folder in laravel 4 through ajax request > route > controller@method.<br>
I did test ajax success request to the url call right method.<br>
When I use <code>mkdir</code> or <code>File::mkdir($path);</code> (is this method exist?) , I will get the response <code>Failed to load resource: the server responded with a status of 500 (Internal Server Error)</code> and fail to create new folder.. how to solve it ?</p>
<p>route.php</p>
<pre><code>Route::post('admin/article/addimagegallery', 'AdminDashboardController@addImagegallery');
</code></pre>
<p>AdminDashboardController</p>
<pre><code>public function addImagegallery()
{
if (Request::ajax())
{
…
$galleryId = 1; // for test
$path = public_path().'/images/article/imagegallery/'.$galleryId;
File::mkdir($path);
}
}
</code></pre>
<p>js</p>
<pre><code>$.ajax({
url: 'addimagegallery',
type: 'POST',
data: {addimagegallery: 'addimagegallery'},
})
.done(function(response) {
console.log(response);
});
</code></pre> | 21,869,264 | 5 | 1 | null | 2014-02-19 01:37:25.507 UTC | 6 | 2021-12-01 21:02:55.027 UTC | null | null | null | null | 1,775,888 | null | 1 | 30 | php|jquery|ajax|laravel | 111,759 | <p>No, actually it's</p>
<pre><code>use File;
File::makeDirectory($path);
</code></pre>
<p>Also, you may try this:</p>
<pre><code>$path = public_path().'/images/article/imagegallery/' . $galleryId;
File::makeDirectory($path, $mode = 0777, true, true);
</code></pre>
<p><strong>Update:</strong> Actually it does work, <code>mkdir</code> is being used behind the scene. This is the source:</p>
<pre><code>/**
* Create a directory.
*
* @param string $path
* @param int $mode
* @param bool $recursive
* @param bool $force
* @return bool
*/
public function makeDirectory($path, $mode = 0777, $recursive = false, $force = false)
{
if ($force)
{
return @mkdir($path, $mode, $recursive);
}
else
{
return mkdir($path, $mode, $recursive);
}
}
</code></pre>
<p><strong>For deleting:</strong></p>
<pre><code>public function deleteDirectory($directory, $preserve = false);
</code></pre>
<p>Check the source at following path (in your local installation):</p>
<blockquote>
<p>root/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php</p>
</blockquote> |
9,548,144 | Getting TextArea Using JQuery | <p>I am submitting a form using JQuery. The form looks like below</p>
<pre><code><form class="ask-more-form">
<div class="product_info_2">
<textarea name="product_question" class="textbox" placeholder="Ask You Question Here"></textarea>
</div>
<input type="hidden" name="product_id" value="1" id="product_id">
<a href="#" class="whiteButton submit" id="ask-more-submit-button">Ask Question</a>
</form>
</code></pre>
<p>And the JQuery to catch the form looks like this:</p>
<pre><code>$('#ask-more').on('submit', '.ask-more-form', function() {
var product_id = $(this).children('input[name=product_id]').val();
var product_question = $(this).children('textarea[name="product_question"]').text();
alert(product_question);
//submitQuestion(product_id, product_question);
});
</code></pre>
<p>The product_id is always read but the product question is is always null. Can anyone tell me why this is happening?</p> | 9,548,176 | 4 | 0 | null | 2012-03-03 17:25:28.903 UTC | null | 2012-03-04 06:13:19.243 UTC | 2012-03-04 06:13:19.243 UTC | null | 1,183,294 | null | 456,850 | null | 1 | 11 | jquery|textarea | 51,726 | <p><code>.children</code> <a href="http://api.jquery.com/children/" rel="noreferrer">only goes one level down</a>. Use <code>.find</code> instead:</p>
<pre><code>$('#ask-more').on('submit', '.ask-more-form', function () {
var product_id = $(this).children('input[name=product_id]').val();
var product_question = $(this).find('textarea[name="product_question"]').text();
alert(product_question);
//submitQuestion(product_id, product_question);
});
</code></pre> |
52,107,252 | How to take latest changes from dev branch to my current branch | <p>We have below branches on which we work.</p>
<pre><code>master
dev
person A
person B
</code></pre>
<p>We both keep working on our branches i.e. <code>person A</code> or <code>person B</code> (working on same project). When <code>person A</code> finish the work, he commits changes to his branche and then create a pull request to merge the changes into <code>dev</code>, which other person <code>B</code> views and approve. After approval, the changes are then saved in <code>dev</code>. </p>
<p>How <code>B</code> can take the latest changes which <code>A</code> has done, from <code>dev</code> to his branch <code>person B</code>. We are using <a href="https://desktop.github.com/" rel="noreferrer">github desktop</a> to do all the git push/pull but happy to learn commands too. Thanks.</p> | 52,107,400 | 2 | 1 | null | 2018-08-31 01:13:18.08 UTC | 11 | 2022-05-05 23:31:26.143 UTC | null | null | null | null | 6,243,129 | null | 1 | 16 | git | 49,792 | <p>It's a good practice to as soon as feasible after person <em>A</em> pushes the changes to <code>dev</code> for person <em>B</em> to get these changes into their branch <code>b</code>. This is so that person <em>B</em> works on latest code and their eventual merge to <code>dev</code> is easy.</p>
<h3>Option 1, pull</h3>
<ol>
<li>Commit all changes to branch <code>feature_branch</code> (git status shows <code>clean</code>)</li>
<li><code>git checkout dev</code></li>
<li><code>git pull</code> - this fetches (downloads) the changes onto computer <code>b</code> <strong>and</strong> merges these changes into the currently checked out local branch on computer <code>b</code> (in this case branch <code>dev</code>). This operation should normally be a 'fast-forward' (so no merge conflicts)</li>
<li><code>git checkout feature_branch</code></li>
<li><code>git merge dev</code> - this merges changes from <code>b</code>'s local <code>dev</code> to the <code>feature_branch</code>.</li>
<li><code>git mergetool</code> - resolve conflicts</li>
<li><code>git commit</code> - commit your merge</li>
</ol>
<p>With this option <code>b</code>'s both local <code>dev</code> and <code>feature_branch</code> have latest changes.</p>
<h3>Option 2, fetch</h3>
<ol>
<li>Commit all changes to branch <code>feature_branch</code> (git status shows <code>clean</code>)</li>
<li><code>git fetch origin dev</code> - this downloads latest changes to <code>dev</code>, but <em>doesn't</em> merge them to local <code>dev</code></li>
<li><code>git merge origin/dev</code> - this merges changes from the downloaded version of <code>dev</code> to the <code>feature_branch</code>.</li>
</ol>
<p>In this scenario <code>b</code>'s local <code>feature_branch</code> will have the most recent changes from <code>dev</code> <em>as they are on the remote repo</em> and their local <code>dev</code> will not have these changes. This is OK, since <code>b</code> isn't working on <code>dev</code>, (s)he's working on <code>feature_branch</code>.</p>
<hr />
<p>I like option 2 as I don't need to checkout <code>dev</code>, but both options are equally correct.</p> |
31,146,242 | How to round edges of UILabel with Swift | <p>I have looked in the attributes of labels in Xcode 6.3 but I have not found out how to round the edges in the same way that you can round the edges of a text field. </p> | 31,146,390 | 9 | 1 | null | 2015-06-30 18:55:50.4 UTC | 8 | 2021-03-07 15:53:46.127 UTC | 2015-06-30 19:21:37.65 UTC | null | 614,442 | null | 5,066,726 | null | 1 | 78 | ios|swift | 86,582 | <p>Assuming you have added a <code>backgroundColor</code> to your label otherwise there would be no way to tell if it had edges, you can use QuartzCore to round the edges of a label.</p>
<pre><code>import QuartzCore
yourLabel.layer.backgroundColor = UIColor.redColor().CGColor
yourLabel.layer.cornerRadius = 5
yourLabel.layer.masksToBounds = true
</code></pre> |
34,397,349 | How do I include subclasses in Swagger API documentation/ OpenAPI specification using Swashbuckle? | <p>I have an Asp.Net web API 5.2 project in c# and generating documentation with Swashbuckle.</p>
<p>I have model that contain inheritance something like having an Animal property from an Animal abstract class and Dog and Cat classes that derive from it.</p>
<p>Swashbuckle only shows the schema for the Animal class so I tried to play with ISchemaFilter (that what they suggest too) but I couldn't make it work and also I cannot find a proper example.</p>
<p>Anybody can help? </p> | 36,200,684 | 6 | 2 | null | 2015-12-21 13:55:12.263 UTC | 17 | 2021-02-10 19:24:59.773 UTC | 2019-02-07 20:41:41.983 UTC | null | 813,948 | null | 813,948 | null | 1 | 37 | c#|api|swagger|subclassing|openapi | 34,068 | <p>It seems Swashbuckle doesn't implement polymorphism correctly and I understand the point of view of the author about subclasses as parameters (if an action expects an Animal class and behaves differently if you call it with a dog object or a cat object, then you should have 2 different actions...) but as return types I believe that it is correct to return Animal and the objects could be Dog or Cat types.</p>
<p>So to describe my API and produce a proper JSON schema in line with correct guidelines (be aware of the way I describe the disciminator, if you have your own discriminator you may need to change that part in particular), I use document and schema filters as follows:</p>
<pre><code>SwaggerDocsConfig configuration;
.....
configuration.DocumentFilter<PolymorphismDocumentFilter<YourBaseClass>>();
configuration.SchemaFilter<PolymorphismSchemaFilter<YourBaseClass>>();
.....
public class PolymorphismSchemaFilter<T> : ISchemaFilter
{
private readonly Lazy<HashSet<Type>> derivedTypes = new Lazy<HashSet<Type>>(Init);
private static HashSet<Type> Init()
{
var abstractType = typeof(T);
var dTypes = abstractType.Assembly
.GetTypes()
.Where(x => abstractType != x && abstractType.IsAssignableFrom(x));
var result = new HashSet<Type>();
foreach (var item in dTypes)
result.Add(item);
return result;
}
public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
{
if (!derivedTypes.Value.Contains(type)) return;
var clonedSchema = new Schema
{
properties = schema.properties,
type = schema.type,
required = schema.required
};
//schemaRegistry.Definitions[typeof(T).Name]; does not work correctly in SwashBuckle
var parentSchema = new Schema { @ref = "#/definitions/" + typeof(T).Name };
schema.allOf = new List<Schema> { parentSchema, clonedSchema };
//reset properties for they are included in allOf, should be null but code does not handle it
schema.properties = new Dictionary<string, Schema>();
}
}
public class PolymorphismDocumentFilter<T> : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, System.Web.Http.Description.IApiExplorer apiExplorer)
{
RegisterSubClasses(schemaRegistry, typeof(T));
}
private static void RegisterSubClasses(SchemaRegistry schemaRegistry, Type abstractType)
{
const string discriminatorName = "discriminator";
var parentSchema = schemaRegistry.Definitions[SchemaIdProvider.GetSchemaId(abstractType)];
//set up a discriminator property (it must be required)
parentSchema.discriminator = discriminatorName;
parentSchema.required = new List<string> { discriminatorName };
if (!parentSchema.properties.ContainsKey(discriminatorName))
parentSchema.properties.Add(discriminatorName, new Schema { type = "string" });
//register all subclasses
var derivedTypes = abstractType.Assembly
.GetTypes()
.Where(x => abstractType != x && abstractType.IsAssignableFrom(x));
foreach (var item in derivedTypes)
schemaRegistry.GetOrRegister(item);
}
}
</code></pre>
<p>What the previous code implements is specified <a href="http://swagger.io/specification/" rel="noreferrer">here</a>, in the section "Models with Polymorphism Support. It basically produces something like the following:</p>
<pre><code>{
"definitions": {
"Pet": {
"type": "object",
"discriminator": "petType",
"properties": {
"name": {
"type": "string"
},
"petType": {
"type": "string"
}
},
"required": [
"name",
"petType"
]
},
"Cat": {
"description": "A representation of a cat",
"allOf": [
{
"$ref": "#/definitions/Pet"
},
{
"type": "object",
"properties": {
"huntingSkill": {
"type": "string",
"description": "The measured skill for hunting",
"default": "lazy",
"enum": [
"clueless",
"lazy",
"adventurous",
"aggressive"
]
}
},
"required": [
"huntingSkill"
]
}
]
},
"Dog": {
"description": "A representation of a dog",
"allOf": [
{
"$ref": "#/definitions/Pet"
},
{
"type": "object",
"properties": {
"packSize": {
"type": "integer",
"format": "int32",
"description": "the size of the pack the dog is from",
"default": 0,
"minimum": 0
}
},
"required": [
"packSize"
]
}
]
}
}
}
</code></pre> |
57,857,489 | Command 'ui' is not defined in laravel 6.0 | <p>I start a new project in laravel but my composer installed a fresh version of laravel 6.0.1. </p>
<p><code>Php artisan make:auth</code> command can't work. </p>
<p>I try many times but error can't remove</p>
<pre><code>composer require laravel/ui
</code></pre>
<p>installed but
when I use the second command: </p>
<pre><code>php artisan ui vue --auth
</code></pre>
<p>then system show me this message:</p>
<pre><code>Command "ui" is not defined.
Using version ^1.0 for laravel/ui
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
PHP Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 4096 bytes) in phar://C:/ProgramData/ComposerSetup/bin/composer.phar/src/Composer/DependencyResolver/RuleSetGenerator.php on line 129
Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 4096 bytes) in phar://C:/ProgramData/ComposerSetup/bin/composer.phar/src/Composer/DependencyResolver/RuleSetGenerator.php on line 129
Check https://getcomposer.org/doc/articles/troubleshooting.md#memory-limit-errors for more info on how to handle out of memory errors.
</code></pre> | 58,112,219 | 9 | 1 | null | 2019-09-09 16:01:30.32 UTC | 2 | 2022-09-16 19:49:52.807 UTC | 2020-03-02 07:31:32.897 UTC | user12033292 | 8,916,482 | user12033292 | null | null | 1 | 18 | laravel|laravel-6|laravel-authentication | 45,910 | <p>you can try this:</p>
<pre><code> C:\Whatever\Your_project_name>composer require laravel/ui
</code></pre>
<p>and</p>
<pre><code> C:\Whatever\Your_project_name>php artisan ui vue --auth
</code></pre>
<p>Just this two inside your project folder.I am using vue but you can try other ones too.</p> |
7,201,337 | how to get attribute value using selenium and css | <p>I have the following HTML code: </p>
<pre class="lang-html prettyprint-override"><code><a href="/search/?p=2&q=move&mt=1"> 2 </a>
</code></pre>
<p>I would like to get what is contained in href, ie, I was looking for a command which would give me "/search/?p=2&q=move&mt=1" value for href. </p>
<p>Could someone please help me with the respective command and css locator in selenium, for the above query?</p>
<p>if I have something like: </p>
<pre class="lang-html prettyprint-override"><code><a href="/search/?p=2&q=move&mt=1"> 2 </a>
<a href="/search/?p=2&q=move&mt=2"> 3 </a>
</code></pre>
<p>Out of these two if I was to get the attribute value for href whose text conatins '2', then how would my css locator synatx look like? </p> | 7,201,409 | 2 | 0 | null | 2011-08-26 07:25:20.447 UTC | 1 | 2013-07-24 01:23:07.62 UTC | 2011-08-26 07:58:11.75 UTC | null | 106,224 | null | 898,551 | null | 1 | 6 | css|selenium|css-selectors|selenium-rc | 41,439 | <p>If your HTML consists solely of that one <code><a></code> tag, then this should do it:</p>
<pre class="lang-java prettyprint-override"><code>String href = selenium.getAttribute("css=a@href");
</code></pre>
<p>You use the <a href="http://release.seleniumhq.org/selenium-remote-control/0.9.2/doc/java/com/thoughtworks/selenium/DefaultSelenium.html#getAttribute(java.lang.String)" rel="noreferrer"><code>DefaultSelenium#getAttribute()</code> method</a> and pass in a CSS locator, an <code>@</code> symbol, and the name of the attribute you want to fetch. In this case, you select the <code>a</code> and get its <code>@href</code>.</p>
<p>In response to your comment/edit:</p>
<ol>
<li><p>The part after <code>@</code> tells Selenium that that part is the name of the attribute.</p></li>
<li><p>You should place <code>:contains('2')</code> before <code>@href</code> because it's part of the locator, not the attribute. So, like this:</p>
<pre class="lang-java prettyprint-override"><code>selenium.getAttribute("css=a:contains('2')@href");
</code></pre></li>
</ol> |
23,397,347 | ngOptions "track by" expression | <p>I am trying to use the 'track by' expression to track selections by id, in an array of objects. However, I can't seem to make it work like I think it works.</p>
<pre><code>//ids from server
$scope.serverDTO = ['1','2','3'];
//composed objects from the ID set
$scope.composedData = [{id:1,name:"test"},{id:2,name:"test"},{id:3,name:"test"}];
<!-- select box -->
<select ng-model="serverDTO" ng-options="item as item.name for item in composedData track by item.id"></select>
</code></pre>
<p>So based on the <a href="https://docs.angularjs.org/api/ng/directive/select" rel="noreferrer">documentation</a> I though that the options directive on load would see that the serverDTO has the 'track by' ids of 1, 2, and 3, and have those pre-selected. After the user modifies the selection I would need to do something like this to return the array to the server-</p>
<pre><code>//recreate proper DTO [1,2,3];
$scope.serverDTO = $scope.serverDTO.map(function(val){
return val.id;
});
</code></pre>
<p>Am I way off on how this is supposed to work?</p> | 23,397,373 | 2 | 1 | null | 2014-04-30 20:21:50.53 UTC | 3 | 2015-11-19 18:45:59.827 UTC | null | null | null | null | 695,082 | null | 1 | 27 | javascript|angularjs|ng-options | 40,128 | <p><code>track by</code> just helps Angular internally with array sorting as far as I know. The value of the options is defined by the first argument (in your case <code>item</code>). If you want it to be by id then you should use <code>item.id as item.name for item in items</code></p> |
31,702,041 | Multiple commands/tasks with Visual Studio Code | <p>I have a local folder that I use as a scratch pad for multiple little sample and toy pieces of code. I store a host of python, C++, shell scripts etc. in this directory.</p>
<p>I'm using Visual Studio Code (on OS X) and am looking into <a href="https://code.visualstudio.com/Docs/tasks" rel="noreferrer">its tasks</a> to run/compile the code snippets without having to switch to a terminal.</p>
<p>For example, I found <a href="http://www.reddit.com/r/Python/comments/34yvcm/using_visual_studio_code_with_python/" rel="noreferrer">this following task</a> will run python on the currently open file.</p>
<pre class="lang-json prettyprint-override"><code>// A task runner that runs a python program
{
"version": "0.1.0",
"command": "/usr/bin/python",
"args": ["${file}"]
}
</code></pre>
<p>This task will use python as the task runner irrespective of the type of file I'm currently editing.</p>
<p>How do I implement a task to run a command based on the file type (or select between multiple commands)? I.e. if I'm editing a C++ file, it will run clang++.</p>
<ul>
<li>If I can't do it based on file type; are there any alternatives to this?</li>
<li>An alternative would be; are multiple commands supported?</li>
</ul> | 32,290,053 | 6 | 1 | null | 2015-07-29 13:36:07.9 UTC | 14 | 2022-01-19 17:34:17.98 UTC | 2019-03-11 14:17:16.223 UTC | null | 2,631,715 | null | 3,747,990 | null | 1 | 41 | visual-studio-code|vscode-tasks | 62,678 | <p>You can always use bash as your task runner and then assign arbitrary terminal commands as your tasks.</p>
<pre class="lang-json prettyprint-override"><code>{
"version": "0.1.0",
"command": "bash",
"isShellCommand": true,
"showOutput": "always",
"args": [
"-c"
],
"tasks": [
{
"taskName": "My First Command",
"suppressTaskName": true,
"isBuildCommand": true,
"args": ["echo cmd1"]
},
{
"taskName": "My Command Requiring .bash_profile",
"suppressTaskName": true,
"args": ["source ~/.bash_profile && echo cmd2"]
},
{
"taskName": "My Python task",
"suppressTaskName": true,
"args": ["/usr/bin/python ${file}"]
}
]
}
</code></pre>
<p>A few notes on what is happening here:</p>
<ul>
<li>Using bash <code>-c</code> for all tasks by putting it in <code>args</code> list of the command so that we can run arbitrary commands. The <code>echo</code> statements are just examples but could be anything executable from your bash terminal.</li>
<li>The <code>args</code> array will contain a single string to be passed to <code>bash -c</code> (separate items would be treated as multiple arguments to the bash command and not the command associated with the <code>-c</code> arg).</li>
<li><code>suppressTaskName</code> is being used to keep the <code>taskName</code> out of the mix</li>
<li>The second command shows how you can load your <code>~/.bash_profile</code> if you need anything that it provides such as aliases, env variables, whatever</li>
<li>Third command shows how you could use your Python command you mentioned</li>
</ul>
<p>This will not give you any sort of file extension detection, but you can at least use <kbd>cmd</kbd>+<kbd>p</kbd> then type "task " to get a list of your tasks. You can always mark your 2 most common commands with <code>isBuildCommand</code> and <code>isTestCommand</code> to run them via <kbd>cmd</kbd>+<kbd>shift</kbd>+<kbd>b</kbd> or <kbd>cmd</kbd>+<kbd>shift</kbd>+<kbd>t</kbd> respectively.</p>
<p><a href="https://stackoverflow.com/a/30419250/20489">This answer</a> has some helpful information that might be useful to you as well.</p> |
31,373,163 | Anaconda Runtime Error: Python is not installed as a framework? | <p>I've installed Anaconda with the pkg installer:</p>
<pre><code>Python 2.7.10 |Continuum Analytics, Inc.| (default, May 28 2015, 17:04:42)
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://binstar.org
</code></pre>
<p>but when I attempt to use anything from matplotlib, i.e.:</p>
<pre><code> from matplotlib import pyplot as plt
</code></pre>
<p>I get </p>
<pre><code>RuntimeError: Python is not installed as a framework.
The Mac OS X backend will not be able to function correctly if Python is not installed
as a framework. See the Python documentation for more information on installing Python
as a framework on Mac OS X. Please either reinstall Python as a framework,
or try one of the other backends.
</code></pre>
<p>I'm really not sure what this means, or how to go about fixing it.</p> | 31,374,398 | 10 | 3 | null | 2015-07-12 22:23:36.74 UTC | 10 | 2019-01-25 07:39:26.487 UTC | null | null | null | null | 2,673,694 | null | 1 | 39 | python|macos|matplotlib|anaconda | 42,334 | <p>If you experience this error, don't forget to check your bash_profile. </p>
<p>You can do this in terminal by:</p>
<pre><code>cd
</code></pre>
<p>then</p>
<pre><code>nano .bash_profile
</code></pre>
<p>check the contents. Macports and Homebrew add their own headings for things they've done here. You can remove the declarations they make to $PATH. Just leave the one Anaconda has made. I had a If you would like, you can:</p>
<pre><code>cp .bash_profile ./bash_profile_backup_yyyy_mm_dd
</code></pre>
<p>and have a backup of the file, with filename indexing to the date you changed it. That is, provided you actually put in the date in instead of just the formatting characters I'm suggesting. </p>
<pre><code>source ~/.bash_profile
</code></pre>
<p>will refresh your system's reference to the bash_profile and you should be good to go in importing and using matplotlib</p> |
18,904,853 | Update without touching timestamps (Laravel) | <p>Is it possible to update a user without touching the timestamps?</p>
<p>I don't want to disable the timestamps completly..</p>
<p>grtz</p> | 18,906,324 | 9 | 1 | null | 2013-09-19 21:02:11.5 UTC | 21 | 2021-09-21 01:37:44.517 UTC | null | null | null | null | 1,970,352 | null | 1 | 87 | php|laravel|laravel-4|eloquent | 70,037 | <p>Disable it temporarily:</p>
<pre><code>$user = User::find(1);
$user->timestamps = false;
$user->age = 72;
$user->save();
</code></pre>
<p>You can optionally re-enable them after saving.</p>
<p><strong>This is a Laravel 4 and 5 only feature</strong> and does not apply to Laravel 3.</p> |
27,920,852 | Nginx SSL inside a docker container | <p>I have configured a Docker container to run Nginx and setup the /etc/nginx/sites-available/default file as shown below</p>
<pre><code>server
{
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
root /usr/share/nginx/html;
index index.php index.html index.htm;
server_name example.com;
location / {
try_files $uri $uri/ /index.html;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
server
{
listen 443;
root /usr/share/nginx/html;
index index.php index.html index.htm;
server_name example.com;
ssl on;
ssl_certificate /etc/ssl/certs/ssl-cert-snakeoil.pem;
ssl_certificate_key /etc/ssl/private/ssl-cert-snakeoil.key;
location / {
try_files $uri $uri/ /index.html;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
</code></pre>
<p>I map the /etc/ssl/certs & /etc/ssl/private folders on the host when I run the docker container</p>
<pre><code>docker run -dt -p 8080:443 -p 8081:80 -v /t-base/log:/var/log/nginx -v
/etc/ssl/certs:/etc/ssl/certs -v /etc/ssl/private:/etc/ssl/private nginx
Docker ps shows
Up n minutes 0.0.0.0:8081->80/tcp 0.0.0.0:8080->443/tcp <container-name>
</code></pre>
<p>and the nginx error log file inside the mapped /t-base/log folder stays empty. </p>
<pre><code>docker exec -it <container-name> /bin/bash
</code></pre>
<p>followed by </p>
<pre><code>service nginx status
</code></pre>
<p>just comes back and says that nginx is running.</p>
<p>All of the above would indicate that everything is working correctly. However, I find that whilst I am able to browse to </p>
<pre><code>http://example.com:8080
</code></pre>
<p>turns up the default page</p>
<pre><code>https://example.com:8081
</code></pre>
<p>has the Chrome showing me its default "sad smiley" error page. I cannot see what I might be doing wrong here. I'd much appreciate any help.</p> | 28,084,954 | 1 | 1 | null | 2015-01-13 11:14:40.837 UTC | 7 | 2015-01-22 09:16:04.333 UTC | null | null | null | null | 1,077,485 | null | 1 | 25 | nginx|docker | 47,571 | <p>You have interchanged the ports. According to this command line <code>-p 8080:443 -p 8081:80</code>, you should do:</p>
<p><code>https://example.com:8080</code> note this is http<strong>s</strong></p>
<p>and</p>
<p><code>http://example.com:8081</code></p>
<p>This should work</p> |
2,190,095 | SQL Server creating a temporary table from another table | <p>I am looking to create a temporary table which is used as an intermediate table while compiling a report.</p>
<p>For a bit of background I am porting a VB 6 app to .net </p>
<p>To create the table I can use...</p>
<pre><code>SELECT TOP 0 * INTO #temp_copy FROM temp;
</code></pre>
<p>This creates an empty copy of temp, But it doesn't create a primary key </p>
<p>Is there a way to create a temp table plus the constraints?</p>
<p>Should I create the constraints afterwards?</p>
<p>Or am I better off just creating the table using create table, I didn't want to do this because there are 45 columns in the table and it would fill the procedure with a lot of unnecessary cruft.</p>
<p>The table is required because a lot of people may be generating reports at the same time so I can't use a single intermediary table </p> | 2,190,107 | 3 | 0 | null | 2010-02-03 06:24:36.527 UTC | 0 | 2010-02-03 06:32:38.917 UTC | null | null | null | null | 193,506 | null | 1 | 11 | sql|sql-server|tsql | 63,370 | <p>Do you actually need a Primary Key? If you are flitering and selecting only the data needed by the report won't you have to visit every row in the temp table anyway?</p> |
2,064,480 | django: best practice way to get model from an instance of that model | <p>Say <code>my_instance</code> is of model <code>MyModel</code>.<br>
I'm looking for a good way to do:</p>
<pre><code>my_model = get_model_for_instance(my_instance)
</code></pre>
<p>I have not found any really direct way to do this.
So far I have come up with this:</p>
<pre><code>from django.db.models import get_model
my_model = get_model(my_instance._meta.app_label, my_instance.__class__.__name__)
</code></pre>
<p>Is this acceptable? Is it even a sure-fire, best practice way to do it?<br>
There is also <code>_meta.object_name</code> which seems to deliver the same as <code>__class__.__name__</code>. Does it? Is better or worse? If so, why?</p>
<p>Also, how do I know I'm getting the correct model if the app label occurs multiple times within the scope of the project, e.g. 'auth' from 'django.contrib.auth' and let there also be 'myproject.auth'?<br>
Would such a case make <code>get_model</code> unreliable?</p>
<p>Thanks for any hints/pointers and sharing of experience!</p> | 2,064,875 | 3 | 2 | null | 2010-01-14 13:53:15.953 UTC | 9 | 2018-09-04 03:37:17.57 UTC | 2010-01-21 17:22:01.863 UTC | null | 25,163 | null | 221,496 | null | 1 | 80 | django | 42,469 | <pre><code>my_model = type(my_instance)
</code></pre>
<p>To prove it, you can create another instance:</p>
<pre><code>my_new_instance = type(my_instance)()
</code></pre>
<p>This is why there's no direct way of doing it, because python objects already have this feature.</p>
<p><strong>updated...</strong></p>
<p>I liked <a href="https://stackoverflow.com/a/6759498/238877">marcinn's response</a> that uses <code>type(x)</code>. This is identical to what the original answer used (<code>x.__class__</code>), but I prefer using functions over accessing magic attribtues. In this manner, I prefer using <code>vars(x)</code> to <code>x.__dict__</code>, <code>len(x)</code> to <code>x.__len__</code> and so on.</p>
<p><strong>updated 2...</strong></p>
<p>For deferred instances (mentioned by @Cerin in comments) you can access the original class via <code>instance._meta.proxy_for_model</code>.</p> |
8,998,419 | @RequestMapping annotation in Spring MVC | <p>I have a controller with request mapping as <code>@RequestMapping("/**")</code>
What does it mean?</p>
<p>If I want to exclude certain url pattern from the above mapping how would I do that?</p>
<p>Could someone please shed some light on it?</p> | 8,998,669 | 2 | 1 | null | 2012-01-25 05:48:57.953 UTC | 3 | 2015-10-09 09:39:12.703 UTC | 2015-10-09 09:39:12.703 UTC | null | 1,031,945 | null | 450,206 | null | 1 | 9 | spring-mvc|request-mapping | 40,001 | <p>Your URL will intercept all requests matching '/**'. Depending on where you are defining this I am not sure why you would want to do this. On class level this should define the base path while on method level it should be refined to the specific function.</p>
<p>If you would like to exclude a pattern you could define another controller that is ordered at a higher priority to the controller specifying '/**'</p>
<p>Here are 2 good references from spring source:</p>
<ol>
<li><p><a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html" rel="noreferrer">http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html</a></p></li>
<li><p><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html" rel="noreferrer">http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html</a></p></li>
</ol> |
8,948,403 | YouTube API Target (multiple) existing iframe(s) | <p>I'm trying to understand how to target an existing iframe using the YouTube API (i.e. without constructing an iframe with the script).</p>
<p>As usual, Google does not give enough API examples, but explains that it IS possible, here <a href="http://code.google.com/apis/youtube/iframe_api_reference.html">http://code.google.com/apis/youtube/iframe_api_reference.html</a></p>
<p>Here is an example of what I'm trying to do - the video underneath the thumbnail should play. I am almost there, but only the first video plays...</p>
<p><a href="http://jsfiddle.net/SparrwHawk/KtbYR/2/">http://jsfiddle.net/SparrwHawk/KtbYR/2/</a></p> | 8,949,636 | 1 | 1 | null | 2012-01-20 21:58:32.81 UTC | 18 | 2012-02-23 10:07:36.327 UTC | 2012-02-23 10:07:36.327 UTC | null | 938,089 | null | 664,806 | null | 1 | 17 | javascript|youtube-api|youtube-javascript-api | 29,288 | <h2>TL;DR: DEMO: <a href="http://jsfiddle.net/KtbYR/5/" rel="noreferrer">http://jsfiddle.net/KtbYR/5/</a></h2>
<p><code>YT_ready</code>, <code>getFrameID</code> and <code>onYouTubePlayerAPIReady</code> are functions as defined in <strong><a href="https://stackoverflow.com/questions/7988476/listening-for-youtube-event-in-jquery/7988536#7988536">this answer</a></strong>. Both methods can be implemented without any preloaded library. In my previous answer, I showed a method to implement the feature for a single frame.</p>
<p>In this answer, I focus on multiple frames.</p>
<p><strong>HTML example code</strong> (important tags and attributes are capitalized, <code><iframe src id></code>):</p>
<pre><code><div>
<img class='thumb' src='http://i2.cdnds.net/11/34/odd_alan_partridge_bio_cover.jpg'>
<IFRAME ID="frame1" SRC="http://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1" width="640" height="390" frameborder="0"></IFRAME>
</div>
<div>
<img class='thumb' src='http://i2.cdnds.net/11/34/odd_alan_partridge_bio_cover.jpg'>
<IFRAME ID="frame2" SRC="http://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1" width="640" height="390" frameborder="0"></IFRAME>
</div>
</code></pre>
<p><strong>JavaScript code (<code>YT_ready</code>, <code>getFrameID</code>, <code>onYouTubePlayerAPIReady</code> and the <em>YouTube Frame API</em> script loader are defined <a href="https://stackoverflow.com/questions/7988476/listening-for-youtube-event-in-jquery/7988536#7988536">here</a>)</strong></p>
<pre><code>var players = {}; //Define a player storage object, to expose methods,
// without having to create a new class instance again.
YT_ready(function() {
$(".thumb + iframe[id]").each(function() {
var identifier = this.id;
var frameID = getFrameID(identifier);
if (frameID) { //If the frame exists
players[frameID] = new YT.Player(frameID, {
events: {
"onReady": createYTEvent(frameID, identifier)
}
});
}
});
});
// Returns a function to enable multiple events
function createYTEvent(frameID, identifier) {
return function (event) {
var player = players[frameID]; // Set player reference
var the_div = $('#'+identifier).parent();
the_div.children('.thumb').click(function() {
var $this = $(this);
$this.fadeOut().next().addClass('play');
if ($this.next().hasClass('play')) {
player.playVideo();
}
});
}
}
</code></pre>
<p>In my previous answer, I bound the <code>onStateChange</code> event. In this example, I used the <code>onReady</code> event, because you want to call the functions only once, at initialization.</p>
<p>This example works as follows:</p>
<ul>
<li><p>The following methods are defined in <a href="https://stackoverflow.com/questions/7988476/listening-for-youtube-event-in-jquery/7988536#7988536">this answer</a>.</p>
<ol>
<li>The <em>YouTube Frame API</em> is loaded from <a href="http://youtube.com/player_api" rel="noreferrer">http://youtube.com/player_api</a>.</li>
<li>When this external script has finished loading, <code>onYoutubePlayerAPIReady</code> is called, which in his turn activates all functions as defined using <code>YT_ready</code></li>
</ol></li>
<li><p>The declaration of the following methods are shown here, but implemented using <a href="https://stackoverflow.com/questions/7988476/listening-for-youtube-event-in-jquery/7988536#7988536">this answer</a>. Explanation based on the example:</p>
<ol>
<li>Loops through each <code><iframe id></code> object, which is placed right after <code><.. class="thumb"></code>.</li>
<li>At each frame element, the <code>id</code> is retrieved, and stored in the <code>identifier</code> variable.</li>
<li>The internal ID of the iframe is retrieved through <code>getFrameID</code>. This ensures that the <code><iframe></code> is properly formatted for the API. <em>In this example code, the returned ID is equal to <code>identifier</code>, because I have already attached an ID to the <code><iframe></code>.</em></li>
<li>When the <code><iframe></code> exists, and a valid YouTube video, a new player instance is created, and the reference is stored in the <code>players</code> object, accessible by key <code>frameID</code>.</li>
<li>At the creation of the player instance, a **<code>onReady</code>* event is defined. This method will be invoked when the API is fully initialized for the frame.</li>
<li><p><strong><code>createYTEvent</code></strong><br />
This method returns a dynamically created function, which adds functionality for separate players. The most relevant parts of the code are:</p>
<pre><code>function createYTEvent(frameID, identifier) {
return function (event) {
var player = players[frameID]; // Set player reference
...
player.playVideo();
}
}
</code></pre>
<ul>
<li><code>frameID</code> is the ID of the frame, used to enable the <em>YouTube Frame API</em>.</li>
<li><code>identifier</code> is the ID as defined in <code>YT_ready</code>, not necessarily an <code><iframe></code> element. <code>getFrameID</code> will attempt to find the closest matching frame for a given id. That is, it returns the ID of a given <code><iframe></code> element, or: If the given element is not an <code><iframe></code>, the function looks for a child which is a <code><iframe></code>, and returns the ID of this frame. If the frame does not exists, the function will postfix the given ID by <code>-frame</code>.</li>
<li>players[playerID]` refers to the initialized player instance. </li>
</ul></li>
</ol></li>
</ul>
<h2>Make sure that you <em>also</em> check <a href="https://stackoverflow.com/questions/7988476/listening-for-youtube-event-in-jquery/7988536#7988536">this answer</a>, because the core functionality of this answer is based on that.</h2>
<p><a href="https://stackoverflow.com/search?q=user%3A938089+[youtube-api]&submit=search">Other YouTube Frame API answers</a>. In these answers, I showed various implementations of the YouTube Frame/JavaScript API.</p> |
579,244 | MySQL database optimization best practices | <p>What are the best practices for optimizing a MySQL installation for best performance when handling somewhat larger tables (> 50k records with a total of around 100MB per table)? We are currently looking into rewriting DelphiFeeds.com (a news site for the Delphi programming community) and noticed that simple Update statements can take up to 50ms. This seems like a lot. Are there any recommended configuration settings that we should enable/set that are typically disabled on a standard MySQL installation (e.g. to take advantage of more RAM to cache queries and data and so on)?</p>
<p>Also, what performance implications does the choice of storage engines have? We are planning to go with InnoDB, but if MyISAM is recommended for performance reasons, we might use MyISAM.</p> | 579,589 | 4 | 1 | null | 2009-02-23 20:42:19.233 UTC | 19 | 2009-07-18 22:14:40.75 UTC | 2009-03-09 19:06:17.99 UTC | Vordreller | 11,795 | Dennis G. | 65,084 | null | 1 | 16 | mysql|database|performance | 6,246 | <p>The "best practice" is:</p>
<ol>
<li>Measure performance, isolating the relevant subsystem as well as you can. </li>
<li>Identify the root cause of the bottleneck. Are you I/O bound? CPU bound? Memory bound? Waiting on locks?</li>
<li>Make changes to alleviate the root cause you discovered.</li>
<li>Measure again, to demonstrate that you fixed the bottleneck and <em>by how much</em>.</li>
<li>Go to step 2 and repeat as necessary until the system works fast enough.</li>
</ol>
<p>Subscribe to the RSS feed at <a href="http://www.mysqlperformanceblog.com" rel="noreferrer">http://www.mysqlperformanceblog.com</a> and read its historical articles too. That's a hugely useful resource for performance-related wisdom. For example, you asked about InnoDB vs. MyISAM. Their conclusion: InnoDB has ~30% higher performance than MyISAM on average. Though there are also a few usage scenarios where MyISAM out-performs InnoDB.</p>
<ul>
<li><a href="http://www.mysqlperformanceblog.com/2007/01/08/innodb-vs-myisam-vs-falcon-benchmarks-part-1/" rel="noreferrer">InnoDB vs. MyISAM vs. Falcon benchmarks - part 1</a></li>
</ul>
<p>The authors of that blog are also co-authors of "High Performance MySQL," the book mentioned by @Andrew Barnett.</p>
<hr>
<p>Re comment from @ʞɔıu: How to tell whether you're I/O bound versus CPU bound versus memory bound is platform-dependent. The operating system may offer tools such as ps, iostat, vmstat, or top. Or you may have to get a third-party tool if your OS doesn't provide one.</p>
<p>Basically, whichever resource is pegged at 100% utilization/saturation is likely to be your bottleneck. If your CPU load is low but your I/O load is at its maximum for your hardware, then you are I/O bound.</p>
<p>That's just one data point, however. The remedy may also depend on other factors. For instance, a complex SQL query may be doing a filesort, and this keeps I/O busy. Should you throw more/faster hardware at it, or should you redesign the query to avoid the filesort? </p>
<p>There are too many factors to summarize in a StackOverflow post, and the fact that many books exist on the subject supports this. Keeping databases operating efficiently and making best use of the resources is a full-time job requiring specialized skills and constant study.</p>
<hr>
<p>Jeff Atwood just wrote a nice blog article about finding bottlenecks in a system:</p>
<ul>
<li><a href="http://www.codinghorror.com/blog/archives/001235.html" rel="noreferrer">The Computer Performance Shell Game</a></li>
</ul> |
178,899 | Serializing Lists of Classes to XML | <p>I have a collection of classes that I want to serialize out to an XML file. It looks something like this:</p>
<pre><code>public class Foo
{
public List<Bar> BarList { get; set; }
}
</code></pre>
<p>Where a bar is just a wrapper for a collection of properties, like this:</p>
<pre><code>public class Bar
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
</code></pre>
<p>I want to mark this up so that it outputs to an XML file - this will be used for both persistence, and also to render the settings via an XSLT to a nice human-readable form. </p>
<p>I want to get a nice XML representation like this:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<Foo>
<BarList>
<Bar>
<Property1>Value</Property1>
<Property2>Value</Property2>
</Bar>
<Bar>
<Property1>Value</Property1>
<Property2>Value</Property2>
</Bar>
</Barlist>
</Foo>
</code></pre>
<p>where are all of the Bars in the Barlist are written out with all of their properties. I'm fairly sure that I'll need some markup on the class definition to make it work, but I can't seem to find the right combination.</p>
<p>I've marked Foo with the attribute </p>
<pre><code>[XmlRoot("Foo")]
</code></pre>
<p>and the <code>list<Bar></code> with the attribute</p>
<pre><code>[XmlArray("BarList"), XmlArrayItem(typeof(Bar), ElementName="Bar")]
</code></pre>
<p>in an attempt to tell the Serializer what I want to happen. This doesn't seem to work however and I just get an empty tag, looking like this:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<Foo>
<Barlist />
</Foo>
</code></pre>
<p>I'm not sure if the fact I'm using Automatic Properties should have any effect, or if the use of generics requires any special treatment. I've gotten this to work with simpler types like a list of strings, but a list of classes so far eludes me.</p> | 178,931 | 4 | 0 | null | 2008-10-07 15:06:59.633 UTC | 13 | 2017-11-10 05:17:49.3 UTC | 2015-06-15 18:25:45.21 UTC | Jon Artus | 76,337 | Jon Artus | 4,019 | null | 1 | 35 | c#|xml|serialization | 84,903 | <p>Just to check, have you marked Bar as [Serializable]?</p>
<p>Also, you need a parameter-less ctor on Bar, to deserialize</p>
<p>Hmm, I used:</p>
<pre><code>public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Foo f = new Foo();
f.BarList = new List<Bar>();
f.BarList.Add(new Bar { Property1 = "abc", Property2 = "def" });
XmlSerializer ser = new XmlSerializer(typeof(Foo));
using (FileStream fs = new FileStream(@"c:\sertest.xml", FileMode.Create))
{
ser.Serialize(fs, f);
}
}
}
public class Foo
{
[XmlArray("BarList"), XmlArrayItem(typeof(Bar), ElementName = "Bar")]
public List<Bar> BarList { get; set; }
}
[XmlRoot("Foo")]
public class Bar
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
</code></pre>
<p>And that produced:</p>
<pre><code><?xml version="1.0"?>
<Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<BarList>
<Bar>
<Property1>abc</Property1>
<Property2>def</Property2>
</Bar>
</BarList>
</Foo>
</code></pre> |
894,093 | Idiomatic, classy, open-source examples of Cocoa Interfaces? | <p>Greetings, I'm currently learning Cocoa and Objective-C. I've run through "all" the tutorials and I'm fairly comfortable with the ObjC language. What I'm looking for now is to learn Cocoa idioms and see real code used in nice-looking Cocoa apps. </p>
<p>It seems like serious apps (iTunes, etc.) don't just drop in the IB elements. They do a lot more with code to tweak them to look good. (Example: the iTunes playlist drawer. How does one go about getting that styling?)</p>
<p>Here are some examples of nice UI's that are open source that I've found:</p>
<ul>
<li>Smultron (<a href="http://www.peterborgapps.com/smultron" rel="nofollow noreferrer">current home</a>, <a href="https://github.com/jfmoy/Fraise" rel="nofollow noreferrer">open-source fork</a>)</li>
<li><a href="http://www.transmissionbt.com/" rel="nofollow noreferrer">Transmission</a></li>
<li><a href="http://www.vienna-rss.org/" rel="nofollow noreferrer">Vienna</a></li>
<li><a href="https://github.com/Caged/gitnub/wiki" rel="nofollow noreferrer">Gitnub</a> </li>
</ul>
<p>Any other suggestions on Open-Source apps that have great Cocoa user interfaces?</p> | 894,200 | 1 | 2 | null | 2009-05-21 17:25:39.453 UTC | 10 | 2013-02-21 13:02:18.307 UTC | 2013-02-21 13:02:18.307 UTC | null | 92,610 | null | 110,644 | null | 1 | 11 | objective-c|cocoa | 3,244 | <p>You might want to look at <a href="http://www.brandonwalkin.com/bwtoolkit/" rel="noreferrer">BWToolkit</a>, by Brandon Walkin. It's pretty awesome, containing an elegant collection of UI elements and other objects. The source code is provided so you can see how custom controls and views were created.</p>
<p>Brandon even provides some walkthrough movies, such as "Creating an iCal interface in 3 minutes."</p>
<p>A few other open source apps to dig into are <a href="http://caminobrowser.org" rel="noreferrer">Camino</a>, <a href="http://colloquy.info/" rel="noreferrer">Colloquy</a> for both Mac and iPhone, <a href="http://adium.im/" rel="noreferrer">Adium</a>, and <a href="http://code.google.com/p/blacktree-alchemy/" rel="noreferrer">Quicksilver</a> (lots of UI customization).</p> |
856,817 | Finding last index of a string in Oracle | <p>I need to find the last index of a string (e.g. <code>-</code>) within another string (e.g. <code>JD-EQ-0001</code> in Oracle's SQL (<em>version 8i</em>). Is there a way to do this with <code>INSTR()</code> or another function?</p> | 856,832 | 1 | 0 | null | 2009-05-13 08:42:27.923 UTC | 6 | 2020-01-27 11:31:33.287 UTC | 2020-01-27 11:31:33.287 UTC | null | 5,841,306 | null | 79,965 | null | 1 | 75 | oracle|string | 140,640 | <p>Use -1 as the start position:</p>
<pre><code>INSTR('JD-EQ-0001', '-', -1)
</code></pre> |
19,765,713 | “Convert” Option[x] to x | <p>I working with play for Scala (2.1) and I need to convert an <code>Option[Long]</code> value to <code>Long</code>.</p>
<p>I know how to do the opposite, I mean:</p>
<pre class="lang-scala prettyprint-override"><code>def toOption[Long](value: Long): Option[Long] = if (value == null) None else Some(value)
</code></pre>
<p>But in my case, I have to pass a value of <code>Option[Long]</code> as a type into a method that takes <code>Long</code>.</p> | 19,765,976 | 6 | 0 | null | 2013-11-04 10:24:46.15 UTC | 8 | 2022-07-17 20:41:22.94 UTC | 2022-07-17 20:41:22.94 UTC | null | 1,161,484 | null | 2,067,546 | null | 1 | 37 | scala|casting|playframework|type-conversion | 51,998 | <p>First of all, your implementation of "the opposite" has some serious problems. By putting a type parameter named <code>Long</code> on the method you're shadowing the <code>Long</code> type from the standard library. You probably mean the following instead:</p>
<pre><code>def toOption(value: Long): Option[Long] =
if (value == null) None else Some(value)
</code></pre>
<p>Even this is kind of nonsensical (since <code>scala.Long</code> is not a reference type and can never be <code>null</code>), unless you're referring to <code>java.lang.Long</code>, which is a recipe for pain and confusion. Finally, even if you were dealing with a reference type (like <code>String</code>), you'd be better off writing the following, which is exactly equivalent:</p>
<pre><code>def toOption(value: String): Option[String] = Option(value)
</code></pre>
<p>This method will return <code>None</code> if and only if <code>value</code> is <code>null</code>.</p>
<p>To address your question, suppose we have the following method:</p>
<pre><code>def foo(x: Long) = x * 2
</code></pre>
<p>You shouldn't generally think in terms of passing an <code>Option[Long]</code> to <code>foo</code>, but rather of "lifting" <code>foo</code> into the <code>Option</code> via <code>map</code>:</p>
<pre><code>scala> val x: Option[Long] = Some(100L)
x: Option[Long] = Some(100)
scala> x map foo
res14: Option[Long] = Some(200)
</code></pre>
<p>The whole point of <code>Option</code> is to model (at the type level) the possibility of a "null" value in order to avoid a whole class of <code>NullPointerException</code>-y problems. Using <code>map</code> on the <code>Option</code> allows you to perform computations on the value that may be in the <code>Option</code> while continuing to model the possibility that it's empty.</p>
<p>As another answer notes, it's also possible to use <code>getOrElse</code> to "bail out" of the <code>Option</code>, but this usually isn't the idiomatic approach in Scala (except in cases where there really is a reasonable default value).</p> |
23,425,909 | Javascript/jQuery get root url of website | <p>I have website:
"<a href="http://www.example.com/folder1/mywebsite/subfolder/page.html" rel="noreferrer">http://www.example.com/folder1/mywebsite/subfolder/page.html</a>"</p>
<p>Root of the site is: "<a href="http://www.example.com/folder1/mywebsite" rel="noreferrer">http://www.example.com/folder1/mywebsite</a>"</p>
<p>I would like to get root url of "mywebsite" dynamicly.
If I will publish this site to another place, then I will no need to change script.</p>
<p>For example to: "<a href="http://www.example.com/otherFolder/test/myChangedWebsite/subfolder/page.html" rel="noreferrer">http://www.example.com/otherFolder/test/myChangedWebsite/subfolder/page.html</a>" </p>
<p>I will get:
"<a href="http://www.example.com/otherFolder/test/myChangedWebsite" rel="noreferrer">http://www.example.com/otherFolder/test/myChangedWebsite</a>"</p>
<p>I tried in "page.html" javascript:
var url = window.location.protocol + "//" + window.location.host + '/otherPage.html</p>
<p>but this gives me only "<a href="http://www.example.com/otherPage.html" rel="noreferrer">http://www.example.com/otherPage.html</a>".</p>
<p>Also I know about location.origin but this is not supported for all browser as I found that on link: <a href="http://www.w3schools.com/jsref/prop_loc_origin.asp" rel="noreferrer">http://www.w3schools.com/jsref/prop_loc_origin.asp</a></p>
<p>If it can be done with jQuery, it will be good as well.</p> | 27,778,372 | 4 | 0 | null | 2014-05-02 10:25:52.647 UTC | 4 | 2021-10-22 18:19:54.717 UTC | 2015-10-06 08:09:39.083 UTC | null | 206,730 | null | 1,020,806 | null | 1 | 21 | javascript|jquery|html | 53,780 | <p>Here's a function doing the same as Hawk's post above, only much, much shorter:</p>
<pre><code>function getBaseUrl() {
var re = new RegExp(/^.*\//);
return re.exec(window.location.href);
}
</code></pre>
<p>Details here: <a href="https://www.w3schools.com/js/js_window_location.asp" rel="nofollow noreferrer">Javascript: Get base URL or root URL</a></p> |
20,292,828 | How can I get post data into an array in CodeIgniter? post items are arrays | <p>In CodeIgniter, I'm trying to accomplish a batch update from form inputs that share the same name. But don't know how to get post data into an array. A simplified view of the form is as follows:</p>
<pre><code><input name="id[]" value="1"/><input name = title[] value="some-title"/><input name ="sort_order[]" value="1"/>
<input name="id[]" value="2"/><input name = title[] value="some-tuttle"/><input name="sort_order[]" value="2"/>
<input name="id[]" value="3"/><input name = title[] value="some-turtle"/><input name="sort_order[]" value="3"/>
</code></pre>
<p>In my controller I have this for now: </p>
<pre><code>function set_sort_order(){
$data = array(
array('id' => 1,'sort_order' => 14),
array('id' => 2,'sort_order' => 5),
array('id' => 3,'sort_order' => 9)
);
$this->db->update_batch('press_releases', $data, 'id');//works!
$this->load->view(pr_listing);
}
</code></pre>
<p>The array is hard-wired to test in the input_batch function, which is working. So how can I get the post data into an array?</p> | 20,292,948 | 2 | 0 | null | 2013-11-29 20:18:10.493 UTC | 1 | 2013-11-29 20:29:50.177 UTC | 2013-11-29 20:20:21.163 UTC | null | 1,906,862 | null | 543,551 | null | 1 | 5 | php|arrays|codeigniter | 45,573 | <pre><code>$id = $this->input->post('id');
$sort_order = $this->input->post('sort_order');
$data = array();
foreach($id as $key=>$val)
{
$data[] = array('id'=>$val,'sort_order'=>$sort_order[$key]);
}
</code></pre> |
20,045,946 | Applying the changes from branch A to B, without merging or adding commits | <p>My scenario is that I have one branch in which I've made big improvements to the build process (branch A) and in another I'm working on a unrelated feature (branch B). So now when I'm hacking away at branch B, I want to pull in the stuff I wrote in branch A because I want faster and easier builds. However, I don't want to "pollute" my branch B, just add changes from branchA to unstaged changes. </p>
<p>What I've tried (when standing on branchB):</p>
<pre><code>git merge --no-commit branchA
</code></pre>
<p>Doesn't work because it puts you inside a merge. If it didn't, it would be perfect.</p>
<pre><code>git checkout branchA -- .
</code></pre>
<p>Doesn't work because it applies changes between branchA..branchB and not the changes master..branchA.</p>
<p>Anything else?</p>
<p>Edit: Yes, changes on branch A are committed. In this example there is only one branch with build improvements, but there may be up to N branches with build improvements that I want to apply while working on a feature branch. </p> | 41,772,786 | 6 | 0 | null | 2013-11-18 10:52:02.84 UTC | 38 | 2021-12-29 11:56:15 UTC | 2021-12-29 11:56:15 UTC | null | 8,129,254 | null | 189,247 | null | 1 | 122 | git|merge|branch | 42,000 | <p>I just had to do something similar and was able to fix it by adding <code>--squash</code> to the merge command</p>
<pre><code>git merge --no-commit --squash branchA
git reset HEAD # to unstage the changes
</code></pre> |
35,284,649 | How to get user posts using Graph API? | <p>I want to fetch all the public posts from a user's wall with my user access token. I know that read_stream permission is required for this. However this permission has been deprecated now.</p>
<p><a href="https://developers.facebook.com/docs/facebook-login/permissions#reference-read_stream" rel="noreferrer">https://developers.facebook.com/docs/facebook-login/permissions#reference-read_stream</a></p>
<blockquote>
<p>read_stream</p>
<p>This permission is only available for apps using Graph API version
v2.3 or older.</p>
</blockquote>
<p>I want to use version v2.5, so how can I do this now?</p> | 35,285,614 | 3 | 0 | null | 2016-02-09 05:36:49.077 UTC | 3 | 2021-08-12 21:59:42.337 UTC | null | null | null | null | 5,405,093 | null | 1 | 11 | facebook|facebook-graph-api | 41,098 | <p><strong>/me/feed</strong> gives you posts published by this person.</p>
<p>Filtered versions are:</p>
<p><strong>/me/posts</strong> shows only the posts published by this person.</p>
<p><strong>/me/tagged</strong> shows only posts that this person is tagged in.</p>
<p>Your app needs <strong>user_posts</strong> permission from the person who created the post or the person tagged in the post. </p>
<p>Then your app can read:</p>
<p>Timeline posts from the person who gave you the permission.
The posts that other people made on that person Timeline.
The posts that other people have tagged that person in.</p>
<p>If you attempt to read data from a feed that your app has not been authorized to access, the call will return an empty array.</p>
<p>For more details: <a href="https://developers.facebook.com/docs/graph-api/reference/v2.5/user/feed" rel="noreferrer">https://developers.facebook.com/docs/graph-api/reference/v2.5/user/feed</a></p>
<p><strong>Edit</strong> :
From a user access token, you can only get feed of that user and his facebook friends who are users of this app. Also all those users must grant user_posts permission to your app otherwise it will return only empty data set like in your case</p>
<p>For other users ( who have granted user_posts permission and friend of current access token user ) feed use: <strong>/{user_id}/feed</strong></p>
<p><strong>{user_id}</strong> of friends ( who are also user of your app ) available in <strong>/me/friends</strong></p> |
36,714,640 | How setbounds of drawable works in Android? | <p>I am confused with setbounds method of drawable in Android. I know it is used with drawable and it set where drawable and how large it is. Briefly, it defines, bounding rectangle for drawable. But I am confused: does it set border or padding or its width or height?</p>
<p>This is how we use setbounds</p>
<pre><code>drawableInstance.setBounds(L,T,R,B);
</code></pre>
<h2>First scenario</h2>
<p>So in above case, If I set 5,5,5,5 for L,T,R,B respectively, L,T,R,B of drawable will be always from its parent respectively? I mean will it be like setting hidden 5px border to every side?Besides, if image is not large enough to meets that border width to its parent, will image be bigger?</p>
<h2>Second scenario</h2>
<p>I set 5,5,100,100 for L,T,R,B respectively. What I am confusing is, it will starts drawing from away from parent 5px to the top and 5px to the left. That will be the start point. Then image with will be 100px because I set 100 for right. So it goes to the right 100px. Same to bottom with right.</p>
<p>But I tested it. I think both is not as what I think. How does it work, especially in relation to each parameter of setBounds?</p> | 36,715,160 | 1 | 0 | null | 2016-04-19 09:45:01.557 UTC | 8 | 2018-11-17 16:42:13.22 UTC | 2018-11-17 16:42:13.22 UTC | null | 472,495 | null | 4,675,736 | null | 1 | 30 | android|android-drawable | 24,145 | <p>The bounds values are absolute, not relative. That is, <code>width == right - left</code>, and <code>height == bottom - top</code>.</p>
<p>Your first example will have the top left corner of the <code>Drawable</code> at <code>(5, 5)</code>, but the width and height will both be <code>0</code>.</p>
<p>The second example will also have the top left corner at <code>(5, 5)</code>, and the width and height will both be <code>95</code>.</p>
<p>The bounds are not dependent on the dimensions of the <code>Canvas</code> to which the <code>Drawable</code> is drawn. For instance, if you draw a <code>Drawable</code> with the bounds of your second example onto a <code>View</code> that is only <code>50</code> by <code>50</code>, its left and top sides will be inset by <code>5</code>, but it will get cut off at the right and bottom borders.</p> |
18,954,758 | How to load view from alternative directory in Laravel 4 | <p>In my Laravel 4 application's root directory, I have a folder <strong><code>themes</code></strong>. Inside the <strong><code>themes</code></strong> folder, I have <strong><code>default</code></strong> and <strong><code>azure</code></strong>.
How can I access view from this <strong><code>themes/default</code></strong> folder in a specific route. </p>
<pre><code>Route::get('{slug}', function($slug) {
// make view from themes/default here
});
</code></pre>
<h2>My directory structure:</h2>
<p><em>-app</em></p>
<p><em>--themes</em></p>
<p><em>---default</em></p>
<p><em>---azure</em></p>
<p>I need to load views from <code>localhost/laravel/app/themes/default</code> folder. Please explain this.</p> | 18,956,853 | 4 | 0 | null | 2013-09-23 08:27:33.503 UTC | 17 | 2017-02-28 20:14:57.617 UTC | 2014-05-21 03:41:16.947 UTC | null | 1,317,935 | null | 1,926,343 | null | 1 | 29 | php|laravel|laravel-4|namespaces | 24,850 | <p>Here I am not accessing my project from <strong><code>public</code></strong> folder. Instead of this I am accessing from project root itself. </p>
<p>I have seen a forum discussion about <strong><code>Using alternative path for views</code></strong> <a href="http://forums.laravel.io/viewtopic.php?id=8277" rel="noreferrer">here</a>. But I am little confused about this.The discussed solution was,</p>
<p>You'd add a <strong><code>location</code></strong> like,</p>
<pre><code>View::addLocation('/path/to/your/views');
</code></pre>
<p>Then add <strong><code>namespace</code></strong> for theme,</p>
<pre><code>View::addNamespace('theme', '/path/to/themes/views');
</code></pre>
<p>Then render it,</p>
<pre><code>return View::make('theme::view.name');
</code></pre>
<p>What will be the value for <code>/path/to/</code> ? </p>
<p>Can I use the same project in different operating system without changing the path?</p>
<p>Yes, we can do this using the following,</p>
<p>Put the following in <code>app/start/global.php</code></p>
<pre><code> View::addLocation(app('path').'/themes/default');
View::addNamespace('theme', app('path').'/themes/default');
</code></pre>
<p>Then call view like the default way,</p>
<pre><code> return View::make('page');
</code></pre>
<p>This will render <code>page.php</code> or <code>page.blade.php</code> file from <code>project_directory/app/themes/defualt</code> folder.</p> |
30,709,972 | geom_bar define border color with different fill colors | <p>I want to draw a bar plot with <code>geom_bar</code> where I want unique fill colors surrounded by a black border. However the instruction <code>color="black"</code> is not interpreted as "black" as I want it to be and I get red borders. </p>
<pre><code>library(ggplot2)
test=as.data.frame(cbind(a=c(1,1,2,3), b=1:4, c=as.character(1:4)))
ggplot(test) + geom_bar(aes(x=a, y=b, fill=c, colour="black"), stat="identity")
</code></pre>
<p>How do I correctly use <code>geom_bar</code> so that it gives me the correct black border?</p> | 30,710,152 | 1 | 0 | null | 2015-06-08 13:06:41.32 UTC | 7 | 2015-06-08 13:23:34.177 UTC | 2015-06-08 13:23:34.177 UTC | null | 122,005 | null | 4,986,317 | null | 1 | 25 | r|ggplot2 | 74,773 | <p>You have to put <code>colour</code> outside <code>aes</code>:</p>
<pre><code>ggplot(test) + geom_bar(aes(x=a, y=b, fill=c), colour="black", stat="identity")
</code></pre>
<p><img src="https://i.stack.imgur.com/aUl7h.png" alt="enter image description here"></p> |
22,769,568 | System specific variables in ansible | <p>Ansible expects python 2. On my system (Arch Linux), "python" is Python 3, so I have to pass <code>-e "ansible_python_interpreter=/usr/bin/python2"</code> with every command.</p>
<pre><code>ansible-playbook my-playbook.yml -e "ansible_python_interpreter=/usr/bin/python2"
</code></pre>
<p>Is there a away to set <code>ansible_python_interpreter</code> globally on my system, so I don't have to pass it to every command? I don't want to add it to my playbooks, as not all systems that runs the playbook has a setup similar to mine.</p> | 22,771,791 | 3 | 0 | null | 2014-03-31 18:39:52.66 UTC | 5 | 2019-04-09 10:28:37.773 UTC | null | null | null | null | 26,051 | null | 1 | 31 | ansible | 39,057 | <p>Well you can set in three ways</p>
<ol>
<li><a href="http://docs.ansible.com/intro_inventory.html#list-of-behavioral-inventory-parameters" rel="noreferrer">http://docs.ansible.com/intro_inventory.html#list-of-behavioral-inventory-parameters</a> <code>ansible_python_interpreter=/usr/bin/python2</code> this will set it per host</li>
<li>Set it <em>host_vars/</em> <code>ansible_python_interpreter: "/usr/bin/python2"</code> this will set it per host</li>
<li>set it for <strong>all nodes</strong> in the file <code>group_vars/all</code> (you may need to create the directory <code>group_vars</code> and the file <code>all</code>) as <code>ansible_python_interpreter: "/usr/bin/python2"</code></li>
</ol>
<p>Hope that helps</p> |
45,929,548 | What's the kube-public namespace for? | <p>Just curious about the intent for this default namespace.</p> | 45,934,899 | 2 | 0 | null | 2017-08-29 01:48:46.347 UTC | 4 | 2020-07-13 02:55:38.41 UTC | 2020-07-13 02:55:38.41 UTC | null | 12,825,713 | null | 1,325,322 | null | 1 | 31 | kubernetes|kubeadm | 7,851 | <p>That namespace exists in clusters created with kubeadm for now. It contains a single ConfigMap object, cluster-info, that aids discovery and security bootstrap (basically, contains the CA for the cluster and such). This object is readable without authentication.</p>
<p>If you are courious:</p>
<pre><code>$ kubectl get configmap -n kube-public cluster-info -o yaml
</code></pre>
<p>There are more details in this <a href="https://kubernetes.io/blog/2017/01/stronger-foundation-for-creating-and-managing-kubernetes-clusters/" rel="noreferrer">blog post</a> and the <a href="https://github.com/kubernetes/community/blob/master/contributors/design-proposals/cluster-lifecycle/bootstrap-discovery.md#new-kube-public-namespace" rel="noreferrer">design document</a>:</p>
<blockquote>
<h2>NEW: kube-public namespace</h2>
<p>[...] To create a config map that everyone can see, we introduce a new kube-public namespace. This namespace, by convention, is readable by all users (including those not authenticated). [...]</p>
<p>In the initial implementation the kube-public namespace (and the cluster-info config map) will be created by kubeadm. That means that these won't exist for clusters that aren't bootstrapped with kubeadm. [...]</p>
</blockquote> |
37,443,565 | How to get the element-wise mean of an ndarray | <p>I'd like to calculate element-wise average of numpy ndarray.</p>
<pre><code>In [56]: a = np.array([10, 20, 30])
In [57]: b = np.array([30, 20, 20])
In [58]: c = np.array([50, 20, 40])
</code></pre>
<p>What I want:</p>
<pre><code>[30, 20, 30]
</code></pre>
<p>Is there any in-built function for this operation, other than vectorized sum and dividing? </p> | 37,443,624 | 2 | 0 | null | 2016-05-25 17:06:12.977 UTC | 1 | 2022-08-29 20:39:53.57 UTC | 2022-08-29 20:39:53.57 UTC | null | 7,758,804 | null | 3,907,250 | null | 1 | 45 | python|numpy|vectorization | 36,229 | <p>You can just use <code>np.mean</code> directly:</p>
<pre class="lang-py prettyprint-override"><code>>>> np.mean([a, b, c], axis=0)
array([ 30., 20., 30.])
</code></pre> |
40,182,944 | What's the difference between raise, try, and assert? | <p>I have been learning Python for a while and the <code>raise</code> function and <code>assert</code> are (what I realised is that both of them crash the app, unlike try - except) really similar and I can't see a situation where you would use <code>raise</code> or <code>assert</code> over <code>try</code>.</p>
<p>So, what is the difference between <code>raise</code>, <code>try</code>, and <code>assert</code>?</p> | 40,183,195 | 10 | 2 | null | 2016-10-21 18:07:38.183 UTC | 29 | 2021-05-15 13:08:51.413 UTC | 2021-02-05 15:33:36.43 UTC | null | 9,835,872 | null | 7,019,398 | null | 1 | 81 | python|assert|raise | 81,978 | <p>Assert:</p>
<p>Used when you want to "stop" the script based on a certain condition and return something to help debug faster:</p>
<pre><code>list_ = ["a","b","x"]
assert "x" in list_, "x is not in the list"
print("passed")
#>> prints passed
list_ = ["a","b","c"]
assert "x" in list_, "x is not in the list"
print("passed")
#>>
Traceback (most recent call last):
File "python", line 2, in <module>
AssertionError: x is not in the list
</code></pre>
<hr />
<p>Raise:</p>
<p>Two reasons where this is useful:</p>
<p>1/ To be used with try and except blocks. Raise an error of your choosing, could be custom like below and doesn't stop the script if you <code>pass</code> or <code>continue</code> the script; or can be predefined errors <code>raise ValueError()</code></p>
<pre><code>class Custom_error(BaseException):
pass
try:
print("hello")
raise Custom_error
print("world")
except Custom_error:
print("found it not stopping now")
print("im outside")
>> hello
>> found it not stopping now
>> im outside
</code></pre>
<p>Noticed it didn't stop? We can stop it using just exit(1) in the except block.</p>
<p>2/ Raise can also be used to re-raise the current error to pass it up the stack to see if something else can handle it.</p>
<pre><code>except SomeError, e:
if not can_handle(e):
raise
someone_take_care_of_it(e)
</code></pre>
<hr />
<p>Try/Except blocks:</p>
<p>Does exactly what you think, tries something if an error comes up you catch it and deal with it however you like. No example since there's one above.</p> |
45,332,410 | ROC for multiclass classification | <p>I'm doing different text classification experiments. Now I need to calculate the AUC-ROC for each task. For the binary classifications, I already made it work with this code:</p>
<pre><code>scaler = StandardScaler(with_mean=False)
enc = LabelEncoder()
y = enc.fit_transform(labels)
feat_sel = SelectKBest(mutual_info_classif, k=200)
clf = linear_model.LogisticRegression()
pipe = Pipeline([('vectorizer', DictVectorizer()),
('scaler', StandardScaler(with_mean=False)),
('mutual_info', feat_sel),
('logistregress', clf)])
y_pred = model_selection.cross_val_predict(pipe, instances, y, cv=10)
# instances is a list of dictionaries
#visualisation ROC-AUC
fpr, tpr, thresholds = roc_curve(y, y_pred)
auc = auc(fpr, tpr)
print('auc =', auc)
plt.figure()
plt.title('Receiver Operating Characteristic')
plt.plot(fpr, tpr, 'b',
label='AUC = %0.2f'% auc)
plt.legend(loc='lower right')
plt.plot([0,1],[0,1],'r--')
plt.xlim([-0.1,1.2])
plt.ylim([-0.1,1.2])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.show()
</code></pre>
<p>But now I need to do it for the multiclass classification task. I read somewhere that I need to binarize the labels, but I really don't get how to calculate ROC for multiclass classification. Tips?</p> | 45,335,434 | 4 | 1 | null | 2017-07-26 16:16:09.273 UTC | 22 | 2022-02-19 06:07:46.513 UTC | 2021-02-18 15:12:38.76 UTC | null | 4,685,471 | null | 7,245,549 | null | 1 | 40 | python|scikit-learn|text-classification|roc|multiclass-classification | 82,943 | <p>As people mentioned in comments you have to convert your problem into binary by using <code>OneVsAll</code> approach, so you'll have <code>n_class</code> number of ROC curves.</p>
<p>A simple example:</p>
<pre><code>from sklearn.metrics import roc_curve, auc
from sklearn import datasets
from sklearn.multiclass import OneVsRestClassifier
from sklearn.svm import LinearSVC
from sklearn.preprocessing import label_binarize
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
iris = datasets.load_iris()
X, y = iris.data, iris.target
y = label_binarize(y, classes=[0,1,2])
n_classes = 3
# shuffle and split training and test sets
X_train, X_test, y_train, y_test =\
train_test_split(X, y, test_size=0.33, random_state=0)
# classifier
clf = OneVsRestClassifier(LinearSVC(random_state=0))
y_score = clf.fit(X_train, y_train).decision_function(X_test)
# Compute ROC curve and ROC area for each class
fpr = dict()
tpr = dict()
roc_auc = dict()
for i in range(n_classes):
fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i])
roc_auc[i] = auc(fpr[i], tpr[i])
# Plot of a ROC curve for a specific class
for i in range(n_classes):
plt.figure()
plt.plot(fpr[i], tpr[i], label='ROC curve (area = %0.2f)' % roc_auc[i])
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic example')
plt.legend(loc="lower right")
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/ByrqW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ByrqW.png" alt="enter image description here" /></a><a href="https://i.stack.imgur.com/pqC8U.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pqC8U.png" alt="enter image description here" /></a><a href="https://i.stack.imgur.com/ydVNu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ydVNu.png" alt="enter image description here" /></a></p> |
25,822,679 | Packed bit fields in c structures - GCC | <p>I am working with structs in c on linux.
I started using bit fields and the "packed" attribute and I came across a wierd behavior:</p>
<pre><code>struct __attribute__((packed)) {
int a:12;
int b:32;
int c:4;
} t1;
struct __attribute__((packed)) {
int a:12;
int b;
int c:4;
}t2;
void main()
{
printf("%d\n",sizeof(t1)); //output - 6
printf("%d\n",sizeof(t2)); //output - 7
}
</code></pre>
<p>How come both structures - that are exactly the same - take diffrent number of bytes?</p> | 25,822,849 | 2 | 2 | null | 2014-09-13 11:19:25.037 UTC | 8 | 2021-07-08 00:28:48.3 UTC | 2021-07-08 00:28:48.3 UTC | null | 4,748,326 | null | 4,037,515 | null | 1 | 24 | c|gcc|struct|bit-fields|packed | 30,812 | <p>Your structures are not "exactly the same". Your first one has three consecutive bit-fields, the second has one bit-field, an (non bit-field) int, and then a second bit-field.</p>
<p>This is significant: consecutive (non-zero width) bit-fields are merged into a single <em>memory location</em>, while a bit-field followed by a non-bit-field are distinct memory locations.</p>
<p>Your first structure has a single memory location, your second has three. You can take the address of the <code>b</code> member in your second struct, not in your first. Accesses to the <code>b</code> member don't race with accesses the <code>a</code> or <code>c</code> in your second struct, but they do in your first.</p>
<p>Having a non-bit-field (or a zero-length bit-field) right after a bit-field member "closes" it in a sense, what follows will be a different/independent memory location/object. The compiler cannot "pack" your <code>b</code> member inside the bit-field like it does in the first struct.</p> |
32,573,924 | Composer hanging while updating dependencies | <p>I tried updating a Laravel project I'm working on today using <code>composer update</code></p>
<p>But it hung on <code>Updating dependencies (including require-dev)</code></p>
<p>So I tried things like updating composer, dump-autoload, but nothing seemed to work. Then I ran it in verbose mode: <code>composer update -vvv</code></p>
<p>And I noticed it hung while reading this json:</p>
<pre><code>Reading path/to/Composer/repo/https---packagist.org/provider-cordoval$hamcrest-php.json from cache
</code></pre>
<p>I tried searching for cordoval/hamcrest-php on packagist.org and couldn't find it. This isn't listed as a dependency in my <code>composer.json</code></p>
<p>Searching through my vendor folder, I notice the <code>mockery/mockery</code> package I use requires <code>hamcrest/hamcrest-php</code>, but I can't find anything that makes any reference to <code>cordoval</code>.</p>
<p>Any idea what's wrong and how I can fix it so that I can do the update?</p>
<p>Here's my composer.json:</p>
<pre><code>{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"require": {
"laravel/framework": "4.2.*",
"iron-io/iron_mq": "dev-master",
"phpunit/phpunit": "4.2.*",
"mockery/mockery": "dev-master",
"xethron/migrations-generator": "dev-master",
"mailgun/mailgun-php": "dev-master"
},
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php"
]
},
"scripts": {
"post-install-cmd": [
"php artisan clear-compiled",
"php artisan optimize"
],
"post-update-cmd": [
"php artisan clear-compiled",
"php artisan optimize"
],
"post-create-project-cmd": [
"php artisan key:generate"
]
},
"config": {
"preferred-install": "dist"
},
"minimum-stability": "stable"
}
</code></pre>
<h2>Update</h2>
<p>I've tried removing some of the packages from my composer.json, including the "mockery/mockery" package. The only change it made was that Composer would hang on a different file.</p>
<p>After leaving Composer running like that for quite a long time, it finally exited with an error such as the following:</p>
<pre><code>/path/to/ComposerSetup/bin/composer: line 18: 1356 Segmentation fault php "${dir}/composer.phar" $*
</code></pre>
<p>Not sure what to do about that...</p> | 32,681,601 | 14 | 4 | null | 2015-09-14 21:04:28.367 UTC | 14 | 2022-01-19 16:07:07.45 UTC | 2015-09-17 15:24:12.183 UTC | null | 1,193,304 | null | 1,193,304 | null | 1 | 60 | json|composer-php|hamcrest | 66,237 | <p>So it turns out the problem was with php's <code>xdebug</code> extension. After disabling it in my <code>php.ini</code>, composer ran without any problems.</p>
<p>And just to note, the hang-up wasn't actually occurring while reading files from the cache. It was the step right after where composer was trying to resolve dependencies. It just never finished that step and never printed the output. That's why no matter what I did, it always appeared to be stuck reading a file from the cache.</p> |
4,252,426 | WebClient Unicode - Which UTF8? | <p>When I create a WebClient to consume some RESTful xml, I can specify the unicode encoding 2 ways:</p>
<pre><code>WebClient wc = new WebClient ();
wc.Encoding = Encoding.UTF8;
wc.Encoding = UTF8Encoding.UTF8;
</code></pre>
<p>Which is correct/better ?</p> | 4,252,456 | 1 | 1 | null | 2010-11-23 03:11:57.11 UTC | 3 | 2010-11-23 17:00:32.677 UTC | 2010-11-23 17:00:32.677 UTC | null | 34,397 | null | 172,861 | null | 1 | 57 | c#|.net|unicode|utf-8|webclient | 40,363 | <p>They're identical.</p>
<p><code>UTF8Encoding</code> inherits <code>Encoding</code>.<br>
Therefore, you can access all of the static members declared by <code>Encoding</code> through the <code>UTF8Encoding</code> qualifier.</p>
<p>In fact, you can even write <code>ASCIIEncoding.UTF8</code>, and it will still work.</p>
<p>It will compile to identical IL, even in debug mode.</p>
<hr>
<p>I would recommend using <code>Encoding.UTF8</code>, as it shows what's going on more clearly.</p> |
20,108,334 | Traverse FILE line by line using fscanf | <p>Ok so i have a text file database.txt.</p>
<p>Each line is a user with the format below</p>
<pre><code>"John Smith"| 4| 80.00| "123 Lollipop Lane"| "New Jersey"| "08080"
</code></pre>
<p>When I try do the following:</p>
<pre><code>database = fopen(fileName,"r");
while(fscanf(database,"%[^\n]", buffer) != EOF) {
printf("ATTEMPT TO: Insert user %s\n\n", buffer);
if (insert_Customer(clients, create_Customer(buffer)) < 0) {
printf("\nERROR: Failed to insert and create customer %s\n", buffer);
}
else printf("\nSUCCESS: Inserted Customer %s\n\n", buffer);
}
</code></pre>
<p>It runs fine for the first line, sending in the ENTIRE line to the create_Customer(char * buffer) function. For some reason I do not understand, after this first line it continually tries to send "John Smith" instead of moving on to the next line. I believe my format is incorrect but I can't figure out how to accomplish what I am trying to accomplish which is read this file line by line and pass each line into the create_Customer function.</p> | 20,108,623 | 4 | 1 | null | 2013-11-20 22:23:18.73 UTC | 3 | 2021-06-12 09:51:51.003 UTC | 2021-06-12 09:51:51.003 UTC | null | 330,457 | null | 2,886,798 | null | 1 | 6 | c|file|printf|traversal|scanf | 53,735 | <p>I think you need a closing <code>\n</code> in your pattern. I saw the a bunch of scrolling text with the same first line with <code>%[^\n]</code>, but with <code>%[^\n]\n</code> I saw the expected output. </p>
<p>However, if the line in the file exceeds that of the buffer, you may run into a problem where your buffer doesn't have enough space. The results</p>
<h1>Test v1:</h1>
<h2>Code</h2>
<pre><code>#include <stdio.h>
int main(int argc, char * argv[])
{
FILE * database;
char buffer[30];
database = fopen("test.txt", "r");
if (NULL == database)
{
perror("opening database");
return (-1);
}
while (EOF != fscanf(database, "%[^\n]\n", buffer))
{
printf("> %s\n", buffer);
}
fclose(database);
return (0);
}
</code></pre>
<h2>Results</h2>
<pre><code>> 12343456567856789
> zbasdflkjasdfkjklsdafjklas
> zxcvjkleryjkldhfg
> 1234567890123456789012341234
> 12345678901234567890123123asdfjklzxcv;jkl;eqwrtjklkzlcxvjkleqrt41234
*** stack smashing detected ***: ./fscanf terminated
Segmentation fault (core dumped)
</code></pre>
<h1>Test v2:</h1>
<p>Let's fix the code so that we don't overrun our buffer. We do this by changing <code>%[^\n]\n</code> to <code>%30[^\n]\n</code>. This tells fscanf that it can only use upto the size of the buffer -- 30.</p>
<h2>Code</h2>
<pre><code>#include <stdio.h>
int main(int argc, char * argv[])
{
FILE * database;
char buffer[30];
database = fopen("test.txt", "r");
if (NULL == database)
{
perror("opening database");
return (-1);
}
while (EOF != fscanf(database, "%30[^\n]\n", buffer))
{
printf("> %s\n", buffer);
}
fclose(database);
return (0);
}
</code></pre>
<h2>Results</h2>
<p>It looks like it worked!</p>
<pre><code>> 12343456567856789
> zbasdflkjasdfkjklsdafjklas
> zxcvjkleryjkldhfg
> 1234567890123456789012341234
> 12345678901234567890123123asdf
> jklzxcv;jkl;eqwrtjklkzlcxvjkle
> qrt41234
</code></pre>
<h1>test.txt</h1>
<p>This is what the test file looks like that I was using.</p>
<pre><code>12343456567856789
zbasdflkjasdfkjklsdafjklas
zxcvjkleryjkldhfg
1234567890123456789012341234
12345678901234567890123123asdfjklzxcv;jkl;eqwrtjklkzlcxvjkleqrt41234
</code></pre>
<hr>
<p>Any reason you are using <code>fscanf</code> and not <code>fgets</code>?</p>
<p>One thing to note if you use <code>fgets</code>, you may want to strip the <code>\n</code> character because it will be included as part of the string.</p>
<p>From <a href="http://www.cplusplus.com/reference/cstdio/fgets/" rel="noreferrer">cplusplus.com</a> <code>fgets</code>:</p>
<blockquote>
<p>Reads characters from stream and stores them as a C string into str
until (num-1) characters have been read or either a newline or the
end-of-file is reached, whichever happens first.</p>
</blockquote>
<p><strong>Example:</strong></p>
<pre><code>/* fgets example */
#include <stdio.h>
int main()
{
FILE * database;
int res;
char buffer [100];
database = fopen(fileName,"r");
if (NULL == database) {
perror("opening database file");
return (-1);
}
/* while not end-of-file */
while (!feof(database)) {
/* we expect buffer pointer back if all is well, get out if we don't get it */
if (buffer != fgets(buffer, 100, database))
break;
/* strip /n */
int len = strlen(buffer);
if (buffer[len - 1] == '\n')
buffer[len - 1] = 0;
printf("ATTEMPT TO: Insert user %s\n\n", buffer);
if (insert_Customer(clients, create_Customer(buffer)) < 0)
printf("\nERROR: Failed to insert and create customer %s\n", buffer);
else
printf("\nSUCCESS: Inserted Customer %s\n\n", buffer);
}
/* a little clean-up */
fclose(database);
return (0);
}
</code></pre> |
6,940,120 | how to pass ip address and portnumber as url | <p>To pass url i have ip address and port number , how can that be send as http url</p>
<pre><code>ex: ip address 10.5.90.948
port number as 71
http://10.5.90.948/71
</code></pre>
<p>does that takes to the url? if not how it can be passes as http address.</p>
<p>thanks,</p>
<p>michaeld</p> | 6,940,159 | 2 | 0 | null | 2011-08-04 10:54:26.06 UTC | 2 | 2011-08-04 10:56:37.517 UTC | null | null | null | null | 790,922 | null | 1 | 11 | http|https | 43,089 | <pre><code>http://10.5.90.948:71
scheme://host:port
</code></pre> |
7,645,316 | Change style scrollbar div for my site | <p>I would like the style of the scrollbar of my div style was similar to the iPhone or the new finder osx Lion.
It must be compatible with all browsers.
Is it possible?</p> | 7,645,983 | 3 | 0 | null | 2011-10-04 08:46:37.39 UTC | 5 | 2011-10-06 16:04:26.537 UTC | 2011-10-06 16:04:26.537 UTC | null | 707,534 | null | 707,534 | null | 1 | 8 | jquery|html|css|cross-browser|scrollbar | 52,315 | <p>There are actually ways to change the looks of the scrollbars in webkit browsers, with CSS only <a href="http://css-tricks.com/9130-custom-scrollbars-in-webkit/" rel="noreferrer">http://css-tricks.com/9130-custom-scrollbars-in-webkit/</a> It is currently not possible to style scrollbars to have a uniform cross browser appearance, though. You will have to resort to jQuery to get this done <a href="http://www.net-kit.com/jquery-custom-scrollbar-plugins/" rel="noreferrer">http://www.net-kit.com/jquery-custom-scrollbar-plugins/</a></p> |
7,050,137 | Flask-principal tutorial (auth + authr) | <p>Anybody know of a good tutorial about flask-principal? I'm trying to do authentication and authorization (needRole and needIdentity) and I haven't gotten anywhere.</p>
<p>I am almost sure there's no really comprehensive tutorial -- maybe some of you has some time on their hands and would like to post a tutorial-as-answer? I'm REALLY determined to use flask instead of django but need to fix this.</p> | 9,781,669 | 3 | 3 | null | 2011-08-13 11:28:37.74 UTC | 26 | 2014-11-02 03:05:18.04 UTC | 2012-04-04 23:22:40.093 UTC | null | 500,584 | null | 845,313 | null | 1 | 29 | python|authentication|authorization|flask | 21,239 | <p>I know this question is kind of old, but a couple of days ago I was looking for the same thing so hopefully this will help someone in the future . . . </p>
<p>A good place to start is on <a href="https://github.com/mattupstate/flask-principal">the github repo for Flask-Principal</a>.</p>
<p>I've had some trouble with Flask-Principal (FP) too. If you're new to <a href="http://wiki.python.org/moin/PythonDecorators">decorators</a>, <a href="http://docs.python.org/library/stdtypes.html#context-manager-types">context-managers</a>, and <a href="http://docs.python.org/library/signal.html">signals</a> you'll probably want to research them a little before using FP.</p>
<p>Flask registers signals based on a package called <a href="http://discorporate.us/projects/Blinker/docs/1.1/signals.html">Blinker</a>. If you don't have Blinker, Flask will still allow you to <strong>declare</strong> signals however they <strong>won't do anything</strong>. To see what I mean, have a look in the source for Flask's <a href="https://github.com/mitsuhiko/flask/blob/master/flask/signals.py">signals.py</a>. </p>
<p>So why does this matter for FP? Well, it turns out that FP uses signals to register and update identities. Specifically:</p>
<ol>
<li><p><code>identity_loaded</code>: When this signal is called, we know to create an identity object for the user. (It's <strong>called</strong> via <code>Principal._set_thread_identity()</code>)</p></li>
<li><p><code>identity_changed</code>: When this signal is called, we know to update the user's identity. (When it's called it <strong>executes</strong> <code>Principal._on_identity_changed()</code>)</p></li>
</ol>
<p>So what do I mean by <em>called</em>? First, we need to know how signals are set up. Blinker works by allowing functions to "subscribe" to signals. So, for example, <code>Principal._on_identity_changed()</code> is set up as a subscriber for the signal <code>identity_changed</code>. Whenever the signal <code>identity_changed</code> is sent, _on_identity_changed() is executed. The code looks like this:</p>
<pre><code>from blinker import signal
test = signal('test')
test.connect(func_we_want_to_execute_when_signal_is_called)
</code></pre>
<p>Back to the question of how signals are called. In Blinker, signals handlers are executed when we call <code>send()</code> on the signal object. So for our <code>test</code> signal, the syntax is just:</p>
<pre><code>test.send()
</code></pre>
<p>When <code>test.send()</code> is called <code>func_we_want_to_execute_when_signal_is_called</code> will execute. Hopefully this example in the FP documentation makes a bit more sense now:</p>
<pre><code>def login_view(req):
username = req.form.get('username')
# Your authentication here.
# Notice our signal (identity_changed) is being called (identity_changed.send())
# What function is being called? Principal._on_identity_changed()
identity_changed.send(app, identity=Identity(username))
</code></pre>
<p>However we can simplify setting up signals if we use a decorator to do it for us. Pretend again that I've set up my test signal but haven't connected it. We can do:</p>
<pre><code>@test.connect
def func_we_want_to_execute_when_signal_is_called():
return stuff
</code></pre>
<p>What the above code does is essentially sets up the function we want to execute when our test signal is sent. Hopefully now the following code from the FP documentation makes sense:</p>
<pre><code># We're setting up our signal (identity_loaded)
# to execute the function below (on_identity_loaded)
# when we call our signal (identity_loaded.send())
# which is called in Principal._set_thread_identity()
@identity_loaded.connect
def on_identity_loaded(sender, identity):
# Get the user information from the db
user = db.get(identity.name)
# Update the roles that a user can provide
for role in user.roles:
identity.provides.add(RoleNeed(role.name))
# Save the user somewhere so we only look it up once
identity.user = user
</code></pre>
<p>So you can see that signals really drive the identity process. Roles and permissions are really an (easier) afterthought if you're looking for a way to do authorization of any kind.</p>
<p>For me, wrapping my head around signals was the hardest part; I hope this was helpful for someone else, too. But I'd really encourage you to read through the source code I've linked above for Flask-Principal; it is probably going to be the best way to understand what is going on.</p> |
7,045,729 | automatically position text box in matplotlib | <p>Is there a way of telling pyplot.text() a location like you can with pyplot.legend()?</p>
<p>Something like the legend argument would be excellent:</p>
<pre><code>plt.legend(loc="upper left")
</code></pre>
<p>I am trying to label subplots with different axes using letters (e.g. "A","B"). I figure there's got to be a better way than manually estimating the position.</p>
<p>Thanks</p> | 33,417,697 | 3 | 0 | null | 2011-08-12 20:06:55.837 UTC | 26 | 2019-11-29 17:33:54.997 UTC | null | null | null | null | 299,000 | null | 1 | 67 | python|textbox|matplotlib | 85,736 | <p>I'm not sure if this was available when I originally posted the question but using the loc parameter can now actually be used. Below is an example:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnchoredText
# make some data
x = np.arange(10)
y = x
# set up figure and axes
f, ax = plt.subplots(1,1)
# loc works the same as it does with figures (though best doesn't work)
# pad=5 will increase the size of padding between the border and text
# borderpad=5 will increase the distance between the border and the axes
# frameon=False will remove the box around the text
anchored_text = AnchoredText("Test", loc=2)
ax.plot(x,y)
ax.add_artist(anchored_text)
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/Vgzyo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Vgzyo.png" alt="enter image description here"></a></p> |
7,119,806 | Reading data from XML | <p>I'm planning to use XML for database purpose. Only thing I was able to do is read whole XML file. I want to be able to read only some data and I don't know how to do that.</p>
<p>Here is a simple XML</p>
<pre><code><Books>
<Book>
<Title>Animals</Title>
<Author>J. Anderson</Author>
</Book>
<Book>
<Title>Car</Title>
<Author>L. Sawer</Author>
</Book>
</Books>
</code></pre>
<p>I'm interested in app where output is gonna be</p>
<pre><code>Books:
Animals
Cars
Authors:
J. Anderson
L. Sawer
</code></pre>
<p>I'm just want to learn how read specific data from XML not whole file. </p>
<p>[SOLVED]
I have used Linq to XML</p> | 7,119,947 | 4 | 2 | null | 2011-08-19 09:46:46.83 UTC | 10 | 2017-04-24 16:18:29.177 UTC | 2015-11-07 21:49:40.073 UTC | null | 4,370,109 | null | 850,569 | null | 1 | 23 | c#|xml|database | 207,454 | <p>I don't think you can "legally" load only part of an XML file, since then it would be malformed (there would be a missing closing element somewhere).</p>
<p>Using LINQ-to-XML, you can do <code>var doc = XDocument.Load("yourfilepath")</code>. From there its just a matter of querying the data you want, say like this:</p>
<pre><code>var authors = doc.Root.Elements().Select( x => x.Element("Author") );
</code></pre>
<p>HTH.</p>
<p><strong>EDIT:</strong></p>
<p>Okay, just to make this a better sample, try this (with @JWL_'s suggested improvement):</p>
<pre><code>using System;
using System.Xml.Linq;
namespace ConsoleApplication1 {
class Program {
static void Main( string[] args ) {
XDocument doc = XDocument.Load( "XMLFile1.xml" );
var authors = doc.Descendants( "Author" );
foreach ( var author in authors ) {
Console.WriteLine( author.Value );
}
Console.ReadLine();
}
}
}
</code></pre>
<p>You will need to adjust the path in <code>XDocument.Load()</code> to point to your XML file, but the rest should work. Ask questions about which parts you don't understand.</p> |
24,262,430 | hardware requirement for hadoop installation on Laptop | <p>I am planning to gain some experience on Hadoop , MapReduce and other big data things. Initially I want to install it on laptop. I was wondering what is best Laptop hardware recommended for installing Hadoop on windows. I assume I have to install a single node installation, if not please guide me the correct configuration.
regards
Nadeem</p> | 29,223,973 | 4 | 1 | null | 2014-06-17 11:20:25.91 UTC | 3 | 2018-04-05 15:36:02.76 UTC | 2018-04-05 15:36:02.76 UTC | null | 1,513,636 | null | 2,838,082 | null | 1 | 5 | hadoop|mapreduce|hardware | 39,038 | <p>I know you mentioned wanting to install on Windows, but Cloudera is offering single-node Hadoop Linux VM images that can get you up and running in no time. You even have examples and scripts included, it's a very good place to start.</p>
<p><a href="https://www.cloudera.com/downloads.html" rel="nofollow noreferrer">https://www.cloudera.com/downloads.html</a></p>
<p>(Don't forget to look at the <a href="https://www.cloudera.com/downloads/quickstart_vms/5-10.html" rel="nofollow noreferrer">Getting Started</a> section.)</p>
<p>In my opinion, if you want to learn about Big Data and Hadoop, you should also invest some time in familiarising yourself with Linux, as most of the real environments out there are Linux-based.</p>
<p>System Requirements: Per Cloudera page, the VM takes 4GB RAM and 3GB of disk space. This means your laptop should have more than that (I'd recommend 8GB+). Storage-wise, as long as you have enough to test with small and medium-sized data sets (10s of GB), you'll be fine. As for the CPU, if your machine has that amount of RAM you'll most likely be fine. I'm using a single-node crappy Pentium G3210 with 4GB of ram for testing my small jobs and it works just fine.</p>
<p>Later if you outgrow this environment you can simply move to your own pseudo-distributed setup.</p>
<p>Of course, if what I just said makes no sense to you, then you have some reading ahead...</p> |
7,797,769 | How to add a new Class in a Scala Compiler Plugin? | <p>In a Scala Compiler Plugin, I'm trying to create a new class that implement a pre-existing trait. So far my code looks like this:</p>
<pre><code>def trait2Impl(original: ClassDef, newName: String): ClassDef = {
val impl = original.impl
// Seems OK to have same self, but does not make sense to me ...
val self = impl.self
// TODO: implement methods ...
val body = impl.body
// We implement original
val parents = original :: impl.parents
val newImpl = treeCopy.Template(impl, parents, self, body)
val name = newTypeName(newName)
// We are a syntheic class, not a user-defined trait
val mods = (original.mods | SYNTHETIC) &~ TRAIT
val tp = original.tparams
val result = treeCopy.ClassDef(original, mods, name, tp, newImpl)
// Same Package?
val owner = original.symbol.owner
// New symbol. What's a Position good for?
val symbol = new TypeSymbol(owner, NoPosition, name)
result.setSymbol(symbol)
symbol.setFlag(SYNTHETIC)
symbol.setFlag(ABSTRACT)
symbol.resetFlag(INTERFACE)
symbol.resetFlag(TRAIT)
owner.info.decls.enter(symbol)
result
}
</code></pre>
<p>But it doesn't seem to get added to the package. I suspect that is because actually the package got "traversed" before the trait that causes the generation, and/or because the "override def transform(tree: Tree): Tree" method of the TypingTransformer can only return <em>one</em> Tree, for every Tree that it receives, so it cannot actually produce a new Tree, but only modify one.</p>
<p>So, how do you add a new Class to an existing package? Maybe it would work if I transformed the package when "transform(Tree)" gets it, but I that point I don't know the content of the package yet, so I cannot generate the new Class this early (or could I?). Or maybe it's related to the "Position" parameter of the Symbol?</p>
<p>So far I found several examples where Trees are modified, but none where a completely new Class is created in a Compiler Plugin.</p> | 9,236,583 | 1 | 6 | null | 2011-10-17 18:11:49.807 UTC | 3 | 2012-02-11 00:11:44.537 UTC | null | null | null | null | 481,602 | null | 1 | 35 | scala | 1,079 | <p>The full source code is here: <a href="https://gist.github.com/1794246" rel="nofollow">https://gist.github.com/1794246</a></p>
<p>The trick is to store the newly created <code>ClassDef</code>s and use them when creating a new <code>PackageDef</code>. Note that you need to deal with both Symbols and trees: a package symbol is just a handle. In order to generate code, you need to generate an AST (just like for a class, where the symbol holds the class name and type, but the code is in the <code>ClassDef</code> trees).</p>
<p>As you noted, package definitions are higher up the tree than classes, so you'd need to recurse first (assuming you'll generate the new class from an existing class). Then, once the subtrees are traversed, you can prepare a new PackageDef (every compilation unit has a package definition, which by default is the empty package) with the new classes. </p>
<p>In the example, assuming the source code is </p>
<pre><code>class Foo {
def foo {
"spring"
}
}
</code></pre>
<p>the compiler wraps it into</p>
<pre><code>package <empty> {
class Foo {
def foo {
"spring"
}
}
}
</code></pre>
<p>and the plugin transforms it into</p>
<pre><code>package <empty> {
class Foo {
def foo {
"spring"
}
}
package mypackage {
class MyClass extends AnyRef
}
}
</code></pre> |
21,629,752 | Using node http-proxy to proxy websocket connections | <p>I have an application that uses websockets via socket.io. For my application I would like to use a separate HTTP server for serving the static content and JavaScript for my application. Therefore, I need to put a proxy in place.</p>
<p>I am using <a href="https://github.com/nodejitsu/node-http-proxy" rel="noreferrer">node-http-proxy</a>. As a starting point I have my websockets app running on port 8081. I am using the following code to re-direct socket.io communications to this standalone server, while using express to serve the static content:</p>
<pre><code>var http = require('http'),
httpProxy = require('http-proxy'),
express = require('express');
// create a server
var app = express();
var proxy = httpProxy.createProxyServer({ ws: true });
// proxy HTTP GET / POST
app.get('/socket.io/*', function(req, res) {
console.log("proxying GET request", req.url);
proxy.web(req, res, { target: 'http://localhost:8081'});
});
app.post('/socket.io/*', function(req, res) {
console.log("proxying POST request", req.url);
proxy.web(req, res, { target: 'http://localhost:8081'});
});
// Proxy websockets
app.on('upgrade', function (req, socket, head) {
console.log("proxying upgrade request", req.url);
proxy.ws(req, socket, head);
});
// serve static content
app.use('/', express.static(__dirname + "/public"));
app.listen(8080);
</code></pre>
<p>The above application works just fine, however, I can see that socket.io is no longer using websockets, it is instead falling back to XHR polling.</p>
<p>I can confirm that by looking at the logs from the proxy code:</p>
<pre><code>proxying GET request /socket.io/1/?t=1391781619101
proxying GET request /socket.io/1/xhr-polling/f-VVzPcV-7_IKJJtl6VN?t=13917816294
proxying POST request /socket.io/1/xhr-polling/f-VVzPcV-7_IKJJtl6VN?t=1391781629
proxying GET request /socket.io/1/xhr-polling/f-VVzPcV-7_IKJJtl6VN?t=13917816294
proxying GET request /socket.io/1/xhr-polling/f-VVzPcV-7_IKJJtl6VN?t=13917816294
</code></pre>
<p>Does anyone know how to proxy the web sockets communication? All the examples from <code>node-http-proxy</code> assume that you want to proxy all traffic, rather than proxying some and serving others.</p> | 22,605,135 | 2 | 2 | null | 2014-02-07 14:03:12.65 UTC | 8 | 2014-03-24 09:14:35.047 UTC | null | null | null | null | 249,933 | null | 1 | 15 | node.js|websocket|socket.io|node-http-proxy | 18,336 | <p>Just stumbled upon your question, and I see that it is still not answered. Well, in case you are still looking for the solution...
The problem in your code is that <code>app.listen(8080)</code> is just syntactic sugar for</p>
<pre><code>require('http').createServer(app).listen(8080)
</code></pre>
<p>while <code>app</code> itself is just a handler function, not an instance of httpServer (I personally believe that this feature should be removed from Express to avoid confusion).
Thus, your <code>app.on('upgrade')</code> is actually never used. You should instead write</p>
<pre><code>var server = require('http').createServer(app);
server.on('upgrade', function (req, socket, head) {
proxy.ws(req, socket, head);
});
server.listen(8080);
</code></pre>
<p>Hope, that helps.</p> |
2,306,470 | Finding the URL for podcast feeds from an iTunes id. (iTMS API) | <p>I'm look at a way of turning an iTunes podcast id into the RSS feed that the podcast producer serves.</p>
<p>I'm aware of the <a href="http://ax.itunes.apple.com/rss" rel="noreferrer">RSS generator</a>, which can be used to generate a feed of links to podcasts, but these links are to HTML pages. </p>
<p>If you have iTunes open, you can manually export the list of podcasts by exporting to OPML, so we can surmise that iTunes eventually knows how to decode them (i.e. they're not exclusively going through an iTMS host).</p>
<p>I have looked at the <a href="http://www.apple.com/itunesaffiliates/API/AffiliatesSearch2.1.pdf" rel="noreferrer">Affiliate API document</a> which gives you some nice JSON back. This gives you a <code>collectionViewUrl</code> which is the same as the ones given in the RSS generator, and incidentally, the <a href="http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/itmsLinkMaker" rel="noreferrer">iTunes Link Generator</a>. It also give you the <code>id</code>, and a whole load of other things including a preview audio file which is not hosted on the phobos.</p>
<p>At this point, I'm looking for anything that would help me solve this question, including any language, unofficial or not. </p>
<p>(in actual fact, I'd prefer something vaguely supported, and in Java, that didn't involve HTML scraping).</p> | 3,987,322 | 4 | 0 | null | 2010-02-21 16:13:55.173 UTC | 17 | 2021-12-06 00:56:02.81 UTC | 2010-08-07 22:35:14.24 UTC | null | 4,737 | null | 4,737 | null | 1 | 16 | api|rss|itunes|podcast | 8,295 | <p>Through a combination of answers from <a href="https://stackoverflow.com/questions/2816881/get-the-latest-podcasts-from-itunes-store-with-link-by-rss-json-or-something">these</a> <a href="https://stackoverflow.com/questions/423714/get-a-list-of-itunes-podcasts-available">two</a> questions, I have found a way to do what I want.</p>
<h2>Example of finding podcasts</h2>
<p>First: grab a list of podcasts from iTunes, using the RSS generator. I'm not sure how the query parameters work yet, but here is an RSS feed for top tech podcasts in the US.</p>
<pre><code>http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/toppodcasts/sf=143441/limit=25/genre=1318/xml
</code></pre>
<ul>
<li><code>sf</code> relates to country, and is optional. I would guess that this defaults to global if absent. </li>
<li><code>genre</code> relates to genre, and is optional. I would guess that this defaults to "all genres" is absent.</li>
<li><code>limit</code> is optional, and seems to default to 9.</li>
</ul>
<p>This gives you an Atom feed of podcasts. You'll need to do some sperlunking with XPath to get to the ITMS id of podcast, but you're looking for the numeric id contained in the URL found at the following XPath: </p>
<pre><code>/atom:feed/atom:entry/atom:link[@rel='alernate']/@href
</code></pre>
<p>For example, the excellent JavaPosse has an id of 81157308.</p>
<h2>The Answer to the Question</h2>
<p>Once you have that id, you can get another document which will tell you the last episode, and the original feed URL. The catch here is that you need to use an iTunes user-agent to get this document.</p>
<p>e.g. </p>
<pre><code>wget --user-agent iTunes/7.4.1 \
--no-check-certificate \
"https://buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/com.apple.jingle.app.finance.DirectAction/subscribePodcast?id=81157308&wasWarnedAboutPodcasts=true"
</code></pre>
<p>This is a plist containing some metadata about the podcast, including the feed URL. </p>
<pre><code><key>feedURL</key><string>http://feeds.feedburner.com/javaposse</string>
</code></pre>
<p>The XPath for this could be something like: </p>
<pre><code>//key[@text='feedURL']/following-sibling::string/text()
</code></pre>
<h2>Disclaimer</h2>
<p>Not entirely sure how stable any of this is, or how legal it is. YMMV.</p> |
1,349,868 | How to write a functional specification? | <p>We always write functions or classes and their logic is very complicated.
If there is no specification for these structures, later it will be hard for even ourselves to grasp the ideas. </p>
<p>How do you write specifications for complicated functions and classes?</p>
<p>Please tell me something about your own experience, but not just some link, thanks.</p> | 1,349,914 | 4 | 4 | null | 2009-08-28 23:28:43.14 UTC | 15 | 2014-11-14 14:46:36.047 UTC | 2009-08-29 07:45:59.503 UTC | null | 49,246 | null | 140,899 | null | 1 | 18 | specifications|functional-specifications | 18,386 | <p>I find the biggest challenge with functional specifications is not the format directly, but keeping them in sync with things that drive them (requirements) and things that build upon them (test cases, documentation).</p>
<p>For that reason, I prefer to handle this issue with a model-driven approach rather than a paper-driven one.</p>
<p>I use a UML modeling tool (Enterprise Architect by Sparx Systems, but many tools work as well) to capture all of the artifacts of the project in one place and create traceability between them. In Enterprise Architect, I can create traceability from a requirement artifact to a design artifact (for example) by just putting them both on the same diagram and creating a connector from one to the other with a mouse drag.</p>
<p>My "functional specification" is actually a collection of activity diagrams, one per use case in the system. Each use case ties back to one or more requirements that necessitate that use case. Even end users find it easy enough to follow the activity diagrams and validate them (how easy is it to get end users to read, let alone understand and validate, a traditional, paper-based functional specification?)</p>
<p>In a similar manner, I can create traceability from my activity diagrams (use cases) to specific design artifacts like class diagrams.</p>
<p>QA can model test cases and create traceability from their test cases to the use cases. That way, we see if there are any use cases that do not have test cases (or don't have enough test cases).</p>
<p>The nice thing about Enterprise Architect as a tool is that all of these artifacts are stored in a SQL database, so I can just run some queries that I have built up over time to find artifacts with nothing tracing to/from them.</p> |
2,092,890 | Add hyperlink to textblock WPF | <p>I have some text in a db and it is as follows:</p>
<blockquote>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis
tellus nisl, venenatis et pharetra ac, tempor sed sapien. Integer
pellentesque blandit velit, in tempus urna semper sit amet. Duis
mollis, libero ut consectetur interdum, massa tellus posuere nisi, eu
aliquet elit lacus nec erat. Praesent a commodo quam. <code>[a href='http://somesite.example]some site[/a]</code> Suspendisse at nisi sit amet
massa molestie gravida feugiat ac sem. Phasellus ac mauris ipsum, vel
auctor odio</p>
</blockquote>
<p>My question is: How can I display a <code>Hyperlink</code> in a <code>TextBlock</code>? I don't want to use a webBrowser control for this purpose.
I don't want to use this control either: <a href="https://www.codeproject.com/Articles/33196/WPF-Html-supported-TextBlock" rel="nofollow noreferrer">https://www.codeproject.com/Articles/33196/WPF-Html-supported-TextBlock</a></p> | 2,118,635 | 4 | 0 | null | 2010-01-19 10:56:30.023 UTC | 14 | 2022-06-19 10:00:07.55 UTC | 2022-06-19 09:58:28.193 UTC | null | 1,145,388 | null | 218,450 | null | 1 | 41 | html|wpf|hyperlink|textblock | 53,541 | <p>You can use Regex with a value converter in such situation. </p>
<p>Use this for your requirements (original idea from <a href="https://stackoverflow.com/questions/26323/regex-to-parse-hyperlinks-and-descriptions/26339#26339">here</a>):</p>
<pre><code> private Regex regex =
new Regex(@"\[a\s+href='(?<link>[^']+)'\](?<text>.*?)\[/a\]",
RegexOptions.Compiled);
</code></pre>
<p>This will match all links in your string containing links, and make 2 named groups for each match : <code>link</code> and <code>text</code></p>
<p>Now you can iterate through all the matches. Each match will give you a</p>
<pre><code> foreach (Match match in regex.Matches(stringContainingLinks))
{
string link = match.Groups["link"].Value;
int link_start = match.Groups["link"].Index;
int link_end = match.Groups["link"].Index + link.Length;
string text = match.Groups["text"].Value;
int text_start = match.Groups["text"].Index;
int text_end = match.Groups["text"].Index + text.Length;
// do whatever you want with stringContainingLinks.
// In particular, remove whole `match` ie [a href='...']...[/a]
// and instead put HyperLink with `NavigateUri = link` and
// `Inlines.Add(text)`
// See the answer by Stanislav Kniazev for how to do this
}
</code></pre>
<p><strong>Note :</strong> use this logic in your custom <code>ConvertToHyperlinkedText</code> value converter.</p> |
1,684,202 | How to round an integer up or down to the nearest 10 using Javascript | <p>Using Javascript, I would like to round a number passed by a user to the nearest 10. For example, if 7 is passed I should return 10, if 33 is passed I should return 30.</p> | 1,684,207 | 4 | 0 | null | 2009-11-05 22:46:40.68 UTC | 7 | 2022-03-20 15:21:35.007 UTC | 2014-05-14 18:14:56.67 UTC | null | 58 | null | 51,649 | null | 1 | 97 | javascript | 92,100 | <p>Divide the number by <code>10</code>, round the result and multiply it with <code>10</code> again, for example:</p>
<ol>
<li><code>33 / 10 = 3.3</code></li>
<li><code>3.3 rounded = 3</code></li>
<li><code>3 × 10 = 30</code></li>
</ol>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log(Math.round(prompt('Enter a number', 33) / 10) * 10);</code></pre>
</div>
</div>
</p> |
1,934,826 | What's the difference between a Resource and an Embedded Resource in a C# application? | <p>When should I use one or the other?</p>
<p>I'd like all of the files I use in my app (images, sound, xml file, etc.) to be inside of the .exe file so I don't deploy with a bunch of folders and files.</p>
<p>Thanks for the info.</p> | 1,935,035 | 4 | 0 | null | 2009-12-20 04:18:06.393 UTC | 13 | 2019-04-21 07:11:25.93 UTC | 2018-06-03 23:31:15.257 UTC | null | 584,192 | null | 112,355 | null | 1 | 100 | c#|.net|wpf|resources|embedded-resource | 38,179 | <p>“Resource” and “Content” build actions are to access the WPF resources using the Uris. However “Embedded Resource” is for prior technologies. However both options embed the resource in assembly but “Resource” option to be used for WPF.</p>
<p>MSDN provides full explanation <a href="https://docs.microsoft.com/en-us/dotnet/framework/wpf/app-development/wpf-application-resource-content-and-data-files" rel="noreferrer">here</a>.</p> |
10,406,135 | UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 2: ordinal not in range(128) | <p>I am attempting to work with a very large dataset that has some non-standard characters in it. I need to use unicode, as per the job specs, but I am baffled. (And quite possibly doing it all wrong.)</p>
<p>I open the CSV using:</p>
<pre><code> 15 ncesReader = csv.reader(open('geocoded_output.csv', 'rb'), delimiter='\t', quotechar='"')
</code></pre>
<p>Then, I attempt to encode it with:</p>
<pre><code>name=school_name.encode('utf-8'), street=row[9].encode('utf-8'), city=row[10].encode('utf-8'), state=row[11].encode('utf-8'), zip5=row[12], zip4=row[13],county=row[25].encode('utf-8'), lat=row[22], lng=row[23])
</code></pre>
<p>I'm encoding everything except the lat and lng because those need to be sent out to an API. When I run the program to parse the dataset into what I can use, I get the following Traceback.</p>
<pre><code>Traceback (most recent call last):
File "push_into_db.py", line 80, in <module>
main()
File "push_into_db.py", line 74, in main
district_map = buildDistrictSchoolMap()
File "push_into_db.py", line 32, in buildDistrictSchoolMap
county=row[25].encode('utf-8'), lat=row[22], lng=row[23])
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 2: ordinal not in range(128)
</code></pre>
<p>I think I should tell you that I'm using python 2.7.2, and this is part of an app build on django 1.4. I've read several posts on this topic, but none of them seem to directly apply. Any help will be greatly appreciated.</p>
<p>You might also want to know that some of the non-standard characters causing the issue are Ñ and possibly É.</p> | 10,406,161 | 12 | 2 | null | 2012-05-02 00:17:08.873 UTC | 38 | 2022-07-18 22:23:41.613 UTC | null | null | null | null | 1,368,892 | null | 1 | 121 | python|django|utf-8 | 362,491 | <p>Unicode is not equal to UTF-8. The latter is just an <em>encoding</em> for the former.</p>
<p>You are doing it the wrong way around. You are <em>reading</em> UTF-8-<em>encoded</em> data, so you have to <em>decode</em> the UTF-8-encoded String into a unicode string.</p>
<p>So just replace <code>.encode</code> with <code>.decode</code>, and it should work (if your .csv is UTF-8-encoded).</p>
<p>Nothing to be ashamed of, though. I bet 3 in 5 programmers had trouble at first understanding this, if not more ;)</p>
<p>Update:
If your input data is <em>not</em> UTF-8 encoded, then you have to <code>.decode()</code> with the appropriate encoding, of course. If nothing is given, python assumes ASCII, which obviously fails on non-ASCII-characters.</p> |
7,097,684 | VBA: Arrays and Global Variable Declarations | <p>I need to declare an array in VBA that will be used by every function. However, I cannot declare it as a global as I would do in C++.</p>
<p>My code is as follows:</p>
<pre><code>Option Explicit
Dim test(0 to 10) as String
test(0) = "avds"
test(1) = "fdsafs"
....
</code></pre>
<p>The following conceptualizes what I am trying to do. </p>
<pre><code> public function store() as boolean
Worksheets("test").cells(1,1) = test(0)
End Function
</code></pre>
<p>How can I achieve this functionality?</p> | 7,098,968 | 5 | 0 | null | 2011-08-17 18:33:04.193 UTC | 1 | 2019-06-18 09:48:40.977 UTC | 2018-07-09 18:41:45.953 UTC | null | -1 | null | 684,101 | null | 1 | 3 | arrays|excel|global-variables|scope|vba | 40,231 | <p>For global declaration, change Dim to Public like so:</p>
<pre><code>Public test(0 to 10) as String
</code></pre>
<p>You can call this like (assuming it is in Module1, else change Module1 to whatever you've named it):</p>
<pre><code>Module1.test(0) = "something"
</code></pre>
<p>Or simply:</p>
<pre><code>test(0) = "something"
</code></pre> |
7,290,298 | convert integer to std_logic | <p>Suppose you have a loop</p>
<pre><code>for i in 1 downto 0 loop
for j in 1 downto 0 loop
tS0 <= i;
</code></pre>
<p>But I need to convert the integer (which is natural) to std_logic. <strong>tS0</strong> is declared as std_logic. I am only doing it one bit (0 or 1). That is, my <strong>i</strong> and <strong>j</strong> can only represent the value {0,1}. </p>
<p>I think I am heading to the wrong approach here. Can someone please tell me what should I do instead? </p>
<p>I don't think std_logic has to_unsigned method. i tried letting <strong>tS0</strong> to be a vector (1 down to 0), and assigned like <strong>tS0(0) <= i</strong>, and etc. But it still didn't work out.</p>
<p>Thank you very much!</p> | 7,291,124 | 5 | 1 | null | 2011-09-03 00:06:30.88 UTC | 2 | 2018-11-19 09:13:21.693 UTC | null | null | null | null | 230,884 | null | 1 | 7 | vhdl | 57,044 | <p>You will need to use a vector, either unsigned or std_logic, but it can be one bit long. ie:</p>
<pre><code>signal tS0 : unsigned (0 downto 0);
...
tS0 <= to_unsigned(i, tS0'length);
</code></pre>
<p>...or...</p>
<pre><code>signal tS0: std_logic_vector(0 downto 0);
...
tS0 <= std_logic_vector(to_unsigned(i,tS0'length);
</code></pre> |
7,164,184 | Suppress directory names being listed with DIR | <p>I want to list the files in a folder but not sub-folders. <code>DIR</code> enables you to list specific types of files (hidden, archive ready etc) and also only folders but I cannot see how to list only files.</p>
<p>I need the following statement to return files for further processing, but folder names are messing things up!</p>
<pre><code>for /f %%a in ('dir /b %csvPath%') do (
)
</code></pre> | 7,164,243 | 5 | 0 | null | 2011-08-23 16:15:29.77 UTC | 6 | 2015-08-31 15:39:35.16 UTC | 2015-08-31 15:39:35.16 UTC | null | 3,826,372 | null | 898,377 | null | 1 | 23 | windows|cmd | 44,753 | <p><code>dir /b /a-d</code> will give you files without directories. Note there is no space between <code>/a-d</code>. The '-' says "NOT" directories.</p>
<p>From the <code>dir /?</code> help information:</p>
<pre><code> /A Displays files with specified attributes.
attributes D Directories R Read-only files
H Hidden files A Files ready for archiving
S System files - Prefix meaning not
/B Uses bare format (no heading information or summary).
</code></pre> |
7,450,940 | Automatic HTTPS connection/redirect with node.js/express | <p>I've been trying to get HTTPS set up with a node.js project I'm working on. I've essentially followed the <a href="http://nodejs.org/docs/v0.4.11/api/https.html">node.js documentation</a> for this example:</p>
<pre><code>// curl -k https://localhost:8000/
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);
</code></pre>
<p>Now, when I do </p>
<pre><code>curl -k https://localhost:8000/
</code></pre>
<p>I get </p>
<pre><code>hello world
</code></pre>
<p>as expected. But if I do </p>
<pre><code>curl -k http://localhost:8000/
</code></pre>
<p>I get </p>
<pre><code>curl: (52) Empty reply from server
</code></pre>
<p>In retrospect this seems obvious that it would work this way, but at the same time, people who eventually visit my project aren't going to type in <strong>https</strong>://yadayada, and I want all traffic to be https from the moment they hit the site. </p>
<p>How can I get node (and Express as that is the framework I'm using) to hand off all incoming traffic to https, regardless of whether or not it was specified? I haven't been able to find any documentation that has addressed this. Or is it just assumed that in a production environment, node has something that sits in front of it (e.g. nginx) that handles this kind of redirection?</p>
<p>This is my first foray into web development, so please forgive my ignorance if this is something obvious.</p> | 7,458,587 | 22 | 1 | null | 2011-09-16 22:15:28.12 UTC | 100 | 2022-01-19 15:37:08.46 UTC | null | null | null | null | 949,645 | null | 1 | 229 | node.js|https|express | 239,007 | <p>Ryan, thanks for pointing me in the right direction. I fleshed out your answer (2nd paragraph) a little bit with some code and it works. In this scenario these code snippets are put in my express app:</p>
<pre><code>// set up plain http server
var http = express();
// set up a route to redirect http to https
http.get('*', function(req, res) {
res.redirect('https://' + req.headers.host + req.url);
// Or, if you don't want to automatically detect the domain name from the request header, you can hard code it:
// res.redirect('https://example.com' + req.url);
})
// have it listen on 8080
http.listen(8080);
</code></pre>
<p>The https express server listens ATM on 3000. I set up these iptables rules so that node doesn't have to run as root:</p>
<pre><code>iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 3000
</code></pre>
<p>All together, this works exactly as I wanted it to.</p>
<p>To prevent theft of cookies over HTTP, see <a href="http://stackoverflow.com/questions/8605720/how-to-force-ssl-https-in-express-js#comment-14832113">this answer</a> (from the comments) or use this code:</p>
<pre class="lang-js prettyprint-override"><code>const session = require('cookie-session');
app.use(
session({
secret: "some secret",
httpOnly: true, // Don't let browser javascript access cookies.
secure: true, // Only use cookies over https.
})
);
</code></pre> |
14,166,591 | Automate npm and bower install with grunt | <p>I have a node / angular project that uses npm for backend dependency management and bower for frontend dependency management. I'd like to use a grunt task to do both install commands. I haven't been able to figure out how to do it.</p>
<p>I made an attempt using <code>exec</code>, but it doesn't actually install anything.</p>
<pre><code>module.exports = function(grunt) {
grunt.registerTask('install', 'install the backend and frontend dependencies', function() {
// adapted from http://www.dzone.com/snippets/execute-unix-command-nodejs
var exec = require('child_process').exec,
sys = require('sys');
function puts(error, stdout, stderr) { console.log(stdout); sys.puts(stdout) }
// assuming this command is run from the root of the repo
exec('bower install', {cwd: './frontend'}, puts);
});
};
</code></pre>
<p>When I <code>cd</code> into frontend, open up <code>node</code>, and run this code from the console, this works fine. What am I doing wrong in the grunt task?</p>
<p>(I also tried to use the bower and npm APIs, but couldn't make that work either.)</p> | 14,284,130 | 5 | 1 | null | 2013-01-04 23:15:27.18 UTC | 29 | 2016-01-08 22:36:39.047 UTC | null | null | null | null | 147,601 | null | 1 | 63 | javascript|node.js|npm|bower|gruntjs | 29,492 | <p>You need to tell grunt that you're using an async method (<code>.exec</code>) by calling the <code>this.async()</code> method, getting a callback, and calling that when exec is done.</p>
<p>This should work:</p>
<pre><code>module.exports = function(grunt) {
grunt.registerTask('install', 'install the backend and frontend dependencies', function() {
var exec = require('child_process').exec;
var cb = this.async();
exec('bower install', {cwd: './frontend'}, function(err, stdout, stderr) {
console.log(stdout);
cb();
});
});
};
</code></pre>
<p>See <a href="http://gruntjs.com/frequently-asked-questions#why-doesn-t-my-asynchronous-task-complete">Why doesn't my asynchronous task complete?</a></p> |
32,823,046 | C++ std::function variable with varying arguments | <p>In my callback system I want to store <code>std::function</code> (or something else) with varying arguments.</p>
<p>Example:</p>
<ol>
<li>I want to call <code>void()</code> </li>
<li>I want to call <code>void(int, int)</code></li>
</ol>
<p>I want 1) and 2) to be stored in the same variable and choose what to call in actuall call</p>
<pre><code>FunctionPointer f0;
FunctionPointer f2;
f0();
f2(4, 5);
</code></pre>
<p>Is it possible to do something like this? Or I have to create several "FuntionPointer" templates based on input arguments count.</p>
<p><strong>EDIT</strong></p>
<p>Is it possible to utilize std::bind somehow for this task? With std::bind I can have <code>std::function<void()> f = std::bind(test, 2, 5);</code></p>
<p><strong>EDIT 2</strong></p>
<p>Practical use case: I have a trigger system and I want to assign funtion pointers to actions, so when action happen, function is called.
Pseudo-code sample:</p>
<pre><code>structure Trigger
{
Function f;
}
Init:
Trigger0.f = pointer to some function ()
Trigger1.f = pointer to some function (a, b)
Input:
Find Trigger by input
if (in == A) Trigger.f();
else Trigger.f(10, 20)
</code></pre>
<p>or if possible</p>
<pre><code>Input:
Find Trigger by input
if (in == A) f = bind(Trigger.f);
else f = bind(Trigger.f, 10, 20);
f()
</code></pre> | 32,825,041 | 6 | 4 | null | 2015-09-28 12:30:51.663 UTC | 9 | 2015-09-30 08:53:23.26 UTC | 2015-09-28 15:32:19.643 UTC | null | 1,130,231 | null | 1,130,231 | null | 1 | 17 | c++|c++11 | 20,001 | <p>Well, if you can use RTTI, you can define a <code>MultiFuncObject</code> like this, and you can easily bind other functions. Also, you can easily call them. But unfortunately, this approach only works for a limited number of arguments. But actually <code>boost::bind</code> also supports limited number of arguments (by default 9). So you can extend this class to satisfy your needs.</p>
<p>Before giving you the source of <code>MultiFuncObject</code>, I want to show you how you can use it. It takes an template argument to be used as return type. You can bind new functions with <code>+=</code> operator. With some template magic, the class distinguishes differences between bound functions with same count of arguments with at least one different argument type.</p>
<p>You need C++11, because <code>MultiFuncObject</code> uses <code>std::unordered_map</code> and <code>std::type_index</code>.</p>
<p>Here is usage:</p>
<pre><code>#include <iostream>
using namespace std;
void _1() {
cout << "_1" << endl;
}
void _2(char x) {
cout << "_2" << " " << x << endl;
}
void _3(int x) {
cout << "_3" << " " << x << endl;
}
void _4(double x) {
cout << "_4" << " " << x << endl;
}
void _5(int a, int b) {
cout << "_5" << " " << a << " " << b << endl;
}
void _6(char a, int b) {
cout << "_6" << " " << a << " " << b << endl;
}
void _7(int a, int b, int c) {
cout << "_7" << " " << a << " " << b << " " << c << endl;
}
int main() {
MultiFuncObject<void> funcs;
funcs += &_1;
funcs += &_2;
funcs += &_3;
funcs += &_4;
funcs += &_5;
funcs += &_6;
funcs += &_7;
funcs();
funcs('a');
funcs(56);
funcs(5.5);
funcs(2, 5);
funcs('q', 6);
funcs(1, 2, 3);
return 0;
}
</code></pre>
<p>I hope this is close to what you want. Here is the source of <code>MultiFuncObject</code>:</p>
<pre><code>#include <typeinfo>
#include <typeindex>
#include <unordered_map>
using namespace std;
template <typename R>
class MultiFuncObject {
unordered_map<type_index, void (*)()> m_funcs;
public:
MultiFuncObject<R> operator +=( R (* f)() ) {
m_funcs[typeid( R() )] = (void (*)()) f;
return *this;
}
template <typename A1>
MultiFuncObject<R> operator +=( R (* f)(A1) ) {
m_funcs[typeid( R(A1) )] = (void (*)()) f;
return *this;
}
template <typename A1, typename A2>
MultiFuncObject<R> operator +=( R (* f)(A1, A2) ) {
m_funcs[typeid( R(A1, A2) )] = (void (*)()) f;
return *this;
}
template <typename A1, typename A2, typename A3>
MultiFuncObject<R> operator +=( R (* f)(A1, A2, A3) ) {
m_funcs[typeid( R(A1, A2, A3) )] = (void (*)()) f;
return *this;
}
R operator()() const
{
unordered_map<type_index, void (*)()>::const_iterator it = m_funcs.find(typeid( R() ));
if (it != m_funcs.end()) {
R (*f)() = ( R (*)() )(it->second);
(*f)();
}
}
template <typename A1>
R operator()(A1 a1) const
{
unordered_map<type_index, void (*)()>::const_iterator it = m_funcs.find(typeid( R(A1) ));
if (it != m_funcs.end()) {
R (*f)(A1) = ( R (*)(A1) )(it->second);
(*f)(a1);
}
}
template <typename A1, typename A2>
R operator()(A1 a1, A2 a2) const
{
unordered_map<type_index, void (*)()>::const_iterator it = m_funcs.find(typeid( R(A1, A2) ));
if (it != m_funcs.end()) {
R (*f)(A1, A2) = ( R (*)(A1, A2) )(it->second);
(*f)(a1, a2);
}
}
template <typename A1, typename A2, typename A3>
R operator()(A1 a1, A2 a2, A3 a3) const
{
unordered_map<type_index, void (*)()>::const_iterator it = m_funcs.find(typeid( R(A1, A2, A3) ));
if (it != m_funcs.end()) {
R (*f)(A1, A2, A3) = ( R (*)(A1, A2, A3) )(it->second);
(*f)(a1, a2, a3);
}
}
};
</code></pre>
<p>It stores different function prototypes using <code>std::unordered_map</code> with keys of <code>std::type_index</code> and values of <code>void (*)()</code>. When needed, the correct function is retrieved using that map.</p>
<p><a href="http://ideone.com/g2mdq4" rel="nofollow">Here is the working example</a></p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.