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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
43,317,026 | Kotlin- naming convention for boolean returning methods | <p>What is the naming convention for boolean returning methods?</p>
<p>Using an 'is', 'has', 'should', 'can' in the front of method sound ok for some cases, but I'm not sure.
Is there a better way to name such methods?
for example: a function that checks card's validation. Should I call it <code>isValidCard</code> or <code>cardValidation</code> or another name?
(I didn't find it here: <a href="https://kotlinlang.org/docs/reference/coding-conventions.html" rel="noreferrer">https://kotlinlang.org/docs/reference/coding-conventions.html</a>)</p> | 43,317,781 | 3 | 0 | null | 2017-04-10 07:20:05.243 UTC | 3 | 2019-12-11 19:59:56.903 UTC | 2019-12-11 19:59:56.903 UTC | null | 4,774,054 | null | 5,188,979 | null | 1 | 29 | naming-conventions|kotlin | 10,878 | <p>Kotlin naming style assumes you use the Java naming conventions to the possible extend. I suggest you use <a href="https://stackoverflow.com/a/3874378/3144601">this answer</a> to the same question about Java.</p>
<p>UPDATE: they have released coding conventions
<a href="http://kotlinlang.org/docs/reference/coding-conventions.html" rel="noreferrer">http://kotlinlang.org/docs/reference/coding-conventions.html</a></p> |
2,342,935 | How to schedule a stored procedure? | <p>How do I schedule a stored procedure in Sql Server 2005 that it runs once at the start of every month (and on database startup)?</p> | 2,342,947 | 2 | 0 | null | 2010-02-26 16:07:39.397 UTC | 6 | 2018-04-30 15:32:23.833 UTC | 2010-03-06 04:55:56.033 UTC | null | 164,901 | null | 155,077 | null | 1 | 22 | sql|sql-server|stored-procedures|scheduled-tasks | 104,299 | <p>You will need to <a href="http://msdn.microsoft.com/en-us/library/ms186273.aspx" rel="noreferrer">create a job</a> using the <a href="http://msdn.microsoft.com/en-us/library/ms189237.aspx" rel="noreferrer">SQL Server Agent</a>.</p> |
2,873,899 | Javascript in UIWebView callback to C/Objective-C | <p>Is there a way to get a callback to objective-c when a certain event has been detected in a UIWebView? Can Javascript send a callback to Objective-C?</p> | 2,873,952 | 2 | 0 | null | 2010-05-20 13:01:43.79 UTC | 17 | 2015-06-29 14:04:42.527 UTC | 2012-08-10 18:14:02.867 UTC | null | 1,105,514 | null | 56,380 | null | 1 | 35 | javascript|objective-c|ios|cocoa-touch|uiwebview | 26,986 | <p>Update - don't use UIWebView anymore. Use WKWebView, or better yet (if it fits your needs and you're building for iOS 9), a Safari View Controller.</p>
<p>But if you must use UIWebView, in your UIWebView delegate, provide an implementation for <a href="http://developer.apple.com/iphone/library/documentation/uikit/reference/UIWebViewDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UIWebViewDelegate/webView:shouldStartLoadWithRequest:navigationType:" rel="nofollow noreferrer">webView:shouldStartLoadWithRequest:navigationType:</a></p>
<p>In your HTML or Javascript files, add functions that send URLs to a custom scheme (for readability purposes, the custom scheme isn't required). All the URLs sent will be passed to your Objective-C method implementation, and then you can do what you'd like.</p> |
42,228,653 | Exoplayer adaptive hls streaming | <p>I am looking for good and simple example/explanation how to implement <code>ExoPlayer</code> for <code>HLS Adaptive</code> streaming. I am a newbie and do not have experience and knowledge so I can figure how to do this from code example on git.</p>
<p>There are too many 'moving parts' so beginner can understand and reuse it in own projects.</p>
<p>Can somebody help me to learn and understand how to use/implement <code>ExoPlayer</code> in order to achieve this functionality?</p>
<p>Thanks!</p> | 42,362,368 | 2 | 0 | null | 2017-02-14 14:25:37.957 UTC | 8 | 2018-08-06 23:13:48.637 UTC | 2017-02-14 14:57:24.387 UTC | null | 6,340,602 | null | 4,011,802 | null | 1 | 11 | android|http-live-streaming|exoplayer|adaptive-bitrate | 16,756 | <p>The easiest way to get started using ExoPlayer is to add it as a gradle dependency. You need to make sure you have the jcenter repository included in the <strong>build.gradle</strong> file in the root of your project:</p>
<p><code>repositories {
jcenter()
}</code></p>
<p>Next, include the following in your module's <strong>build.gradle</strong> file:</p>
<p><code>compile 'com.google.android.exoplayer:exoplayer:r2.2.0'</code></p>
<p><strong>1. Your Layout File</strong></p>
<pre><code> <?xml version="1.0" encoding="utf-8"?>
<FrameLayout
android:id="@+id/activity_main"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.exoplayer2.ui.SimpleExoPlayerView
android:id="@+id/player_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
app:resize_mode="fill"/>
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone"/>
</FrameLayout>
</code></pre>
<p><strong>2. Your Class File(Activity)</strong></p>
<pre><code> public class VideoPlayerActivity extends AppCompatActivity implements ExoPlayer.EventListener {
private SimpleExoPlayerView simpleExoPlayerView;
private String hlsVideoUri = "http://playertest.longtailvideo.com/adaptive/bbbfull/bbbfull.m3u8";
private SimpleExoPlayer player;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
// 1. Create a default TrackSelector
Handler mainHandler = new Handler();
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveVideoTrackSelection.Factory(bandwidthMeter);
TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
// 2. Create a default LoadControl
LoadControl loadControl = new DefaultLoadControl();
// 3. Create the player
player = ExoPlayerFactory.newSimpleInstance(this, trackSelector, loadControl);
simpleExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.player_view);
simpleExoPlayerView.setPlayer(player);
// Measures bandwidth during playback. Can be null if not required.
DefaultBandwidthMeter defaultBandwidthMeter = new DefaultBandwidthMeter();
// Produces DataSource instances through which media data is loaded.
DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(this,
Util.getUserAgent(this, "Exo2"), defaultBandwidthMeter);
// Produces Extractor instances for parsing the media data.
ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
// This is the MediaSource representing the media to be played.
HlsMediaSource hlsMediaSource = new HlsMediaSource(Uri.parse(hlsVideoUri), dataSourceFactory, mainHandler, new AdaptiveMediaSourceEventListener() {
@Override
public void onLoadStarted(DataSpec dataSpec, int dataType, int trackType, Format trackFormat, int trackSelectionReason, Object trackSelectionData, long mediaStartTimeMs, long mediaEndTimeMs, long elapsedRealtimeMs) {
}
@Override
public void onLoadCompleted(DataSpec dataSpec, int dataType, int trackType, Format trackFormat, int trackSelectionReason, Object trackSelectionData, long mediaStartTimeMs, long mediaEndTimeMs, long elapsedRealtimeMs, long loadDurationMs, long bytesLoaded) {
}
@Override
public void onLoadCanceled(DataSpec dataSpec, int dataType, int trackType, Format trackFormat, int trackSelectionReason, Object trackSelectionData, long mediaStartTimeMs, long mediaEndTimeMs, long elapsedRealtimeMs, long loadDurationMs, long bytesLoaded) {
}
@Override
public void onLoadError(DataSpec dataSpec, int dataType, int trackType, Format trackFormat, int trackSelectionReason, Object trackSelectionData, long mediaStartTimeMs, long mediaEndTimeMs, long elapsedRealtimeMs, long loadDurationMs, long bytesLoaded, IOException error, boolean wasCanceled) {
}
@Override
public void onUpstreamDiscarded(int trackType, long mediaStartTimeMs, long mediaEndTimeMs) {
}
@Override
public void onDownstreamFormatChanged(int trackType, Format trackFormat, int trackSelectionReason, Object trackSelectionData, long mediaTimeMs) {
}
});
player.addListener(this);
player.prepare(hlsMediaSource);
simpleExoPlayerView.requestFocus();
player.setPlayWhenReady(true);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
}
@Override
public void onTimelineChanged(Timeline timeline, Object manifest) {
}
@Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
@Override
public void onLoadingChanged(boolean isLoading) {
}
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
switch (playbackState) {
case Player.STATE_BUFFERING:
//You can use progress dialog to show user that video is preparing or buffering so please wait
progressBar.setVisibility(View.VISIBLE);
break;
case Player.STATE_IDLE:
//idle state
break;
case Player.STATE_READY:
// dismiss your dialog here because our video is ready to play now
progressBar.setVisibility(View.GONE);
break;
case Player.STATE_ENDED:
// do your processing after ending of video
break;
}
}
@Override
public void onPlayerError(ExoPlaybackException error) {
AlertDialog.Builder adb = new AlertDialog.Builder(VideoPlayerActivity.this);
adb.setTitle("Could not able to stream video");
adb.setMessage("It seems that something is going wrong.\nPlease try again.");
adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish(); // take out user from this activity. you can skip this
}
});
AlertDialog ad = adb.create();
ad.show();
}
@Override
public void onPositionDiscontinuity() {
}
@Override
protected void onPause() {
super.onPause();
if (player != null) {
player.setPlayWhenReady(false); //to pause a video because now our video player is not in focus
}
}
@Override
protected void onDestroy() {
super.onDestroy();
player.release();
}
}
</code></pre>
<p>I think this is enough for beginner. Also keep in mind that this library's standard audio and video components rely on Android’s MediaCodec API, which was released in Android 4.1 (API level 16). So it will not work on android 4.0 and below.</p>
<p>Don't forget to add this permission to the <code>manifest file</code> :</p>
<p><code><uses-permission android:name="android.permission.INTERNET"/></code></p> |
18,163,821 | Excel - return "true" if a value exists in both columns | <p>I have two columns of data. column A and column B. in the third column (C) I want to type a formula that will return "true" if a data in column B exists anywhere in column A. Just this :) Thank you in advance. </p> | 18,163,969 | 1 | 0 | null | 2013-08-10 16:14:26.027 UTC | 4 | 2018-01-18 02:26:49.233 UTC | 2013-08-10 16:42:55.727 UTC | null | 2,207,117 | null | 2,207,117 | null | 1 | 6 | excel|compare|lookup | 64,843 | <p><strong>Try This:</strong></p>
<pre><code>=NOT(ISNA(VLOOKUP(B1,A:A,1,0)))
</code></pre>
<p>Assuming you are starting in cell C1.</p>
<p>VLOOKUP returns the value of B1 in the column A, or #N/A if it's not found. ISNA will return TRUE if no value is found, or FALSE if it is, finally NOT negates the result such that it will return TRUE if value is found and FALSE otherwise.</p> |
2,503,234 | sql server ports 445 and 1433 | <p>What is the difference between sql server ports 445 and 1433 and what is each port intended for?</p> | 2,503,284 | 3 | 0 | null | 2010-03-23 20:09:27.75 UTC | null | 2014-04-02 18:45:58.887 UTC | 2014-04-02 18:45:58.887 UTC | null | 467,079 | null | 289,877 | null | 1 | 6 | sql-server|sql-server-2005 | 46,177 | <p>445 is not a SQL port, is a SMB port. It is involved in SQL Server only if you use named pipes protocol, as named pipes are over SMB and this in turn uses 445 for '<a href="http://support.microsoft.com/kb/204279" rel="noreferrer">SMB over IP</a>', aka. as SMB 'NETBIOSless' as opposed to the old NetBIOS based SMB, which uses 137-139.</p>
<p>1433 is the SQL Server TCP listener port when SQL Server uses directly TCP.</p>
<p>To configure the server to listen on specific protocols, use <a href="http://technet.microsoft.com/en-us/library/ms174212.aspx" rel="noreferrer">SQL Server configuration Manager</a>. To configure the client allowed protocols, see <a href="http://msdn.microsoft.com/en-us/library/ms190425.aspx" rel="noreferrer">Configuring Client Network Protocols</a>.</p>
<p>It is better to disable Net Pipes and rely solely on TCP (1433), for reasons of performance and easy of deployment/configuration.</p> |
7,311,415 | How is the complexity of bucket sort is O(n+k) if we implement buckets using linked lists? | <p>I am curious about why bucket sort has a runtime of O(n + k) if we use buckets implemented with linked lists. For example, suppose that we have this input:</p>
<pre><code>n = no of element= 8
k = range = 3
array = 2,2,1,1,1,3,1,3
</code></pre>
<p>The buckets will look like this:</p>
<pre><code>1: 1 -> 1 -> 1 -> 1
2: 2 -> 2
3: 3 -> 3
</code></pre>
<p>The total time spent inserting into these buckets is O(n), assuming that we store a tail pointer in the linked lists.</p>
<p>For deleting we have to go to each bucket and then delete each node in that bucket. Hence complexity should be O(K * average length of link list of bucket) as we are traversing each linked list.</p>
<p>However, I read that bucket sort's complexity is O(n + k). Why doesn't this agree with my analysis? Please correct me as I am still learning computational complexity.</p> | 7,341,355 | 1 | 5 | null | 2011-09-05 18:05:44.203 UTC | 23 | 2015-11-16 13:28:22.893 UTC | 2013-05-09 15:55:44.933 UTC | null | 501,557 | null | 323,422 | null | 1 | 24 | algorithm|sorting|data-structures|big-o | 34,817 | <p>Your analysis is <em>almost</em> correct, but there's an important detail that you're missing.</p>
<p>Right now, you are correct that iterating across the input array to distribute the elements into buckets takes time O(n). However, you are slightly off when you say that the total amount of time required to assemble the array is O(k * (average number of elements per bucket)). Note that because there are n elements and k buckets, this would come out to O(k * (n / k)) = O(n), for a total runtime of O(n). To see why the real answer is O(n + k), we need to look more carefully at that big-O term.</p>
<p>For starters, you are absolutely right that the average amount of time that you spend on each bucket is O(n / k). You then say that since there are k buckets, the total runtime is then O(k * (n / k)) = O(n). However, this is incorrect: in particular, it is <strong>not</strong> true that k * O(n / k) = O(n). The reason for this is that the term O(n / k) is hiding a constant factor. When you visit each bucket and take a look at the elements it contains, it doesn't take exactly n / k time, or even some constant multiple of n / k time. For example, what happens if the bucket is empty? In that case, you're still spending some amount of time looking at the bucket, since you have to determine that you shouldn't iterate over its elements. Thus a more accurate representation of the time required per bucket is something like c<sub>0</sub>(n / k) + c<sub>1</sub>, where c<sub>0</sub> and c<sub>1</sub> are implementation-specific constants. This expression is, of course, O(n / k).</p>
<p>The catch is what happens when you multiply this expression by k to get the total amount of work done. If you compute</p>
<blockquote>
<p>k * (c<sub>0</sub>(n / k) + c<sub>1</sub>)</p>
</blockquote>
<p>You get</p>
<blockquote>
<p>c<sub>0</sub>n + c<sub>1</sub>k</p>
</blockquote>
<p>As you can see, this expression depends directly on k, so the total runtime is O(n + k).</p>
<p>A more direct way to arrive at this result would be to look at the code for the second step of the bucket sort, which looks like this:</p>
<pre><code>For each bucket b:
For each element x in b:
Append x to the array.
</code></pre>
<p>How much work is done overall? Well, there are k different buckets, so the outermost loop must take at least O(k) time, because we have to look in each bucket. Inside, the inner loop will execute a total of O(n) times overall, because there are a total of n elements distributed across the buckets. From this, we get the O(n + k) total runtime.</p>
<p>The reason that this is important is that it means that if you try doing a bucket sort with a huge number of buckets (say, much greater than n), the runtime might be dominated by the time required to scan over all the buckets looking for the buckets that you actually used, even if most of them are empty. The reason that radix sort is useful is that it uses multiple iterations of bucket sort where there are only two buckets, which runs in time O(n + 2) = O(n). Since you only need to do O(lg U) iterations of this (where U is the maximum value in the array), the runtime is O(n lg U) instead of the O(n + U) you'd get from bucket sort, which is much worse.</p>
<p>Hope this helps!</p> |
22,580,623 | Is [CallerMemberName] slow compared to alternatives when implementing INotifyPropertyChanged? | <p>There are good articles that suggest <a href="http://blog.amusedia.com/2013/06/inotifypropertychanged-implementation.html" rel="noreferrer">different ways for implementing <code>INotifyPropertyChanged</code></a>.</p>
<p>Consider the following basic implementation:</p>
<pre><code>class BasicClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void FirePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
private int sampleIntField;
public int SampleIntProperty
{
get { return sampleIntField; }
set
{
if (value != sampleIntField)
{
sampleIntField = value;
FirePropertyChanged("SampleIntProperty"); // ouch ! magic string here
}
}
}
}
</code></pre>
<p>I'd like to replace it with this one:</p>
<pre><code>using System.Runtime.CompilerServices;
class BetterClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
// Check the attribute in the following line :
private void FirePropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
private int sampleIntField;
public int SampleIntProperty
{
get { return sampleIntField; }
set
{
if (value != sampleIntField)
{
sampleIntField = value;
// no "magic string" in the following line :
FirePropertyChanged();
}
}
}
}
</code></pre>
<p>But sometimes I read that the <code>[CallerMemberName]</code> attribute has poor performances compared to alternatives. Is that true and why? Does it use reflection?</p> | 22,580,624 | 1 | 0 | null | 2014-03-22 16:55:44.403 UTC | 24 | 2017-07-27 22:10:48.963 UTC | 2016-12-14 00:52:51.833 UTC | null | 2,157,640 | null | 218,873 | null | 1 | 114 | c#|inotifypropertychanged|callermembername | 34,226 | <p>No, <strong>the use of <code>[CallerMemberName]</code> is not slower</strong> than the upper basic implementation.</p>
<p>This is because, according to <a href="https://msdn.microsoft.com/en-us/library/hh534540(v=vs.110).aspx" rel="noreferrer">this MSDN page</a>, </p>
<blockquote>
<p>Caller Info values are emitted as literals into the Intermediate
Language (IL) at compile time</p>
</blockquote>
<p>We can check that with any IL disassembler (like <a href="http://ilspy.net/" rel="noreferrer">ILSpy</a>) : the code for the "SET" operation of the property is compiled exactly the same way :
<img src="https://i.stack.imgur.com/KEjL4.png" alt="Decompiled property with CallerMemberName"></p>
<p>So no use of Reflection here.</p>
<p>(sample compiled with VS2013)</p> |
38,916,912 | How to decode JWT (Header and Body) in java using Apache Commons Codec? | <p>I am looking decode the following <code>JWT</code> using <code>Apache Commons Codec</code>. How we can do that ?</p>
<pre><code> eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0Iiwicm9sZXMiOiJST0xFX0FETUlOIiwiaXNzIjoibXlzZ
WxmIiwiZXhwIjoxNDcxMDg2MzgxfQ.1EI2haSz9aMsHjFUXNVz2Z4mtC0nMdZo6bo3-x-aRpw
</code></pre>
<p>This should retrieve <code>Header</code>, <code>Body</code> and <code>Signature</code> part. Whats the code ?</p> | 38,916,927 | 2 | 0 | null | 2016-08-12 11:29:07.22 UTC | 14 | 2020-02-03 14:16:38.767 UTC | 2018-02-28 22:26:12.533 UTC | null | 3,124,333 | user4821194 | null | null | 1 | 30 | apache|jwt|apache-commons-codec | 70,187 | <p>Here you go:</p>
<pre><code>import org.apache.commons.codec.binary.Base64;
@Test
public void testDecodeJWT(){
String jwtToken = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0Iiwicm9sZXMiOiJST0xFX0FETUlOIiwiaXNzIjoibXlzZWxmIiwiZXhwIjoxNDcxMDg2MzgxfQ.1EI2haSz9aMsHjFUXNVz2Z4mtC0nMdZo6bo3-x-aRpw";
System.out.println("------------ Decode JWT ------------");
String[] split_string = jwtToken.split("\\.");
String base64EncodedHeader = split_string[0];
String base64EncodedBody = split_string[1];
String base64EncodedSignature = split_string[2];
System.out.println("~~~~~~~~~ JWT Header ~~~~~~~");
Base64 base64Url = new Base64(true);
String header = new String(base64Url.decode(base64EncodedHeader));
System.out.println("JWT Header : " + header);
System.out.println("~~~~~~~~~ JWT Body ~~~~~~~");
String body = new String(base64Url.decode(base64EncodedBody));
System.out.println("JWT Body : "+body);
}
</code></pre>
<p>The output below:</p>
<pre><code>------------ Decode JWT ------------
~~~~~~~~~ JWT Header ~~~~~~~
JWT Header : {"alg":"HS256"}
~~~~~~~~~ JWT Body ~~~~~~~
JWT Body : {"sub":"test","roles":"ROLE_ADMIN","iss":"myself","exp":1471086381}
</code></pre> |
31,675,192 | Not able to start Sonar Server | <p>I am using Sonar to generate code review reports of my project. But I am not able to start the server. I am getting </p>
<blockquote>
<p>HeapDumpOnOutOfMemoryError</p>
</blockquote>
<p>while running </p>
<blockquote>
<p>StartSonar.bat</p>
</blockquote>
<p>file.</p>
<p>Please find the logs generated while sonar start up. </p>
<blockquote>
<p>C:\TEMP2\Sonar\sonarqube-4.5\bin\windows-x86-32>StartSonar.bat wrapper
| --> Wrapper Started as Console wrapper | Launching a JVM... jvm 1<br>
| Wrapper (Version 3.2.3) <a href="http://wrapper.tanukisoftware.org" rel="noreferrer">http://wrapper.tanukisoftware.org</a> jvm 1 |
Copyright 1999-2006 Tanuki Software, Inc. All Rights Reserved. jvm 1
| jvm 1 | 2015.07.28 07:30:51 INFO
app[o.s.p.m.JavaProcessLauncher] Launch process[search]:
C:\Software\jdk1.6.0_18\jre\bin\java -Xmx256m -Xms256m - Xss256k
-Djava.net.preferIPv4Stack=true -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyO nly -XX:+HeapDumpOnOutOfMemoryError -Djava.awt.headless=true -Djava.io.tmpdir=C:\TEMP2\Sonar\sonarqube-4.5\temp -cp ./lib/common/<em>;./lib/search/</em> org. sonar.search.SearchServer
C:\Users\gxs114\AppData\Local\Temp\sq-process8934190933893070058properties
jvm 1 | 2015.07.28 07:30:57 INFO app[o.s.p.m.Monitor]
Process[search] is up jvm 1 | 2015.07.28 07:30:57 INFO
app[o.s.p.m.JavaProcessLauncher] Launch process[web]:
C:\Software\jdk1.6.0_18\jre\bin\java -Xmx768m -XX:MaxPermSi ze=160m
-XX:+HeapDumpOnOutOfMemoryError -Djava.net.preferIPv4Stack=true -Djava.awt.headless=true -Dfile.encoding=UTF-8 -Djruby.management.enabled=fals e -Djava.io.tmpdir=C:\TEMP2\Sonar\sonarqube-4.5\temp -cp ./lib/common/<em>;./lib/server/</em> org.sonar.server.app.WebServer
C:\Users\gxs114\AppData\Local\Te
mp\sq-process4251708419326591677properties jvm 1 | 2015.07.28
07:30:57 INFO app[o.s.p.m.TerminatorThread] Process[search] is
stopping jvm 1 | 2015.07.28 07:30:58 INFO
app[o.s.p.m.TerminatorThread] Process[search] is stopped wrapper |
<-- Wrapper Stopped</p>
<p>C:\TEMP2\Sonar\sonarqube-4.5\bin\windows-x86-32></p>
</blockquote>
<p>How can I solve this issue ? Any idea/solution appreciated.</p> | 31,693,357 | 7 | 0 | null | 2015-07-28 11:37:08.697 UTC | 3 | 2022-07-19 08:19:00.847 UTC | null | null | null | null | 546,888 | null | 1 | 12 | sonarqube-4.5 | 56,921 | <p>I got the solution from sonar log files itself. You can find server start up logs in the sonar.log file under directory "sonarqube-4.5\logs". </p>
<p>I was not able to start the server due to following port binding exception :</p>
<pre><code>2015.07.29 02:46:36 ERROR web[o.a.c.h.Http11Protocol] Failed to initialize end point associated with ProtocolHandler ["http-bio-0.0.0.0-9000"]
java.net.BindException: Address already in use: JVM_Bind /0.0.0.0:9000
at org.apache.tomcat.util.net.JIoEndpoint.bind(JIoEndpoint.java:411) ~[tomcat-embed-core-7.0.54.jar:7.0.54]
at org.apache.tomcat.util.net.AbstractEndpoint.init(AbstractEndpoint.java:640) ~[tomcat-embed-core-7.0.54.jar:7.0.54]
at org.apache.coyote.AbstractProtocol.init(AbstractProtocol.java:434) ~[tomcat-embed-core-7.0.54.jar:7.0.54]
at org.apache.coyote.http11.AbstractHttp11JsseProtocol.init(AbstractHttp11JsseProtocol.java:119) [tomcat-embed-core-7.0.54.jar:7.0.54]
</code></pre>
<p>So, I changed the port number to "4950" from "9000" in sonar.properties file under directory "sonarqube-4.5\conf".</p>
<pre><code># TCP port for incoming HTTP connections. Disabled when value is -1.
sonar.web.port=4950
# TCP port for incoming HTTPS connections. Disabled when value is -1 (default).
#sonar.web.https.port=-1
</code></pre>
<p>The server got successfully started after changing the port number.</p> |
48,560,072 | How to add vertical scrollbar to select box options list? | <p>I need vertical scrollbar for select box options list. I have to show only first few items of the list. I don't have any control over number of items in the list. </p>
<p>I have checked all similar questions here and nothing worked out. Anyway to do that?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper{
width:200px;
padding:20px;
height: 150px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="wrapper" ><select name="" id="" class="form-control">
<option value="">One</option>
<option value="">Two</option>
<option value="">Three</option>
<option value="">Four</option>
<option value="">Five</option>
<option value="">Six</option>
<option value="">Seven</option>
<option value="">Eight</option>
<option value="">Nine</option>
<option value="">Ten</option>
</select></div></code></pre>
</div>
</div>
</p> | 48,560,262 | 4 | 0 | null | 2018-02-01 10:07:11.587 UTC | 6 | 2022-08-05 08:52:20.207 UTC | 2020-04-22 09:14:05.657 UTC | null | 8,565,438 | null | 6,603,094 | null | 1 | 11 | javascript|jquery|css|html|twitter-bootstrap | 58,130 | <p><code>Overflow-y</code> doesn't work on select boxes. What I would recommend using is <code>size</code> on your select box. In my example I've used 5 as the value, you can obviously change this to your liking.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper{
width:200px;
padding:20px;
height: 150px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="wrapper"><select name="" id="" class="form-control" onfocus='this.size=5;' onblur='this.size=1;' onchange='this.size=1; this.blur();'>
<option value="">One</option>
<option value="">Two</option>
<option value="">Three</option>
<option value="">Four</option>
<option value="">Five</option>
<option value="">Six</option>
<option value="">Seven</option>
<option value="">Eight</option>
<option value="">Nine</option>
<option value="">Ten</option>
</select></div></code></pre>
</div>
</div>
</p>
<p><strong>Edit:</strong> Amended my answer to include some js to provide OP with the desired result.</p> |
50,571,316 | Strange variable scoping behavior in Jenkinsfile | <p>When I run the below Jenkins pipeline script:</p>
<pre><code>def some_var = "some value"
def pr() {
def another_var = "another " + some_var
echo "${another_var}"
}
pipeline {
agent any
stages {
stage ("Run") {
steps {
pr()
}
}
}
}
</code></pre>
<p>I get this error:</p>
<pre><code>groovy.lang.MissingPropertyException: No such property: some_var for class: groovy.lang.Binding
</code></pre>
<p>If the <code>def</code> is removed from <code>some_var</code>, it works fine. Could someone explain the scoping rules that cause this behavior?</p> | 50,573,082 | 2 | 0 | null | 2018-05-28 17:44:25.263 UTC | 21 | 2019-11-20 14:07:04.157 UTC | 2019-11-20 14:07:04.157 UTC | null | 95,750 | null | 95,750 | null | 1 | 43 | jenkins|groovy|jenkins-pipeline|jenkins-groovy|groovyshell | 21,257 | <h2>TL;DR</h2>
<ul>
<li>variables defined <strong>with</strong> <code>def</code> in the main script body cannot be accessed from other methods.</li>
<li>variables defined <strong>without</strong> <code>def</code> can be accessed directly by any method even from different scripts. It's a bad practice.</li>
<li>variables defined <strong>with</strong> <code>def</code> <strong>and</strong> <a href="http://docs.groovy-lang.org/2.4.9/html/gapi/groovy/transform/Field.html" rel="noreferrer"><code>@Field</code> </a> annotation can be accessed directly from methods defined in the same script.</li>
</ul>
<h2>Explanation</h2>
<p>When groovy compiles that script it actually moves everything to a class that <strong>roughly</strong> looks something like this</p>
<pre><code>class Script1 {
def pr() {
def another_var = "another " + some_var
echo "${another_var}"
}
def run() {
def some_var = "some value"
pipeline {
agent any
stages {
stage ("Run") {
steps {
pr()
}
}
}
}
}
}
</code></pre>
<p>You can see that <code>some_var</code> is clearly out of scope for <code>pr()</code> becuse it's a local variable in a different method.</p>
<p>When you define a variable <strong>without</strong> <code>def</code> you actually put that variable into a <a href="http://docs.groovy-lang.org/latest/html/api/groovy/lang/Binding.html" rel="noreferrer">Binding</a> of the script (so-called <em>binding variables</em>). So when groovy executes <code>pr()</code> method firstly it tries to find a local variable with a name <code>some_var</code> and if it doesn't exist it then tries to find that variable in a Binding (which exists because you defined it without <code>def</code>).</p>
<p>Binding variables are considered bad practice because if you load multiple scripts (<code>load</code> step) binding variables will be accessible in all those scripts because Jenkins shares the same Binding for all scripts. A much better alternative is to use <a href="http://docs.groovy-lang.org/2.4.9/html/gapi/groovy/transform/Field.html" rel="noreferrer"><code>@Field</code> </a>annotation. This way you can make a variable accessible in all methods inside one script without exposing it to other scripts.</p>
<pre><code>import groovy.transform.Field
@Field
def some_var = "some value"
def pr() {
def another_var = "another " + some_var
echo "${another_var}"
}
//your pipeline
</code></pre>
<p>When groovy compiles this script into a class it will look something like this</p>
<pre><code>class Script1 {
def some_var = "some value"
def pr() {
def another_var = "another " + some_var
echo "${another_var}"
}
def run() {
//your pipeline
}
}
</code></pre> |
36,239,903 | What's the difference between Remove and Exclude when refactoring with PyCharm? | <p>The <a href="https://www.jetbrains.com/help/pycharm/2016.1/refactoring-source-code.html?origin=old_help" rel="noreferrer">official PyCharm docs</a> explain <code>Exclude</code> when it comes to refactoring: One can, say, rename something with refactoring (Shift+F6), causing the Find window to pop up with a Preview. Within, it shows files which will be updated as a result of the refactor. One can right-click on a file or folder in this Preview and choose <code>Remove</code> or <code>Exclude</code>. What's the difference? </p> | 48,336,566 | 1 | 0 | null | 2016-03-26 19:29:55.693 UTC | 2 | 2019-02-15 12:24:16.383 UTC | null | null | null | null | 682,515 | null | 1 | 33 | refactoring|pycharm | 1,341 | <p>Final effect is the same - entry which was <code>Removed</code> or <code>Excluded</code> won't be refactored, the difference is in presentation. After selecting <code>Exclude</code> you keep entry in the <code>Refactoring Preview</code>, but <code>Remove</code> deletes it from that window.</p>
<p>I think that <code>Remove</code> could be useful when you deal with quite large refactoring and marking everything as excluded could lead to unreadable mess.</p>
<p>Keep in mind, that <strong>remove action can't be undone</strong> - you have to start new refactoring...</p> |
34,457,568 | How to show options in telegram bot? | <p>I want to write a bot telegram.How to put possible option in my bot.I insert a picture of sample bot with this functionality.<br><br><a href="https://i.stack.imgur.com/PPlQ0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PPlQ0.png" alt="enter image description here"></a></p> | 34,458,436 | 4 | 0 | null | 2015-12-24 20:21:08.723 UTC | 11 | 2022-08-13 19:47:55.787 UTC | null | null | null | null | 3,733,985 | null | 1 | 39 | telegram-bot | 77,652 | <p>For that, you have to talk to BotFather.</p>
<ol>
<li><p>In the Telegram App, open the chat with BotFather.</p>
</li>
<li><p>Send him <code>/setcommands</code>. He will present you with a list of your bots.</p>
</li>
<li><p>Pick the bot for which you want to set the command menu.</p>
</li>
<li><p>Compose and send the command list. Using your image as an example, these 4 lines should do:</p>
</li>
</ol>
<p>start - Description 1<br />
menu - Description 2<br />
help - Description 3<br />
stop - Description 4</p>
<p>Note that command part of each line(left side of <code>-</code> signs) must have just <strong>lowercase</strong> characters, and <strong>no slashes</strong>. There should also be <strong>spaces</strong> around the <code>-</code> sign.</p>
<p>Once you complete this process, <strong>exit and kill</strong> the Telegram App. Re-open it, go to the chat with your target bot, type a <code>/</code> (or tab on the <code>/</code> button next to the text field), the command menu should come up.</p> |
29,742,847 | jenkins trigger build if new tag is released | <p>I want to configure jenkins so that it starts building if a new tag is released in any branch of an git repository. How do I configure this behaviour?</p>
<p><img src="https://i.stack.imgur.com/w7jhD.png" alt="git jenkins config" /></p>
<p>Triggering:
<img src="https://i.stack.imgur.com/2LXTk.png" alt="build trigger" /></p>
<p>Thanks for any help</p> | 29,743,054 | 8 | 0 | null | 2015-04-20 08:34:39.63 UTC | 21 | 2022-04-14 17:21:51.037 UTC | 2021-03-08 09:41:02.043 UTC | null | 4,298,200 | null | 1,771,213 | null | 1 | 68 | git|jenkins|tags | 77,389 | <p>What do you mean by new tag? Does it has some template name?</p>
<p>You can surely define it in <strong>Advanced</strong> --> <strong>Refspec</strong> --><code>refs/tags/{tagname}</code> .</p>
<p>You can even do <code>refs/tags/*</code> for finding really ANY new tags.</p>
<p><img src="https://i.stack.imgur.com/66NEA.png" alt="enter image description here"></p> |
52,437,946 | Start motion scene programmatically | <p>I have a motion layout with this layoutDescription: <code>app:layoutDescription="@xml/scene"</code></p>
<p><strong>scene.xml</strong></p>
<pre><code><MotionScene
xmlns:motion="http://schemas.android.com/apk/res-auto">
<Transition
motion:constraintSetStart="@layout/view_home_card_start"
motion:constraintSetEnd="@layout/view_home_card_end"
motion:duration="1000">
<OnSwipe
motion:touchAnchorId="@+id/button"
motion:touchAnchorSide="left"
motion:dragDirection="dragLeft" />
</Transition>
</MotionScene>
</code></pre>
<p>I think that the xml of <code>view_home_card_start</code> and <code>view_home_card_end</code> is irrelevant.</p>
<p>How can I call this animation programatically?</p> | 52,474,529 | 8 | 0 | null | 2018-09-21 06:36:42.7 UTC | 6 | 2022-09-11 17:13:41.697 UTC | 2019-01-31 14:00:49.193 UTC | null | 3,383,038 | null | 3,994,630 | null | 1 | 52 | android|android-motionlayout | 25,393 | <p>Finally Im doing this:</p>
<pre><code>((MotionLayout)findViewById(R.id.motionLayout)).transitionToEnd();
((MotionLayout)findViewById(R.id.motionLayout)).transitionToStart();
</code></pre> |
31,926,315 | Why do people like to pair CLEAR_TOP and SINGLE_TOP in android | <p>The flag <code>FLAG_ACTIVITY_CLEAR_TOP</code> finds the task containing activity X and clears the top to bring X to its resume state. The flag <code>FLAG_ACTIVITY_SINGLE_TOP</code>, would only keep a single instance of X at the top. Therefore, I should never need to include <code>SINGLE_TOP</code> if I am already using <code>CLEAR_TOP</code>: that's because <code>CLEAR_TOP</code>'s behavior includes <code>SINGLE_TOP</code>'s behavior. So why do so many sample codes include the two together? Is it because those developers don't understand the full power of <code>CLEAR_TOP</code>? Again, almost every example I see online includes the two together. Why the redundancy?</p>
<p>For example if I call <code>CLEAR_TOP</code> for X on the task <code>W->X->Y->Z</code>, then I get <code>W->X</code>. On the other hand, if I were to call SINGLE_TOP for X on the task <code>W->X->Y->Z</code> I would end up with <code>W->X->Y->Z->X</code> and if I were to call it for Z I would get <code>W->X->Y->Z</code>. So really <code>CLEAR_TOP</code> adds nothing to the equation: it's like adding 0 to some other value.</p> | 31,926,916 | 1 | 0 | null | 2015-08-10 18:11:47.363 UTC | 8 | 2015-08-10 18:46:15.433 UTC | null | null | null | null | 2,187,407 | null | 1 | 18 | android|android-intent|android-activity | 3,364 | <p>The behaviour of <code>CLEAR_TOP</code> is different, depending on whether or not the Activity is a <code>singleTop</code> activity or the flag <code>SINGLE_TOP</code> is also provided.</p>
<p>Let's first assume that the Activity has a standard launch mode (not <code>singleTop</code>). If you use the <code>CLEAR_TOP</code> flag without <code>SINGLE_TOP</code>, Android does the following:</p>
<ul>
<li>Clears the Activity stack back to (<strong>and including</strong>) the target Activity (by finishing all activities in the stack that were on top of target activity and finishing the existing instance of the target activity).</li>
<li>Creates a <strong>new instance</strong> of the target Activity and calls <code>onCreate()</code> on that instance.</li>
</ul>
<p>Instead, let's assume that the Activity still has a standard launch mode (not <code>singleTop</code>). If you use the <code>CLEAR_TOP</code> flag <strong>together with</strong> the <code>SINGLE_TOP</code> flag, Android does the following:</p>
<ul>
<li>Clears the Activity stack back to (<strong>but NOT including</strong>) the target Activity (by finishing all activities in the stack that were on top of the target activity).</li>
<li>Calls <code>onNewIntent()</code> on the existing instance of the target Activity, passing the <code>Intent</code> that was used in the <code>startActivity()</code> call.</li>
</ul>
<p>As you can see, the behaviour is different.</p>
<p>NOTE: If the target Activity is declared as <code>launchMode="singleTop"</code> in the manifest, then the behaviour of using <code>CLEAR_TOP</code> should be the same as if you also specified <code>SINGLE_TOP</code>. However, there are some bugs in Android related to this (I can't find the links at the moment). So you shouldn't rely on the <code>launchMode</code> setting, but always specify <code>SINGLE_TOP</code> flag if you want the existing instance of the target Activity NOT to be recreated.</p> |
22,909,227 | How can add space\margin between two elements in iTextSharp\iText? | <p>I am pretty new in <strong>iTextSharpt</strong> (the <strong>iText</strong> porting for C#) and I have the following doubt.</p>
<p>In my code I have something like it:</p>
<pre><code>iTextSharp.text.Paragraph titolo = new iTextSharp.text.Paragraph(currentVuln.Title, _fontTitolo0);
titolo.Alignment = iTextSharp.text.Element.ALIGN_CENTER;
_document.Add(titolo);
table = new PdfPTable(3);
table.WidthPercentage = 98;
cell = new PdfPCell(new Phrase("Header spanning 3 columns"));
cell.Colspan = 3;
cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
table.AddCell(cell);
table.AddCell("Col 1 Row 1");
table.AddCell("Col 2 Row 1");
table.AddCell("Col 3 Row 1");
table.AddCell("Col 1 Row 2");
table.AddCell("Col 2 Row 2");
table.AddCell("Col 3 Row 2");
_document.Add(table);
</code></pre>
<p>As you can see I simply print a title (usinga <strong>Paragraph</strong> object) and under it a place a table.</p>
<p>The problem is that there is no space (margin) between my title and my table and the graphic result is not good, this is what I obtain in the generated PDF:</p>
<p><img src="https://i.stack.imgur.com/ljfMt.png" alt="enter image description here"></p>
<p>What can I do to add some space\margin between the title paragraph and the table? What is the best way to do it? I am trying to do it but, untill now, I have found no solution</p>
<p>Tnx</p> | 22,913,609 | 2 | 0 | null | 2014-04-07 10:02:00.61 UTC | 4 | 2020-10-22 09:49:29.387 UTC | null | null | null | null | 1,833,945 | null | 1 | 25 | c#|asp.net|.net|itextsharp|itext | 48,388 | <p>You have a couple of different options. You could set the <code>SpacingAfter</code> on your paragraph:</p>
<pre><code>titolo.SpacingAfter = 20;
</code></pre>
<p>You could also set the <code>SpacingBefore</code> on the table:</p>
<pre><code>table.SpacingBefore = 20;
</code></pre>
<p>Or you could just add some returns to your paragraph:</p>
<pre><code>iTextSharp.text.Paragraph titolo = new iTextSharp.text.Paragraph("Hello World\n\n");
</code></pre> |
22,792,848 | Pretty print JSON python | <p>if anybody with some knowledge about pretty printing JSON could help me with this I would be extremely grateful!</p>
<p>I'm looking to convert a complex python string into JSON format, using the function below to move the JSON string to a file:</p>
<pre><code>with open('data.txt', 'wt') as out:
pprint(string, stream=out)
</code></pre>
<p>The problem is that I'm getting syntax errors for the square brackets I believe, as this is a new topic for me and I can't figure out how to get around this. The JSON format I require is like this: </p>
<pre><code> {
cols:[{id: 'Time', "label":"Time","type": "datetime"},
{id: 'Time', "label":"Latency","type":"number"}],
rows:[{c: [{v: %s}, {v: %s}]},
{c: [{v: %s}, {v: %s}]},
{c: [{v: %s}, {v: %s}]},
{c: [{v: %s}, {v: %s}]}
]
}
</code></pre>
<p>I'm following the Google Visualization API, you may be familier with it, but I need dynamic graphs. The above code is the format which the API requires to create a graph, so I am in the process of figuring out how to get my data from MYSQL into this format, so the graph can read and be displayed. The method I thought of was to update a file containing the required JSON format periodically, which is why the %s are present, however MartijnPeters suggests this is invalid. </p>
<p>Does anybody know the simplest way I can do this, or can you point me to any material which can help? Thank you!! </p> | 22,792,883 | 1 | 0 | null | 2014-04-01 17:32:36.643 UTC | 8 | 2014-10-28 08:34:23.497 UTC | 2014-04-02 08:17:59.33 UTC | null | 2,716,029 | null | 2,716,029 | null | 1 | 14 | python|json|string|google-visualization|pprint | 32,620 | <p>You are writing <em>Python representations</em>, not JSON.</p>
<p>Use the <a href="https://docs.python.org/2/library/json.html#json.dump"><code>json.dump()</code> function</a> to write pretty-printed JSON instead, directly to your file:</p>
<pre><code>with open('data.txt', 'wt') as out:
res = json.dump(obj, out, sort_keys=True, indent=4, separators=(',', ': '))
</code></pre> |
40,599,512 | How to achieve behavior of setTimeout in Elm | <p>I'm writing a web game in Elm with lot of time-dependent events and I'm looking for a way to schedule an event at a specific time delay.</p>
<p>In JavaScript I used <code>setTimeout(f, timeout)</code>, which obviously worked very well, but - for various reasons - I want to avoid JavaScript code and use Elm alone. </p>
<p>I'm aware that I can <code>subscribe</code> to <code>Tick</code> at specific interval and recieve clock ticks, but this is not what I want - my delays have no reasonable common denominator (for example, two of the delays are 30ms and 500ms), and I want to avoid having to handle a lot of unnecessary ticks.</p>
<p>I also came across <code>Task</code> and <code>Process</code> - it seems that by using them I am somehow able to what I want with <code>Task.perform failHandler successHandler (Process.sleep Time.second)</code>. </p>
<p>This works, but is not very intuitive - my handlers simply ignore all possible input and send same message. Moreover, I do not expect the timeout to ever fail, so creating the failure handler feels like feeding the library, which is not what I'd expect from such an elegant language. </p>
<p>Is there something like <code>Task.delayMessage time message</code> which would do exactly what I need to (send me a copy of its message argument after specified time), or do I have to make my own wrapper for it?</p> | 40,600,653 | 4 | 2 | null | 2016-11-14 23:22:29.317 UTC | 7 | 2022-04-04 19:33:32.03 UTC | null | null | null | null | 2,671,214 | null | 1 | 30 | elm | 7,516 | <p>One thing that may not be obvious at first is the fact that subscriptions can change based on the model. They are effectively evaluated after every update. You can use this fact, coupled with some fields in your model, to control what subscriptions are active at any time.</p>
<p>Here is an example that allows for a <a href="https://freakingawesome.github.io/drunk-label/">variable cursor blink interval</a>:</p>
<pre class="lang-elm prettyprint-override"><code>subscriptions : Model -> Sub Msg
subscriptions model =
if model.showCursor
then Time.every model.cursorBlinkInterval (always ToggleCursor)
else Sub.none
</code></pre>
<p>If I understand your concerns, this should overcome the potential for handling unnecessary ticks. You can have multiple subscriptions of different intervals by using <code>Sub.batch</code>.</p> |
39,354,566 | What is the equivalent of np.std() in TensorFlow? | <p>Just looking for the equivalent of np.std() in TensorFlow to calculate the standard deviation of a tensor.</p> | 39,354,802 | 2 | 0 | null | 2016-09-06 17:19:49.593 UTC | 1 | 2017-07-04 18:50:37.197 UTC | null | null | null | null | 4,962,207 | null | 1 | 29 | python|tensorflow | 21,862 | <p>To get the mean and variance just use <code>tf.nn.moments</code>.</p>
<pre><code>mean, var = tf.nn.moments(x, axes=[1])
</code></pre>
<p>For more on <code>tf.nn.moments</code> params see <a href="https://www.tensorflow.org/api_docs/python/tf/nn/moments" rel="noreferrer">docs</a></p> |
2,639,430 | Graphing perpendicular offsets in a least squares regression plot in R | <p>I'm interested in making a plot with a least squares regression line and line segments connecting the datapoints to the regression line as illustrated here in the graphic called perpendicular offsets:
<a href="http://mathworld.wolfram.com/LeastSquaresFitting.html" rel="nofollow noreferrer">http://mathworld.wolfram.com/LeastSquaresFitting.html</a>
<a href="https://i.stack.imgur.com/bH6SM.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bH6SM.gif" alt="alt text"></a><br>
<sub>(from MathWorld - A Wolfram Web Resource: <a href="http://mathworld.wolfram.com/images/eps-gif/LeastSquaresOffsets_1000.gif" rel="nofollow noreferrer">wolfram.com</a>)</sub> </p>
<p>I have the plot and regression line done here:</p>
<pre><code>## Dataset from http://www.apsnet.org/education/advancedplantpath/topics/RModules/doc1/04_Linear_regression.html
## Disease severity as a function of temperature
# Response variable, disease severity
diseasesev<-c(1.9,3.1,3.3,4.8,5.3,6.1,6.4,7.6,9.8,12.4)
# Predictor variable, (Centigrade)
temperature<-c(2,1,5,5,20,20,23,10,30,25)
## For convenience, the data may be formatted into a dataframe
severity <- as.data.frame(cbind(diseasesev,temperature))
## Fit a linear model for the data and summarize the output from function lm()
severity.lm <- lm(diseasesev~temperature,data=severity)
# Take a look at the data
plot(
diseasesev~temperature,
data=severity,
xlab="Temperature",
ylab="% Disease Severity",
pch=16,
pty="s",
xlim=c(0,30),
ylim=c(0,30)
)
abline(severity.lm,lty=1)
title(main="Graph of % Disease Severity vs Temperature")
</code></pre>
<p>Should I use some kind of for loop and segments <a href="http://www.iiap.res.in/astrostat/School07/R/html/graphics/html/segments.html" rel="nofollow noreferrer">http://www.iiap.res.in/astrostat/School07/R/html/graphics/html/segments.html</a> to do the perpendicular offsets? Is there a more efficient way? Please provide an example if possible.</p> | 2,640,087 | 1 | 0 | null | 2010-04-14 17:07:45.077 UTC | 14 | 2019-07-23 01:22:24.713 UTC | 2019-07-23 01:22:24.713 UTC | null | 4,751,173 | null | 255,312 | null | 1 | 16 | r|statistics|plot|linear-regression|least-squares | 2,481 | <p>You first need to figure out the coordinates for the base of the perpendicular segments, then call the <code>segments</code> function which can take vectors of coordinates as inputs (no need for a loop).</p>
<pre><code>perp.segment.coord <- function(x0, y0, lm.mod){
#finds endpoint for a perpendicular segment from the point (x0,y0) to the line
# defined by lm.mod as y=a+b*x
a <- coef(lm.mod)[1] #intercept
b <- coef(lm.mod)[2] #slope
x1 <- (x0+b*y0-a*b)/(1+b^2)
y1 <- a + b*x1
list(x0=x0, y0=y0, x1=x1, y1=y1)
}
</code></pre>
<p>Now just call segments:</p>
<pre><code>ss <- perp.segment.coord(temperature, diseasesev, severity.lm)
do.call(segments, ss)
#which is the same as:
segments(x0=ss$x0, x1=ss$x1, y0=ss$y0, y1=ss$y1)
</code></pre>
<p>Note that the results will not look perpendicular unless you ensure that the x-unit and y-unit of your plot have the same apparent length (isometric scales). You can do that by using <code>pty="s"</code> to get a square plot and set <code>xlim</code> and <code>ylim</code> to the same range.</p> |
50,776,647 | Android - Best Practices for ViewModel State in MVVM? | <p>I am working on an Android App using the MVVM pattern along LiveData (possibly Transformations) and DataBinding between View and ViewModel. Since the app is "growing", now ViewModels contain lots of data, and most of the latter are kept as LiveData to have Views subscribe to them (of course, this data is needed for the UI, be it a Two-Way Binding as per EditTexts or a One-Way Binding). I heard (and googled) about keeping data that represents the UI state in the ViewModel. However, the results I found were just simple and generic. I would like to know if anyone has hints or could share some knowledge on best practices for this case. In simple words, What could be the best way to store the state of an UI (View) in a ViewModel considering LiveData and DataBinding available? Thanks in advance for any answer!</p> | 51,002,027 | 2 | 0 | null | 2018-06-09 17:05:40.477 UTC | 31 | 2020-02-09 20:19:33.387 UTC | 2018-06-12 10:49:52.477 UTC | null | 9,918,581 | null | 9,918,581 | null | 1 | 30 | android|mvvm|state|viewmodel | 22,876 | <p>I struggled with the same problem at work and can share what is working for us. We're developing 100% in Kotlin so the following code samples will be as well.</p>
<h2>UI state</h2>
<p>To prevent the <code>ViewModel</code> from getting bloated with lots of <code>LiveData</code> properties, expose a single <code>ViewState</code> for views (<code>Activity</code> or <code>Fragment</code>) to observe. It may contain the data previously exposed by the multiple <code>LiveData</code> and any other info the view might need to display correctly:</p>
<pre><code>data class LoginViewState (
val user: String = "",
val password: String = "",
val checking: Boolean = false
)
</code></pre>
<blockquote>
<p>Note, that I'm using a Data class with immutable properties for the state and deliberately don't use any Android resources. This is not something specific to MVVM, but an immutable view state prevents UI inconsistencies and threading problems.</p>
</blockquote>
<p>Inside the <code>ViewModel</code> create a <code>LiveData</code> property to expose the state and initialize it:</p>
<pre><code>class LoginViewModel : ViewModel() {
private val _state = MutableLiveData<LoginViewState>()
val state : LiveData<LoginViewState> get() = _state
init {
_state.value = LoginViewState()
}
}
</code></pre>
<p>To then emit a new state, use the <code>copy</code> function provided by Kotlin's Data class from anywhere inside the <code>ViewModel</code>:</p>
<pre><code>_state.value = _state.value!!.copy(checking = true)
</code></pre>
<p>In the view, observe the state as you would any other <code>LiveData</code> and update the layout accordingly. In the View layer you can translate the state's properties to actual view visibilities and use resources with full access to the <code>Context</code>:</p>
<pre><code>viewModel.state.observe(this, Observer {
it?.let {
userTextView.text = it.user
passwordTextView.text = it.password
checkingImageView.setImageResource(
if (it.checking) R.drawable.checking else R.drawable.waiting
)
}
})
</code></pre>
<h2>Conflating multiple data sources</h2>
<p>Since you probably previously exposed results and data from database or network calls in the <code>ViewModel</code>, you may use a <code>MediatorLiveData</code> to conflate these into the single state:</p>
<pre><code>private val _state = MediatorLiveData<LoginViewState>()
val state : LiveData<LoginViewState> get() = _state
_state.addSource(databaseUserLiveData, { name ->
_state.value = _state.value!!.copy(user = name)
})
...
</code></pre>
<h2>Data binding</h2>
<p>Since a unified, immutable <code>ViewState</code> essentially breaks the notification mechanism of the Data binding library, we're using a mutable <code>BindingState</code> that extends <code>BaseObservable</code> to selectively notify the layout of changes. It provides a <code>refresh</code> function that receives the corresponding <code>ViewState</code>:</p>
<p><strong>Update: Removed the if statements checking for changed values since the Data binding library already takes care of only rendering actually changed values.</strong> Thanks to @CarsonHolzheimer</p>
<pre><code>class LoginBindingState : BaseObservable() {
@get:Bindable
var user = ""
private set(value) {
field = value
notifyPropertyChanged(BR.user)
}
@get:Bindable
var password = ""
private set(value) {
field = value
notifyPropertyChanged(BR.password)
}
@get:Bindable
var checkingResId = R.drawable.waiting
private set(value) {
field = value
notifyPropertyChanged(BR.checking)
}
fun refresh(state: AngryCatViewState) {
user = state.user
password = state.password
checking = if (it.checking) R.drawable.checking else R.drawable.waiting
}
}
</code></pre>
<p>Create a property in the observing view for the <code>BindingState</code> and call <code>refresh</code> from the <code>Observer</code>:</p>
<pre><code>private val state = LoginBindingState()
...
viewModel.state.observe(this, Observer { it?.let { state.refresh(it) } })
binding.state = state
</code></pre>
<p>Then, use the state as any other variable in your layout:</p>
<pre><code><layout ...>
<data>
<variable name="state" type=".LoginBindingState"/>
</data>
...
<TextView
...
android:text="@{state.user}"/>
<TextView
...
android:text="@{state.password}"/>
<ImageView
...
app:imageResource="@{state.checkingResId}"/>
...
</layout>
</code></pre>
<h2>Advanced info</h2>
<p>Some of the boilerplate would definitely benefit from extension functions and Delegated properties like updating the <code>ViewState</code> and notifying changes in the <code>BindingState</code>.</p>
<p><strong>If you want more info on state and status handling with Architecture Components using a "clean" architecture you may checkout <a href="https://github.com/etiennelenhart/Eiffel" rel="noreferrer">Eiffel on GitHub</a>.</strong></p>
<p>It's a library I created specifically for handling immutable view states and data binding with <code>ViewModel</code> and <code>LiveData</code> as well as glueing it together with Android system operations and business use cases.
The documentation goes more in depth than what I'm able to provide here.</p> |
38,536,571 | What is the difference between enum struct and enum class? | <p>Looking at the <a href="http://en.cppreference.com/w/cpp/language/enum" rel="noreferrer"><code>enum</code> documentation</a>, there was one thing that I noticed:</p>
<blockquote>
<p><em><strong>enum-key</strong></em> - one of <code>enum</code>, <code>enum class</code>(since C++11), or <code>enum struct</code>(since C++11)</p>
</blockquote>
<p><code>enum</code> and <code>enum class</code>, sure, but what is a <code>enum struct</code>?</p>
<p>The docs seem to say that <code>enum class</code> and <code>enum struct</code> are exactly the same:</p>
<blockquote>
<p>[...] <em>scoped enumeration</em> (declared with the <em>enum-key</em> <code>enum class</code> or <code>enum struct</code>)</p>
<hr>
<ul>
<li><code>enum struct</code>|<code>class</code> <em>name</em> <code>{ enumerator = constexpr , enumerator = constexpr , ... }</code></li>
<li>[...]</li>
</ul>
</blockquote>
<p>Are they really exactly the same? Or are there any differences that I missed? What is the point (if they are the same) to have 2 different syntax for the same thing?</p> | 38,536,583 | 2 | 1 | null | 2016-07-22 23:26:19.09 UTC | 5 | 2019-03-04 15:19:37.61 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 3,980,929 | null | 1 | 39 | c++|c++11|enums | 18,892 | <p><code>enum class</code> and <code>enum struct</code> are the same (emphasis mine).</p>
<blockquote>
<p><strong>7.2 Enumeration declarations</strong><br>...<br>
<sup>2</sup> .... The <em>enum-keys</em> <code>enum class</code> and <code>enum struct</code> are <strong><em>semantically equivalent</em></strong>;
an enumeration type declared with one of these is a <em>scoped enumeration</em>, and its <em>enumerators</em> are <em>scoped
enumerators</em>.</p>
</blockquote> |
42,119,750 | What is the difference between strings and characters in Matlab? | <p>What is the difference between string and character class in MATLAB?</p>
<pre><code>a = 'AX'; % This is a character.
b = string(a) % This is a string.
</code></pre> | 42,120,091 | 4 | 0 | null | 2017-02-08 17:26:09.127 UTC | 8 | 2020-03-01 15:28:39.873 UTC | 2018-02-27 16:49:48.023 UTC | null | 3,924,118 | null | 2,991,243 | null | 1 | 15 | string|matlab|char | 14,442 | <p>The <a href="https://www.mathworks.com/help/matlab/matlab_prog/represent-text-with-character-and-string-arrays.html" rel="nofollow noreferrer">documentation suggests</a>:</p>
<blockquote>
<p>There are two ways to represent text in MATLAB®. You can store text in character arrays. A typical use is to store short pieces of text as character vectors. And starting in Release 2016b, you can also store multiple pieces of text in string arrays. String arrays provide a set of functions for working with text as data.</p>
</blockquote>
<p>This is how the two representations differ:</p>
<ul>
<li><p><strong>Element access</strong>. To represent <code>char</code> vectors of different length, one had to use <code>cell</code> arrays, e.g. <code>ch = {'a', 'ab', 'abc'}</code>. With strings, they can be created in actual arrays: <code>str = [string('a'), string('ab'), string('abc')]</code>.
However, to <a href="https://www.mathworks.com/help/matlab/matlab_prog/create-string-arrays.html#zmw57dd0e13371" rel="nofollow noreferrer">index characters</a> in a string array directly, the curly bracket notation has to be used:</p>
<pre><code>str{3}(2) % == 'b'
</code></pre></li>
<li><p><strong>Memory use</strong>. Chars use exactly two bytes per character. <code>string</code>s have overhead:</p>
<pre><code>a = 'abc'
b = string('abc')
whos a b
</code></pre>
<p>returns</p>
<blockquote>
<pre><code>Name Size Bytes Class Attributes
a 1x3 6 char
b 1x1 132 string
</code></pre>
</blockquote></li>
</ul> |
42,094,180 | SpaCy: how to load Google news word2vec vectors? | <p>I've tried several methods of loading the google news word2vec vectors (<a href="https://code.google.com/archive/p/word2vec/" rel="noreferrer">https://code.google.com/archive/p/word2vec/</a>):</p>
<pre><code>en_nlp = spacy.load('en',vector=False)
en_nlp.vocab.load_vectors_from_bin_loc('GoogleNews-vectors-negative300.bin')
</code></pre>
<p>The above gives:</p>
<pre><code>MemoryError: Error assigning 18446744072820359357 bytes
</code></pre>
<p>I've also tried with the .gz packed vectors; or by loading and saving them with gensim to a new format:</p>
<pre><code>from gensim.models.word2vec import Word2Vec
model = Word2Vec.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True)
model.save_word2vec_format('googlenews2.txt')
</code></pre>
<p>This file then contains the words and their word vectors on each line.
I tried to load them with:</p>
<pre><code>en_nlp.vocab.load_vectors('googlenews2.txt')
</code></pre>
<p>but it returns "0".</p>
<p>What is the correct way to do this?</p>
<p><strong>Update:</strong></p>
<p>I can load my own created file into spacy.
I use a test.txt file with "string 0.0 0.0 ...." on each line. Then zip this txt with .bzip2 to test.txt.bz2.
Then I create a spacy compatible binary file:</p>
<pre><code>spacy.vocab.write_binary_vectors('test.txt.bz2', 'test.bin')
</code></pre>
<p>That I can load into spacy:</p>
<pre><code>nlp.vocab.load_vectors_from_bin_loc('test.bin')
</code></pre>
<p>This works!
However, when I do the same process for the googlenews2.txt, I get the following error:</p>
<pre><code>lib/python3.6/site-packages/spacy/cfile.pyx in spacy.cfile.CFile.read_into (spacy/cfile.cpp:1279)()
OSError:
</code></pre> | 42,115,356 | 4 | 0 | null | 2017-02-07 15:50:16.633 UTC | 9 | 2019-05-13 17:26:27.823 UTC | 2019-05-13 17:26:27.823 UTC | null | 1,165,181 | null | 815,315 | null | 1 | 23 | python|nlp|word2vec|spacy | 17,770 | <p>For spacy 1.x, load Google news vectors into gensim and convert to a new format (each line in .txt contains a single vector: string, vec):</p>
<pre><code>from gensim.models.word2vec import Word2Vec
from gensim.models import KeyedVectors
model = KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True)
model.wv.save_word2vec_format('googlenews.txt')
</code></pre>
<p>Remove the first line of the .txt:</p>
<pre><code>tail -n +2 googlenews.txt > googlenews.new && mv -f googlenews.new googlenews.txt
</code></pre>
<p>Compress the txt as .bz2:</p>
<pre><code>bzip2 googlenews.txt
</code></pre>
<p>Create a SpaCy compatible binary file:</p>
<pre><code>spacy.vocab.write_binary_vectors('googlenews.txt.bz2','googlenews.bin')
</code></pre>
<p>Move the googlenews.bin to /lib/python/site-packages/spacy/data/en_google-1.0.0/vocab/googlenews.bin of your python environment.</p>
<p>Then load the wordvectors:</p>
<pre><code>import spacy
nlp = spacy.load('en',vectors='en_google')
</code></pre>
<p>or load them after later:</p>
<pre><code>nlp.vocab.load_vectors_from_bin_loc('googlenews.bin')
</code></pre> |
35,390,835 | Is comparison of const_iterator with iterator well-defined? | <p>Consider the following code:</p>
<pre><code>#include <vector>
#include <iostream>
int main()
{
std::vector<int> vec{1,2,3,5};
for(auto it=vec.cbegin();it!=vec.cend();++it)
{
std::cout << *it;
// A typo: end instead of cend
if(next(it)!=vec.end()) std::cout << ",";
}
std::cout << "\n";
}
</code></pre>
<p>Here I've introduced a typo: in the comparison I called <code>vec.end()</code> instead of <code>vec.cend()</code>. This appears to work as intended with gcc 5.2. But is it actually well-defined according to the Standard? Can <code>iterator</code> and <code>const_iterator</code> be safely compared?</p> | 35,392,987 | 3 | 0 | null | 2016-02-14 10:43:57.097 UTC | 5 | 2016-02-14 15:13:08.89 UTC | null | null | null | null | 673,852 | null | 1 | 35 | c++|iterator|comparison-operators|const-iterator | 4,147 | <p>Surprisingly, C++98 and C++11 didn't say that you can compare a <code>iterator</code> with a <code>const_iterator</code>. This leads to <a href="http://cplusplus.github.io/LWG/lwg-defects.html#179">LWG issue 179</a> and <a href="http://cplusplus.github.io/LWG/lwg-defects.html#2263">LWG issue 2263</a>. Now in C++14, this is explicitly permitted by § 23.2.1[container.requirements.general]p7</p>
<blockquote>
<p>In the expressions</p>
<pre><code>i == j
i != j
i < j
i <= j
i >= j
i > j
i - j
</code></pre>
<p>where <code>i</code> and <code>j</code> denote objects of a container's <code>iterator</code> type, either or
both may be replaced by an object of the container's <code>const_iterator</code>
type referring to the same element with no change in semantics.</p>
</blockquote> |
25,099,668 | PG::UndefinedTable: ERROR: missing FROM-clause entry for table when using joins and where | <p>I have two models, <code>Courier</code> and <code>Order</code>. </p>
<p>I have the following query below:</p>
<pre><code>active_couriers = Courier.
available_courier_status.
where(:service_region_id => @service_region.id).
includes(:orders)
</code></pre>
<p>This query works, however, it pulls in all orders. I want to limit the orders to only orders for the day. So I added the following query <code>where("orders.created_at >= ?", Time.zone.now.beginning_of_day)</code>.</p>
<pre><code>active_couriers = Courier.
available_courier_status.
where(:service_region_id => @service_region.id).
includes(:current_orders).
includes(:orders).
where("orders.created_at >= ?", Time.zone.now.beginning_of_day)
</code></pre>
<p>This give me the error:</p>
<pre><code>PG::UndefinedTable: ERROR: missing FROM-clause entry for table "orders"
</code></pre>
<p>What am I doing incorrectly here?</p> | 25,099,818 | 3 | 0 | null | 2014-08-02 21:41:36.503 UTC | 14 | 2019-10-30 12:59:48.74 UTC | 2017-06-15 16:07:48.777 UTC | null | 302,246 | null | 1,154,722 | null | 1 | 58 | ruby-on-rails|ruby-on-rails-4|psql | 56,141 | <p>Hmm it looks like you're trying to include <code>current_orders</code> and include <code>order</code>. Are these the same tables with different conditions? This might be confuse active record. Also, I'm pretty sure it's wise to include the <code>references</code> method when referencing a joined table. Perhaps, try something like this:</p>
<pre><code>active_couriers = Courier.includes(:orders)
.available_courier_status
.where(:service_region_id => @service_region.id)
.where("orders.created_at >= ?", Time.zone.now.beginning_of_day)
.references(:orders)
</code></pre> |
25,662,723 | Phabricator restrict git push | <p>I want my team including myself to review commits of each other. None of commits should be pushed including mine into repo until it's not audited by other team member. I kind of lost in phabricator documentation, so i'm asking here, is there any way to setup that kind of workflow?</p> | 25,667,786 | 2 | 0 | null | 2014-09-04 10:08:23.877 UTC | 9 | 2014-09-04 14:26:16.543 UTC | null | null | null | null | 1,121,521 | null | 1 | 16 | phabricator | 6,961 | <p>You can only restrict pushes to repositories hosted by Phabricator. If your repository is hosted elsewhere (like GitHub), Phabricator obviously can't prevent users from pushing to it.</p>
<p>To restrict pushes, create a new Herald rule (in the Herald application), like this:</p>
<ul>
<li>Create a new "Commit Hook: Commit Content" rule.</li>
<li>Select "Global" as the rule type.</li>
</ul>
<p>Then configure the rule like this:</p>
<pre><code>When [all of] these conditions are met:
[Accepted Differential revision][does not exist]
Take these actions every time this rule matches:
[Block change with message][Review is required for all changes.]
</code></pre>
<p>You may want to use additional conditions like this, to run the rule only in certain repositories:</p>
<pre><code>[Repository][is any of][ ... list of review-requied repositories ... ]
</code></pre>
<p>Or a condition like this, to let users bypass the rule by writing some string like "@bypass-review" in a message in an emergency:</p>
<pre><code>[Body][does not contain][@bypass-review]
</code></pre>
<p>If you add a bypass like this, you can mention it in the rejection message.</p> |
43,445,975 | What is a cluster in MongoDB? | <p>I am someone new to mongoDB and has absolutely no knowledge regarding databases so would like to know what is a cluster in MongoDB and what is the point of connecting to one in MongoDB? Is it a must to connect to one or can we just connect to the localhost?</p> | 43,447,558 | 3 | 0 | null | 2017-04-17 06:02:00.297 UTC | 17 | 2020-06-04 01:12:13.05 UTC | null | null | null | null | 7,876,941 | null | 1 | 79 | mongodb | 56,923 | <p>A mongodb cluster is the word usually used for <strong>sharded cluster</strong> in mongodb. The main purposes of a sharded mongodb are:</p>
<ul>
<li>Scale reads and writes along several nodes</li>
<li>Each node does not handle the whole data so you can separate data along all the nodes of the shard. Each node is a member of a shard (which is a replicaset, see below for the explanation) and the data are separated on all shards.</li>
</ul>
<p>This is the representation of a mongodb sharded cluster from the official <a href="https://docs.mongodb.com/v3.0/core/sharding-introduction/" rel="noreferrer">doc</a>.</p>
<p><a href="https://i.stack.imgur.com/zCOvb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zCOvb.png" alt="mongodb sharded cluster"></a></p>
<p><strong>If you are starting with mongodb, I do not recommend you to shard your data</strong>. Shards are way more complicated to maintain and handle than replicasets are.
You should have a look at a basic replicaset. It is fault tolerant and sufficient for simple needs.</p>
<p>The ideas of a replicaset are :</p>
<ul>
<li>Every data are repartited on each node</li>
<li>Only one node accept writes</li>
</ul>
<p>A replicaset representation from the official <a href="https://docs.mongodb.com/v3.0/core/replication-introduction/" rel="noreferrer">doc</a></p>
<p><a href="https://i.stack.imgur.com/Wr0pR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Wr0pR.png" alt="enter image description here"></a></p>
<p>For simple apps <strong>there is no problem to have your mongodb cluster on the same host than your application</strong>. You can even have them on a single member replicaset but you won't be fault tolerant anymore.</p> |
43,321,026 | Can I define multiple agent labels in a declarative Jenkins Pipeline? | <p>I'm using <a href="https://jenkins.io/doc/book/pipeline/syntax/#declarative-pipeline" rel="noreferrer">declarative Jenkins pipelines</a> to run some of my build pipelines and was wondering if it is possible to define multiple agent labels.</p>
<p>I have a number of build agents hooked up to my Jenkins and would like for this specific pipeline to be able to be built by various agents that have different labels (but not by ALL agents).</p>
<p>To be more concrete, let's say I have 2 agents with a label 'small', 4 with label 'medium' and 6 with label 'large'. Now I have a pipeline that is very resource-low and I want it to be executed on only a 'small'- or 'medium'-sized agent, but not on a large one as it may cause larger builds to wait in the queue for an unnecessarily long time. </p>
<p>All the examples I've seen so far only use one single label.
I tried something like this:</p>
<pre><code> agent { label 'small, medium' }
</code></pre>
<p>But it failed.</p>
<p>I'm using version 2.5 of the Jenkins Pipeline Plugin.</p> | 43,372,100 | 5 | 0 | null | 2017-04-10 10:39:39.793 UTC | 10 | 2022-07-19 07:53:27.23 UTC | 2017-05-24 16:20:23.377 UTC | null | 1,000,551 | null | 6,571,352 | null | 1 | 56 | jenkins|groovy|jenkins-pipeline | 80,488 | <p>You can see the 'Pipeline-syntax' help within your Jenkins installation and see the sample step "node" reference. </p>
<p>You can use <code>exprA||exprB</code>:</p>
<pre><code>node('small||medium') {
// some block
}
</code></pre> |
22,127,754 | How to install C# language support in Atom | <p>I've just started using <a href="https://atom.io/">https://atom.io/</a> on OSX</p>
<p>If I open a C# file it doesn't syntax highlight.</p>
<p>I've found <a href="https://github.com/atom/language-csharp">https://github.com/atom/language-csharp</a></p>
<p>Do I just clone that and copy it into /Applications/Atom.app/Contents/Resources/app/node_modules ?</p> | 22,127,785 | 5 | 0 | null | 2014-03-02 12:50:00.413 UTC | 4 | 2018-08-28 03:19:37.397 UTC | 2014-03-20 18:03:25.143 UTC | null | 321,731 | null | 435,129 | null | 1 | 30 | programming-languages|syntax-highlighting|atom-editor | 23,095 | <p>Go into preferences -> Packages and type 'CSharp'</p>
<p><img src="https://i.stack.imgur.com/DkKiP.png" alt="enter image description here"></p>
<p>I've used Lisp in the picture as I already installed CSharp so it won't show up any more.</p> |
2,706,044 | How do I stop jetty server in clojure? | <p>I am writing a web application using ring and clojure. I am using the jetty adapter for the development server and emacs/SLIME for IDE. While wrap-reload does help, run-jetty blocks my slime session and I would like to be able to start/stop it at will without having to run it in a separate terminal session. Ideally, I would like to define a server agent and functions start-server and stop-server that would start/stop the server inside the agent. Is this possible?</p> | 2,706,239 | 3 | 0 | null | 2010-04-24 20:40:51.59 UTC | 21 | 2022-04-22 23:26:16.85 UTC | 2011-03-07 17:58:22.543 UTC | null | 339,701 | null | 302,268 | null | 1 | 62 | clojure|jetty|ring | 14,722 | <p>I usually have a line in my Ring app that looks like the following:</p>
<pre><code>(defonce server (run-jetty #'my-app {:port 8080 :join? false}))
</code></pre>
<p>This prevents locking up the REPL. It also allows me to recompile this file without worrying that my server will get redefined. It also lets you interact at the REPL like so:</p>
<pre><code>user=> (.stop server)
</code></pre>
<p>and</p>
<pre><code>user=> (.start server)
</code></pre> |
2,948,156 | Algorithm Complexity & Security: MD5 or SHA1? | <blockquote>
<p><strong>Which is the best overall hashing algorithm in terms of complexity and security? md5 or sha1?</strong></p>
</blockquote>
<p>From what I know <em>md5</em> is faster than <em>sha1</em> but <em>SHA1</em> is more complex than md5. </p>
<p>Am I missing anything?</p> | 2,948,163 | 3 | 2 | null | 2010-06-01 08:14:28.517 UTC | 23 | 2017-03-16 17:28:19.643 UTC | 2012-04-26 15:24:10.68 UTC | null | 295,264 | null | 295,264 | null | 1 | 70 | algorithm|hash | 91,799 | <p>First of all, MD5 is broken - you can generate a collision, so MD5 should not be used for any security applications. SHA1 is not known to be broken and is believed to be secure. Other than that - yes, MD5 is faster but has 128-bit output, while SHA1 has 160-bit output.</p>
<p><strong>Update:</strong> SHA1 has been broken: a team of researchers at Google and CWI have published a collision - <a href="https://shattered.io/static/shattered.pdf" rel="noreferrer">https://shattered.io/static/shattered.pdf</a></p> |
2,465,111 | Dependency Walker reports IESHIMS.DLL and WER.DLL missing? | <p>On a Windows XP Professional SP3 with Internet Explorer 8 box, when I run Dependency Walker on an executable of mine it reports that:
IESHIMS.DLL and WER.DLL can't be found.</p>
<ol>
<li>Do I need these DLL's?</li>
<li>Where can I get them?</li>
</ol>
<p>I believe they are supposed to located in
C:\Windows\System32\Wer.dll and
C:\Program Files\Internet Explorer\Ieshims.dll</p> | 2,465,488 | 4 | 2 | null | 2010-03-17 19:08:37.187 UTC | 14 | 2018-12-06 09:08:02.003 UTC | null | null | null | null | 155,268 | null | 1 | 99 | internet-explorer-8|dll|dependency-walker|windows-xp-sp3 | 157,301 | <p><code>ieshims.dll</code> is an artefact of Vista/7 where a shim DLL is used to proxy certain calls (such as <code>CreateProcess</code>) to handle protected mode IE, which doesn't exist on XP, so it is unnecessary. <code>wer.dll</code> is related to Windows Error Reporting and again is probably unused on Windows XP which has a slightly different error reporting system than Vista and above.</p>
<p>I would say you shouldn't need either of them to be present on XP and would normally be delay loaded anyway. </p> |
40,557,637 | How to return an image in Spring Boot controller and serve like a file system | <p>I've tried the various ways given in Stackoverflow, maybe I missed something.</p>
<p>I have an Android client (whose code I can't change) which is currently getting an image like this:</p>
<pre><code>HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
</code></pre>
<p>Where <code>url</code> is the location of the image (static resource on CDN). Now my Spring Boot API endpoint needs to behave like a file resource in the same way so that the same code can get images from the API (Spring boot version 1.3.3).</p>
<p>So I have this:</p>
<pre><code>@ResponseBody
@RequestMapping(value = "/Image/{id:.+}", method = RequestMethod.GET, consumes = MediaType.ALL_VALUE, produces = MediaType.IMAGE_JPEG_VALUE)
public ResponseEntity<byte[]> getImage(@PathVariable("id")String id) {
byte[] image = imageService.getImage(id); //this just gets the data from a database
return ResponseEntity.ok(image);
}
</code></pre>
<p>Now when the Android code tries to get <code>http://someurl/image1.jpg</code> I get this error in my logs:</p>
<blockquote>
<p>Resolving exception from handler [public
org.springframework.http.ResponseEntity
com.myproject.MyController.getImage(java.lang.String)]:
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not
find acceptable representation</p>
</blockquote>
<p>Same error happens when I plug <code>http://someurl/image1.jpg</code> into a browser.</p>
<p>Oddly enough my tests check out ok:</p>
<pre><code>Response response = given()
.pathParam("id", "image1.jpg")
.when()
.get("MyController/Image/{id}");
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
byte[] array = response.asByteArray(); //byte array is identical to test image
</code></pre>
<p>How do I get this to behave like an image being served up in the normal way? (Note I can't change the content-type header that the android code is sending)</p>
<p><strong>EDIT</strong></p>
<p>Code after comments (set content type, take out <code>produces</code>):</p>
<pre><code>@RequestMapping(value = "/Image/{id:.+}", method = RequestMethod.GET, consumes = MediaType.ALL_VALUE)
public ResponseEntity<byte[]> getImage(@PathVariable("id")String id, HttpServletResponse response) {
byte[] image = imageService.getImage(id); //this just gets the data from a database
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
return ResponseEntity.ok(image);
}
</code></pre>
<p>In a browser this just seems to give a stringified junk (byte to chars i guess). In Android it doesn't error, but the image doesn't show.</p> | 40,585,852 | 4 | 5 | null | 2016-11-11 23:12:59.547 UTC | 10 | 2019-03-28 21:55:55.847 UTC | 2016-11-17 23:55:46.64 UTC | null | 1,689,965 | null | 2,393,012 | null | 1 | 17 | java|spring-mvc|spring-boot | 45,438 | <p>Finally fixed this... I had to add a <code>ByteArrayHttpMessageConverter</code> to my <code>WebMvcConfigurerAdapter</code> subclass:</p>
<pre><code>@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
final ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
final List<MediaType> list = new ArrayList<>();
list.add(MediaType.IMAGE_JPEG);
list.add(MediaType.APPLICATION_OCTET_STREAM);
arrayHttpMessageConverter.setSupportedMediaTypes(list);
converters.add(arrayHttpMessageConverter);
super.configureMessageConverters(converters);
}
</code></pre> |
37,200,162 | Swift: Get an element from a tuple | <p>If I have a tuple like this</p>
<pre><code>var answer: (number: Int, good: Bool)
</code></pre>
<p>How do I get one of the elements?</p>
<p>This doesn't work:</p>
<pre><code>answer["number"]
</code></pre>
<p>I am modeling this question after <a href="https://stackoverflow.com/questions/26536538/swift-get-an-array-of-element-from-an-array-of-tuples">Swift: Get an array of element from an array of tuples</a>, but my question was a little more basic. I did find the answer buried in the <a href="https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html" rel="noreferrer">documentation</a> so I am adding my answer below in Q&A format for faster searching in the future.</p> | 37,200,163 | 2 | 0 | null | 2016-05-13 02:10:16.887 UTC | 4 | 2016-05-13 02:39:00.503 UTC | 2017-05-23 12:25:54.497 UTC | null | -1 | null | 3,681,880 | null | 1 | 32 | swift|tuples | 24,485 | <p>According to the <a href="https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html">documentation</a> (scroll down to Tuples), there are three ways to do it.</p>
<p>Given</p>
<pre><code>var answer: (number: Int, good: Bool) = (100, true)
</code></pre>
<p><strong>Method 1</strong></p>
<p>Put the element variable name within a tuple.</p>
<pre><code>let (firstElement, _) = answer
let (_, secondElement) = answer
</code></pre>
<p>or </p>
<pre><code>let (firstElement, secondElement) = answer
</code></pre>
<p><strong>Method 2</strong></p>
<p>Use the index.</p>
<pre><code>let firstElement = answer.0
let secondElement = answer.1
</code></pre>
<p><strong>Method 3</strong></p>
<p>Use the names. This only works, of course, if the elements were named in the Tuple declaration.</p>
<pre><code>let firstElement = answer.number
let secondElement = answer.good
</code></pre> |
49,196,173 | Move cypress folder from the root of the project | <p>When I install and run cypress, it scaffolds a <code>cypress/</code> folder in the root of my project.</p>
<p>The problem is that all other test related data is stored in the <code>test/</code> folder. Is there an easy way to move it to <code>test/cypress</code> and configure cypress to look there?</p> | 49,196,174 | 4 | 0 | null | 2018-03-09 14:43:01.857 UTC | 7 | 2022-07-07 22:50:22.023 UTC | null | null | null | null | 4,603,159 | null | 1 | 37 | testing|integration-testing|cypress | 21,699 | <p>Cypress has a few configuration options to specify custom folder structure.</p>
<p>For that you will need to have <code>cypress.json</code> file in the root of your project and specify the following structure there for cypress to properly pick up the files in <code>test/cypress/</code>:</p>
<pre><code>{
"fixturesFolder": "test/cypress/fixtures",
"integrationFolder": "test/cypress/integration",
"pluginsFile": "test/cypress/plugins/index.js",
"screenshotsFolder": "test/cypress/screenshots",
"videosFolder": "test/cypress/videos",
"downloadsFolder": "test/cypress/downloads",
"supportFile": "test/cypress/support/index.js"
}
</code></pre>
<p>More info in the <a href="https://docs.cypress.io/guides/references/configuration.html#Folders-Files" rel="noreferrer">cypress docs</a>.</p> |
49,282,471 | Lombok causing "Actual and formal arguments lists differ in length error" | <p>I have the following class:</p>
<pre><code>@Builder @NoArgsConstructor
public class ConsultationPointOfContact {
private String fullName;
private String phoneNumber;
private String userLogin;
}
</code></pre>
<p>When the <code>@Builder</code> annotation exists, it is causing problems with the <code>@NoArgsConstructor</code>.</p>
<p>I am getting the error:</p>
<pre><code>Error:(11, 1) java: constructor ConsultationPointOfContact in class models.ConsultationPointOfContact cannot be applied to given types;
required: no arguments
found: java.lang.String,java.lang.String,java.lang.String
reason: actual and formal argument lists differ in length
</code></pre> | 49,282,701 | 3 | 0 | null | 2018-03-14 16:01:53.65 UTC | 9 | 2021-11-26 07:06:56.893 UTC | null | null | null | null | 1,688,441 | null | 1 | 54 | java|lombok|intellij-lombok-plugin | 23,528 | <p>Add <code>@AllArgsConstructor</code> as well and this should fix the issue</p> |
13,747,468 | How to copy rows of from one sheet to another sheet using vbscript | <p>Suppose I have Sheet(1) in an excel. Now i do also have 2500 rows which has data for the columns from A to BO.Now I want the data to copy from these sheet to another sheet of the same Excel file for 2500 rows but not the whole the columns,rather i need only columns from A to AA data to copy to the new sheet.</p>
<p>So how to frame it using VBscript?</p>
<p>Please help me. </p>
<p>How to copy rows of from one sheet to another sheet using vbscript</p> | 13,748,244 | 3 | 1 | null | 2012-12-06 15:56:05.967 UTC | 1 | 2017-07-17 18:51:55.317 UTC | null | null | null | null | 2,767,755 | null | 1 | 0 | vbscript | 42,213 | <p>To copy data from one sheet to another you can use the Copy en PasteSpecial commands. To do this with a <code>.vbs</code> script do the following:</p>
<pre><code>' Create Excel object
Set objExcel = CreateObject("Excel.Application")
' Open the workbook
Set objWorkbook = objExcel.Workbooks.Open _
("C:\myworkbook.xlsx")
' Set to True or False, whatever you like
objExcel.Visible = True
' Select the range on Sheet1 you want to copy
objWorkbook.Worksheets("Sheet1").Range("A1:AA25").Copy
' Paste it on Sheet2, starting at A1
objWorkbook.Worksheets("Sheet2").Range("A1").PasteSpecial
' Activate Sheet2 so you can see it actually pasted the data
objWorkbook.Worksheets("Sheet2").Activate
</code></pre>
<p>If you want to do this in Excel with a VBS macro you can also call the copy and paste methods. Only your workbook object will be something like <code>ActiveWorkbook</code> </p> |
1,102,673 | SQL Server subquery syntax | <p>When I run the query :</p>
<pre><code>select count(*) from
(select idCover from x90..dimCover group by idCover having count(*) > 1)
</code></pre>
<p>I get the error :</p>
<pre><code>Server: Msg 170, Level 15, State 1, Line 2
Line 2: Incorrect syntax near ')'
</code></pre>
<p>How do I formulate this query correctly?</p>
<p>I'm on SQL Server 2000</p> | 1,102,679 | 2 | 0 | null | 2009-07-09 09:01:04.637 UTC | 1 | 2014-12-10 15:49:59.903 UTC | 2009-07-09 10:05:49.03 UTC | null | 36,189 | null | 36,189 | null | 1 | 29 | sql|sql-server | 25,869 | <p>Add an alias after your last bracket.</p>
<pre><code>select count(*) from
(select idCover from x90..dimCover group by idCover having count(*) > 1) a
</code></pre> |
939,673 | How is a blob column annotated in Hibernate? | <p>How is a blob column annotated in Hibernate?
So far I have a class that has:</p>
<pre><code>@Column( name = "FILEIMAGE" )
private byte[ ] fileimage ;
//
public byte[ ] getFileimage ( ) { return this.fileimage ; }
public void setFilename ( String filename ) { this.filename = filename ; }
</code></pre> | 939,725 | 2 | 0 | null | 2009-06-02 13:49:46.993 UTC | 5 | 2014-08-22 20:59:47.987 UTC | null | null | null | quinn | null | null | 1 | 35 | hibernate|annotations|blob | 59,485 | <p>@Lob should do the trick for blob and clob (use String as type)</p>
<pre><code>@Column( name = "FILEIMAGE" )
@Lob(type = LobType.BLOB)
private byte[] fileimage;
</code></pre> |
2,903,610 | Visual Studio: reset user settings when debugging | <p>In a C# Winforms-App I have several user settings stored.</p>
<p>Is there an easy way to clear those settings each time I start debugging the project from Visual Studio 2008?</p>
<p>Otherwise it always starts up with the settings from the last debug-session.</p> | 2,903,657 | 6 | 0 | null | 2010-05-25 09:56:33.733 UTC | 10 | 2018-01-26 12:39:50.007 UTC | 2016-10-18 20:36:44.903 UTC | null | 2,840,103 | null | 196,253 | null | 1 | 26 | c#|visual-studio-2008|settings|reset | 40,402 | <p>Add a pre-build action to delete:</p>
<p><code>%USERPROFILE%\Local Settings\Application Data\[AppName]\...\[Version]\user.config</code></p>
<p>or if your version number changes alot just delete</p>
<p><code>%USERPROFILE%\Local Settings\Application Data\[AppName]\</code></p> |
2,396,548 | Appending to boost::filesystem::path | <p>I have a certain <code>boost::filesystem::path</code> in hand and I'd like to append a string (or path) to it.</p>
<pre><code>boost::filesystem::path p("c:\\dir");
p.append(".foo"); // should result in p pointing to c:\dir.foo
</code></pre>
<p>The only overload <code>boost::filesystem::path</code> has of <code>append</code> wants two <code>InputIterator</code>s.</p>
<p>My solution so far is to do the following:</p>
<pre><code>boost::filesystem::path p2(std::string(p.string()).append(".foo"));
</code></pre>
<p>Am I missing something?</p> | 2,396,827 | 6 | 0 | null | 2010-03-07 14:20:52.773 UTC | 5 | 2022-07-04 08:30:33.793 UTC | null | null | null | null | 210,311 | null | 1 | 40 | c++|boost | 72,904 | <pre><code>#include <iostream>
#include <string>
#include <boost/filesystem.hpp>
int main() {
boost::filesystem::path p (__FILE__);
std::string new_filename = p.leaf() + ".foo";
p.remove_leaf() /= new_filename;
std::cout << p << '\n';
return 0;
}
</code></pre>
<p>Tested with 1.37, but <em>leaf</em> and <em>remove_leaf</em> are also documented in <a href="http://www.boost.org/doc/libs/1_35_0/libs/filesystem/doc/reference.html" rel="noreferrer">1.35</a>. You'll need to test whether the last component of <em>p</em> is a filename first, if it might not be.</p> |
2,776,397 | Create a basic matrix in C (input by user !) | <p>I'm trying to ask the user to enter the number of columns and rows they want in a matrix, and then enter the values in the matrix... I'm going to let them insert numbers one row at a time.</p>
<p>How can I create such function ?</p>
<pre><code>#include<stdio.h>
main(){
int mat[10][10],i,j;
for(i=0;i<2;i++)
for(j=0;j<2;j++){
scanf("%d",&mat[i][j]);
}
for(i=0;i<2;i++)
for(j=0;j<2;j++)
printf("%d",mat[i][j]);
}
</code></pre>
<p>This works for entering the numbers, but it displays them all in one line... The issue here is that I don't know how many columns or rows the user wants, so I cant print out %d %d %d in a matrix form...</p>
<p>Any thoughts?</p>
<p>Thanks :)</p> | 2,776,452 | 7 | 0 | null | 2010-05-05 20:07:15.213 UTC | 2 | 2017-10-17 13:10:32.583 UTC | 2017-02-10 12:13:32.59 UTC | null | 3,563,841 | null | 331,734 | null | 1 | 9 | c|matrix | 261,231 | <p>How about the following?</p>
<p>First ask the user for the number of rows and columns, store that in say, <code>nrows</code> and <code>ncols</code> (i.e. <code>scanf("%d", &nrows);</code>) and then <a href="http://pleasemakeanote.blogspot.com/2008/06/2d-arrays-in-c-using-malloc.html" rel="noreferrer">allocate memory for a 2D array</a> of size <em>nrows x ncols</em>. Thus you can have a matrix of a size specified by the user, and not fixed at some dimension you've hardcoded!</p>
<p>Then store the elements with <code>for(i = 0;i < nrows; ++i) ...</code> and display the elements in the same way except you throw in newlines after every row, i.e.</p>
<pre><code>for(i = 0; i < nrows; ++i)
{
for(j = 0; j < ncols ; ++j)
{
printf("%d\t",mat[i][j]);
}
printf("\n");
}
</code></pre> |
2,390,230 | Do copyright dates need to be updated? | <p>Every now and then I see a web site that has an old copyright date. In my mind, I always think "Look at the sucker who forgot to update his copyright year!" Then, while I was hard-coding a copyright year into the site I'm currently designing, it suddenly struck me: </p>
<p>How the hell am I going to remember to update this?</p>
<p>My immediate reaction was just to use some server-side coding to automatically display the current year. Bam, fixed.</p>
<p>Later, I began to ponder to myself, if someone as big and smart as Google can <a href="http://goo.gl/" rel="noreferrer">overlook this</a>, perhaps there's something wrong in doing it this way. Maybe I'm doing something wrong? I guess what I'm really wondering is <em>why I feel compelled</em> to keep the copyright year up to date. Is there a reason, or is my chronic OCD to blame?</p>
<p>If there is a good reason to keep them up to date, why don't more developers use server-side code? I see these "mistakes" <a href="http://www.times.com/ref/membercenter/help/copyright.html" rel="noreferrer">all</a> <a href="http://www.myflorida.com/myflorida/copyright.html" rel="noreferrer">over</a> <a href="http://www.fpsece.net/" rel="noreferrer">the</a> <a href="http://copyright.columbia.edu/copyright/" rel="noreferrer">place</a>.</p> | 2,391,555 | 7 | 6 | null | 2010-03-05 21:59:53.153 UTC | 84 | 2021-03-09 10:09:06.54 UTC | 2012-10-11 17:53:36.897 UTC | null | 493,939 | null | 84,088 | null | 1 | 340 | server-side|copyright-display | 166,707 | <p>The copyright notice on a work establishes a claim to copyright. The date on the notice establishes how far back the claim is made. This means if you update the date, you are no longer claiming the copyright for the original date and that means if somebody has copied the work in the meantime and they claim its theirs on the ground that their publishing the copy was before your claim, then it will be difficult to establish who is the originator of the work.</p>
<p>Therefore, if the claim is based on common law copyright (not formally registered), then the date should be the date of first publication. If the claim is a registered copyright, then the date should be the date claimed in the registration. In cases where the work was substantially revised you may establish a new copyright claim to the revised work by adding another copyright notice with a newer date or by adding an additional date to the existing notice as in "© 2000, 2010". Again, the added date establishes how far back the claim is made on the revision.</p> |
25,407,428 | How to access CoreData model in today extension (iOS) | <p>Is it possible to work with my CoreData model in the today extension in swift like in the original app? If yes, how can I create the NSManagedObjectContext? <br>
I really have no clue, beside the group-identifier, but unfortunatly I don't know how to get the context.. <br>
In the past I created apps with the check at the beginning that I want to use CoreData and then I got the managedObjectContext via my AppDelegate.. But how can I do somethink like that in an extension? Apple doesn't offer information about that..</p>
<p>I edited this line in AppDelegate:</p>
<pre><code>NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"HTWcampus.sqlite"];
</code></pre>
<p>to this (after including the group to both targets):</p>
<pre><code>NSURL *storeURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.BenchR.TodayExtensionSharingDefaults"];
storeURL = [storeURL URLByAppendingPathComponent:@"HTWcampus.sqlite"];
NSLog(@"StoreURL2: %@", storeURL);
</code></pre>
<p>With that the existing database in my app was gone (what is great, because I think it worked to put the database in the shared segment).</p>
<p>But how can I create an instance of my context in the extension? And how can I access my NSManagedObject-subclasses?</p>
<p>In the extension I have this code so far:</p>
<pre><code>var context: NSManagedObjectContext!
override func viewDidLoad() {
super.viewDidLoad()
var storeURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.BenchR.TodayExtensionSharingDefaults")
storeURL = storeURL?.URLByAppendingPathComponent("HTWcampus.sqlite")
let modelURL = NSBundle.mainBundle().URLForResource("HTWcampus", withExtension: "momd")
let model = NSManagedObjectModel(contentsOfURL: modelURL)
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: nil)
context = NSManagedObjectContext()
context.persistentStoreCoordinator = coordinator
}
</code></pre>
<p>Is this right? And if yes, how can I get my NSManagedObject-Subclasses in there? And do I have to add the momd-file to the extensions target? If yes, how can I do that?</p> | 25,408,472 | 1 | 0 | null | 2014-08-20 14:31:11.45 UTC | 19 | 2015-07-30 23:12:50.693 UTC | 2014-12-23 13:35:59.537 UTC | null | 3,126,646 | null | 2,607,748 | null | 1 | 38 | ios|core-data|swift|ios8|today-extension | 20,343 | <p>What you really want is to access your persistent store (most likely a SQLite database).
In order to achieve that, you need to configure App Groups and make sure that your host app configures the Core Data stack using your shared container (so your store is accessible in extension as well).
Something like:</p>
<pre><code> NSString *containerPath = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:YOUR_SECURITY_APP_GROUP].path;
NSString *sqlitePath = [NSString stringWithFormat:@"%@/%@", containerPath, @"database.sqlite"];
</code></pre>
<p>Then in your extension just create persistent store coordinator with managed object contexts using database in shared container.
You can share your model (.momd) and managed object subclasses with extension just by making sure they are included in extension target as well.</p>
<p><strong>Edit:</strong></p>
<p>To add your model and managed object subclasses:</p>
<p><img src="https://i.stack.imgur.com/4dYls.png" alt="1. Make sure you have your app and extension targets" /></p>
<ol>
<li><p>Make sure you have your app and extension targets</p>
<p><img src="https://i.stack.imgur.com/X7hUY.png" alt="2. Click on your model file, and select both targets under 'Target Membership' on right-hand panel" /></p>
</li>
<li><p>Click on your model file, and select both targets under 'Target Membership' on right-hand panel</p>
<p><img src="https://i.stack.imgur.com/i6ktJ.png" alt="3. Repeat the same with all your managed object subclasses" /></p>
</li>
<li><p>Repeat the same with all your managed object subclasses</p>
</li>
</ol> |
25,387,660 | iBeacon region monitoring AND proximity for >20 beacons? | <p>I have been working on a prototype iOS app utilizing iBeacons to provide location-relevant information to office employees depending on where in the office they are. The ideal use case is that whenever an employee enters or exits their office, a callback is fired which provides them some information in the form of a notification (it might make a server query to get information first, etc - that sort of thing). We also want to be able to do this when the app is backgrounded or terminated; fortunately, we already know that beacon region boundary crossings trigger the appropriate CoreLocation callbacks even if the app is backgrounded or suspended.</p>
<p>From looking around, I understand that broadly, I have two options for how to approach the beacon region monitoring:</p>
<ol>
<li>Give each iBeacon its own CLBeaconRegion, and monitor for each of these regions independently.</li>
<li>Monitor for CLBeaconRegions that correspond to multiple iBeacons - for example, each iBeacon has the same UUID and only monitor for a CLBeaconRegion corresponding to that UUID - then try to determine which beacon triggered the boundary crossing using ranging.</li>
</ol>
<p>Thus far, I had chosen option #1. The advantage of this approach is that I get didEnterRegion: and didExitRegion: calls for each individual beacon and immediately know which beacon I have entered/exited. Also, I only get one enter call and one exit call, which is exactly what I want. Unfortunately, I just realized that this approach also limits me to 20 beacons (since each beacon gets its own region).</p>
<p>I'm not as familiar with the exact implementation details of #2, so correct me if I'm wrong. But it seems that this approach has more drawbacks:</p>
<ul>
<li>Apple discourages ranging when the app is in the background because the results may not be as accurate.</li>
<li>The ranging calls fire once every second, while I only want to have "enter/exit" callbacks.</li>
<li>If the beacons have region overlap, the ranging calls might continually flip which one is "closest", which would further complicate things.</li>
</ul>
<p>Basically, I'm wondering if there is a way to utilize option #2, but still have the benefits of option #1 - a quick and easy way to immediately determine which beacon triggered the region change with only one enter or exit callback? </p>
<p>I hope this question is clear enough. It's not all entirely clear in my own head, especially how ranging works.</p> | 25,389,318 | 3 | 0 | null | 2014-08-19 15:43:33.233 UTC | 11 | 2014-08-28 15:22:49.77 UTC | null | null | null | null | 1,722,048 | null | 1 | 13 | ios|ibeacon | 7,290 | <p>Option #2 is absolutely more complicated, but you must accept these complications in order to get around the 20 region monitoring limit.</p>
<p>A few points:</p>
<ul>
<li><p>In the background, you only have around 5 seconds of ranging time, which does not give you as much time to average RSSI (signal strength) from each beacon to get a good distance estimate. So, yes, the estimates will be less accurate. If you understand this limitation and can live with it for your use case, there is nothing wrong with ranging in the background.</p></li>
<li><p>Yes, you will get multiple ranging calls per beacon after region entry, and you won't get any callbacks on region exit. You have to write extra code to take care of this. I have done this by maintaining a NSMutableArray of all the unique beacons (same uuid/major/minor) seen and update it in the ranging callback. You can then access this array in the region exit callback, so you know which beacons disappeared. Of course, it is possible that additional beacons were seen after the 5 seconds of background ranging time expires, but your app will never know about them. With this option, you must accept this limitation.</p></li>
<li><p>While it is true that errors on the distance estimate in ranging may incorrectly tell you which beacon is closest, you have an even worse problem when doing monitoring, because you don't get a distance estimate at all. If multiple beacons come into monitoring range around the same time, there is no guarantee that the first entered region callback you get will be for the closest beacon. So if your use case requires taking action based on the closest beacon, then you must do ranging (knowing that there may be error on the distance estimate.)</p></li>
</ul> |
25,160,245 | Clang linking with a .so file | <p>I keep getting</p>
<pre class="lang-none prettyprint-override"><code>ld: library not found for -lchaiscript_stdlib-5.3.1.so
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code></pre>
<p>When trying to link to a <em>.so</em> file.</p>
<p>I'm using this command:</p>
<pre class="lang-none prettyprint-override"><code>clang++ Main.cpp -o foo -L./ -lchaiscript_stdlib-5.3.1.so
</code></pre>
<p>What am I doing wrong?</p>
<p>File <em>libchaiscript_stdlib-5.3.1.so</em> is in the same directory as file <em>Main.cpp</em>. I thought the <code>-L./</code> would add the <em>.so</em> to the library search paths.</p> | 25,160,298 | 1 | 0 | null | 2014-08-06 12:20:44.61 UTC | 9 | 2020-12-30 22:43:14.173 UTC | 2020-12-30 22:40:54.563 UTC | null | 63,550 | user245019 | null | null | 1 | 14 | c++|linker|clang|chaiscript | 34,476 | <p>Yes, the <code>-L</code> option adds the search path, but the linker adds the <code>.so</code> (or <code>.a</code>) suffix itself (just like it adds the <code>lib</code> prefix). So you only need to have <code>-lchaiscript_stdlib-5.3.1</code> and the linker will find it.</p>
<p>You can also skip the adding of the path, and link directly with the file:</p>
<pre class="lang-none prettyprint-override"><code>clang++ Main.cpp -o foo libchaiscript_stdlib-5.3.1.so
</code></pre>
<hr />
<p>Note that the runtime linker (which is what actually loads the shared libraries when you run your program) might not be able to find the library if it's not in the runtime linker's path. You can tell the (compile time) linker to add a path to the shared-library path in the generated program though:</p>
<pre class="lang-none prettyprint-override"><code>clang++ Main.cpp -o foo libchaiscript_stdlib-5.3.1.so -Wl,-rpath,/absolute/path
</code></pre>
<p>The <code>-Wl</code> option tells the compiler front-end to pass an option to the linker, and the linker option <code>-rpath</code> adds a path to the runtime-linker search path.</p> |
6,121,276 | Is it possible to Load an assembly from the GAC without the FullName? | <p>I know how to load an assembly from a filename, and also from the GAC.
As My .msi file will put a dll project into the GAC, I'm wondering if it's possible to load it from the GAC unknowing the FullName (I mean just with the assembly name, or even the dll filename), because I have to Load this assembly from another project.</p> | 6,131,116 | 2 | 1 | null | 2011-05-25 07:58:33.403 UTC | 9 | 2017-02-24 23:37:11.843 UTC | 2017-02-24 23:37:11.843 UTC | null | 41,071 | null | 580,319 | null | 1 | 20 | c#|assemblies|load|gac | 6,306 | <p>Here is a piece of code that allows to do this, and an exemple:</p>
<pre><code> string path = GetAssemblyPath("System.DirectoryServices");
Assembly.LoadFrom(path);
</code></pre>
<p>Note if you need a specific processor architecture, since it supports partial name, you can write this kind of things:</p>
<pre><code> // load from the 32-bit GAC
string path = GetAssemblyPath("Microsoft.Transactions.Bridge.Dtc, ProcessorArchitecture=X86");
// load from the 64-bit GAC
string path = GetAssemblyPath("Microsoft.Transactions.Bridge.Dtc, ProcessorArchitecture=AMD64");
</code></pre>
<p>This is the implementation:</p>
<pre><code> /// <summary>
/// Gets an assembly path from the GAC given a partial name.
/// </summary>
/// <param name="name">An assembly partial name. May not be null.</param>
/// <returns>
/// The assembly path if found; otherwise null;
/// </returns>
public static string GetAssemblyPath(string name)
{
if (name == null)
throw new ArgumentNullException("name");
string finalName = name;
AssemblyInfo aInfo = new AssemblyInfo();
aInfo.cchBuf = 1024; // should be fine...
aInfo.currentAssemblyPath = new String('\0', aInfo.cchBuf);
IAssemblyCache ac;
int hr = CreateAssemblyCache(out ac, 0);
if (hr >= 0)
{
hr = ac.QueryAssemblyInfo(0, finalName, ref aInfo);
if (hr < 0)
return null;
}
return aInfo.currentAssemblyPath;
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("e707dcde-d1cd-11d2-bab9-00c04f8eceae")]
private interface IAssemblyCache
{
void Reserved0();
[PreserveSig]
int QueryAssemblyInfo(int flags, [MarshalAs(UnmanagedType.LPWStr)] string assemblyName, ref AssemblyInfo assemblyInfo);
}
[StructLayout(LayoutKind.Sequential)]
private struct AssemblyInfo
{
public int cbAssemblyInfo;
public int assemblyFlags;
public long assemblySizeInKB;
[MarshalAs(UnmanagedType.LPWStr)]
public string currentAssemblyPath;
public int cchBuf; // size of path buf.
}
[DllImport("fusion.dll")]
private static extern int CreateAssemblyCache(out IAssemblyCache ppAsmCache, int reserved);
</code></pre> |
18,596,867 | What is the git command to list ignored files? | <p>My netbeans IDE shows ignored files on a different color.
I presume, the IDE is knowing this by using some git command.</p>
<p>I wish to know what files on a project folder and subfolders are being ignored.</p>
<p>What command should we use?</p> | 18,596,993 | 1 | 1 | null | 2013-09-03 16:10:00.427 UTC | 4 | 2013-09-03 16:18:15.3 UTC | null | null | null | null | 378,170 | null | 1 | 29 | git | 24,722 | <p><code>git status --ignored</code> will show all untracked files. It also includes the normal status output. There does not appear to be a status option to only show the ignored files.</p> |
30,942,556 | Laravel: dynamic where clause with Elouquent | <p>I am calling URL with search params which are dynamic. How could I form proper <strong>Eloquent query</strong>?</p>
<p>In theory:</p>
<ol>
<li>query</li>
<li><strong>query where(someParam1)</strong></li>
<li><strong>query where(someParam2)</strong></li>
<li>query orderby(someParam3)</li>
<li>query get</li>
</ol>
<p>I need this kind of structure so I can use where clause if <strong>param exists</strong>.
If there is some other way in Laravel, please let me know.</p> | 30,943,421 | 6 | 0 | null | 2015-06-19 16:04:00.23 UTC | 10 | 2020-08-25 14:55:12.41 UTC | null | null | null | null | 3,103,116 | null | 1 | 35 | laravel|eloquent | 34,754 | <p>It's easy with Laravel. Just do something like this:</p>
<pre><code>$query = User::query();
if ($this == $that) {
$query = $query->where('this', 'that');
}
if ($this == $another_thing) {
$query = $query->where('this', 'another_thing');
}
if ($this == $yet_another_thing) {
$query = $query->orderBy('this');
}
$results = $query->get();
</code></pre> |
31,289,895 | Threshold image using opencv (Java) | <p>I am working with Opencv for my project. I need to convert the image below to threshold image </p>
<p><img src="https://i.stack.imgur.com/w8eyt.jpg" alt="Original Image"></p>
<p>I tried this function: </p>
<pre><code>Imgproc.threshold(imgGray, imgThreshold, 0, 255, Imgproc.THRESH_BINARY + Imgproc.THRESH_OTSU);
</code></pre>
<p>But the result was not so good, as you see below </p>
<p><img src="https://i.stack.imgur.com/VR6PI.png" alt="threshold"></p>
<p>So I tried the <code>adaptiveThreshold function</code>: </p>
<pre><code>Imgproc.adaptiveThreshold(imgGray, imgThreshold, 255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY, 11, 2);
</code></pre>
<p>and it resulted:</p>
<p><img src="https://i.stack.imgur.com/7bP3g.png" alt="adaptiveThreshold"></p>
<p>I just expect a binary image with white background and black text only, no black area or noise ( I do not prefer using <code>Photo.fastNlMeansDenoising</code> because it takes a lot of time). Please help me with a solution for this. </p>
<p>Also, I am using <code>Tesseract</code> for Japanese recognization but the accuracy rate is not good. Do you have any suggestion on better OCR for Japanese, or any method to improve Tesseract quality? </p> | 31,290,735 | 1 | 1 | null | 2015-07-08 10:24:34.963 UTC | 11 | 2020-11-16 16:51:59.953 UTC | 2015-07-08 11:42:51.24 UTC | null | 4,968,030 | null | 1,840,768 | null | 1 | 12 | java|android|opencv|image-processing|tesseract | 25,749 | <p><code>adaptiveThreshold</code> is the right choice here. <strong>Just need a litte tuning</strong>.
With these parameters (it's C++, but you can easily translate to Java)</p>
<pre><code>Mat1b gray= imread("path_to_image", IMREAD_GRAYSCALE);
Mat1b result;
adaptiveThreshold(gray, result, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 15, 40);
</code></pre>
<p>the resulting image is:</p>
<p><img src="https://i.stack.imgur.com/QZxPX.png" alt="enter image description here"></p> |
31,399,411 | Go to "next" iteration in JavaScript forEach loop | <p>How do I go to the next iteration of a JavaScript <code>Array.forEach()</code> loop?</p>
<p>For example:</p>
<pre><code>var myArr = [1, 2, 3, 4];
myArr.forEach(function(elem){
if (elem === 3) {
// Go to "next" iteration. Or "continue" to next iteration...
}
console.log(elem);
});
</code></pre>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach" rel="noreferrer">MDN docs</a> only mention breaking out of the loop entirely, not moving to next iteration.</p> | 31,399,448 | 3 | 1 | null | 2015-07-14 06:38:17.343 UTC | 22 | 2019-08-11 22:45:28.753 UTC | 2019-08-11 22:45:28.753 UTC | null | 4,642,212 | null | 1,001,938 | null | 1 | 310 | javascript|foreach | 227,038 | <p>You can simply <code>return</code> if you want to skip the current iteration.</p>
<p>Since you're in a function, if you <code>return</code> before doing anything else, then you have effectively skipped execution of the code below the <code>return</code> statement.</p> |
19,628,393 | How to begin with Windows Kernel Programming? | <p>I am an application developer mostly work in C#. I have some knowledge of C/C++. I am very much fascinated and interested in windows Kernel Development. I Sketched out a layout to learn this.</p>
<pre><code>1. Understand Windows internals(By books)
2. Try Simple Modules and keep expanding.
</code></pre>
<p>To achieve this, I need some help on:</p>
<pre><code>1. The books I should read.
2. The Websites I should follow.
3. Setting up my dev environment.(Most important as I can start realizing.)
</code></pre>
<p>Kindly help.</p> | 19,634,253 | 2 | 0 | null | 2013-10-28 06:30:49.943 UTC | 27 | 2019-07-07 08:12:11.003 UTC | 2013-10-28 08:19:07.56 UTC | null | 1,157,680 | null | 1,157,680 | null | 1 | 21 | kernel|windows-kernel | 23,446 | <p>Read <a href="http://technet.microsoft.com/en-us/sysinternals/bb963901.aspx" rel="noreferrer">Windows Internals</a>.</p>
<p>Read <a href="http://msdn.microsoft.com/en-us/library/windows/hardware/ff557573%28v=vs.85%29.aspx" rel="noreferrer">Windows Drivers Development</a>.</p>
<p>Follow and read <a href="https://community.osr.com/categories/ntdev" rel="noreferrer">OSR Online</a>.</p>
<p>To start writing read <a href="http://msdn.microsoft.com/en-us/library/windows/hardware/ff554811%28v=vs.85%29.aspx" rel="noreferrer">Writing your first driver</a>.</p>
<p>This should cover you for several years or more.</p> |
19,448,902 | Changing the width of Bootstrap popover | <p>I am designing a page using Bootstrap 3. I am trying to use a popover with <code>placement: right</code> on an input element. The new Bootstrap ensures that if you use <code>form-control</code> you basically have a full-width input element.</p>
<p>The HTML code looks something like this: </p>
<pre><code><div class="row">
<div class="col-md-6">
<label for="name">Name:</label>
<input id="name" class="form-control" type="text"
data-toggle="popover" data-trigger="hover"
data-content="My popover content.My popover content.My popover content.My popover content." />
</div>
</div>
</code></pre>
<p>The popovers width is too low, in my opinion because their isn't any width left in the div.
I want the input form on the left side, and a wide popover on the right side.</p>
<p>Mostly, I'm looking for a solution where I don't have to override Bootstrap. </p>
<p>The attached JsFiddle. The second input option. Haven't used jsfiddle a lot so don't know, but try increasing the size of the output box to see results, on smaller screens wouldn't even see it.
<a href="http://jsfiddle.net/Rqx8T/" rel="noreferrer">http://jsfiddle.net/Rqx8T/</a></p> | 19,604,395 | 24 | 0 | null | 2013-10-18 11:46:17.187 UTC | 38 | 2022-03-11 09:58:39.987 UTC | 2015-01-17 05:41:34.057 UTC | null | 3,998,712 | null | 1,152,297 | null | 1 | 216 | css|twitter-bootstrap|twitter-bootstrap-3|popover | 308,173 | <pre><code><div class="row" data-toggle="popover" data-trigger="hover"
data-content="My popover content.My popover content.My popover content.My popover content.">
<div class="col-md-6">
<label for="name">Name:</label>
<input id="name" class="form-control" type="text" />
</div>
</div>
</code></pre>
<p>Basically i put the popover code in the row div, instead of the input div. Solved the problem.</p> |
19,140,148 | C++ Get Total File Line Number | <p>Is there a function I can use to get total file line number in <code>C++</code>, or does it have to be manually done by <code>for</code> loop?</p>
<pre><code>#include <iostream>
#include <ifstream>
ifstream aFile ("text.txt");
if (aFile.good()) {
//how do i get total file line number?
}
</code></pre>
<p><em>text.txt</em></p>
<pre><code>line1
line2
line3
</code></pre> | 19,140,254 | 7 | 0 | null | 2013-10-02 15:01:55.64 UTC | 3 | 2021-04-14 23:19:04.077 UTC | 2016-11-15 13:17:00.827 UTC | null | 7,055,233 | null | 2,797,246 | null | 1 | 6 | c++|get|numbers|size|line | 65,914 | <p>There is no such function. Counting can be done by reading whole lines </p>
<pre><code>std::ifstream f("text.txt");
std::string line;
long i;
for (i = 0; std::getline(f, line); ++i)
;
</code></pre>
<p>A note about scope, variable <code>i</code> must be outside <a href="https://en.cppreference.com/w/cpp/language/for#Explanation" rel="nofollow noreferrer"><code>for</code></a>, if you want to access it after the loop.</p>
<hr>
<p>You may also read character-wise and check for linefeeds </p>
<pre><code>std::ifstream f("text.txt");
char c;
long i = 0;
while (f.get(c))
if (c == '\n')
++i;
</code></pre> |
19,216,580 | Requirejs: paths vs map | <p>Trying to understand where it's right to use "map" with a wildcard vs "paths". </p>
<p>Looking at the require source (but certainly not being 100% fluent with it) it seems like there would functionally be no difference between these two snippets. Is that true? </p>
<p>Using Paths:</p>
<pre><code> require.config({
baseUrl: "include/js/",
paths: {
foo: "stuff/foo",
}
});
</code></pre>
<p>Using Map:</p>
<pre><code> require.config({
baseUrl: "include/js/",
map: {
'*': {foo: "stuff/foo"},
}
});
</code></pre> | 24,305,846 | 4 | 0 | null | 2013-10-07 03:19:27.317 UTC | 2 | 2022-01-30 20:28:58.313 UTC | 2013-10-26 11:33:51.717 UTC | null | 578,411 | null | 60,247 | null | 1 | 31 | requirejs | 14,253 | <p>From the RequireJS Docs "In addition, the paths config is only for setting up root paths for module IDs, not for mapping one module ID to another one."</p>
<p>This means "paths" is meant for mapping just the path to your resource when it is not in the default location (baseUrl). I guess this is what you were trying to do.</p>
<p>On the other hand, with "map" you can have several versions of your resource (foo1, foo2...) which you can map to be loaded from different paths (i.e. you want to load foo1 from a desktop browser and foo2 which is a modification of the first one from a mobile browser).</p>
<p>So, unless you have different versions of foo I would use "path" although you are right and "map" would also work in that case.</p> |
37,032,203 | Make syscall in Python | <p>I want to make <code>syscall</code> in Python and the function is not in <code>libc</code>, is there a way to do it in Python?</p>
<p>More specifically, I want to call <a href="http://man7.org/linux/man-pages/man2/getdents.2.html" rel="noreferrer"><code>getdents</code></a>, whose manpage says </p>
<blockquote>
<p>Note: There are no glibc wrappers for these system calls;</p>
</blockquote>
<p>All existing related solutions I found on the web uses <code>ctypes</code> with <code>libc.so</code>: for <a href="http://ubuntuforums.org/archive/index.php/t-1452881.html" rel="noreferrer">example</a>.</p>
<p>Please don't question why I want to use <code>getdents</code> directly, I have a very specific reason to do that, and it would be distracting to discuss in this question. Thank you.</p> | 37,032,683 | 1 | 0 | null | 2016-05-04 15:33:27.393 UTC | 9 | 2016-05-04 16:48:37.88 UTC | 2016-05-04 16:00:45.497 UTC | null | 416,224 | null | 875,044 | null | 1 | 30 | python|python-2.7|system-calls | 19,845 | <p>Libc exposes a function to invoke "custom" syscalls: <a href="http://man7.org/linux/man-pages/man2/syscall.2.html" rel="noreferrer"><code>long syscall(long number, ...);</code></a></p>
<blockquote>
<p><code>syscall()</code> is a small library function that invokes the system call
whose assembly language interface has the specified <code>number</code> with the
specified arguments. Employing <code>syscall()</code> is useful, for example,
when invoking a system call that has no wrapper function in the C
library.</p>
</blockquote>
<p>Just access this function like any foreign function:</p>
<pre><code>import ctypes
libc = ctypes.CDLL(None)
syscall = libc.syscall
</code></pre>
<p>e.g.</p>
<pre><code>syscall(39) # 39 = getpid, but you get the gist
</code></pre>
<p>Or to translate the example in the man page:</p>
<pre><code>import os, ctypes
off_t = ctypes.c_long # YMMV
__NR_getdents = 78 # YMMV
class linux_dirent(ctypes.Structure):
_fields_ = [
('d_ino', ctypes.c_long),
('d_off', off_t),
('d_reclen', ctypes.c_ushort),
('d_name', ctypes.c_char)
]
_getdents = ctypes.CDLL(None).syscall
_getdents.restype = ctypes.c_int
_getdents.argtypes = ctypes.c_long, ctypes.c_uint, ctypes.POINTER(ctypes.c_char), ctypes.c_uint
fd = os.open('/tmp/', os.O_RDONLY | os.O_DIRECTORY)
buf = ctypes.ARRAY(ctypes.c_char, 1024)()
while True:
nread = _getdents(__NR_getdents, fd, buf, len(buf))
if nread == -1:
raise OSError('getdents')
elif nread == 0:
break
pos = 0
while pos < nread:
d = linux_dirent.from_buffer(buf, pos)
name = buf[pos + linux_dirent.d_name.offset : pos + d.d_reclen]
name = name[:name.index('\0')]
print 'name:', name
pos += d.d_reclen
</code></pre> |
29,971,837 | Changing password on p12 file | <p>I was forwarded a p12 file from a client with the push cert. </p>
<p>Can I change the password of this p12 file without any ramifications and if yes, can I use something like this:</p>
<pre><code>openssl pkcs12 -in Certificates.p12 -out temp.pem -passin pass: -passout
pass:temppassword
openssl pkcs12 -export -in temp.pem -out Certificates-final.p12 -passin
pass:temppassword -passout pass:newpassword
rm -rf temp.pem
</code></pre>
<p>I found this on this website <a href="http://readpaul.com/blog/1620.html/comment-page-1" rel="noreferrer">here</a></p> | 35,609,431 | 4 | 2 | null | 2015-04-30 15:29:49.83 UTC | 16 | 2019-09-11 15:09:07.75 UTC | 2017-07-21 10:55:08.72 UTC | null | 177,701 | null | 1,819,000 | null | 1 | 38 | ios|push-notification|apple-push-notifications | 54,425 | <p>There will be no problem. </p>
<p>PFX is an encrypted container, changing the password of the container will have no effect on the certificates inside the container.</p> |
48,556,768 | How to configure prometheus with alertmanager? | <p><strong>docker-compose.yml:</strong>
This is the docker-compose to run the prometheus, node-exporter and alert-manager service. All the services are running great. Even the health status in target menu of prometheus shows ok.</p>
<pre><code>version: '2'
services:
prometheus:
image: prom/prometheus
privileged: true
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
- ./alertmanger/alert.rules:/alert.rules
command:
- '--config.file=/etc/prometheus/prometheus.yml'
ports:
- '9090:9090'
node-exporter:
image: prom/node-exporter
ports:
- '9100:9100'
alertmanager:
image: prom/alertmanager
privileged: true
volumes:
- ./alertmanager/alertmanager.yml:/alertmanager.yml
command:
- '--config.file=/alertmanager.yml'
ports:
- '9093:9093'
</code></pre>
<p><strong>prometheus.yml</strong></p>
<p>This is the prometheus config file with targets and alerts target sets. The alertmanager target url is working fine.</p>
<pre><code>global:
scrape_interval: 5s
external_labels:
monitor: 'my-monitor'
# this is where I have simple alert rules
rule_files:
- ./alertmanager/alert.rules
scrape_configs:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
- job_name: 'node-exporter'
static_configs:
- targets: ['node-exporter:9100']
alerting:
alertmanagers:
- static_configs:
- targets: ['some-ip:9093']
</code></pre>
<p><strong>alert.rules:</strong>
Just a simple alert rules to show alert when service is down</p>
<pre><code>ALERT service_down
IF up == 0
</code></pre>
<p><strong>alertmanager.yml</strong></p>
<p>This is to send the message on slack when alerting occurs.</p>
<pre><code>global:
slack_api_url: 'https://api.slack.com/apps/A90S3Q753'
route:
receiver: 'slack'
receivers:
- name: 'slack'
slack_configs:
- send_resolved: true
username: 'tara gurung'
channel: '#general'
api_url: 'https://hooks.slack.com/services/T52GRFN3F/B90NMV1U2/QKj1pZu3ZVY0QONyI5sfsdf'
</code></pre>
<p><strong>Problems:</strong>
All the containers are working fine I am not able to figure out the exact problem.What am I really missing. Checking the alerts in prometheus shows.</p>
<p><strong>Alerts
No alerting rules defined</strong> </p>
<p><a href="https://i.stack.imgur.com/C7sWG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/C7sWG.png" alt="enter image description here"></a></p> | 48,559,174 | 2 | 1 | null | 2018-02-01 06:41:29.123 UTC | 9 | 2022-04-28 14:27:32.327 UTC | 2018-02-01 12:29:49.447 UTC | null | 4,966,953 | null | 4,412,382 | null | 1 | 10 | docker-compose|prometheus | 16,812 | <p>Your <code>./alertmanager/alert.rules</code> file is not included in your docker config, so it is not available in the container. You need to add it to the prometheus service:</p>
<pre><code>prometheus:
image: prom/prometheus
privileged: true
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
- ./alertmanager/alert.rules:/alertmanager/alert.rules
command:
- '--config.file=/etc/prometheus/prometheus.yml'
ports:
- '9090:9090'
</code></pre>
<p>And probably give an absolute path inside <code>prometheus.yml</code>:</p>
<pre><code>rule_files:
- "/alertmanager/alert.rules"
</code></pre>
<p>You also need to make sure you alerting rules are valid. Please see the <a href="https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/" rel="noreferrer">prometheus docs</a> for details and examples. You <code>alert.rules</code> file should look something like this:</p>
<pre><code>groups:
- name: example
rules:
# Alert for any instance that is unreachable for >5 minutes.
- alert: InstanceDown
expr: up == 0
for: 5m
</code></pre>
<p>Once you have multiple files, it may be better to add the entire directory as a volume rather than individual files.</p> |
48,619,733 | react-router Redirect vs history.push | <p>I was reading <a href="https://github.com/ReactTraining/react-router/tree/master/packages/react-router-redux/examples" rel="noreferrer">react-router-redux examples</a> and I confused,
what is the difference beetween:</p>
<pre><code>import { Redirect } from 'react-router-dom'
...
<Redirect to='/login' />
</code></pre>
<p>and </p>
<pre><code>import { push } from 'react-router-redux'
...
push('/login')
</code></pre> | 50,525,884 | 3 | 2 | null | 2018-02-05 09:52:20.297 UTC | 12 | 2021-07-02 14:44:39.45 UTC | null | null | null | null | 4,204,843 | null | 1 | 57 | react-router|react-router-v4|react-router-redux|react-router-dom | 51,623 | <p><strong>Redirect</strong></p>
<p>Rendering a <code><Redirect></code> will navigate to a new location. The new location will <code>override the current location in the history stack,</code> like server-side redirects (HTTP 3xx) do.</p>
<p>whereas <strong>History</strong></p>
<p><strong>push function</strong> <code>Pushes a new entry onto the history stack</code></p> |
8,439,657 | Copy an entire worksheet to a new worksheet in Excel 2010 | <p>I have found similar questions that deal with copying an entire worksheet in one workbook and pasting it to another workbook, but I am interested in simply copying an entire worksheet and pasting it to a new worksheet -- in the same workbook. </p>
<p>I'm in the process of converting a 2003 .xls file to 2010 .xlsm and the old method used for copying and pasting between worksheets doesn't paste with the correct row heights. My initial workaround was to loop through each row and grab the row heights from the worksheet I am copying from, then loop through and insert those values for the row heights in the worksheet I am pasting to, but the problem with this approach is that the sheet contains buttons which generate new rows which changes the row numbering and the format of the sheet is such that all rows cannot just be one width. </p>
<p>What I would really like to be able to do is just simply copy the entire worksheet and paste it. Here is the code from the 2003 version:</p>
<pre><code>ThisWorkbook.Worksheets("Master").Cells.Copy
newWorksheet.Paste
</code></pre>
<p>I'm surprised that converting to .xlsm is causing this to break now. Any suggestions or ideas would be great.</p> | 8,439,771 | 6 | 0 | null | 2011-12-09 00:32:24.483 UTC | 7 | 2018-05-11 15:10:29.91 UTC | 2015-03-26 17:03:36.517 UTC | null | 1,505,120 | user567677 | null | null | 1 | 27 | vba|excel|excel-2010 | 335,509 | <p>It is simpler just to run an exact copy like below to put the copy in as the last sheet</p>
<pre><code>Sub Test()
Dim ws1 As Worksheet
Set ws1 = ThisWorkbook.Worksheets("Master")
ws1.Copy ThisWorkbook.Sheets(Sheets.Count)
End Sub
</code></pre> |
8,868,486 | What's the difference between MemoryCache.Add and MemoryCache.Set? | <p>I read the <a href="https://msdn.microsoft.com/en-us/library/dd780623(v=vs.110).aspx">MSDN documentation</a> but didn't really understand it.</p>
<p>I believe that the behavior of <code>Set</code> is "replace existing, or add" (atomically).</p>
<p>Is that correct?</p> | 8,868,522 | 1 | 0 | null | 2012-01-15 08:40:35.607 UTC | 8 | 2016-11-15 07:00:16.307 UTC | 2015-10-24 15:43:03.457 UTC | null | 3,191,599 | null | 136,999 | null | 1 | 114 | .net|memorycache | 27,752 | <p><code>Add</code> does nothing (returns <code>false</code>) if there is already a value for that key. <code>Set</code> does an insert or update, as necessary.</p>
<p><code>Remove</code> + <code>Add</code> would leave a gap in the middle when another thread querying that key would get no clue (<code>Set</code> does not; the swap is typically atomic); as such, while <code>Set</code> has the same <strong>end result</strong> as <code>Remove</code> + <code>Add</code>, the mechanism difference is important since it could impact other callers.</p>
<p>For example of <a href="http://msdn.microsoft.com/en-us/library/dd780614.aspx">Add</a>:</p>
<blockquote>
<p>Return Value</p>
<p>Type: System.Boolean true if insertion succeeded, or false if there is an already an entry in the cache that has the same key as key. </p>
</blockquote> |
26,969,166 | counting occurrences in data.frame in r | <p>I have a data frame 200 columns containing 150 genes (rows) in each column.</p>
<p>I want to count the number occurrences for each gene in the whole data frame</p>
<pre><code>mydat <-
V1 V2 V3 V4 V5 V6 V7 V8
1 TGFBR2 TGFBR2 TGFBR2 TGFBR2 TGFBR2 TGFBR2 TGFBR2 TGFBR2
2 MAML2 MAML2 MAML2 MAML2 MAML2 MAML2 MAML2 MAML2
3 BMPR2 EIF5A WRAP53 WRAP53 EIF5A EIF5A EIF5A EIF5A
4 EIF5A BMPR2 EIF5A EIF5A ADAMTSL3 BMPR2 WRAP53 BMPR2
5 EIF5AL1 WRAP53 ADAMTSL3 BMPR2 BMPR2 WRAP53 BMPR2 EIF5AL1
6 WRAP53 EIF5AL1 BMPR2 ADAMTSL3 WRAP53 EIF5AL1 EIF5AL1 WRAP53
7 TBC1D5 ADAMTSL3 EIF5AL1 EIF5AL1 EIF5AL1 ADAMTSL3 ADAMTSL3 C1QTNF7
8 ADAMTSL3 C1QTNF7 C1QTNF7 C1QTNF7 FHL1 YAP1 AURKB ADAMTSL3
9 C1QTNF7 FHL1 RGS7BP LIFR C1QTNF7 TMEM43 C1QTNF7 LIFR
10 AURKB RGS5 AURKB FAM198B AURKB C1QTNF7 PSMB6 PDGFD
</code></pre>
<p>So I want the output to be something like this:</p>
<pre><code>occurences
TGFBR2: 8
MALM2 : 8
FHL1: 3
</code></pre>
<p>etc. But I want to count every gene in the data frame.</p>
<p>How do I do this?</p> | 26,969,215 | 2 | 1 | null | 2014-11-17 09:14:15.883 UTC | 3 | 2014-11-17 10:37:12 UTC | 2014-11-17 10:32:48.84 UTC | null | 1,627,235 | null | 4,079,590 | null | 1 | 17 | r|dataframe | 50,936 | <p>try</p>
<pre><code>occurences<-table(unlist(mydat))
</code></pre>
<p>(I assigned the result so you don't get a full screen of gene names and so each gene's occurence can be accessed by <code>occurences["genename"]</code>)</p> |
26,543,127 | PowerShell Setting advanced NTFS permissions | <p>I'm trying to apply NTFS permissions that are defined in the 'Advanced' tab of the Windows security settings. One ACL <code>$Rule</code> is for <code>This folder only</code> and another one is for the <code>Subfolders and files only</code>.</p>
<p>The permissions are heavily modified as you can see below:</p>
<pre><code>(Get-Acl 'L:\Test\Beez\RAPJOUR\Appels List\Correct').Access
FileSystemRights : FullControl
AccessControlType : Allow
IdentityReference : BUILTIN\Administrators
IsInherited : False
InheritanceFlags : ContainerInherit, ObjectInherit
PropagationFlags : None
FileSystemRights : CreateFiles, AppendData, DeleteSubdirectoriesAndFiles, ReadAndExecute, Synchronize
AccessControlType : Allow
IdentityReference : Domain\Dirk
IsInherited : False
InheritanceFlags : None
PropagationFlags : None
FileSystemRights : DeleteSubdirectoriesAndFiles, Modify, Synchronize
AccessControlType : Allow
IdentityReference : Domain\Dirk
IsInherited : False
InheritanceFlags : ContainerInherit, ObjectInherit
PropagationFlags : InheritOnly
</code></pre>
<p><img src="https://i.stack.imgur.com/R4MEA.jpg" alt="This folder only"></p>
<ul>
<li>Everything is on except for : Full control, Write attributes, Write extended attributes, Delete, Change permissions and Take ownership.</li>
</ul>
<p><img src="https://i.stack.imgur.com/r42M4.jpg" alt="Subfolders and files only"></p>
<ul>
<li>Everything is on except for : Full control, Change permissions and Take ownership.</li>
</ul>
<p>This is a piece of the code I use to apply permissions. In this case it has to be defined in the part <code>Change</code>:</p>
<pre><code> $f = 'L:\Test\Beez\RAPJOUR\Appels List\Wrong'
$ADobject = 'Domain\User'
$acl = Get-Acl $f
$Grant = 'Change'
# Remove user/group first
$rule = New-Object system.security.AccessControl.FileSystemAccessRule("$ADobject","Read",,,"Allow")
$acl.RemoveAccessRuleAll($rule)
# Add read permissions
if ($Grant -eq 'ReadAndExecute') {
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$ADobject", "ReadAndExecute", "ContainerInherit, ObjectInherit", "None", "Allow")
}
if ($Grant -eq 'Change') {
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$ADobject", "Modify", "ContainerInherit, ObjectInherit", "Synchronize", "Allow DeleteSubdirectoriesAndFiles")
$acl.AddAccessRule($rule)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$ADobject", "AppendData", "ContainerInherit, ObjectInherit", "ReadAndExecute","Synchronize", "Allow CreateFiles","DeleteSubdirectoriesAndFiles")
}
if ($Grant -eq 'Modify') {
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$ADobject", "Modify", "ContainerInherit, ObjectInherit", "None", "Allow")
}
if ($Grant -eq 'FullControl') {
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$ADobject", "FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
}
if ($Grant -eq 'ListFolderContents') {
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$ADobject", "ReadAndExecute", "ContainerInherit", "None", "Allow")
}
$acl.AddAccessRule($rule)
Set-Acl $f $acl
</code></pre>
<p>I can't seem to get the syntax right.. Thank you for your help.</p>
<p>Thanks to this <a href="http://camillelemouellic.blog.com/2011/07/22/powershell-security-descriptors-inheritance-and-propagation-flag-possibilities/" rel="noreferrer">post</a> I've already found the part for:</p>
<ul>
<li>'Subfolders and files only': <code>"ContainerInherit, ObjectInherit", "InheritOnly"</code></li>
<li>'This folder only': <code>"None", "InheritOnly"</code></li>
</ul> | 26,544,463 | 2 | 0 | null | 2014-10-24 07:12:33.383 UTC | 5 | 2017-12-14 07:12:46.1 UTC | 2014-10-24 12:01:44.457 UTC | null | 2,304,170 | null | 2,304,170 | null | 1 | 9 | powershell|permissions|ntfs | 82,602 | <p>Object access permissions in Windows are controlled via <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa374872%28v=vs.85%29.aspx" rel="noreferrer">Access Control Lists</a> (ACL), which basically consist of a list of <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa374868%28v=vs.85%29.aspx" rel="noreferrer">Access Control Entries</a> (ACE). Each ACE is a set of attributes that controls whether access is granted or denied, who the ACE applies to, if the ACE was inherited from a parent object, and whether it should be inherited by child objects.</p>
<p>If you take a look at the documentation of the <a href="http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.filesystemaccessrule%28v=vs.110%29.aspx" rel="noreferrer"><code>FileSystemAccessRule</code></a> class, you'll see that the "full" constructor takes 5 parameters:</p>
<ul>
<li><code>IdentityReference</code>/<code>String</code>: An object or string that identifies the trustee (user, group, computer, ...) to whom the ACE applies.</li>
<li><code>FileSystemRights</code>: The actual <a href="http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.filesystemrights%28v=vs.110%29.aspx" rel="noreferrer">permissions</a> to be granted or denied.</li>
<li><code>InheritanceFlags</code>: Flags to control which object types inherit permissions from this object (containers, leaf objects, or none).</li>
<li><code>PropagationFlags</code>: Flags to control <a href="https://msdn.microsoft.com/en-us/library/ms229747%28v=vs.110%29.aspx" rel="noreferrer">propagation</a> of permissions. The flag <code>InheritOnly</code> exempts the current object from receiving the ACE. The flag <code>NoPropagateInherit</code> restricts inheritance to immediate child objects.</li>
<li><code>AccessControlType</code>: The <a href="http://msdn.microsoft.com/en-us/library/w4ds5h86%28v=vs.110%29.aspx" rel="noreferrer">type</a> of the ACE (allow or deny).</li>
</ul>
<p>Now, if you want to assign multiple access rights to a given trustee, you can either do that with individual ACEs:</p>
<pre class="lang-psh prettyprint-override"><code>$acl = Get-Acl $path
$ace1 = New-Object Security.AccessControl.FileSystemAccessRule 'DOMAIN\user',
<b>'ListDirectory'</b>, 'ContainerInherit, ObjectInherit', 'InheritOnly',
'Allow'
$acl.AddAccessRule($ace1)
$ace2 = New-Object Security.AccessControl.FileSystemAccessRule 'DOMAIN\user',
<b>'ReadAttributes'</b>, 'ContainerInherit, ObjectInherit', 'InheritOnly',
'Allow'
$acl.AddAccessRule($ace2)
...</code></pre>
<p>Or by providing the permissions as a comma-separated string:</p>
<pre class="lang-psh prettyprint-override"><code>$acl = Get-Acl $path
$ace = New-Object Security.AccessControl.FileSystemAccessRule 'DOMAIN\user',
<b>'ListDirectory, ReadAttributes, ...'</b>, 'ContainerInherit, ObjectInherit',
'InheritOnly', 'Allow'
$acl.AddAccessRule($ace)</code></pre>
<p>Note, however, that you cannot grant and deny permissions with the same ACE. If you want to deny specific access rights you need to do it with a separate ACE:</p>
<pre class="lang-psh prettyprint-override"><code>$acl = Get-Acl $path
$ace1 = New-Object Security.AccessControl.FileSystemAccessRule 'DOMAIN\user',
<b>'Modify'</b>, 'ContainerInherit, ObjectInherit', 'InheritOnly',
<b>'Allow'</b>
$acl.AddAccessRule($ace1)
$ace2 = New-Object Security.AccessControl.FileSystemAccessRule 'DOMAIN\user',
<b>'CreateDirectories'</b>, 'ContainerInherit, ObjectInherit', 'InheritOnly',
<b>'Deny'</b>
$acl.AddAccessRule($ace2)
...</code></pre>
<p>Note also, that explicit permissions take precedence over inherited permissions, and <code>Deny</code> takes precedence over <code>Allow</code>.</p> |
26,649,180 | 'Show' segue in Xcode 6 presents the viewcontroller as a modal in iOS 7 | <p>I have two view controllers in my iPhone application (built with swift) built with Xcode 6.1 and uses storyboards.</p>
<p>The first view controller is embedded in a navigation controller in the storyboard and the segue for the second view controller is a 'Show' segue. </p>
<p>When the application is run, it properly shows the transition as a push in iOS 8.x, but in iOS 7.x it appears as a modal without the navigation bar.</p>
<p>My application requirement is to show the transition as a push regardless of whether it's iOS 7 or iOS 8. Any ideas to get this working as push in both versions of the iOS?</p>
<p>I saw a related post where this issue is mentioned, but could not find a solution to the problem: <a href="https://stackoverflow.com/questions/24184003/adaptive-segue-in-storyboard-xcode-6-is-push-deprecated">Adaptive segue in storyboard Xcode 6. Is push deprecated?</a></p>
<p>Any help is appreciated...</p>
<p>Thanks</p> | 33,377,134 | 11 | 0 | null | 2014-10-30 09:24:06.913 UTC | 3 | 2017-12-05 14:43:00.613 UTC | null | null | null | null | 2,717,398 | null | 1 | 28 | ios|swift|uistoryboardsegue | 13,489 | <blockquote>
<p>This solution is different from the others in the following ways:</p>
</blockquote>
<ol>
<li>It includes a method to examine and verify the issue</li>
<li>The cause of the issue is traced to the source (a change in the segue type)</li>
<li>The solution is very simple (delete and recreate a new segue)</li>
<li>Please note the requirements in the text</li>
</ol>
<p>I just gave a <a href="https://stackoverflow.com/questions/24184003/adaptive-segue-in-storyboard-xcode-6-is-push-deprecated/33376713#33376713">very detailed SO answer</a> that fully explains what is happening and why, but the simple solution is you can delete the Segue that is not pushing and then recreate it on the storyboard. The reason is that there is likely a broken bit of xml in the segue (see extended answer for example/instructions how to confirm this issue).</p>
<p>After you confirm that you have at least one UINavigationController within the view hierarchy, be sure that the segue is NOT a manual segue and does NOT have an action associated with it (by viewing the segue in the storyboard as Source Code). Delete the existing segue and then Ctrl-drag from a UIView/UIControl to the target view controller and if custom action is needed intercept the call to destination controller in <strong>prepareForSegue</strong>.</p>
<blockquote>
<p>Also to confirm that this solution works for you please do the
following:</p>
</blockquote>
<ul>
<li>Verify that your initial view controller (with the arrow on it) is a
UINavigationController and that it has a normal content view
controller as it's root view controller. (or that you embed your
initial view controller inside of a UINavigationController)</li>
<li>Read my extended comments on an earlier response to a very similar question (linked above).</li>
</ul> |
61,522,624 | How to create an optional field in a dataclass that is inherited? | <pre class="lang-py prettyprint-override"><code>from typing import Optional
@dataclass
class Event:
id: str
created_at: datetime
updated_at: Optional[datetime]
#updated_at: datetime = field(default_factory=datetime.now) CASE 1
#updated_at: Optional[datetime] = None CASE 2
@dataclass
class NamedEvent(Event):
name: str
</code></pre>
<p>When creating an event instance I will generally not have an <code>updated_at</code> field. I can either pass the <code>current time</code> as default value or add a value to it when making the insertion in the database and fetch it in subsequent uses of the object. Which is the better way?
As per my understanding, I cannot create a <code>NamedEvent</code> instance <em>without passing the updated_at</em> field in case1 and case2 since I do not have a default value in name field. </p> | 61,562,009 | 1 | 0 | null | 2020-04-30 11:44:48.137 UTC | 2 | 2022-07-24 02:49:28.38 UTC | null | null | null | null | 7,125,235 | null | 1 | 31 | python|python-3.x|python-dataclasses | 44,535 | <p>The underlying problem that you have seems to be the same one that is described <a href="https://stackoverflow.com/questions/51575931/class-inheritance-in-python-3-7-dataclasses/53085935#53085935">here</a>. The short version of that post is that in a function signature (including the dataclass-generated <code>__init__</code> method), obligatory arguments (like NamedEvent's <code>name</code>) can not follow after arguments with default values (which are necessary to define the behavior of Event's <code>updated_at</code>) - a child's fields will always follow after those of its parent.</p>
<p>So either you have no default values in your parent class (which doesn't work in this case) or all your child's fields need default values (which is annoying, and sometimes simply not feasible).</p>
<p>The post I linked above discusses some patterns that you can apply to solve your problem, but as a nicer alternative you can also use the third part party package <a href="https://pydantic-docs.helpmanual.io/usage/dataclasses/" rel="noreferrer"><code>pydantic</code></a> which already solved this problem for you. A sample implementation could look like this:</p>
<pre class="lang-py prettyprint-override"><code>import pydantic
from datetime import datetime
class Event(pydantic.BaseModel):
id: str
created_at: datetime = None
updated_at: datetime = None
@pydantic.validator('created_at', pre=True, always=True)
def default_created(cls, v):
return v or datetime.now()
@pydantic.validator('updated_at', pre=True, always=True)
def default_modified(cls, v, values):
return v or values['created_at']
class NamedEvent(Event):
name: str
</code></pre>
<p>The default-value specification through validators is a bit cumbersome, but overall it's a very useful package that fixes lots of the shortcomings that you run into when using dataclasses, plus some more.</p>
<p>Using the class definition, an instance of <code>NamedEvent</code> can be created like this:</p>
<pre class="lang-py prettyprint-override"><code>>>> NamedEvent(id='1', name='foo')
NamedEvent(id='1', created_at=datetime.datetime(2020, 5, 2, 18, 50, 12, 902732), updated_at=datetime.datetime(2020, 5, 2, 18, 50, 12, 902732), name='foo')
</code></pre> |
30,733,904 | Renaming a File() object in JavaScript | <p>I'd like for my users to be able to re-name a file before uploading it.</p>
<p>I have a <code>File</code> object in Javascript which has a <code>name</code> property that is already set, but i'd like for this to be able to be updated. Right now doing the obvious <code>myFile.name = "new-name.txt"</code> returns an error that this property is read only.</p>
<p>What's the best way of changing the <code>name</code> property on a JavaScript <code>File</code> object?</p> | 30,734,316 | 6 | 0 | null | 2015-06-09 13:46:55.153 UTC | 4 | 2021-11-18 16:08:09.473 UTC | null | null | null | null | 79,677 | null | 1 | 38 | javascript|file|rename|file-rename | 33,182 | <p>You can add an <code>input</code> tag with the name on it and hide the <code>name</code> property from the user. On the server, just use the <code>input</code> as the name and ignore the default name.</p> |
43,841,091 | Spark2.1.0 incompatible Jackson versions 2.7.6 | <p>I am trying to run a simple spark example in intellij, but I get the error like that:</p>
<pre><code>Exception in thread "main" java.lang.ExceptionInInitializerError
at org.apache.spark.SparkContext.withScope(SparkContext.scala:701)
at org.apache.spark.SparkContext.textFile(SparkContext.scala:819)
at spark.test$.main(test.scala:19)
at spark.test.main(test.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Incompatible Jackson version: 2.7.6
at com.fasterxml.jackson.module.scala.JacksonModule$class.setupModule(JacksonModule.scala:64)
at com.fasterxml.jackson.module.scala.DefaultScalaModule.setupModule(DefaultScalaModule.scala:19)
at com.fasterxml.jackson.databind.ObjectMapper.registerModule(ObjectMapper.java:730)
at org.apache.spark.rdd.RDDOperationScope$.<init>(RDDOperationScope.scala:82)
at org.apache.spark.rdd.RDDOperationScope$.<clinit>(RDDOperationScope.scala)
</code></pre>
<p>I have try to update my Jackson dependency, but it seems not work, I do this:</p>
<pre><code>libraryDependencies += "com.fasterxml.jackson.core" % "jackson-core" % "2.8.7"
libraryDependencies += "com.fasterxml.jackson.core" % "jackson-databind" % "2.8.7"
</code></pre>
<p>but it still appear the same error messages, can some one help me to fix the error?</p>
<p>Here is spark example code:</p>
<pre><code>object test {
def main(args: Array[String]): Unit = {
if (args.length < 1) {
System.err.println("Usage: <file>")
System.exit(1)
}
val conf = new SparkConf()
val sc = new SparkContext("local","wordcount",conf)
val line = sc.textFile(args(0))
line.flatMap(_.split(" ")).map((_, 1)).reduceByKey(_+_).collect().foreach(println)
sc.stop()
}
}
</code></pre>
<p>And here is my built.sbt:</p>
<pre><code>name := "testSpark2"
version := "1.0"
scalaVersion := "2.11.8"
libraryDependencies += "com.fasterxml.jackson.core" % "jackson-core" % "2.8.7"
libraryDependencies += "com.fasterxml.jackson.core" % "jackson-databind" % "2.8.7"
libraryDependencies += "org.apache.spark" % "spark-core_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-mllib_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-repl_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-streaming-flume_2.10" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-sql_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-network-shuffle_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-streaming-kafka-0-10_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-hive_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-streaming-flume-assembly_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-mesos_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-graphx_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-catalyst_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-launcher_2.11" % "2.1.0"
</code></pre> | 43,845,063 | 3 | 0 | null | 2017-05-08 06:27:47.367 UTC | 9 | 2020-05-18 05:20:47.557 UTC | 2017-05-08 06:34:19.85 UTC | null | 7,978,963 | null | 7,978,963 | null | 1 | 36 | scala|apache-spark|jackson|sbt|incompatibletypeerror | 25,760 | <p>Spark 2.1.0 contains <code>com.fasterxml.jackson.core</code> as transitive dependency. So, we do not need to include then in <code>libraryDependencies</code>. </p>
<p>But if you want to add a different <code>com.fasterxml.jackson.core</code> dependencies' version then you have to override them. Like this:</p>
<pre><code>name := "testSpark2"
version := "1.0"
scalaVersion := "2.11.8"
dependencyOverrides += "com.fasterxml.jackson.core" % "jackson-core" % "2.8.7"
dependencyOverrides += "com.fasterxml.jackson.core" % "jackson-databind" % "2.8.7"
dependencyOverrides += "com.fasterxml.jackson.module" % "jackson-module-scala_2.11" % "2.8.7"
libraryDependencies += "org.apache.spark" % "spark-core_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-mllib_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-repl_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-streaming-flume_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-sql_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-network-shuffle_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-streaming-kafka-0-10_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-hive_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-streaming-flume-assembly_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-mesos_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-graphx_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-catalyst_2.11" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-launcher_2.11" % "2.1.0"
</code></pre>
<p>So, change your <code>build.sbt</code> like the one above and it will work as expected.</p>
<p>I hope it helps!</p> |
880,937 | Vary by control properties using PartialCaching in ASP.NET | <p>I am using the PartialCaching attribute on the base class of a user control.</p>
<p>I would like the cached controls to vary based on the properties set on the control instance.</p>
<p>For example:</p>
<pre><code><mycontrols:control1 runat="server" param1="10" param2="20" />
</code></pre>
<p>...output would be cached separately from a control instance with different properties:</p>
<pre><code><mycontrols:control1 runat="server" param1="15" param2="20" />
</code></pre>
<p>...and this control would be cached separately as well:</p>
<pre><code><mycontrols:control1 runat="server" param1="10" param2="25" />
</code></pre>
<p>However, if two control instances on two separate pages had <strong>identical</strong> param1 and param2 properties, I'd like them to cache as one object (so that cached control would be shared).</p>
<p>Can the above use case be achieved with PartialCaching attribute? What settings would I use? varyByControl?</p>
<p>Also, is it possible to make the cache duration variable at runtime?</p>
<p>Thanks.</p> | 903,429 | 3 | 0 | null | 2009-05-19 04:10:59.683 UTC | 10 | 2014-09-12 19:35:59.19 UTC | null | null | null | null | 52,529 | null | 1 | 12 | asp.net|caching|outputcache | 10,198 | <p>To answer your first Q, let me first tell you that your question itself has the answer ;). 'Shared' ... yes that's the keyword :) To have a single instance in cache for the user control across all the pages, set Shared='true' in the @OutputCache directive. This should be set at the user control level i.e. in the ascx page.</p>
<p>To cache the user control based on user control properties, you should specify the fully qualified name of the properties in the varyByControls section of the PartialCachingAttribute. Multiple properties if any should be separated by semi-colons.</p>
<pre><code><%@ Control Language="C#" AutoEventWireup="true"
CodeFile="WebUserControl.ascx.cs"
Inherits="UC_WebUserControl" %>
<%@ OutputCache Duration="60"
VaryByControl="UC_WebUserControl.param1;UC_WebUserControl.param2"
VaryByParam="none" Shared="true" %>
</code></pre>
<p>or you can also include the PartialCache attribute for the user control:</p>
<pre><code>[PartialCaching(60, null, "UC_WebUserControl.param1;UC_WebUserControl.param2", null, true)]
public partial class UC_WebUserControl : System.Web.UI.UserControl
{
public string param1 { get; set; }
public string param2 { get; set; }
}
</code></pre>
<p>OR another way to cache the control on the combination of both values would be:</p>
<pre><code>[PartialCaching(60, null, "UC_WebUserControl.BothParams", null, true)]
public partial class UC_WebUserControl : System.Web.UI.UserControl
{
public string param1 { get; set; }
public string param2 { get; set; }
public string BothParams
{
get { return String.Concat(param1, param2); }
}
}
</code></pre>
<p>The last parameter (true) specifies shared. Duration is specified by 60. Refer to the link <a href="http://msdn.microsoft.com/en-us/library/z72yz1zs.aspx" rel="noreferrer">How to: Cache Multiple Versions of a User Control Based on Parameters</a></p>
<p>To answer your second Q, to make the cache duration for the user control variable at run time, you can do it in two ways:</p>
<ol>
<li><p>Assign it in the user control code behind:</p>
<pre><code>[PartialCaching(60, null, "UC_WebUserControl.BothParams", null, true)]
public partial class WebUserControl1 : System.Web.UI.UserControl
{
...
protected void Page_Load(object sender, EventArgs e)
{
this.CachePolicy.Duration = new TimeSpan(0, 0, 60);
}
}</code></pre></li>
<li><p>You can assign it in the code behind of the page where user control is referenced using the ID of the user control.</p></li>
</ol>
<p>e.g. If the user control on the aspx is:</p>
<pre><code><mycontrols:control1 ID="ucControl1" runat="server" param1="15" param2="20" />
</code></pre>
<p>then in the code behind of aspx, you should write:</p>
<pre><code>this.ucControl1.CachePolicy.Duration = new TimeSpan(0, 0, 60);
</code></pre>
<p>FYI, if both the user control and page are cached: If the page output cache duration is less than that of a user control, the user control will be cached until its duration has expired, even after the remainder of the page is regenerated for a request. For example, if page output caching is set to 50 seconds and the user control's output caching is set to 100 seconds, the user control expires once for every two times the rest of the page expires. </p> |
282,282 | How does StackOverflow's 'tags' textbox autocomplete work? | <p>I know they're using a jQuery plugin, but I can't seem to find which one they used. In particular, what I'm looking for is autocomplete with exactly the same functionality as SO's autocomplete, where it will perform an AJAX command with each new word typed in and allow you to select one from a dropdown.</p> | 282,328 | 3 | 3 | null | 2008-11-11 21:59:14.723 UTC | 17 | 2014-08-03 03:30:47.26 UTC | null | null | null | Erik | 16,942 | null | 1 | 38 | javascript|jquery|ajax|textbox|autocomplete | 7,569 | <p>Note that the tag editor <a href="https://meta.stackexchange.com/questions/100669/feedback-wanted-improved-tag-editor">has been completely re-written now</a>, and no longer resembles the original, simple text box w/ suggestion drop-down that adorned the site for nearly three years. </p>
<p>If you're interested in the new form, see this Meta question: <a href="https://meta.stackexchange.com/questions/102510/can-i-use-the-tag-textbox-script">https://meta.stackexchange.com/questions/102510/can-i-use-the-tag-textbox-script</a></p>
<p><a href="http://docs.jquery.com/UI/Autocomplete" rel="nofollow noreferrer">Autocomplete</a> is the plugin used originally, albeit with various tweaks and customizations made to it over the years.</p> |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
- Downloads last month
- 17