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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
27,948,018 | How to make an instance property only visible to subclass swift | <p>I'm trying to declare a instance property in swift so that it is only visible to it's class and subclasses. I believe this would be referred to as a protected property in other languages. Is there a way to achieve this in Swift?</p> | 27,948,532 | 2 | 0 | null | 2015-01-14 16:39:56.067 UTC | 3 | 2017-05-31 09:15:15.627 UTC | null | null | null | null | 2,471,333 | null | 1 | 50 | swift|access-control | 24,834 | <p>Access control along inheritance lines doesn't really fit with the design philosophies behind Swift and Cocoa:</p>
<blockquote>
<p>When designing access control levels in Swift, we considered two main use cases:</p>
<ul>
<li>keep <code>private</code> details of a class hidden from the rest of the app</li>
<li>keep <code>internal</code> details of a framework hidden from the client app</li>
</ul>
<p>These correspond to <code>private</code> and <code>internal</code> levels of access, respectively.</p>
<p>In contrast, <code>protected</code> conflates access with inheritance, adding an entirely new control axis to reason about. It doesn’t actually offer any real protection, since a subclass can always expose “protected” API through a new public method or property. It doesn’t offer additional optimization opportunities either, since new overrides can come from anywhere. And it’s unnecessarily restrictive — it allows subclasses, but not any of the subclass’s helpers, to access something.</p>
</blockquote>
<p>There's further explanation <a href="https://developer.apple.com/swift/blog/?id=11" rel="noreferrer">on Apple's Swift blog</a>.</p> |
40,592,662 | What happens to entrypoint of Docker parent image when child defines another one? | <p>Let's say I've got the Docker image <em>parent</em> built by this Dockerfile:</p>
<pre><code>FROM ubuntu
ENTRYPOINT ["parent-entry"]
</code></pre>
<p>Now I inherit from this <em>parent</em> image in my child image built with this code:</p>
<pre><code>FROM parent
ENTRYPOINT ["child-entry"]
</code></pre>
<p>As far as I have tested it the entrypoint of the child image overwrites the one in the parent image.</p>
<p>But since I am new to Docker I am not sure about this. My research also hasn't yet resulted in a satisfying answer. So is the assumption above correct?</p> | 40,592,965 | 1 | 2 | null | 2016-11-14 15:47:28.113 UTC | 6 | 2020-06-06 20:12:09.727 UTC | 2016-11-14 16:00:44.89 UTC | null | 3,067,148 | null | 3,067,148 | null | 1 | 60 | inheritance|docker|entry-point | 14,916 | <p>The last entrypoint is used, only the last one. </p>
<p>You can check, put several lines with different <code>ENTRYPOINT</code> in your <code>Dockerfile</code>, and check what happens.</p> |
2,520,632 | How do I jump to a breakpoint within GDB? | <p>I set a breakpoint, which worked fine.</p>
<p>Is there a way to jump immediately to that breakpoint without using "next" or "step"?</p>
<p>Using "next" or "step", it takes really long to get to the final breakpoint.</p> | 2,520,690 | 1 | 0 | null | 2010-03-26 01:31:14.037 UTC | 7 | 2019-08-13 03:16:03.13 UTC | 2019-08-13 03:15:26.973 UTC | null | 63,550 | null | 300,656 | null | 1 | 35 | debugging|console|gdb | 50,085 | <p>Just press <strong>c</strong>. It will continue execution until the next breakpoint.</p>
<p>You can also disable intermediate breakpoints by using <code>disable #breakpointnumber</code> as stated <a href="http://www.unknownroad.com/rtfm/gdbtut/gdbbreak.html#DISABLE" rel="noreferrer">here</a>.</p> |
47,880,625 | POWERBI - Object reference not set to an instance of an object | <p>I'm trying to connect oracle database using prowerbi desktop. Throwing following error</p>
<p>Details: "An error happened while reading data from the provider: 'Object reference not set to an instance of an object.'"</p>
<p>Any idea why i see this error? I have searched it before posting here and found no clue.</p> | 48,106,826 | 4 | 0 | null | 2017-12-19 05:40:01.897 UTC | 1 | 2022-05-25 21:50:34.213 UTC | null | null | null | null | 1,544,977 | null | 1 | 8 | powerbi|powerbi-datasource | 38,719 | <p>Solved - The issue is because of the versions of Oracle client and Power BI desktop. </p>
<p>Oracle client was 32 bit and Powerbi was 64 bit, after updating oracle client to 64 bit everything works great.</p> |
31,568,453 | Using different font styles in annotate (ggplot2) | <p>I'm using the code below to generate a simple chart with some annotations:</p>
<pre><code>require(ggplot2); data(mtcars)
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
annotate("text", x = 4, y = 25, label = "This should be bold\nand this not",
colour = "red") +
geom_vline(xintercept = 3.2, colour = "red")
</code></pre>
<p><a href="https://i.stack.imgur.com/EW7AJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/EW7AJ.png" alt="Simple plot"></a></p>
<p>On that chart I would like to apply <strong>bold font</strong> to the first part of the phrase in the text annotation:</p>
<blockquote>
<p>This should be bold</p>
</blockquote>
<p>but the I wish for the remaining part of the text to remain unaltered with respect to the font face and style.</p> | 31,569,390 | 3 | 1 | null | 2015-07-22 16:08:20.7 UTC | 12 | 2022-01-15 08:42:19.243 UTC | null | null | null | null | 1,655,567 | null | 1 | 38 | r|text|charts|ggplot2|annotations | 56,065 | <p>How about using <strong>plotmath</strong> syntax with <code>parse = TRUE</code>:</p>
<pre><code>ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
annotate("text", x = 4, y = 25,
label = 'atop(bold("This should be bold"),"this should not")',
colour = "red", parse = TRUE) +
geom_vline(xintercept = 3.2, colour = "red")
</code></pre>
<p><a href="https://i.stack.imgur.com/yOSCY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yOSCY.png" alt="enter image description here"></a></p> |
5,764,893 | Node.js Parsing A Number Inside a String | <p>Given a string like:</p>
<pre><code>Recipient: [email protected]
Action: failed
Status: 5.0.0 (permanent failure)
Diagnostic: No
</code></pre>
<p>How do I get the "5.0.0" and "permanent failure" only if it's always after Status: ? ?</p>
<p>Thanks</p> | 5,765,301 | 1 | 0 | null | 2011-04-23 14:56:18.377 UTC | 3 | 2017-07-16 09:14:04.553 UTC | null | null | null | null | 435,951 | null | 1 | 15 | regex|node.js|serverside-javascript | 48,498 | <pre><code>var regex = /Status: ([0-9\.]+) \(([a-zA-Z ]+)\)/
var result = string.match(regex);
var statusNumber = result[1];
var statusString = result[2];
</code></pre>
<p>You should extend these: [0-9\.], [a-zA-Z ] selectors if you expect other characters in these values. For now the first one expects numbers and dots, the second characters and spaces</p> |
35,528,409 | Write a large Inputstream to File in Kotlin | <p>I have a large stream of text coming back from REST web service and I would like to write it directly to file. What is the simplest way of doing this?</p>
<p>I have written the following function extension that WORKS. But I can't help thinking that there is a cleaner way of doing this.</p>
<p><strong>Note</strong>: I was hoping to use try with resources to auto close the stream and file</p>
<pre><code>fun File.copyInputStreamToFile(inputStream: InputStream) {
val buffer = ByteArray(1024)
inputStream.use { input ->
this.outputStream().use { fileOut ->
while (true) {
val length = input.read(buffer)
if (length <= 0)
break
fileOut.write(buffer, 0, length)
}
fileOut.flush()
}
}
}
</code></pre> | 35,529,070 | 5 | 0 | null | 2016-02-20 20:09:36.887 UTC | 6 | 2020-08-25 21:41:33.97 UTC | 2017-08-04 18:31:03.933 UTC | null | 2,949,612 | null | 1,347,005 | null | 1 | 42 | kotlin | 31,515 | <p>You can simplify your function by using the <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-input-stream/copy-to.html" rel="noreferrer">copyTo function</a>:</p>
<pre><code>fun File.copyInputStreamToFile(inputStream: InputStream) {
this.outputStream().use { fileOut ->
inputStream.copyTo(fileOut)
}
}
</code></pre> |
28,414,234 | Where can I find the example applicationContext.xml file | <p>With Spring 3 distribution there was a project folder which was packaged in the distribution . This project folder had sample <code>applicationContext.xml</code> file which can be used . However when I have downloaded Spring 4 distribution from <a href="http://maven.springframework.org/release/org/springframework/spring/4.1.4.RELEASE/" rel="noreferrer">here</a> it does not come with a project folder and I am not able to find the sample <code>applicationContext.xml</code>. Where can I find the example <code>applicationContext.xml</code> file.</p> | 28,418,012 | 1 | 0 | null | 2015-02-09 16:16:15.76 UTC | 4 | 2017-02-11 12:15:46.83 UTC | 2017-02-11 12:15:46.83 UTC | null | 1,577,363 | null | 1,573,271 | null | 1 | 15 | xml|spring|spring-mvc|applicationcontext | 74,093 | <p>You can use this for further information check <a href="http://crunchify.com/simplest-spring-mvc-hello-world-example-tutorial-spring-model-view-controller-tips/" rel="noreferrer">here</a>. </p>
<p>Below sample contains configuration as follows:</p>
<ul>
<li>component-scan base com.foo which thinking as your root folder.</li>
<li>Basic dataSource definition.</li>
<li>Property place holder file(database.properties)</li>
<li>Message Source for localization support.</li>
</ul>
<p><strong>sample ApplicationContext.xml</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:c="http://www.springframework.org/schema/c"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:property-placeholder location="classpath:/database.properties" />
<context:component-scan base-package="com.foo" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
</beans>
</code></pre> |
55,198,988 | Get the current active screen route of the tab navigator in react navigation | <p>This is my navigation stack using react navigation <em>v3.2.1</em>:</p>
<ol>
<li><p>I have a switch navigator to switch to Authentication navigation stack and Authenticated App stack.</p></li>
<li><p>The App stack is made using a bottom tab navigator.</p></li>
<li><p>I would like to use a custom component for the tab navigator.</p></li>
</ol>
<p>How do I get the current routeName of the tab navigator when using <code>createBottomTabNavigator</code> and a custom <code>tabBarComponent</code>.</p>
<p>Eg:</p>
<ol>
<li>Suppose the tab navigation stack has 2 navigation screens, i.e., Home and Chat.</li>
<li>Inside the custom BottomBar, how do I check if the focused/active/current routeName is Home/Chat so that I can change the style of icons respectively?</li>
</ol>
<p>AppContainer.js</p>
<pre><code>const switchStack = createSwitchNavigator({
AuthLoading: AuthLoadingScreen,
App: AppStack,
Auth: AuthStack
}, {
initialRouteName: 'AuthLoading',
})
export default createAppContainer(switchStack)
</code></pre>
<p>AppStack.js</p>
<pre><code>const AppStack = createBottomTabNavigator({
Home: {
screen: HomeStack,
},
Chat: {
screen: ChatStack
},
}, {
initialRouteName: 'Home',
activeColor: '#f0edf6',
inactiveColor: '#3e2465',
shifting: false,
barStyle: {
backgroundColor: '#694fad',
},
labeled: false,
tabBarComponent: ({navigation}) => <BottomBar navigation={navigation}/>
})
export default AppStack
</code></pre>
<p>BottomBar.js</p>
<pre><code>export default class BottomBar extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<View style={styles.container}>
<IconComponent routeName={'Home'}/>
<IconComponent routeName={'Chat'}/>
</View>
)
}
}
</code></pre>
<p>IconComponent.js</p>
<pre><code>export default class IconComponent extends React.Component {
constructor(props) {
super(props)
}
...
render() {
let IconComponent
let iconName
let iconSize = 25
switch (this.props.routeName) {
case 'Home':
IconComponent = MaterialCommunityIcons
// iconName = `home${focused ? '' : '-outline'}`;
iconName = `home`;
break
case 'Chat':
IconComponent = AntDesign
iconName = `message1`
iconSize = 22
break
}
let tintColor = 'green'
// if focused Home is current tab screen then change style eg. tint color.
// similary if current tab screen is Chat, then change style.
return (
<Animated.View
style={[
styles.container,
{
opacity: this.opacity
}
]}
>
<IconComponent name={iconName} size={iconSize} color={tintColor}/>
</Animated.View>
)
}
}
</code></pre> | 55,199,346 | 5 | 0 | null | 2019-03-16 16:29:35.057 UTC | 1 | 2022-04-22 05:21:47.14 UTC | null | null | null | null | 2,018,197 | null | 1 | 11 | reactjs|react-native|react-navigation | 39,286 | <p>navigation object of your custom BottomBar has an index that hold the current active screen index</p>
<pre><code>tabBarComponent: ({navigation}) => <BottomBar navigation={navigation}/>
navigation.state.index
</code></pre>
<p>If Home screen is active >> navigation.state.index would be 0
If Chat screen is active >> navigation.state.index would be 1 ...etc</p> |
2,387,033 | Android table with round border | <p>How can I make a table with a round border, similar to the photo below, in Android?</p>
<p><img src="https://i.stack.imgur.com/iDwyy.png" alt="Round-bordered table"></p> | 2,387,746 | 3 | 0 | null | 2010-03-05 13:33:32.37 UTC | 16 | 2012-05-29 22:55:57.757 UTC | 2012-05-29 22:55:57.757 UTC | null | 85,950 | null | 258,863 | null | 1 | 26 | android|tablelayout | 26,813 | <p>I think Androidbase linked to the wrong question... he asked a similar question recently, and here's the <a href="https://stackoverflow.com/questions/2379578/how-to-show-group-tableview-android/2381894#2381894">answer</a> I gave him:</p>
<p>You can put a coloured background with rounded corners into a table by using a Shape background. Create such a shape in an XML file, put in your drawables folder.</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#99FFFFFF"/>
<corners android:radius="30px"/>
<padding android:left="0dp" android:top="0dp" android:right="0dp" android:bottom="0dp" />
</shape>
</code></pre>
<p>For example the above creates a semi-transparent white background with 30px rounded corners. You set this to the table by using</p>
<pre><code>android:background="@drawable/my_shape_file"
</code></pre>
<p>in the XML file where you defined your table layout.</p> |
51,317,534 | how to reverse the URL of a ViewSet's custom action in django restframework | <p>I have defined a custom action for a ViewSet</p>
<pre><code>from rest_framework import viewsets
class UserViewSet(viewsets.ModelViewSet):
@action(methods=['get'], detail=False, permission_classes=[permissions.AllowAny])
def gender(self, request):
....
</code></pre>
<p>And the viewset is registered to url in the conventional way</p>
<pre><code>from django.conf.urls import url, include
from rest_framework import routers
from api import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet, base_name='myuser')
urlpatterns = [
url(r'^', include(router.urls)),
]
</code></pre>
<p>The URL <code>/api/users/gender/</code> works. But I don't know how to get it using <code>reverse</code> in unit test. (I can surely hard code this URL, but it'll be nice to get it from code) </p>
<p>According to the <a href="https://docs.djangoproject.com/en/1.11/ref/urlresolvers/#reverse" rel="noreferrer">django documentation</a>, the following code should work</p>
<pre><code>reverse('admin:app_list', kwargs={'app_label': 'auth'})
# '/admin/auth/'
</code></pre>
<p>But I tried the following and they don't work</p>
<pre><code>reverse('myuser-list', kwargs={'app_label':'gender'})
# errors out
reverse('myuser-list', args=('gender',))
# '/api/users.gender'
</code></pre>
<p>In the <a href="http://www.django-rest-framework.org/api-guide/viewsets/#reversing-action-urls" rel="noreferrer">django-restframework documentation</a>, there is a function called <code>reverse_action</code>. However, my attempts didn't work</p>
<pre><code>from api.views import UserViewSet
a = UserViewSet()
a.reverse_action('gender') # error out
from django.http import HttpRequest
req = HttpRequest()
req.method = 'GET'
a.reverse_action('gender', request=req) # still error out
</code></pre>
<p>What is the proper way to reverse the URL of that action?</p> | 51,317,608 | 5 | 0 | null | 2018-07-13 04:11:29.98 UTC | 3 | 2022-09-22 20:49:35.22 UTC | null | null | null | null | 534,298 | null | 1 | 48 | python|django|url|django-rest-framework | 23,800 | <p>You can use <code>reverse</code> just add to viewset's basename action:</p>
<pre><code>reverse('myuser-gender')
</code></pre>
<p>See <a href="http://www.django-rest-framework.org/api-guide/routers/#routing-for-extra-actions" rel="noreferrer">related part</a> of docs.</p> |
38,237,907 | How can I find my shell version using a Linux command? | <p>I would like to know about my shell version using a Linux command. I tried the following command, but it shows the type of the shell I am in.</p>
<p>Command:</p>
<pre><code>echo $SHELL
</code></pre>
<p>Result:</p>
<pre><code>/bin/bash
</code></pre> | 38,237,949 | 4 | 1 | null | 2016-07-07 05:10:34.427 UTC | 10 | 2020-12-22 11:54:53.327 UTC | 2019-12-14 17:50:46.583 UTC | null | 63,550 | null | 6,531,580 | null | 1 | 54 | linux|shell | 94,251 | <p>This will do it:</p>
<pre><code>$SHELL --version
</code></pre>
<p>In my case, the output is:</p>
<pre><code>zsh 5.0.2 (x86_64-pc-linux-gnu)
</code></pre> |
897,792 | Where is Python's sys.path initialized from? | <p>Where is Python's sys.path initialized from?</p>
<p><strong>UPD</strong>: Python is adding some paths before refering to PYTHONPATH:</p>
<pre><code> >>> import sys
>>> from pprint import pprint as p
>>> p(sys.path)
['',
'C:\\Python25\\lib\\site-packages\\setuptools-0.6c9-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\orbited-0.7.8-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\morbid-0.8.6.1-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\demjson-1.4-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\stomper-0.2.2-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\uuid-1.30-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\stompservice-0.1.0-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\cherrypy-3.0.1-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\pyorbited-0.2.2-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\flup-1.0.1-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\wsgilog-0.1-py2.5.egg',
'c:\\testdir',
'C:\\Windows\\system32\\python25.zip',
'C:\\Python25\\DLLs',
'C:\\Python25\\lib',
'C:\\Python25\\lib\\plat-win',
'C:\\Python25\\lib\\lib-tk',
'C:\\Python25',
'C:\\Python25\\lib\\site-packages',
'C:\\Python25\\lib\\site-packages\\PIL',
'C:\\Python25\\lib\\site-packages\\win32',
'C:\\Python25\\lib\\site-packages\\win32\\lib',
'C:\\Python25\\lib\\site-packages\\Pythonwin']
</code></pre>
<p>My PYTHONPATH is:</p>
<pre><code> PYTHONPATH=c:\testdir
</code></pre>
<p>I wonder where those paths before PYTHONPATH's ones come from?</p> | 897,810 | 2 | 0 | null | 2009-05-22 13:19:05.867 UTC | 55 | 2018-11-29 19:54:45.94 UTC | 2016-10-30 09:11:51.503 UTC | null | 3,743,216 | null | 85,185 | null | 1 | 128 | python|path|sys | 165,901 | <p>"Initialized from the environment variable PYTHONPATH, plus an installation-dependent default"</p>
<p>-- <a href="http://docs.python.org/library/sys.html#sys.path" rel="noreferrer">http://docs.python.org/library/sys.html#sys.path</a></p> |
2,442,407 | Android Color Picker | <p>Does anyone know of a quick color picker widget that I could grab to use in my application? </p>
<p>I've seen one in a few different applications that have a wheel with colors, and that you tap in the center to select, but I'm not sure where to find it. </p>
<p>Any color picker would be fine though.</p> | 2,442,743 | 5 | 0 | null | 2010-03-14 14:07:32.703 UTC | 26 | 2017-07-05 21:16:15.97 UTC | 2015-08-17 07:26:47.96 UTC | null | 165,071 | null | 118,241 | null | 1 | 60 | java|android|colors | 87,908 | <p>The wheel color picker that you are talking about is in the API Demos.</p>
<p><a href="https://android.googlesource.com/platform/development/+/master/samples/ApiDemos/src/com/example/android/apis/graphics/ColorPickerDialog.java" rel="nofollow noreferrer">https://android.googlesource.com/platform/development/+/master/samples/ApiDemos/src/com/example/android/apis/graphics/ColorPickerDialog.java</a></p> |
2,354,716 | Convert lowercase letter to upper case in javascript | <p>I have a <a href="http://www.liewcf.com/archives/2004/04/javascript-convert-characters-to-uppercase-when-typing/" rel="noreferrer">code</a> that will convert lower case letters to uppercase but it works only with IE and not in Crome or Firefox.</p>
<pre><code>function ChangeToUpper()
{
key = window.event.which || window.event.keyCode;
if ((key > 0x60) && (key < 0x7B))
window.event.keyCode = key-0x20;
}
<asp:TextBox ID="txtJobId" runat="server" MaxLength="10" onKeypress="ChangeToUpper();"></asp:TextBox>
</code></pre>
<p>Even I tried with </p>
<pre><code>document.getElementById("txtJobId").value=document.getElementById("txtJobId").value.toUpperCase();
</code></pre>
<p><strong>onBlur event of the textbox</strong></p>
<p>What should I do to make it work in all browsers?</p>
<p>Thanks</p> | 2,354,770 | 6 | 0 | null | 2010-03-01 09:04:35.083 UTC | 3 | 2015-11-25 13:51:41.657 UTC | 2010-03-01 09:10:10.19 UTC | null | 246,935 | null | 246,935 | null | 1 | 21 | javascript | 59,868 | <pre><code><script type="text/javascript">
function ChangeCase(elem)
{
elem.value = elem.value.toUpperCase();
}
</script>
<input onblur="ChangeCase(this);" type="text" id="txt1" />
</code></pre>
<p>separate javascript from your HTML</p>
<pre><code>window.onload = function(){
var textBx = document.getElementById ( "txt1" );
textBx.onblur = function() {
this.value = this.value.toUpperCase();
};
};
<asp:TextBox ID="txt1" runat="server"></asp:TextBox>
</code></pre>
<p>If the textbox is inside a naming container then use something like this</p>
<pre><code>var textBx = document.getElementById ("<%= txt1.ClientID %>");
textBx.onblur = function() {
this.value = this.value.toUpperCase();
};)
</code></pre> |
2,678,180 | How does Dropbox use Python on Windows and OS X? | <p>In Windows the Dropbox client uses python25.dll and the MS C runtime libraries (msvcp71.dll, etc). On OS X the Python code is compiled bytecode (pyc).</p>
<p>My guess is they are using a common library they have written then just have to use different hooks for the different platforms.</p>
<p>What method of development is this? It clearly isn't IronPython or PyObjC. This paradigm is so appealing to me, but my CS foo and Google foo are failing me.</p> | 2,679,695 | 6 | 0 | null | 2010-04-20 19:53:53.45 UTC | 29 | 2014-08-24 03:36:07.84 UTC | null | null | null | null | 110,210 | null | 1 | 40 | python|windows|macos|dropbox | 18,093 | <p>Dropbox uses a combination of wxPython and PyObjC on the Mac (less wxPython in the 0.8 series). It looks like they've built a bit of a UI abstraction layer but nothing overwhelming—i.e., they're doing their cross-platform app the right way.</p>
<p>They include their own Python mainly because the versions of Python included on the Mac vary by OS version (and Dropbox supports back to 10.4 IIRC); also, they've customized the Python interpreter a bit to improve threading and I/O behavior.</p>
<p>(I do not work for Dropbox or have any inside knowledge; all I did was read their forums and examine the filenames in <code>site-packages.zip</code> in the Dropbox app bundle.)</p> |
2,597,142 | When was the NULL macro not 0? | <p>I vaguely remember reading about this a couple of years ago, but I can't find any reference on the net.</p>
<p>Can you give me an example where the NULL macro didn't expand to 0?</p>
<p>Edit for clarity: Today it expands to either <code>((void *)0)</code>, <code>(0)</code>, or <code>(0L)</code>. However, there were architectures long forgotten where this wasn't true, and NULL expanded to a different address. Something like</p>
<pre><code>#ifdef UNIVAC
#define NULL (0xffff)
#endif
</code></pre>
<p>I'm looking for an example of such a machine.</p>
<p><strong>Update to address the issues:</strong> </p>
<p>I didn't mean this question in the context of current standards, or to upset people with my incorrect terminology. However, my assumptions were confirmed by the accepted answer:</p>
<blockquote>Later models used [blah], evidently as a sop to all the extant poorly-written C code which made incorrect assumptions.</blockquote>
<p>For a discussion about null pointers in the current standard, see <a href="https://stackoverflow.com/questions/2599207/can-a-conforming-c-implementation-define-null-to-be-something-wacky">this question</a>.</p> | 2,597,232 | 7 | 3 | null | 2010-04-08 02:14:58.787 UTC | 10 | 2019-07-18 05:16:35.5 UTC | 2017-05-23 12:13:51.79 UTC | null | -1 | null | 127,007 | null | 1 | 40 | c|null|macros|history | 12,921 | <p>The C FAQ has some examples of historical machines with non-0 NULL representations.</p>
<p>From <a href="http://c-faq.com/" rel="noreferrer">The C FAQ List</a>, <a href="http://c-faq.com/null/machexamp.html" rel="noreferrer">question 5.17</a>:</p>
<blockquote>
<p>Q: Seriously, have any actual machines really used nonzero null
pointers, or different representations for pointers to different
types?</p>
<p>A: The Prime 50 series used segment 07777, offset 0 for the null
pointer, at least for PL/I. Later models used segment 0, offset 0 for
null pointers in C, necessitating new instructions such as TCNP (Test
C Null Pointer), evidently as a sop to [footnote] all the extant
poorly-written C code which made incorrect assumptions. Older,
word-addressed Prime machines were also notorious for requiring larger
byte pointers (<code>char *</code>'s) than word pointers (<code>int *</code>'s).</p>
<p>The Eclipse MV series from Data General has three architecturally
supported pointer formats (word, byte, and bit pointers), two of which
are used by C compilers: byte pointers for <code>char *</code> and <code>void *</code>, and word
pointers for everything else. For historical reasons during the
evolution of the 32-bit MV line from the 16-bit Nova line, word
pointers and byte pointers had the offset, indirection, and ring
protection bits in different places in the word. Passing a mismatched
pointer format to a function resulted in protection faults.
Eventually, the MV C compiler added many compatibility options to try
to deal with code that had pointer type mismatch errors.</p>
<p>Some Honeywell-Bull mainframes use the bit pattern 06000 for
(internal) null pointers.</p>
<p>The CDC Cyber 180 Series has 48-bit pointers consisting of a ring,
segment, and offset. Most users (in ring 11) have null pointers of
0xB00000000000. It was common on old CDC ones-complement machines to
use an all-one-bits word as a special flag for all kinds of data,
including invalid addresses.</p>
<p>The old HP 3000 series uses a different addressing scheme for byte
addresses than for word addresses; like several of the machines above
it therefore uses different representations for <code>char *</code> and <code>void *</code>
pointers than for other pointers.</p>
<p>The Symbolics Lisp Machine, a tagged architecture, does not even have
conventional numeric pointers; it uses the pair <code><NIL, 0></code> (basically a
nonexistent <code><object, offset></code> handle) as a C null pointer.</p>
<p>Depending on the "memory model" in use, 8086-family processors (PC
compatibles) may use 16-bit data pointers and 32-bit function
pointers, or vice versa.</p>
<p>Some 64-bit Cray machines represent <code>int *</code> in the lower 48 bits of a
word; <code>char *</code> additionally uses some of the upper 16 bits to indicate a
byte address within a word.</p>
</blockquote> |
2,890,347 | Are there any purely functional Schemes or Lisps? | <p>I've played around with a few functional programming languages and really enjoy the s-expr syntax used by Lisps (Scheme in particular).</p>
<p>I also see the advantages of working in a purely functional language. Therefore:</p>
<p><strong>Are there any purely functional Schemes (or Lisps in general)?</strong></p> | 2,890,401 | 9 | 0 | null | 2010-05-23 01:01:53.653 UTC | 11 | 2012-11-10 15:38:22.897 UTC | 2011-04-16 20:35:26.567 UTC | null | 83,805 | null | 338,513 | null | 1 | 39 | haskell|functional-programming|scheme|referential-transparency | 10,004 | <p>Probably not, at least not as anything other than toys/proofs of concept. Note that even Haskell isn't 100% purely functional--it has secret escape hatches, and anything in <code>IO</code> is <a href="http://conal.net/blog/posts/is-haskell-a-purely-functional-language/" rel="noreferrer">only "pure" in some torturous, hand-waving sense of the word</a>.</p>
<p>So, that said, do you <em>really</em> need a purely functional language? You can write purely functional <em>code</em> in almost any language, with varying degrees of inconvenience and inefficiency.</p>
<p>Of course, languages that assume universal state-modification make it painful to keep things pure, so perhaps what you really want is a language that encourages immutability? In that case, you might find it worthwhile to take a look at <a href="http://clojure.org/rationale" rel="noreferrer">Clojure</a>'s philosophy. And it's a Lisp, to boot!</p>
<p>As a final note, do realize that most of Haskell's "syntax" is thick layers of sugar. The underlying language is not much more than a typed lambda calculus, and nothing stops you from writing all your code that way. You may get funny looks from other Haskell programmers, though. There's also <a href="http://lambda-the-ultimate.org/node/2363" rel="noreferrer">Liskell</a> but I'm not sure what state it's in these days.</p>
<p>On a final, practical note: If you want to actually write code you intend to use, not just tinker with stuff for fun, you'll <em>really</em> want a clever compiler that knows how to work with pure code/immutable data structures.</p> |
2,893,970 | Fail to launch application (CreateProcess error=87), can't use shorten classpath workaround | <p>When I launch our application in Eclipse on Windows I receive the following error:</p>
<blockquote>
<p>Exception occured executing command line.</p>
<p>Cannot run program .. : CreateProcess error=87, The parameter is incorrect</p>
</blockquote>
<p>I've solved this in the past by shortening the CLASSPATH.</p>
<p>I've now come to a point where I can no longer shorten the CLASSPATH, and would like to know if there are any other workarounds.</p>
<p><a href="http://support.microsoft.com/kb/830473" rel="noreferrer">http://support.microsoft.com/kb/830473</a> seems to indicate that the max command prompt line length in windows xp is 8191 characters, and the only solution is to shorten folder names, reduce depth of folder trees, using parameter files, etc.</p> | 2,894,135 | 10 | 1 | null | 2010-05-23 23:35:23.94 UTC | 11 | 2014-03-11 14:45:03.87 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 10,814 | null | 1 | 29 | eclipse|windows-xp | 60,650 | <p>This <a href="http://eclipsecoding.wikidot.com/faq#launchError" rel="nofollow noreferrer">eclipsecoding FAQ page</a> does confirm your diagnostic:</p>
<blockquote>
<p>When the <code>CLASSPATH</code> gets too long, the program cannot be launched (at least under Windows) - try to shorten your classpath. In the case of a plugin, you can try to remove unnecessary required plugins.</p>
</blockquote>
<p>And you have <a href="http://www.eclipse.org/forums/index.php?t=rview&goto=494195&th=156565" rel="nofollow noreferrer">here a thread</a> detailing the log errors.</p>
<p>Since you can launch Eclipse, but not the application, I would check if you don't have too many plugins included in your launch configuration. Could you check if you have <a href="https://stackoverflow.com/questions/2858932/eclipse-rcp-standalone-export-problem-with-groovy-scripts/2859358#2859358">added only the required plugins</a>?</p> |
10,611,374 | Clickable Bars in js Highcharts? | <p>I have <strong>horizontal</strong> bar chart with <a href="http://www.highcharts.com/"><em>Highcharts</em></a>. How can I <strong>make each bar clickable</strong> for an event, for example like 'alert' ?</p>
<p>I have this series for example:</p>
<pre><code>series : [{
name: 'John',
data: [5, 3, 4, 7, 2]
}, {
name: 'Jane',
data: [2, 2, 3, 2, 1]
}, {
name: 'Joe',
data: [3, 4, 4, 2, 5]
}];
</code></pre>
<p>What more should I do?</p> | 10,611,546 | 3 | 0 | null | 2012-05-16 02:48:19.313 UTC | 6 | 2020-10-13 08:51:02.453 UTC | 2015-06-29 20:21:54.237 UTC | null | 2,729,534 | null | 775,856 | null | 1 | 21 | javascript|jquery|click|highcharts | 44,736 | <p>You might find the <a href="http://api.highcharts.com/highcharts#plotOptions.series.point.events.click">Highcharts Options Reference</a> a good starting point. </p>
<p>From the reference, here's an example of a column chart
where clicking a column fires an alert. </p>
<p><a href="http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/plotoptions/series-point-events-click-column/">http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/plotoptions/series-point-events-click-column/</a></p> |
10,782,403 | show source code for function in R | <p>I can use <code>lm</code> or <code>class::knn</code> to view the source code, but I failed to show the code for princomp. Was this function(or something else) written in R or some other bytecode used.
I also could not find the source code using advises from <a href="https://stackoverflow.com/questions/5937832/r-show-source-code-of-an-s4-function-in-a-package">How do I show the source code of an S4 function in a package?</a>. Thanks for any help.</p>
<pre><code>> princomp
function (x, ...)
UseMethod("princomp")
<bytecode: 0x9490010>
<environment: namespace:stats>
</code></pre> | 10,784,367 | 2 | 0 | null | 2012-05-28 09:37:00.107 UTC | 18 | 2014-05-28 15:30:57.607 UTC | 2017-05-23 11:54:56.807 UTC | null | -1 | null | 325,224 | null | 1 | 21 | r|open-source|statistics|machine-learning | 56,171 | <p>You have to ask using the corresponding method used by the function. Try this:</p>
<pre><code>princomp # this is what you did without having a good enough answer
methods(princomp) # Next step, ask for the method: 'princomp.default'
getAnywhere('princomp.default') # this will show you the code
</code></pre>
<p>The code you are looking for is:</p>
<pre><code>function (x, cor = FALSE, scores = TRUE, covmat = NULL, subset = rep(TRUE,
nrow(as.matrix(x))), ...)
{
cl <- match.call()
cl[[1L]] <- as.name("princomp")
if (!missing(x) && !missing(covmat))
warning("both 'x' and 'covmat' were supplied: 'x' will be ignored")
z <- if (!missing(x))
as.matrix(x)[subset, , drop = FALSE]
if (is.list(covmat)) {
if (any(is.na(match(c("cov", "n.obs"), names(covmat)))))
stop("'covmat' is not a valid covariance list")
cv <- covmat$cov
n.obs <- covmat$n.obs
cen <- covmat$center
}
else if (is.matrix(covmat)) {
cv <- covmat
n.obs <- NA
cen <- NULL
}
else if (is.null(covmat)) {
dn <- dim(z)
if (dn[1L] < dn[2L])
stop("'princomp' can only be used with more units than variables")
covmat <- cov.wt(z)
n.obs <- covmat$n.obs
cv <- covmat$cov * (1 - 1/n.obs)
cen <- covmat$center
}
else stop("'covmat' is of unknown type")
if (!is.numeric(cv))
stop("PCA applies only to numerical variables")
if (cor) {
sds <- sqrt(diag(cv))
if (any(sds == 0))
stop("cannot use cor=TRUE with a constant variable")
cv <- cv/(sds %o% sds)
}
edc <- eigen(cv, symmetric = TRUE)
ev <- edc$values
if (any(neg <- ev < 0)) {
if (any(ev[neg] < -9 * .Machine$double.eps * ev[1L]))
stop("covariance matrix is not non-negative definite")
else ev[neg] <- 0
}
cn <- paste("Comp.", 1L:ncol(cv), sep = "")
names(ev) <- cn
dimnames(edc$vectors) <- if (missing(x))
list(dimnames(cv)[[2L]], cn)
else list(dimnames(x)[[2L]], cn)
sdev <- sqrt(ev)
sc <- if (cor)
sds
else rep(1, ncol(cv))
names(sc) <- colnames(cv)
scr <- if (scores && !missing(x) && !is.null(cen))
scale(z, center = cen, scale = sc) %*% edc$vectors
if (is.null(cen))
cen <- rep(NA_real_, nrow(cv))
edc <- list(sdev = sdev, loadings = structure(edc$vectors,
class = "loadings"), center = cen, scale = sc, n.obs = n.obs,
scores = scr, call = cl)
class(edc) <- "princomp"
edc
}
<environment: namespace:stats>
</code></pre>
<p>I think this what you were asking for. </p> |
10,773,322 | Event when YouTube video finished | <p>I have simple html code that plays YouTube video after click on the image:</p>
<pre><code><body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="ytapiplayer2" style="display:none;">
<object width="1280" height="745">
<param name="movie" value="http://www.youtube.com/v/kCfP003Btjw?fs=1&hl=en_US&rel=0&autoplay=1"></param>
<param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>
<embed src="http://www.youtube.com/v/kCfP003Btjw?fs=1&hl=en_US&rel=0&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="1280" height="745"></embed>
</object>
</div>
<img src="https://i.qmyimage.com/mgen/global/zGetImageNew.ms?args=%22shpimg4198.jpg%22,425,96,1" id="imageID" />
<script type="text/javascript">
$('#imageID').click(function() {
$('#ytapiplayer2').show();
$('#imageID').hide();
});
</script>
</body>
</code></pre>
<p>I need hide the video and show image back, after video finished play. How is it possible to implement?</p> | 10,773,341 | 1 | 0 | null | 2012-05-27 10:39:59.83 UTC | 8 | 2020-12-24 17:41:19.63 UTC | 2020-12-24 17:41:19.63 UTC | null | 4,370,109 | null | 206,330 | null | 1 | 26 | javascript|youtube|youtube-api|dom-events | 61,209 | <p>Youtube has a JavaScript API: <a href="https://developers.google.com/youtube/js_api_reference" rel="noreferrer">https://developers.google.com/youtube/js_api_reference</a></p>
<p>What you need is the <a href="https://developers.google.com/youtube/js_api_reference#Events" rel="noreferrer">onStateChange</a> event, which will give you 0 when ended.</p>
<pre><code>player.addEventListener("onStateChange", function(state){
if(state === 0){
// the video is end, do something here.
}
});
</code></pre> |
10,608,948 | Visual Studio cannot find custom tool RazorGenerator | <p>I've installed the <a href="http://razorgenerator.codeplex.com/" rel="noreferrer">NuGet package</a> for <code>RazorGenerator.mvc</code> and then run the shell command <code>Enable-RazorGenerator</code> and get the following message:</p>
<blockquote>
<p>Exception calling "RunCustomTool" with "0" argument(s): "The custom tool 'RazorGenerator' failed. The method or operation is not implemented."At \packages\RazorGenerator.Mvc.1.3.2.0\tools\RazorGenerator.psm1:77 char:40+ $_.Object.RunCustomTool <<<< () + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : ComMethodTargetInvocation </p>
</blockquote>
<p>I also tried right-clicking and selecting "Run Custom Tool" and it provides a dialog stating it cannot find the custom tool <code>RazorGenerator</code> on the system.</p>
<p>What am I missing?</p> | 10,608,961 | 1 | 0 | null | 2012-05-15 21:13:10.833 UTC | 5 | 2017-03-15 17:46:43.717 UTC | 2012-06-16 15:48:05.643 UTC | null | 727,208 | null | 175,679 | null | 1 | 53 | asp.net-mvc|visual-studio-2010|nuget|razorgenerator | 21,130 | <p>I had that same problem too and I realized that along with the package for the solution you will also need to install the Visual Studio Extension called <strong>RazorGenerator</strong></p>
<ul>
<li>Go to <strong>Tools</strong>, then <strong>Extension Manager</strong></li>
<li>Search for <strong>Razor Generator</strong></li>
<li>Click the <strong>Download</strong> button.</li>
<li>Once the install has completed, <strong>restart</strong> Visual Studio.</li>
</ul> |
10,854,471 | vim incremental search stop at end of file | <p>In Vim, when I'm doing an incremental search for "x" by entering <code>/x</code> I then press <code>n</code> to jump to the next occurrence. If I have just matched the last occurrence at the file, when I press <code>n</code> the cursor will start to look for a match at the beginning of the file---it will loop back to the beginning. <strong>I do not want it to loop back to the beginning.</strong> I want <code>n</code> to simply not find any more matches after it reaches the final occurrence. The reason I want this behavior is so that I can easily see when I have searched through the entire file.</p>
<p>Does anyone know how to effect this behavior?</p>
<p>FYI: I am using the following .vimrc options:</p>
<pre><code>colorscheme zenburn " zenburn colorscheme
set nocompatible " prevent Vim from emulating Vi's bugs
set scrolloff=5 " keeps cursor away from top/bottom of screen
set nobackup " don't make automatic backups
set incsearch " incremental searching
set ignorecase " case insensitive matching
set smartcase " smart case matching
set showmatch " show matching bracket
set autoindent " indentation
set smartindent " indentation
set cindent " indenting for C code
set tabstop=4 " 4-space tabs
set shiftwidth=4 " 4-space tabs
syntax on " syntax highlighting
filetype on " behavior based on file type
filetype plugin on " behavior based on file type
filetype indent on " behavior based on file type
set visualbell " replace beeping with flashing screen
set gfn=Lucida_Sans_Typewriter:h10:cANSI
</code></pre> | 10,854,493 | 1 | 0 | null | 2012-06-01 16:58:46.78 UTC | 8 | 2012-06-01 17:00:04.097 UTC | null | null | null | null | 1,325,279 | null | 1 | 54 | search|vim | 9,802 | <p>Turn off the <code>'wrapscan'</code> option.</p>
<pre><code>set nowrapscan
</code></pre> |
10,607,990 | How should I copy Strings in Java? | <pre><code> String s = "hello";
String backup_of_s = s;
s = "bye";
</code></pre>
<p>At this point, the backup variable still contains the original value "hello" (this is because of String's immutability right?).</p>
<p>But is it really <strong>safe</strong> to copy Strings with this method (which is of course not safe to copy regular mutable objects), or is better to write this? :</p>
<pre><code> String s = "hello";
String backup_of_s = new String(s);
s = "bye";
</code></pre>
<p>In other words, what's the difference (if any) between these two snippets?</p>
<hr>
<p><strong>EDIT - the reason why the first snippet is safe:</strong></p>
<p>Let me just explain things with a little more detail, based on the good answers already provided (which were essentially focused on the question of difference of performance between the 2 snippets):</p>
<p>Strings are immutable in Java, which means that a String object cannot be modified after its construction.
Hence,</p>
<p><code>String s = "hello";</code> creates a new String instance and assigns its address to <code>s</code> (<code>s</code> being a reference to the instance/object)</p>
<p><code>String backup_of_s = s;</code> creates a new variable <code>backup_of_s</code> and initializes it so that it references the object currently referenced by <code>s</code>.</p>
<p>Note: String immutability guarantees that this object will not be modified: our backup is safe</p>
<p>Note 2: Java garbage collection mechanism guarantees that this object will not be destroyed as long as it is referenced by at least one variable (<code>backup_of_s</code> in this case)</p>
<p>Finally, <code>s = "bye";</code> creates another String instance (because of immutability, it's the only way), and modifies the <code>s</code> variable so that it now references the new object.</p> | 10,608,003 | 5 | 0 | null | 2012-05-15 20:03:46.5 UTC | 27 | 2017-05-02 11:07:59.267 UTC | 2014-03-21 14:41:08.61 UTC | null | 479,851 | null | 479,851 | null | 1 | 227 | java | 307,254 | <p>Since strings are immutable, both versions are safe. The latter, however, is less efficient (it creates an extra object and in some cases copies the character data).</p>
<p>With this in mind, the first version should be preferred.</p> |
6,172,105 | wrong ELF class: ELFCLASS32 | <p>I'm getting this error pointing to some .so file when running my application on a Solaris machine. However, the application runs just fine in my Windows machine. If I'm not mistaken, my application is expecting for the 64-bit version but I only have a 32-bit version of the .so file in the Solaris machine. Is there a way I can fix this so it will use the 32-bit version instead? I understand it has nothing to do with the bytecodes but probably with the JVM. I tried running using -d32 or -d64 but it has no effect.</p>
<p>UPDATE:</p>
<p>This is the exact error: </p>
<pre><code>Exception in thread "main" java.lang.UnsatisfiedLinkError: librvjs11.so: ld.so.1: java: fatal: librvjs11.so: wrong ELF class: ELFCLASS32<br>
at java.lang.ClassLoader$NativeLibrary.load(Native Method)<br>
at java.lang.ClassLoader.loadLibrary0(Unknown Source)<br>
at java.lang.ClassLoader.loadLibrary(Unknown Source)<br>
at java.lang.Runtime.loadLibrary0(Unknown Source)<br>
at java.lang.System.loadLibrary(Unknown Source)<br>
</code></pre>
<p>I've already updated LD_LIBRARY_PATH so it includes the directory containing the file above.</p> | 6,173,613 | 2 | 5 | null | 2011-05-30 03:48:27.283 UTC | 0 | 2011-05-30 07:51:34.907 UTC | 2011-05-30 06:10:08.893 UTC | null | 105,224 | null | 223,465 | null | 1 | 10 | java|jvm|32bit-64bit | 79,787 | <p>Based on <a href="https://stackoverflow.com/questions/6172105/wrong-elf-class-elfclass32/6172255#6172255">the conversation in the other answer</a>, it was inferred that the JVM was a 64-bit process. This was confirmed using the <code>pflags</code> command in Solaris.</p>
<p>Apparently the <code>-d32</code> flag passed to the JVM was being ignored. This was due to the possibility of the JVM being a 64-bit one, which was incapable of operating in the 32-bit mode. The resolution might therefore be to install a 32-bit version of JVM, and use the same.</p> |
5,767,605 | Looping through Regex Matches | <p>This is my source string:</p>
<pre><code><box><3>
<table><1>
<chair><8>
</code></pre>
<p>This is my Regex Patern:</p>
<pre><code><(?<item>\w+?)><(?<count>\d+?)>
</code></pre>
<p>This is my Item class</p>
<pre><code>class Item
{
string Name;
int count;
//(...)
}
</code></pre>
<p>This is my Item Collection;</p>
<pre><code>List<Item> OrderList = new List(Item);
</code></pre>
<p>I want to populate that list with Item's based on source string.
This is my function. It's not working.</p>
<pre><code>Regex ItemRegex = new Regex(@"<(?<item>\w+?)><(?<count>\d+?)>", RegexOptions.Compiled);
foreach (Match ItemMatch in ItemRegex.Matches(sourceString))
{
Item temp = new Item(ItemMatch.Groups["item"].ToString(), int.Parse(ItemMatch.Groups["count"].ToString()));
OrderList.Add(temp);
}
</code></pre>
<p>Threre might be some small mistakes like missing letter it this example because this is easier version of what I have in my app.</p>
<p>The problem is that In the end I have only one Item in OrderList.</p>
<p><strong>UPDATE</strong></p>
<p>I got it working.
Thans for help.</p> | 5,958,154 | 2 | 4 | null | 2011-04-23 23:15:43.317 UTC | 5 | 2015-09-09 20:41:25.507 UTC | 2011-04-24 00:25:06.03 UTC | null | 465,408 | null | 465,408 | null | 1 | 39 | c#|.net|regex|foreach | 58,322 | <pre><code>class Program
{
static void Main(string[] args)
{
string sourceString = @"<box><3>
<table><1>
<chair><8>";
Regex ItemRegex = new Regex(@"<(?<item>\w+?)><(?<count>\d+?)>", RegexOptions.Compiled);
foreach (Match ItemMatch in ItemRegex.Matches(sourceString))
{
Console.WriteLine(ItemMatch);
}
Console.ReadLine();
}
}
</code></pre>
<p>Returns 3 matches for me. Your problem must be elsewhere.</p> |
5,620,128 | Rails not editable text field | <p>I have a form_for written in the following manner: </p>
<pre><code><div class="field">
<%= location.label :city %>
<%= location.text_field :city, :disabled=>true%>
</div>
<div class="field">
<%= location.label :country %>
<%= location.text_field :country, :disabled=>true%>
</div>
</code></pre>
<p>As you can see the 2 textfield are disabled because they are autofilled by a jquery function and I don't want let the user handle them.
The problem is that in this way, the view doesen't pass that parameters to the controller because are disabled !!!
Is there any other way to pass not editable text_field to the controller, taking care that I don't want to use hidden field because I want to show the results to the user inside a textbox</p>
<p>TNX</p> | 5,620,233 | 2 | 2 | null | 2011-04-11 10:41:19.41 UTC | 11 | 2017-03-08 19:50:33.057 UTC | null | null | null | null | 574,708 | null | 1 | 85 | ruby-on-rails|textfield|form-for | 60,251 | <p>Make it readonly !</p>
<pre><code><%= location.text_field :country,:readonly => true%>
</code></pre> |
33,167,390 | list all tables from a database in syBase | <p>In sql server 2012 i'm using</p>
<pre><code>USE myDatabase;
GO
SELECT *
FROM sys.objects
WHERE type = 'U';
</code></pre>
<p>Is it possible to do the same in syBase ?</p> | 33,167,494 | 3 | 0 | null | 2015-10-16 09:49:28.983 UTC | 3 | 2019-12-05 11:28:38.24 UTC | null | null | null | null | 5,367,326 | null | 1 | 6 | sybase|sap-ase|sap-iq | 85,754 | <p>In order to get a list of all tables in the current database, you can filter the sysobjects table by type = ‘U’ e.g.:</p>
<pre><code>select convert(varchar(30),o.name) AS table_name
from sysobjects o
where type = 'U'
order by table_name
</code></pre>
<p>Further <a href="http://benohead.com/sybase-ase-list-tables-current-database-size/" rel="noreferrer">Reference</a></p>
<p>Here is an example of getting all table names in <code>MSSQL</code> or <code>SQL Server database</code>:</p>
<pre><code>USE test; //SELECT DATABASE
SELECT table_name FROM information_schema.tables WHERE table_type = 'base table'
</code></pre>
<p>or you can use sys.tables to get all table names from selected database as shown in following SQL query</p>
<pre><code>USE test; //SELECT DATABASE
SELECT * FROM sys.tables
</code></pre>
<p>That's all on how to find all table names from database in SQL Server.</p> |
32,187,119 | How to specify that a pdf is returned in swagger? | <p>I have a get call in my swagger REST API that needs to return a pdf file. There is no clear example / documentation on how to do this without causing a syntax error.</p>
<pre><code> responses:
200:
description: Returns PDF
schema: [application/pdf]
</code></pre>
<p>and </p>
<pre><code> responses:
200:
description: Returns PDF
schema:
type: file
</code></pre>
<p>and</p>
<pre><code> responses:
200:
description: Returns PDF
schema:
type: [application/pdf]
</code></pre>
<p>all fail. Is this even possible? </p> | 32,197,144 | 2 | 0 | null | 2015-08-24 16:23:21.897 UTC | 5 | 2021-10-17 20:32:49.303 UTC | null | null | null | null | 910,482 | null | 1 | 29 | swagger|swagger-ui|swagger-2.0|swagger-editor | 26,620 | <pre><code> responses:
200:
description: Returns PDF
schema:
type: file
</code></pre>
<p>Out of the options you gave, that's the right option. Also, make sure to use <code>produces: [application/pdf]</code></p>
<p>If it fails for you, make sure you use the latest version of the editor. There was a bug related to the <code>file</code> type that was recently resolved.</p> |
34,198,892 | Ubuntu, how do you remove all Python 3 but not 2 | <p>I have recently get hold of a RackSpace Ubuntu server and it has pythons all over the place: </p>
<p>iPython in 3.5, Pandas in 3.4 &2.7, modules I need like pyodbc etc. are only in 2,7</p>
<p>Therefore, I am keen to clean up the box and, as a 2.7 users, keep everything in 2.7. </p>
<p>So the key question is, is there a way to remove both 3.4 and 3.5 efficiently at the same time while keeping Python 2.7?</p> | 34,220,703 | 6 | 1 | null | 2015-12-10 10:04:59.947 UTC | 2 | 2021-03-09 09:50:30.117 UTC | 2015-12-10 10:11:01.42 UTC | null | 5,299,236 | null | 4,779,515 | null | 1 | 13 | python|ubuntu | 129,599 | <p>So I worked out at the end that you cannot uninstall 3.4 as it is default on Ubuntu.</p>
<p>All I did was simply remove <code>Jupyter</code> and then alias <code>python=python2.7</code> and install all packages on Python 2.7 again.</p>
<p>Arguably, I can install <code>virtualenv</code> but me and my colleagues are only using 2.7. I am just going to be lazy in this case :) </p> |
52,095,022 | IntelliJ cannot log in to GitHub | <p>For some reason, a new IntelliJ installation is unable to log in to GitHub. (The credentials are correct.)</p>
<p>It happens both when I try to "share project on githu" and "checkout project from version control", select Git and then try to log in to GitHub.</p>
<p>Here's the login prompt:</p>
<pre><code>Server: github.com
Login: <my username>
Password: <my password>
</code></pre>
<p>And the error message:</p>
<pre><code>Invalid authentication data. Can't create token:
scopes - [repo, gist] - not IntelliJ Plugin_1 422
Unprocessable Entity - Validation Failed
[OauthAccess; description]already_exists: null
</code></pre>
<p>Now, this is on a freshly installed Windows 10 computer, with a freshly installed IntelliJ. So there are no old tokens or anything like that anywhere in the system. This is the first attempt to access GitHub from IntelliJ. Logging in via web works fine.</p> | 52,095,564 | 11 | 1 | null | 2018-08-30 10:41:43.17 UTC | 5 | 2022-05-31 09:08:54.67 UTC | null | null | null | null | 9,347,168 | null | 1 | 46 | github|intellij-idea | 85,325 | <p>That kind of error messages can be frustrating, as it takes more than a little knowledge on the subject to understand exactly what is wrong. Usually, however, the problem is either the authentication (invalid username/email/password) or that there's a problem with git (locally).</p>
<p>First of all, check that you have git installed by running "git" from the command prompt. This is a more common mistake than one would think.</p>
<p>Second, try y.bedrov's suggestion. Log in to github.com on the web. Settings -> Developer settings -> Personal access tokens. Create a new token and then, in IntelliJ, select Enter Token at the login prompt.</p>
<p>Tokens are considered a more secure way to authenticate, I believe.</p> |
55,848,101 | Memory leak using gridsearchcv | <p><strong>Problem:</strong> My situation appears to be a memory leak when running gridsearchcv. This happens when I run with 1 or 32 concurrent workers (n_jobs=-1). Previously I have run this loads of times with no trouble on ubuntu 16.04, but recently upgraded to 18.04 and did a ram upgrade.</p>
<pre><code>import os
import pickle
from xgboost import XGBClassifier
from sklearn.model_selection import GridSearchCV,StratifiedKFold,train_test_split
from sklearn.calibration import CalibratedClassifierCV
from sklearn.metrics import make_scorer,log_loss
from horsebet import performance
scorer = make_scorer(log_loss,greater_is_better=True)
kfold = StratifiedKFold(n_splits=3)
# import and split data
input_vectors = pickle.load(open(os.path.join('horsebet','data','x_normalized'),'rb'))
output_vector = pickle.load(open(os.path.join('horsebet','data','y'),'rb')).ravel()
x_train,x_test,y_train,y_test = train_test_split(input_vectors,output_vector,test_size=0.2)
# XGB
model = XGBClassifier()
param = {
'booster':['gbtree'],
'tree_method':['hist'],
'objective':['binary:logistic'],
'n_estimators':[100,500],
'min_child_weight': [.8,1],
'gamma': [1,3],
'subsample': [0.1,.4,1.0],
'colsample_bytree': [1.0],
'max_depth': [10,20],
}
jobs = 8
model = GridSearchCV(model,param_grid=param,cv=kfold,scoring=scorer,pre_dispatch=jobs*2,n_jobs=jobs,verbose=5).fit(x_train,y_train)
</code></pre>
<p><strong>Returns:</strong>
UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak.
"timeout or by a memory leak.", UserWarning</p>
<p><strong>OR</strong></p>
<p>TerminatedWorkerError: A worker process managed by the executor was unexpectedly terminated. This could be caused by a segmentation fault while calling the function or by an excessive memory usage causing the Operating System to kill the worker. The exit codes of the workers are {SIGKILL(-9)}</p> | 55,886,425 | 2 | 2 | null | 2019-04-25 11:21:26.293 UTC | 5 | 2020-01-13 01:02:15.543 UTC | null | null | null | null | 6,179,153 | null | 1 | 28 | memory-leaks|scikit-learn|grid-search|gridsearchcv | 17,434 | <p>The cause of my issue was that i put n_jobs=-1 in gridsearchcv, when it should be placed in the classifier. This has solved the issue.</p> |
19,105,706 | Rails 4 LIKE query - ActiveRecord adds quotes | <p>I am trying to do a like query like so</p>
<pre class="lang-ruby prettyprint-override"><code>def self.search(search, page = 1 )
paginate :per_page => 5, :page => page,
:conditions => ["name LIKE '%?%' OR postal_code like '%?%'", search, search], order => 'name'
end
</code></pre>
<p>But when it is run something is adding quotes which causes the sql statement to come out like so</p>
<pre class="lang-sql prettyprint-override"><code>SELECT COUNT(*)
FROM "schools"
WHERE (name LIKE '%'havard'%' OR postal_code like '%'havard'%')):
</code></pre>
<p>So you can see my problem.
I am using Rails 4 and Postgres 9 both of which I have never used so not sure if its and an activerecord thing or possibly a postgres thing.</p>
<p>How can I set this up so I have like <code>'%my_search%'</code> in the end query?</p> | 19,105,790 | 7 | 0 | null | 2013-09-30 23:46:47.037 UTC | 21 | 2020-08-31 07:11:53.963 UTC | 2014-04-22 00:06:55.28 UTC | user456814 | null | null | 503,832 | null | 1 | 135 | sql|ruby-on-rails|ruby|postgresql|activerecord | 161,166 | <p>Your placeholder is replaced by a string and you're not handling it right.</p>
<p>Replace</p>
<pre class="lang-ruby prettyprint-override"><code>"name LIKE '%?%' OR postal_code LIKE '%?%'", search, search
</code></pre>
<p>with</p>
<pre class="lang-ruby prettyprint-override"><code>"name LIKE ? OR postal_code LIKE ?", "%#{search}%", "%#{search}%"
</code></pre> |
47,047,011 | Set row height to fit content height in CSS Grid | <p>I have a grid with two columns and two rows. I have to place two grid items in one column (on the right) and one item on the left. Then I want first element from the right column to have maximum height equal to its content height. How can I accomplish this?</p>
<p>The problem that I'm facing right now is that these two items on the right, have 50% height and I can't find a way to to set first one to minimum possible height, and the other one to the rest of height (auto).</p>
<p>Just to clarify - <strong>height of each items is not fixed</strong>. Below you can see how it look right now.</p>
<p>One more thing, <strong>I can't change order of HTML DIV elements</strong> due to responsive web design.</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>.grid{
display: grid;
grid-template-columns: auto 300px;
grid-column-gap: 20px;
grid-template-areas: "main_content top" "main_content bottom";
}
.left{
grid-area: main_content;
}
.top_right{
grid-area: top;
background: #ffa4a4;
}
.bottom_right{
grid-area: bottom;
background: #c7ffae;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
<div class="top_right">I'm top right</div>
<div class="left">Long left content... Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras semper, eros ut cursus semper, dolor felis gravida ligula, et venenatis neque felis quis justo. Duis aliquet ex vitae tincidunt sodales. Fusce neque metus, pharetra eu molestie sed, tincidunt ac eros. Ut vehicula maximus sodales. Curabitur vehicula sollicitudin erat et rutrum. Aliquam id fermentum erat. Nulla pulvinar vel tortor in imperdiet. Nulla sit amet condimentum eros. Vestibulum tempor et massa eu sagittis. Integer eget nisi sagittis, placerat nibh sed, varius mi. Donec vel lorem at dolor euismod porttitor. Curabitur tincidunt magna facilisis, dapibus odio vitae, pretium orci. Aliquam lacus velit, rhoncus non porta vitae, pellentesque at libero. </div>
<div class="bottom_right">I'm bottom right</div>
</div></code></pre>
</div>
</div>
</p> | 47,047,284 | 2 | 0 | null | 2017-11-01 01:43:14.403 UTC | 9 | 2017-11-02 16:08:45.423 UTC | 2017-11-02 16:08:45.423 UTC | null | 1,736,186 | null | 1,736,186 | null | 1 | 19 | html|css|css-grid | 32,969 | <p>You just need to set the first row to <code>auto</code> (content height) and the second row to <code>1fr</code> (consume remaining space).</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>.grid{
display: grid;
grid-template-rows: auto 1fr; /* NEW */
grid-template-columns: auto 300px;
grid-column-gap: 20px;
grid-template-areas: "main_content top" "main_content bottom";
}
.left{
grid-area: main_content;
}
.top_right{
grid-area: top;
background: #ffa4a4;
}
.bottom_right{
grid-area: bottom;
background: #c7ffae;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
<div class="top_right">I'm top right</div>
<div class="left">Long left content... Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras semper, eros ut cursus semper, dolor felis gravida ligula, et venenatis neque felis quis justo. Duis aliquet ex vitae tincidunt sodales. Fusce neque metus, pharetra eu molestie sed, tincidunt ac eros. Ut vehicula maximus sodales. Curabitur vehicula sollicitudin erat et rutrum. Aliquam id fermentum erat. Nulla pulvinar vel tortor in imperdiet. Nulla sit amet condimentum eros. Vestibulum tempor et massa eu sagittis. Integer eget nisi sagittis, placerat nibh sed, varius mi. Donec vel lorem at dolor euismod porttitor. Curabitur tincidunt magna facilisis, dapibus odio vitae, pretium orci. Aliquam lacus velit, rhoncus non porta vitae, pellentesque at libero. </div>
<div class="bottom_right">I'm bottom right</div>
</div></code></pre>
</div>
</div>
</p> |
25,513,340 | How to provide Python syntax coloring inside Webstorm? | <p>I have a Python project, and I use WebStorm as my Editor. The problem is that Python's syntax doesn't get colored. </p>
<p>How can I display Python pages with a nice syntax? I am not searching more than than. I'm not going to develop pages in Python, but I do want them to get displayed nicely in Webstorm.</p> | 25,545,919 | 3 | 0 | null | 2014-08-26 19:02:15.377 UTC | 5 | 2019-06-18 16:54:09.55 UTC | 2015-10-04 14:02:44.507 UTC | null | 472,495 | null | 279,591 | null | 1 | 32 | python|webstorm | 15,024 | <p>Your ONLY option in WebStorm is to use <strong>TextMate bundles support plugin</strong> with Python bundle -- it will provide syntax highlighting (no completion or syntax checking etc).</p>
<p>This official article (with pictures) is for PhpStorm, but it should work the same for WebStorm as well: <a href="http://confluence.jetbrains.com/display/PhpStorm/TextMate+Bundles+in+PhpStorm" rel="nofollow noreferrer">http://confluence.jetbrains.com/display/PhpStorm/TextMate+Bundles+in+PhpStorm</a></p>
<p>There are several TextMate bundles available for Python: <a href="https://github.com/textmate?utf8=%E2%9C%93&q=python" rel="nofollow noreferrer">https://github.com/textmate?utf8=%E2%9C%93&q=python</a></p>
<p>Alternative solution: migrate to PyCharm Pro -- it does all what WebStorm does + Python.</p>
<hr>
<p><strong>UPDATE: 2019-06-18</strong></p>
<p><strong>2019.2</strong> version will come bundled with syntax highlighting for about 20 languages (all done via the aforementioned TextMate bundles plugin).</p>
<p><a href="https://blog.jetbrains.com/webstorm/2019/05/webstorm-2019-2-eap/" rel="nofollow noreferrer">https://blog.jetbrains.com/webstorm/2019/05/webstorm-2019-2-eap/</a></p>
<blockquote>
<p>In WebStorm 2019.2, we’re adding syntax highlighting for over 20 different programming languages, including PHP, Python, Ruby, and Java. It just works – no additional configuration needed.</p>
<p>With this change we want to improve the experience of our users who occasionally have to look through some code written in different languages that are not supported in WebStorm. But WebStorm is still primarily an IDE for JavaScript and TypeScript developers, so we don’t plan to extend the support for these other languages beyond syntax highlighting.</p>
<p>Syntax highlighting for these languages is built using TextMate grammars, and WebStorm bundles a collection of grammar file for different languages. Currently they are shipped as part of the TextMate Bundles plugin (so you can see a full list of supported languages under <em>Preferences | Editor | TextMate Bundles</em>), but they are going to be moved to the IntelliJ Platform soon.</p>
<p><a href="https://i.stack.imgur.com/azLIE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/azLIE.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/w9l92.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w9l92.png" alt="enter image description here"></a></p>
</blockquote> |
48,527,229 | Where can I find crash feedback from users in the Google Play Console? | <p>When a crash occurs in an application installed via the Google Play app, user's have the option to Send Feedback.</p>
<p><a href="https://i.stack.imgur.com/urePD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/urePD.png" alt="Send Feedback"></a></p>
<p>A user can optional write feedback to describe the problem they have encountered and then submit their crash report.</p>
<ol>
<li>Is the written feedback provided by the user available anywhere in the Google Play Console?</li>
<li>Can the feedback be associated with a stack trace of the crash the user encountered?</li>
</ol> | 50,682,602 | 4 | 1 | null | 2018-01-30 17:26:50.973 UTC | 11 | 2021-04-30 08:13:25.777 UTC | null | null | null | null | 10,216 | null | 1 | 56 | android|google-play|google-play-console | 10,956 | <p>After talking with google support iv received this answer - </p>
<p>"The console has been updated since the IO and some of the function you had in the past is now redundant."</p>
<p>Google has removed the "crash feedback" in the latest update. </p> |
51,945,210 | VueJs how to set prop type to any? | <p>I have props with defined types but I want the last one of them to accept any kind of value</p>
<pre><code>props: {
Size: String,
Label: String,
Name: String,
value: Any
}
</code></pre>
<p>Hpw can I achieve this?</p> | 51,945,285 | 3 | 1 | null | 2018-08-21 09:05:12.66 UTC | 4 | 2022-07-15 19:41:55.75 UTC | null | null | null | null | 8,892,945 | null | 1 | 44 | vue.js | 30,026 | <p>From <a href="https://v2.vuejs.org/v2/guide/components-props.html#Prop-Validation" rel="nofollow noreferrer">VueJS docs</a>:</p>
<blockquote>
<p><code>null</code> and <code>undefined</code> values will pass any type validation</p>
</blockquote>
<p>Or you can use array and place in it all required types:</p>
<pre><code>propB: [String, Number]
</code></pre> |
8,947,920 | How do I get a three column layout with Twitter Bootstrap? | <p>I am trying to create a three column layout that is like the following:</p>
<p><a href="http://www.manisheriar.com/holygrail/index.htm" rel="noreferrer">http://www.manisheriar.com/holygrail/index.htm</a></p>
<p>It should be a <code>fixed width</code> - <code>fluid width</code> - <code>fixed width</code> layout.</p>
<p>Using <code>Twitter Bootstrap</code>, the left sidebar and fluid content work great. But I need the addition of a <code>right sidebar</code> too.</p> | 8,949,800 | 4 | 0 | null | 2012-01-20 21:13:08.38 UTC | 14 | 2014-12-07 11:06:11.773 UTC | 2012-01-21 00:58:07.243 UTC | null | 918,414 | null | 59,202 | null | 1 | 21 | css|twitter-bootstrap | 35,786 | <p>Try this: <a href="http://jsfiddle.net/andresilich/6vPqA/2/" rel="noreferrer">http://jsfiddle.net/andresilich/6vPqA/2/</a></p>
<p><strong>CSS</strong></p>
<pre><code>.container-fluid > .sidebar {
position: relative;
top: 0;
left:auto;
width: 220px; /* width of sidebar */
}
.left {
float:left;
}
.right {
float:right;
}
.container-fluid > .content {
margin: 0 240px; /* width of sidebars + 10px of margin */
}
</code></pre>
<p><strong>HTML</strong></p>
<pre><code><div class="sidebar left">
<div class="well">
<h5>Sidebar</h5>
.....
</div>
</div>
<div class="sidebar right">
<div class="well">
<h5>Sidebar</h5>
.....
</div>
</div>
</code></pre>
<hr>
<p>Per comments, i updated my answer to carry the possibility to switch between right and left sidebar with just a class.</p>
<p>Now you can use the following in the <code><div class="content"></code> div:</p>
<p><strong>CSS</strong></p>
<pre><code>.fixed-fluid {
margin-left: 240px;
}
.fluid-fixed {
margin-right: 240px;
margin-left:auto !important;
}
.fixed-fixed {
margin: 0 240px;
}
</code></pre>
<p>Demo: <a href="http://jsfiddle.net/andresilich/6vPqA/3/show/" rel="noreferrer">http://jsfiddle.net/andresilich/6vPqA/3/show/</a>
Edit: <a href="http://jsfiddle.net/andresilich/6vPqA/3/" rel="noreferrer">http://jsfiddle.net/andresilich/6vPqA/3/</a></p>
<hr>
<p>Another user asked about if this method can be adapted to the latest version of the bootstrap (v2.0 at the time of writing) so here is a demo that uses it:</p>
<p><a href="http://jsfiddle.net/andresilich/6vPqA/13/" rel="noreferrer">http://jsfiddle.net/andresilich/6vPqA/13/</a></p> |
8,565,376 | mongo shell script won't let me include "use <database>" | <p>32-bit mongo 2.0.1 on a windows XP machine</p>
<pre><code>//script filename: test.js (one line shell script file to store a person)
db.cTest.save({Name: "Fred", Age:21});
</code></pre>
<p>run against database dbTest by entering the following 2 shell commands:</p>
<pre><code> > use dbTest
switched to dbTest
> load("test.js")
</code></pre>
<p>So far, so good.</p>
<p>But if I try and include the "use" statement in the script it fails:</p>
<pre><code>//script filename: test.js (including "use" statement)
use dbTest;
db.cTest.save({Name: "Fred", Age:21});
</code></pre>
<p>fails with error msg as follows:</p>
<pre><code> > load("test.js")
SyntaxError: missing ; before statement
Mon Dec 19 11:56:31: Error: error loading js file temp.js (shell):1
</code></pre>
<p>Adding or removing semicolons to test.js doesn't seem to matter.</p>
<p>So how do you put a "use" directive into a mongo shell script?</p> | 8,566,082 | 3 | 0 | null | 2011-12-19 17:56:45.897 UTC | 8 | 2013-04-09 10:21:37.56 UTC | 2011-12-19 19:59:32.17 UTC | null | 175,153 | null | 528,016 | null | 1 | 35 | shell|mongodb|scripting | 22,287 | <p><a href="http://www.mongodb.org/display/DOCS/Scripting+the+shell" rel="noreferrer">http://www.mongodb.org/display/DOCS/Scripting+the+shell</a></p>
<blockquote>
<p><strong>use dbname</strong><br />
This command does not work in scripted mode. Instead you will need to explicitly define the database in the connection (/dbname in the example above).</p>
<p>Alternately, you can also create a connection within the script:</p>
<p>db2 = connect("server:27017/otherdbname")</p>
</blockquote> |
26,782,041 | Scaling shiny plots to window height | <p>I want to scale a shiny plot to the height of the window. This <a href="https://stackoverflow.com/questions/17838709/scale-and-size-of-plot-in-rstudio-shiny">related SO question</a> only uses absolute height specifications in pixels, when a <code>height = 100%</code> would be preferable. I note in the documentation that <code>absolutePanel</code> can achieve this with its <code>top, bottom, left, right</code> arguments, but then you lose the side panel, and in any case the plot (while scaling to width) seems to ignore available height.</p>
<p>I'm guessing this relates to the html quirk that means you need to get the height with javascript <code>innerHeight</code> variable. But I'm unclear how to implement a solution in shiny to get <code>ui.R</code> to utilise this. Grateful for any pointers.</p>
<p>A basic app model for development:</p>
<p><strong>ui.R</strong></p>
<pre><code>library(shiny)
shinyServer(
function(input, output) {
output$myplot <- renderPlot({
hist(rnorm(1000))
})
}
)
</code></pre>
<p><strong>server.R</strong></p>
<pre><code>library(shiny)
pageWithSidebar(
headerPanel("window height check"),
sidebarPanel(),
mainPanel(
plotOutput("myplot")
)
)
</code></pre> | 26,785,047 | 1 | 0 | null | 2014-11-06 14:35:29.683 UTC | 7 | 2014-11-06 16:56:18.617 UTC | 2017-05-23 12:02:51.58 UTC | null | -1 | null | 1,156,245 | null | 1 | 29 | r|shiny | 10,193 | <p>Use CSS3. Declare your height in viewport units <a href="http://caniuse.com/#feat=viewport-units" rel="noreferrer">http://caniuse.com/#feat=viewport-units</a> .
You should be able to declare them using the <code>height</code> argument in <code>plotOutput</code> however <code>shiny::validateCssUnit</code> doesnt recognise them so you can instead declare them in a style header:</p>
<pre><code>library(shiny)
runApp(
list(server= function(input, output) {
output$myplot <- renderPlot({
hist(rnorm(1000))
})
}
, ui = pageWithSidebar(
headerPanel("window height check"),
sidebarPanel(
tags$head(tags$style("#myplot{height:100vh !important;}"))
),
mainPanel(
plotOutput("myplot")
)
)
)
)
</code></pre>
<p>This wont work in the shiny browser but should work correctly in a main browser.</p>
<p><img src="https://i.stack.imgur.com/ggaMy.png" alt="enter image description here"></p> |
58,925 | ASP.NET how to Render a control to HTML? | <p>I have any ASP.NET control. I want the HTML string how to do I get the HTML string of the control?</p> | 58,931 | 3 | 0 | null | 2008-09-12 13:17:46.393 UTC | 9 | 2015-09-24 15:57:31.877 UTC | null | null | null | Longhorn213 | 2,469 | null | 1 | 31 | .net|asp.net | 32,622 | <p>This appears to work.</p>
<pre><code>public string RenderControlToHtml(Control ControlToRender)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter stWriter = new System.IO.StringWriter(sb);
System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(stWriter);
ControlToRender.RenderControl(htmlWriter);
return sb.ToString();
}
</code></pre> |
228,532 | Difference between Char.IsDigit() and Char.IsNumber() in C# | <p>What's the difference between <code>Char.IsDigit()</code> and <code>Char.IsNumber()</code> in C#?</p> | 228,565 | 3 | 0 | null | 2008-10-23 04:23:13.92 UTC | 29 | 2018-11-26 06:11:38.493 UTC | 2013-02-26 09:37:26.21 UTC | jleedev | 75,500 | Guy | 1,463 | null | 1 | 175 | c#|.net|unicode | 90,456 | <p><code>Char.IsDigit()</code> is a subset of <code>Char.IsNumber()</code>.</p>
<p>Some of the characters that are 'numeric' but not digits include 0x00b2 and 0x00b3 which are superscripted 2 and 3 ('²' and '³') and the glyphs that are fractions such as '¼', '½', and '¾'.</p>
<p>Note that there are quite a few characters that <code>IsDigit()</code> returns <code>true</code> for that are not in the ASCII range of 0x30 to 0x39, such as these Thai digit characters: '๐' '๑' '๒' '๓' '๔' '๕' '๖' '๗' '๘' '๙'.</p>
<p>This snippet of code tells you which code points differ:</p>
<pre><code>static private void test()
{
for (int i = 0; i <= 0xffff; ++i)
{
char c = (char) i;
if (Char.IsDigit( c) != Char.IsNumber( c)) {
Console.WriteLine( "Char value {0:x} IsDigit() = {1}, IsNumber() = {2}", i, Char.IsDigit( c), Char.IsNumber( c));
}
}
}
</code></pre> |
22,175,825 | CUDA: invalid device ordinal | <p>I have the following problem. I want to allow my users to choose which GPU to run on. So I was testing on my machine which has only one GPU (device 0) what would happen if they choose a device which doesn't exist.</p>
<p>If I do <code>cudaSetDevice(0);</code> it will work fine.</p>
<p>If I do: <code>cudaSetDevice(1);</code> it will crash with <code>invalid device ordinal</code> (I can handle this as the function returns an error).</p>
<p>If I do: <code>cudaSetDevice(0); cudaSetDevice(1);</code> it will crash with <code>invalid device ordinal</code> (I can handle this as the function returns an error).</p>
<p><strong>However!</strong> If I do: <code>cudaSetDevice(1); cudaSetDevice(0);</code> the second command returns success but on the first calculation I try to compute on my GPU it will crash with <code>invalid device ordinal</code>. I cannot handle this because the second command does not return an error!</p>
<p>It seems to me like the first cudaSetDevice leaves something lying around which affects the second command?</p>
<p>Thanks very much!</p>
<p><strong>Solution:</strong> (Thanks to Robert Crovella!).
I was handling the errors like:</p>
<pre><code>error = cudaSetDevice(1);
if (error) { blabla }
</code></pre>
<p>But apparently you need to call cudaGetLastError() after the cudaSetDevice(1) because otherwise the error message is not removed from some error stack and it just crashes later on where I was doing cudaGetLastError() for another function even though there was no error at this point.</p> | 22,176,841 | 1 | 0 | null | 2014-03-04 15:16:45.517 UTC | 3 | 2019-02-12 15:55:50.51 UTC | 2014-03-07 16:52:32.103 UTC | null | 1,198,173 | null | 1,198,173 | null | 1 | 10 | cuda | 53,453 | <p>You have to check how many GPU's are available in your system first. It's possible by the use of <code>cudaGetDeviceCount</code>.</p>
<pre><code>int deviceCount = 0;
cudaGetDeviceCount(&deviceCount);
</code></pre>
<p>Then check if the user input is greater than the available devices.</p>
<pre><code>if (userDeviceInput < deviceCount)
{
cudaSetDevice(userDeviceInput);
}
else
{
printf("error: invalid device choosen\n");
}
</code></pre>
<p>Remind that<code>cudaSetDevice</code>is 0-index-based! Therefor I check <code>userDeviceInput < deviceCount</code>.</p> |
6,616,470 | Certificates Basic Constraint's Path Length | <p>Is having a Path Length of 0 and None the same thing for Basic Constraint's of a CA type? To clarify, does a path length of 0 mean that the CA can issue no certificates while a path length of none mean that it can issue an infinite amount of certificates?</p> | 6,617,814 | 1 | 0 | null | 2011-07-07 20:06:39.87 UTC | 11 | 2011-07-07 22:20:05.197 UTC | null | null | null | null | 801,835 | null | 1 | 37 | path|certificate|constraints | 37,160 | <p>Taken from <a href="https://www.rfc-editor.org/rfc/rfc5280#page-39" rel="noreferrer">RFC 5280</a>, section 4.2.1.9:</p>
<blockquote>
<p>A pathLenConstraint of zero indicates that no non-self-issued intermediate CA certificates may follow in a valid certification path. Where it appears, the pathLenConstraint field MUST be greater than or equal to zero. Where pathLenConstraint does not appear, no limit is imposed.</p>
</blockquote>
<p>I.e. a <code>pathLenConstraint</code>of 0 does still allow the CA to issue certificates, but these certificates must be end-entity-certificates (the CA flag in BasicConstraints is false - these are the "normal" certificates that are issued to people or organizations).</p>
<p>It also implies that with this certificate, the CA must not issue intermediate CA certificates (where the CA flag is true again - these are certificates that could potentially issue further certificates, thereby increasing the <code>pathLen</code> by 1).</p>
<p>An absent <code>pathLenConstraint</code> on the other hand means that there is no limitation considering the length of certificate paths built from an end-entity certificate that would lead up to our example CA certificate. This implies that the CA could issue a intermediate certificate for a sub CA, this sub CA could again issue an intermediate certificate, this sub CA could again... until finally one sub CA would issue an end-entity certificate.</p>
<p>If the <code>pathLenConstraint</code>of a given CA certificate is > 0, then it expresses the number of possible intermediate CA certificates in a path built from an end-entity certificate up to the CA certificate. Let's say CA X has a <code>pathLenConstraint</code> of 2, the end-entity certificate is issued to EE. Then the following scenarios are valid (I denoting an intermediate CA certificate)</p>
<pre><code>X - EE
X - I1 - EE
X - I1 - I2 - EE
</code></pre>
<p>but this and those scenarios with even more intermediate CAs are not</p>
<pre><code>X - I1 - I2 - I3 - EE
...
</code></pre> |
36,619,212 | How to fail a build on Gitlab CI shell runner | <p>I have a Gitlab CI runner running on windows 10:</p>
<pre><code>before_script:
- "echo off"
- 'call "%VS120COMNTOOLS%\vsvars32.bat"'
- echo.
- set
- echo.
stages:
- build
build:
stage: build
script:
- 'StatusTest.exe'
#- msbuild...
</code></pre>
<p>I am trying to fail the build with StatusText.exe (I tried returning status codes -1,0,1; throwing an exception, etc.) But Runner only logs the exception and continues with following steps.</p>
<p>What determines that CI shell runner should fail the build and not proceed to next step?</p>
<p>Output:</p>
<pre><code>...
windows_tracing_logfile=C:\BVTBin\Tests\installpackage\csilogfile.log
$ echo.
$ StatusTest.exe
Unhandled Exception: System.Exception: tralala
at StatusTest.Program.Main(String[] args)
$ echo "Restoring NuGet Packages..."
...
</code></pre> | 42,066,050 | 2 | 1 | null | 2016-04-14 09:38:48.59 UTC | 5 | 2022-08-01 14:16:26.853 UTC | null | null | null | null | 1,128,259 | null | 1 | 50 | gitlab|gitlab-ci|gitlab-ci-runner | 44,735 | <blockquote>
<p>What determines that CI shell runner should fail the build and not
proceed to next step?</p>
</blockquote>
<p>If a pipeline job exits with the code other than <code>0</code> then that job fails causing all the following jobs in the pipeline to be skipped.</p>
<p>This behaviour can be changed on a per job basis with <a href="https://docs.gitlab.com/ee/ci/yaml/index.html#allow_failure" rel="nofollow noreferrer">allow_failure</a> job keyword.</p>
<p>To make a job to fail forcefully you need to artificially exit from a job with code other than <code>0</code>. Here is an <code>gitlab-ci.yml</code> job example :</p>
<pre class="lang-bash prettyprint-override"><code>some-example-job:
script:
- # ....
- exit 1
</code></pre>
<p><a href="https://i.stack.imgur.com/fmwCj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fmwCj.png" alt="enter image description here" /></a></p>
<p>See the GitLab CI UI sreeenshot example. The third job has failed.</p>
<p><a href="https://i.stack.imgur.com/XPvou.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XPvou.png" alt="enter image description here" /></a></p>
<p>On the opposite remove <code>exit 0</code> and your job would succeed if the remaining <code>script</code> section commands do not exit with code other than <code>0</code>.</p>
<p>Now see all the jobs & the entire pipeline finished successfully.
<a href="https://i.stack.imgur.com/6pz94.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6pz94.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/LSf7w.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LSf7w.png" alt="enter image description here" /></a></p> |
28,620,087 | Print an output in one line using console.log() | <p>Is it possible to print the output in the same line by using <code>console.log()</code> in JavaScript? I know <code>console.log()</code> always returns a new line. For example, have the output of multiple consecutive <code>console.log()</code> calls be:</p>
<pre><code>"0,1,2,3,4,5,"
</code></pre> | 28,620,115 | 13 | 1 | null | 2015-02-20 01:13:39.777 UTC | 10 | 2022-04-25 15:46:16.473 UTC | 2021-02-27 05:48:51.13 UTC | null | 6,495,889 | null | 3,222,088 | null | 1 | 38 | javascript | 138,032 | <p>Couldn't you just put them in the same call, or use a loop?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> var one = "1"
var two = "2"
var three = "3"
var combinedString = one + ", " + two + ", " + three
console.log(combinedString) // "1, 2, 3"
console.log(one + ", " + two + ", " + three) // "1, 2, 3"
var array = ["1", "2", "3"];
var string = "";
array.forEach(function(element){
string += element;
});
console.log(string); //123</code></pre>
</div>
</div>
</p> |
28,708,720 | VS 2013: curly braces size mismatch | <p>I have got a problem with my Visual Studio 2013:</p>
<p>My curly braces have different sizes.</p>
<p>If I write some code in the same line they change the size to match my editor font size.</p>
<p>Is there a config section where I can disable this behavior?</p>
<p><img src="https://i.stack.imgur.com/cZjWe.png" alt="The same size?" /></p> | 28,709,149 | 2 | 1 | null | 2015-02-24 23:58:27.943 UTC | 6 | 2020-06-04 10:09:06.337 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 99,715 | null | 1 | 29 | visual-studio|productivity-power-tools | 1,735 | <p>Well, after a while looking for a solution I found that the problem was an extension: VS Productivity Power Tools 2013: Syntactic Line Compression.</p>
<ol>
<li>Click "Tools" -> "Options"</li>
<li>Choose "Productivity Power Tools" in the Options window</li>
<li>Toggle "Syntactic Line Compression" to "Off"</li>
</ol>
<p>Hope this helps.
PS: This solution works with VS 2015 and VS 2017 too.</p> |
28,849,729 | ASP.NET MVC 5 renders different bool value for hidden input | <p>Given the following viewmodel:</p>
<pre><code>public class FooViewModel
{
public bool IsBoolValue { get; set; }
}
</code></pre>
<p>and this view:</p>
<pre><code><input type="hidden" id="Whatever" data-something="@Model.IsBoolValue" value="@Model.IsBoolValue" />
</code></pre>
<p>The output of the hidden input field is this:</p>
<p><code><input type="hidden" id="Whatever" data-something="True" value="value"></code></p>
<p>How come the <code>value</code> attribute is not set to<code>True</code>, but the <code>data-something</code> attribute is?</p>
<p>Is there a change in MVC 5 that would cause this, since in my MVC 4 apps this problem does not occur.</p> | 28,850,044 | 2 | 1 | null | 2015-03-04 08:28:46.3 UTC | 3 | 2022-03-31 06:17:52.19 UTC | null | null | null | null | 127,440 | null | 1 | 39 | asp.net-mvc|asp.net-mvc-5 | 20,206 | <p>I think I've figured it out.</p>
<p>I believe the Razor viewengine is adhering to the HTML 5 way of setting boolean attributes, as described here:</p>
<p><a href="https://stackoverflow.com/questions/4139786/what-does-it-mean-in-html-5-when-an-attribute-is-a-boolean-attribute">What does it mean in HTML 5 when an attribute is a boolean attribute?</a></p>
<p>In HTML 5, a bool attribute is set like this:</p>
<p><code><input readonly /></code></p>
<p>or</p>
<p><code><input readonly="readonly" /></code></p>
<p>So the Razor viewengine takes your model's bool value and will render (in my case) the <code>value</code> attribute if <code>Model.IsBoolValue</code> is <code>true</code>. Otherwise, if it's <code>false</code> then the <code>value</code> attribute is not rendered at all.</p>
<p>EDIT:</p>
<p>As mentioned Zabavsky in the comments, to force the value of True or False to appear in the <code>value</code> attrbiute, simple use <code>ToString()</code>:</p>
<p><code><input type="hidden" value="@Model.BoolProperty.ToString()" /></code></p> |
20,517,259 | Why vector access operators are not specified as noexcept? | <p>Why <code>std::vector</code>'s <code>operator[]</code>, <code>front</code> and <code>back</code> member functions are not specified as <code>noexcept</code>?</p> | 20,517,333 | 3 | 0 | null | 2013-12-11 10:56:09.69 UTC | 11 | 2019-04-07 05:59:22.053 UTC | null | null | null | null | 609,063 | null | 1 | 51 | c++|exception|c++11|stl|noexcept | 5,010 | <p>The standard's policy on <code>noexcept</code> is to only mark functions that <em>cannot</em> or <em>must not</em> fail, but not those that simply are specified not to throw exceptions. In other words, all functions that have a limited domain (pass the wrong arguments and you get undefined behavior) are not <code>noexcept</code>, even when they are not specified to throw.</p>
<p>Functions that get marked are things like <code>swap</code> (must not fail, because exception safety often relies on that) and <code>numeric_limits::min</code> (cannot fail, returns a constant of a primitive type).</p>
<p>The reason is that implementors might want to provide special debug versions of their libraries that throw on various undefined behavior situations, so that test frameworks can easily detect the error. For example, if you use an out-of-bound index with <code>vector::operator[]</code>, or call <code>front</code> or <code>back</code> on an empty vector. Some implementations want to throw an exception there (which they are allowed to: since it's undefined behavior, they can do anything), but a standard-mandated <code>noexcept</code> on those functions makes this impossible.</p> |
24,160,817 | Getting error Could not locate appropriate constructor on class | <p>I am trying to map native SQL result to my POJO. Here is the configuration. I am using spring.</p>
<pre><code><bean id="ls360Emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
<property name="dataSource" ref="ls360DataSource" />
<property name="jpaVendorAdapter" ref="vendorAdaptor" />
<property name="packagesToScan" value="abc.xyz"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
</code></pre>
<p>Here is my Class</p>
<pre><code>@SqlResultSetMapping(
name="courseCompletionMapping",
classes = {
@ConstructorResult(targetClass = CourseCompletion.class,
columns={
@ColumnResult(name = "StoreId", type = String.class),
@ColumnResult(name = "ProductId", type = String.class),
@ColumnResult(name = "UserName", type = String.class),
@ColumnResult(name = "Score", type = Integer.class),
@ColumnResult(name = "CompletionDate", type = Date.class)
}
)
}
)
@Entity
public class CourseCompletion {
private String storeId;
@Id
private String productId;
private String userName;
private int score;
private Date completionDate;
public CourseCompletion() {
}
public CourseCompletion(String storeId, String productId, String userName, int score, Date completionDate) {
this.storeId = storeId;
this.productId = productId;
this.userName = userName;
this.score = score;
this.completionDate = completionDate;
}
// getters and setters
</code></pre>
<p>Here how i am calling it</p>
<pre><code> Properties coursePropertiesFile = SpringUtil.loadPropertiesFileFromClassPath("course.properties");
String queryString = coursePropertiesFile.getProperty("course.completion.sql");
long distributorId = 1;
String fromDate = "2009-09-22 00:00:00";
String toDate = "2014-04-11 23:59:59";
Query query = em.createNativeQuery(queryString, "courseCompletionMapping");
//Query query = em.createNamedQuery("findAllEmployeeDetails");
query.setParameter("distributorId", distributorId);
query.setParameter("fromDate", fromDate);
query.setParameter("toDate", toDate);
@SuppressWarnings("unchecked")
List<CourseCompletion> courseCompletionList = query.getResultList();
</code></pre>
<p>But when it comes to line </p>
<pre><code>List<CourseCompletion> courseCompletionList = query.getResultList();
</code></pre>
<p>I get an error that</p>
<pre><code>Could not locate appropriate constructor on class : mypackage.CourseCompletion
</code></pre>
<p>Here is the query that i am trying </p>
<pre><code>select d.DISTRIBUTORCODE AS StoreId, u.USERGUID AS ProductId, u.UserName,
lcs.HIGHESTPOSTTESTSCORE AS Score, lcs.CompletionDate
from VU360User u
inner join learner l on u.ID = l.VU360USER_ID
inner join LEARNERENROLLMENT le on le.LEARNER_ID = l.ID
inner join LEARNERCOURSESTATISTICS lcs on lcs.LEARNERENROLLMENT_ID = le.ID
inner join customer c on c.ID = l.CUSTOMER_ID
inner join DISTRIBUTOR d on d.ID = c.DISTRIBUTOR_ID
where d.ID = :distributorId
and lcs.COMPLETIONDATE is not null
and (lcs.COMPLETIONDATE between :fromDate and :toDate)
and lcs.COMPLETED = 1
</code></pre>
<p>Why i am getting this error ?</p>
<p>Thanks</p> | 24,733,398 | 4 | 0 | null | 2014-06-11 10:39:30.24 UTC | 12 | 2021-11-19 18:28:13.647 UTC | null | null | null | null | 1,000,510 | null | 1 | 31 | spring-data-jpa|hibernate-4.x|jpa-2.1 | 38,076 | <p>This exception happens because JPA doesn't change column types returned from the database for native queries. Because of this, you have type mismatch. I'm not sure about which column causes this problem in your case (this depends on DBMS you use), but I would suspect you have <code>BigInteger</code> in the result set instead of <code>Integer</code> for <em>score</em> column. To be 100% sure, add a breakpoint to <code>ConstructorResultColumnProcessor.resolveConstructor(Class targetClass, List<Type> types)</code> and investigate. After you find a mismatch, change field type in your mapping class.</p>
<p>Another solution will be not to use <code>@SqlResultSetMapping</code> at all. As your <code>CourseCompletion</code> class is a managed entity, you should be able to map native query to it directly. See <a href="https://stackoverflow.com/questions/13012584/jpa-how-to-convert-a-native-query-result-set-to-pojo-class-collection">this question</a> for more information.</p> |
36,122,668 | How to sort struct with multiple sort parameters? | <p>I have an array/slice of members:</p>
<pre><code>type Member struct {
Id int
LastName string
FirstName string
}
var members []Member
</code></pre>
<p>My question is how to sort them by <code>LastName</code> and then by <code>FirstName</code>.</p> | 42,382,736 | 12 | 2 | null | 2016-03-21 03:26:57.203 UTC | 18 | 2022-06-29 02:10:38.857 UTC | 2019-04-02 11:27:38.997 UTC | null | 13,860 | null | 2,180,770 | null | 1 | 54 | sorting|go | 43,429 | <p>Use the newer <code>sort.Slice</code> function as such:</p>
<pre><code>sort.Slice(members, func(i, j int) bool {
switch strings.Compare(members[i].FirstName, members[j].FirstName) {
case -1:
return true
case 1:
return false
}
return members[i].LastName > members[j].LastName
})
</code></pre>
<p>or something like that.</p> |
20,162,664 | TypeError: must be str, not float | <p>this is 1/8 of my script:</p>
<pre><code>print('Your skill:', int(charskill))
with open('C:\Documents and Settings\Welcome\My Documents\python\Task 2\lol.txt', 'w') as myFile:
myFile.write(charskill)
</code></pre>
<p>Once I execute on python, it gives me an error of: </p>
<pre><code>Traceback (most recent call last):
File "C:\Documents and Settings\Welcome\My Documents\python\Task 2\Dice generator v2.py", line 39, in <module>
myFile.write(charskill)
TypeError: must be str, not float
</code></pre>
<p>How do I fix this problem? I want the file to run on notepad ;/ because it is my homework at school.</p> | 20,162,833 | 3 | 0 | null | 2013-11-23 13:07:18.637 UTC | 3 | 2013-11-23 13:30:42.893 UTC | 2013-11-23 13:10:32.663 UTC | user395760 | null | null | 3,024,763 | null | 1 | 5 | python|string | 67,227 | <p>If you're using Python 3.x (it's possible you might be given your <code>print</code>), then instead of using <code>.write</code> or string formatting, an alternative is to use:</p>
<pre><code>print('Your Skill:', charskill, file=myFile)
</code></pre>
<p>This has the advantage of putting a space in there, and a newline character for you and not requiring any explicit conversions.</p> |
1,810,891 | Django: How to filter Users that belong to a specific group | <p>I'm looking to narrow a query set for a form field that has a foreignkey to the User's table down to the group that a user belongs to.</p>
<p>The groups have been previously associated by me. The model might have something like the following:</p>
<pre><code>myuser = models.ForeignKey(User)
</code></pre>
<p>And my ModelForm is very bare bones:</p>
<pre><code>class MyForm(ModelForm):
class Meta:
model = MyModel
</code></pre>
<p>So when I instantiate the form I do something like this in my views.py:</p>
<pre><code>form = MyForm()
</code></pre>
<p>Now my question is, how can I take the myuser field, and filter it so only users of group 'foo' show up.. something like:</p>
<pre><code>form.fields["myuser"].queryset = ???
</code></pre>
<p>The query in SQL looks like this:</p>
<pre><code>mysql> SELECT * from auth_user INNER JOIN auth_user_groups ON auth_user.id = auth_user_groups.user_id INNER JOIN auth_group ON auth_group.id = auth_user_groups.group_id WHERE auth_group.name = 'client';
</code></pre>
<p>I'd like to avoid using raw SQL though. Is it possible to do so?</p> | 1,810,985 | 2 | 0 | null | 2009-11-27 22:51:30.177 UTC | 6 | 2019-11-14 08:17:39.893 UTC | 2019-11-14 08:17:39.893 UTC | null | 3,627,387 | null | 175,836 | null | 1 | 41 | python|django | 44,637 | <p>You'll want to use <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships" rel="noreferrer">Django's convention for joining across relationships</a> to join to the group table in your query set.</p>
<p>Firstly, I recommend giving your relationship a <code>related_name</code>. This makes the code more readable than what Django generates by default.</p>
<pre><code>class Group(models.Model):
myuser = models.ForeignKey(User, related_name='groups')
</code></pre>
<p>If you want only a single group, you can join across that relationship and compare the name field using either of these methods:</p>
<pre><code>form.fields['myuser'].queryset = User.objects.filter(
groups__name='foo')
form.fields['myuser'].queryset = User.objects.filter(
groups__name__in=['foo'])
</code></pre>
<p>If you want to qualify multiple groups, use the <code>in</code> clause:</p>
<pre><code>form.fields['myuser'].queryset = User.objects.filter(
groups__name__in=['foo', 'bar'])
</code></pre>
<p>If you want to quickly see the generated SQL, you can do this:</p>
<pre><code>qs = User.objects.filter(groups__name='foo')
print qs.query
</code></pre> |
1,854,237 | Django edit form based on add form? | <p>I've made a nice form, and a big complicated 'add' function for handling it. It starts like this...</p>
<pre><code>def add(req):
if req.method == 'POST':
form = ArticleForm(req.POST)
if form.is_valid():
article = form.save(commit=False)
article.author = req.user
# more processing ...
</code></pre>
<p>Now I don't really want to duplicate all that functionality in the <code>edit()</code> method, so I figured <code>edit</code> could use the exact same template, and maybe just add an <code>id</code> field to the form so the <code>add</code> function knew what it was editing. But there's a couple problems with this</p>
<ol>
<li>Where would I set <code>article.id</code> in the <code>add</code> func? It would have to be after <code>form.save</code> because that's where the article gets created, but it would never even reach that, because the form is invalid due to unique constraints (unless the user edited everything). I can just remove the <code>is_valid</code> check, but then <code>form.save</code> fails instead.</li>
<li>If the form actually <em>is</em> invalid, the field I dynamically added in the edit function isn't preserved.</li>
</ol>
<p>So how do I deal with this?</p> | 1,854,453 | 2 | 0 | null | 2009-12-06 03:18:48.167 UTC | 41 | 2016-07-13 22:38:54.09 UTC | null | null | null | null | 65,387 | null | 1 | 48 | python|django|forms|logic | 53,365 | <p>If you are extending your form from a ModelForm, use the <code>instance</code> keyword argument. Here we pass either an existing <code>instance</code> or a new one, depending on whether we're editing or adding an existing article. In both cases the <code>author</code> field is set on the instance, so <code>commit=False</code> is not required. Note also that I'm assuming only the author may edit their own articles, hence the HttpResponseForbidden response.</p>
<pre><code>from django.http import HttpResponseForbidden
from django.shortcuts import get_object_or_404, redirect, render, reverse
@login_required
def edit(request, id=None, template_name='article_edit_template.html'):
if id:
article = get_object_or_404(Article, pk=id)
if article.author != request.user:
return HttpResponseForbidden()
else:
article = Article(author=request.user)
form = ArticleForm(request.POST or None, instance=article)
if request.POST and form.is_valid():
form.save()
# Save was successful, so redirect to another page
redirect_url = reverse(article_save_success)
return redirect(redirect_url)
return render(request, template_name, {
'form': form
})
</code></pre>
<p>And in your <code>urls.py</code>:</p>
<pre><code>(r'^article/new/$', views.edit, {}, 'article_new'),
(r'^article/edit/(?P<id>\d+)/$', views.edit, {}, 'article_edit'),
</code></pre>
<p>The same <code>edit</code> view is used for both adds and edits, but only the edit url pattern passes an id to the view. To make this work well with your form you'll need to omit the <code>author</code> field from the form:</p>
<pre><code>class ArticleForm(forms.ModelForm):
class Meta:
model = Article
exclude = ('author',)
</code></pre> |
53,569,884 | angular router navigate then reload | <p>So I want to reload the app after navigating to a specific route ..</p>
<p>I use router.navigate to navigate to certain route based on user role and that works fine but I have to reload the page after routing if coming from sign in page (not every time user opens that certain route) - and reloading here is to update page language depending on user's language </p>
<p>so what i tried to do is </p>
<pre><code> else if(this.sp.role === 'Admin') {
console.log('ooo')
this.router.navigate(['/admin/dashboard']);
this.window.location.reload();
</code></pre>
<p>but that reloads the sign in page </p> | 55,394,344 | 4 | 1 | null | 2018-12-01 10:28:35.347 UTC | 5 | 2022-07-06 15:46:19.383 UTC | null | null | null | null | 9,832,888 | null | 1 | 31 | angular|routing|angular5|angular6|angular2-routing | 65,019 | <p>Simple</p>
<pre><code>this.router.navigate(['path/to'])
.then(() => {
window.location.reload();
});
</code></pre> |
53,782,085 | AssemblyVersion using * fails with error "wildcards, which are not compatible with determinism?" | <p>I can't use <code>*</code> in assembly version; when I do I get the following compilation error:</p>
<blockquote>
<p>The specified version string contains wildcards, which are not
compatible with determinism. Either remove wildcards from the version
string, or disable determinism for this compilation</p>
</blockquote>
<p><img src="https://i.stack.imgur.com/uE5af.png" alt="SCRAssembly" /></p> | 54,175,668 | 3 | 2 | null | 2018-12-14 14:56:51.45 UTC | 14 | 2022-01-20 21:48:58.64 UTC | 2022-01-20 21:48:58.64 UTC | null | 3,195,477 | null | 5,656,964 | null | 1 | 90 | c#|visual-studio|.net-core | 41,931 | <p>I guess you were able to use it earlier and can't anymore.</p>
<p>Reason - There have been some changes to Visual Studio as the new project files now default to 'True' for 'Deterministic' attribute.</p>
<p>Solution - as Hans Passant says, edit project file by hand. Cons to doing it, also as he says.</p>
<p>Specifically, edit <code>.csproj</code> to <code><Deterministic>false</Deterministic></code>.</p>
<p>Source - <a href="https://marinovdh.wordpress.com/2018/10/22/68/" rel="noreferrer">https://marinovdh.wordpress.com/2018/10/22/68/</a></p> |
5,710,140 | How do I create a MVC Razor template for DisplayFor() | <p>I have a couple of properties in my view model that are display-only but I need to retrieve their values using jQuery to perform a calculation on the page. The standard <em>Html.DisplayFor()</em> method just writes their value to the page. I want to create a razor template that will allow me to render each element as:</p>
<pre><code><span id="ElementsId">Element's value</span>
</code></pre>
<p>I know I can specify a template in <em>Html.DisplayFor()</em> to use a particular template for rendering the property but within that template how do I identify the <em>id</em> attribute to write into the <em>span</em> tag?</p>
<pre><code>@Html.DisplayFor(model => model.Element, "MyTemplate");
</code></pre> | 5,722,732 | 6 | 0 | null | 2011-04-18 23:55:44.483 UTC | 9 | 2020-08-04 20:43:12.98 UTC | 2020-08-04 20:43:12.98 UTC | null | 132,599 | null | 132,599 | null | 1 | 32 | asp.net-mvc|asp.net-core|asp.net-mvc-4|asp.net-mvc-3|razor | 44,012 | <p>OK, I found it and it's actually very simple. In my <em>Views\Shared\DisplayTemplates</em> folder I have <em>Reading.cshtml</em> containing the following:</p>
<pre><code>@model System.Int32
<span id="@ViewData.ModelMetadata.PropertyName">@Model</span>
</code></pre>
<p>This renders the correct tag using the name of the property as the <em>id</em> attribute and the value of the property as the contents:</p>
<pre><code><span id="Reading">1234</span>
</code></pre>
<p>In the view file this can be called using the following:</p>
<pre><code>@Html.DisplayFor(model => model.Reading, "Reading")
</code></pre>
<p>Or if the model property is decorated with <em>UIHint("Reading")</em> then the template name can be left out of the call to <em>DisplayFor()</em> and it will still render using the template:</p>
<pre><code>@Html.DisplayFor(model => model.Reading)
</code></pre>
<p>This should work equally well with custom editor templates.</p> |
5,898,448 | How to add a new line without breaking the current line? | <p>In vim, I can do this in command mode by typing 'o', which will add a new line below the cursor, and enter the insert mode.</p>
<p>Is there an equivalent in emacs?</p> | 8,539,038 | 8 | 0 | null | 2011-05-05 13:26:04.61 UTC | 10 | 2019-08-02 20:02:41.88 UTC | 2019-06-19 10:37:25.567 UTC | null | 2,311,867 | null | 740,014 | null | 1 | 42 | emacs | 21,910 | <p>The command <kbd>C-o</kbd> <code>open-line</code> that others have suggested is not quite the same as <kbd>o</kbd> in vi, because it splits the current line and lets the cursor remain in the current line.</p>
<p>You get the exact same effect as vi's <kbd>o</kbd> with two strokes: <kbd>C-e</kbd> <kbd>RET</kbd>, which moves the cursor to the end of the current line and then inserts a new line, which leaves the cursor at the beginning of that line.</p>
<p>You could bind that sequence to a key of its own (perhaps overriding the existing definition of <kbd>C-o</kbd>), but I doubt if it's worth the trouble.</p>
<p>(Incidentally, the symmetric sequence <kbd>C-a</kbd> <kbd>RET</kbd> gives you the effect of vi's capital <kbd>O</kbd>, inserting a line <em>before</em> the current line.)</p> |
39,357,415 | VueJS Read Dom Attributes | <p>I want to get the href attribute to the button click event.</p>
<pre><code><a v-on:click.prevent="func($event)" href="/user/all/2">
<i class="fa fa-edit"></i>
<span>Get Data</span>
</a>
</code></pre>
<p>Main.JS Files</p>
<pre><code>new Vue({
el: 'body',
methods: {
func: function (event) {
element = event.target;
console.log(element); // Output : Select span|i|a element
href = element.getAttribute('href');
},
}
});
</code></pre>
<p>Target event does not select a element. It selects the clicked element.</p> | 39,357,594 | 3 | 1 | null | 2016-09-06 20:34:32.33 UTC | 2 | 2019-07-22 14:45:43.82 UTC | null | null | null | null | 2,210,147 | null | 1 | 7 | javascript|vue.js|vue-resource|vue-component | 38,073 | <p>You want <code>event.currentTarget</code>, not <code>event.target</code>. Here's a fiddle of the situation: <a href="https://jsfiddle.net/crswll/553jtefh/" rel="noreferrer">https://jsfiddle.net/crswll/553jtefh/</a></p> |
25,157,451 | SPARK SQL - case when then | <p>I'm new to SPARK-SQL. Is there an equivalent to "CASE WHEN 'CONDITION' THEN 0 ELSE 1 END" in SPARK SQL ?</p>
<p><code>select case when 1=1 then 1 else 0 end from table</code></p>
<p>Thanks
Sridhar</p> | 25,333,239 | 6 | 1 | null | 2014-08-06 10:01:30.83 UTC | 11 | 2022-04-19 15:16:03.097 UTC | 2016-10-31 21:16:54.973 UTC | user6022341 | null | null | 3,279,189 | null | 1 | 46 | sql|apache-spark | 140,263 | <p><strong>Before Spark 1.2.0</strong></p>
<p>The supported syntax (which I just tried out on Spark 1.0.2) seems to be </p>
<pre><code>SELECT IF(1=1, 1, 0) FROM table
</code></pre>
<p>This recent thread <a href="http://apache-spark-user-list.1001560.n3.nabble.com/Supported-SQL-syntax-in-Spark-SQL-td9538.html" rel="noreferrer">http://apache-spark-user-list.1001560.n3.nabble.com/Supported-SQL-syntax-in-Spark-SQL-td9538.html</a> links to the SQL parser source, which may or may not help depending on your comfort with Scala. At the very least the list of keywords starting (at time of writing) on line 70 should help. </p>
<p>Here's the direct link to the source for convenience: <a href="https://github.com/apache/spark/blob/master/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/SqlParser.scala" rel="noreferrer">https://github.com/apache/spark/blob/master/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/SqlParser.scala</a>.</p>
<p><strong>Update for Spark 1.2.0 and beyond</strong></p>
<p>As of Spark 1.2.0, the more traditional syntax is supported, in response to <a href="https://issues.apache.org/jira/browse/SPARK-3813" rel="noreferrer">SPARK-3813</a>: search for "CASE WHEN" in the <a href="https://github.com/apache/spark/blob/master/sql/core/src/test/scala/org/apache/spark/sql/SQLQuerySuite.scala" rel="noreferrer">test source</a>. For example:</p>
<pre><code>SELECT CASE WHEN key = 1 THEN 1 ELSE 2 END FROM testData
</code></pre>
<p><strong>Update for most recent place to figure out syntax from the SQL Parser</strong></p>
<p>The parser source can now be found <a href="https://github.com/apache/spark/blob/master/sql/catalyst/src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBase.g4" rel="noreferrer">here</a>.</p>
<p><strong>Update for more complex examples</strong></p>
<p>In response to a question below, the modern syntax supports complex Boolean conditions.</p>
<pre><code>SELECT
CASE WHEN id = 1 OR id = 2 THEN "OneOrTwo" ELSE "NotOneOrTwo" END AS IdRedux
FROM customer
</code></pre>
<p>You can involve multiple columns in the condition.</p>
<pre><code>SELECT
CASE WHEN id = 1 OR state = 'MA'
THEN "OneOrMA"
ELSE "NotOneOrMA" END AS IdRedux
FROM customer
</code></pre>
<p>You can also nest CASE WHEN THEN expression.</p>
<pre><code>SELECT
CASE WHEN id = 1
THEN "OneOrMA"
ELSE
CASE WHEN state = 'MA' THEN "OneOrMA" ELSE "NotOneOrMA" END
END AS IdRedux
FROM customer
</code></pre> |
48,956,743 | Embedded Postgres for Spring Boot Tests | <p>I'm building a Spring Boot app, backed by Postgres, using Flyway for database migrations. I've been bumping up against issues where I cannot produce a migration that generates the desired outcome in both Postgres, and the embedded unit test database (even with Postgres compatibility mode enabled). So I am looking at using embedded Postgres for unit tests.</p>
<p>I came across <a href="https://github.com/opentable/otj-pg-embedded" rel="noreferrer">an embedded postgres</a> implementation that looks promising, but don't really see how to set it up to run within Spring Boot's unit test framework only (for testing Spring Data repositories). How would one set this up using the mentioned tool or an alternative embedded version of Postgres?</p> | 49,011,982 | 5 | 3 | null | 2018-02-23 21:52:06.783 UTC | 24 | 2021-06-22 21:57:11.763 UTC | null | null | null | null | 168,212 | null | 1 | 39 | spring|postgresql|spring-boot|flyway | 60,192 | <p>I'm the author of the <a href="https://github.com/zonkyio/embedded-database-spring-test" rel="noreferrer">embedded-database-spring-test</a> library that was mentioned by @MartinVolejnik. I think the library should meet all your needs (PostgreSQL + Spring Boot + Flyway + integration testing). I'm really sorry that you're having some trouble, so I've created a <a href="https://github.com/tomix26/embedded-database-demo" rel="noreferrer">simple demo app</a> that demonstrates the use of the library together with Spring Boot framework. Below I summarized some basic steps that you need to do.</p>
<p><strong>Maven configuration</strong></p>
<p>Add the following maven dependency:</p>
<pre class="lang-xml prettyprint-override"><code><dependency>
<groupId>io.zonky.test</groupId>
<artifactId>embedded-database-spring-test</artifactId>
<version>2.0.1</version>
<scope>test</scope>
</dependency>
</code></pre>
<p><strong>Flyway configuration</strong></p>
<p>Add the following property to your application configuration:</p>
<pre class="lang-none prettyprint-override"><code># Sets the schemas managed by Flyway -> change the xxx value to the name of your schema
# flyway.schemas=xxx // for spring boot 1.x.x
spring.flyway.schemas=xxx // for spring boot 2.x.x
</code></pre>
<p>Further, make sure that you do not use <code>org.flywaydb.test.junit.FlywayTestExecutionListener</code>. Because the library has its own test execution listener that can optimize database initialization and this optimization has no effect if the <code>FlywayTestExecutionListener</code> is applied.</p>
<p><strong>Example</strong></p>
<p>An example of test class demonstrating the use of the embedded database:</p>
<pre class="lang-java prettyprint-override"><code>@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureEmbeddedDatabase
public class SpringDataJpaAnnotationTest {
@Autowired
private PersonRepository personRepository;
@Test
public void testEmbeddedDatabase() {
Optional<Person> personOptional = personRepository.findById(1L);
assertThat(personOptional).hasValueSatisfying(person -> {
assertThat(person.getId()).isNotNull();
assertThat(person.getFirstName()).isEqualTo("Dave");
assertThat(person.getLastName()).isEqualTo("Syer");
});
}
}
</code></pre> |
27,575,854 | Vectorizing a function in pandas | <p>I have a dataframe that contains a list of lat/lon coordinates:</p>
<pre><code>d = {'Provider ID': {0: '10001',
1: '10005',
2: '10006',
3: '10007',
4: '10008',
5: '10011',
6: '10012',
7: '10016',
8: '10018',
9: '10019'},
'latitude': {0: '31.215379379000467',
1: '34.22133455500045',
2: '34.795039606000444',
3: '31.292159523000464',
4: '31.69311635000048',
5: '33.595265517000485',
6: '34.44060759100046',
7: '33.254429322000476',
8: '33.50314015000049',
9: '34.74643089500046'},
'longitude': {0: ' -85.36146587999968',
1: ' -86.15937514799964',
2: ' -87.68507485299966',
3: ' -86.25539902199966',
4: ' -86.26549483099967',
5: ' -86.66531866799966',
6: ' -85.75726760699968',
7: ' -86.81407933399964',
8: ' -86.80242858299965',
9: ' -87.69893502799965'}}
df = pd.DataFrame(d)
</code></pre>
<p>My goal is to use the haversine function to figure out the distances between every item in KM:</p>
<pre><code>from math import radians, cos, sin, asin, sqrt
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
# 6367 km is the radius of the Earth
km = 6367 * c
return km
</code></pre>
<p>My goal is to get a dataframe that looks like the result_df below where the values are the distance between each provider id:</p>
<pre><code> result_df = pd.DataFrame(columns = df['Provider ID'], index=df['Provider ID'])
</code></pre>
<p>I can do this in a loop, however it's terribly slow. I'm looking for some help in converting this to a vectorized method:</p>
<pre><code>for first_hospital_coordinates in result_df.columns:
for second_hospital_coordinates in result_df['Provider ID']:
if first_hospital_coordinates == 'Provider ID':
pass
else:
L1 = df[df['Provider ID'] == first_hospital_coordinates]['latitude'].astype('float64').values
O1 = df[df['Provider ID'] == first_hospital_coordinates]['longitude'].astype('float64').values
L2 = df[df['Provider ID'] == second_hospital_coordinates]['latitude'].astype('float64').values
O2 = df[df['Provider ID'] == second_hospital_coordinates]['longitude'].astype('float64').values
distance = haversine(O1, L1, O2, L2)
crit = result_df['Provider ID'] == second_hospital_coordinates
result_df.loc[crit, first_hospital_coordinates] = distance
</code></pre> | 27,576,188 | 3 | 2 | null | 2014-12-20 00:39:03.037 UTC | 13 | 2014-12-23 04:12:15.367 UTC | null | null | null | null | 3,325,052 | null | 1 | 17 | python|pandas|dataframe | 47,888 | <p>To vectorize this code, you will need to operate on complete dataframe and not on the individual lats and longs. I have made an attempt at this. I need the result df and a new function h2, </p>
<pre><code>import numpy as np
def h2(df, p):
inrad = df.applymap(radians)
dlon = inrad.longitude-inrad.longitude[p]
dlat = inrad.latitude-inrad.latitude[p]
lat1 = pd.Series(index = df.index, data = [df.latitude[p] for i in range(len(df.index))])
a = np.sin(dlat/2)*np.sin(dlat/2) + np.cos(df.latitude) * np.cos(lat1) * np.sin(dlon/2)**2
c = 2 * 1/np.sin(np.sqrt(a))
km = 6367 * c
return km
df = df.set_index('Provider ID')
df = df.astype(float)
df2 = pd.DataFrame(index = df.index, columns = df.index)
for c in df2.columns:
df2[c] = h2(df, c)
print (df2)
</code></pre>
<p>This should yield, (I can't be sure if I have the correct answer... my goal was to vectorize the code)</p>
<pre><code>Provider ID 10001 10005 10006 10007 \
Provider ID
10001 inf 5.021936e+05 5.270062e+05 1.649088e+06
10005 5.021936e+05 inf 9.294868e+05 4.985233e+05
10006 5.270062e+05 9.294868e+05 inf 4.548412e+05
10007 1.649088e+06 4.985233e+05 4.548412e+05 inf
10008 1.460299e+06 5.777248e+05 5.246954e+05 3.638231e+06
10011 6.723581e+05 2.004199e+06 1.027439e+06 6.394402e+05
10012 4.559090e+05 3.265536e+06 7.573411e+05 4.694125e+05
10016 7.680036e+05 1.429573e+06 9.105474e+05 7.517467e+05
10018 7.096548e+05 1.733554e+06 1.020976e+06 6.701920e+05
10019 5.436342e+05 9.278739e+05 2.891822e+07 4.638858e+05
Provider ID 10008 10011 10012 10016 \
Provider ID
10001 1.460299e+06 6.723581e+05 4.559090e+05 7.680036e+05
10005 5.777248e+05 2.004199e+06 3.265536e+06 1.429573e+06
10006 5.246954e+05 1.027439e+06 7.573411e+05 9.105474e+05
10007 3.638231e+06 6.394402e+05 4.694125e+05 7.517467e+05
10008 inf 7.766998e+05 5.401081e+05 9.496953e+05
10011 7.766998e+05 inf 1.341775e+06 4.220911e+06
10012 5.401081e+05 1.341775e+06 inf 1.119063e+06
10016 9.496953e+05 4.220911e+06 1.119063e+06 inf
10018 8.236437e+05 1.242451e+07 1.226941e+06 5.866259e+06
10019 5.372119e+05 1.051748e+06 7.514774e+05 9.362341e+05
Provider ID 10018 10019
Provider ID
10001 7.096548e+05 5.436342e+05
10005 1.733554e+06 9.278739e+05
10006 1.020976e+06 2.891822e+07
10007 6.701920e+05 4.638858e+05
10008 8.236437e+05 5.372119e+05
10011 1.242451e+07 1.051748e+06
10012 1.226941e+06 7.514774e+05
10016 5.866259e+06 9.362341e+05
10018 inf 1.048895e+06
10019 1.048895e+06 inf
[10 rows x 10 columns]
</code></pre> |
44,389,464 | Align the form to the center in Bootstrap 4 | <p>I am trying to align the form to the center and keep it responsive. I have tried several ways but no success. I am trying to center all the text and the form. I am using Bootstrap v4. I am not sure if that helps. </p>
<p><a href="https://i.stack.imgur.com/hAWuS.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/hAWuS.jpg" alt="As you can see that the fr is not aligned to the center"></a></p>
<p>HTML:</p>
<pre><code><section id="cover">
<div id="cover-caption">
<div id="container">
<div class="col-sm-10 col-sm offset-1">
<h1 class="display-3">Welcome to Bootstrap 4</h1>
<div class="info-form">
<form action="" class="form-inline">
<div class="form-group">
<label class="sr-only">Name</label>
<input type="text" class="form-control" placeholder="Jane Doe">
</div>
<div class="form-group">
<label class="sr-only">Email</label>
<input type="text" class="form-control" placeholder="[email protected]">
</div>
<button type="submit" class="btn btn-success ">okay, go!</button>
</form>
</div>
<br>
<a href="#nav-main" class="btn btn-secondary-outline btn-sm" role="button">&darr;</a>
</div>
</div>
</div>
</section>
</code></pre>
<p>CSS:</p>
<pre><code>html,
body{
height: 100%;
}
#cover {
background: #222 url('../img/stars.jpg') center center no-repeat;
background-size: cover;
color: white;
height: 100%;
text-align: center;
display: flex;
align-items: center;
</code></pre>
<p>}</p>
<pre><code>#cover-caption {
width: 100%;
</code></pre>
<p>}</p> | 44,389,570 | 3 | 1 | null | 2017-06-06 12:00:27.117 UTC | 11 | 2020-12-27 17:23:55.157 UTC | 2017-06-06 13:27:35.11 UTC | null | 171,456 | null | 6,782,388 | null | 1 | 45 | html|css|twitter-bootstrap|bootstrap-4|twitter-bootstrap-4 | 150,003 | <p>You need to use the various <strong>Bootstrap 4</strong> centering methods...</p>
<ul>
<li>Use <code>text-center</code> for inline elements.</li>
<li>Use <code>justify-content-center</code> for flexbox elements (ie; <code>form-inline</code>)</li>
</ul>
<p><a href="https://codeply.com/go/Am5LvvjTxC" rel="noreferrer">https://codeply.com/go/Am5LvvjTxC</a></p>
<p>Also, to offset the column, the <code>col-sm-*</code> must be contained within a <code>.row</code>, and the <code>.row</code> must be in a container...</p>
<pre><code><section id="cover">
<div id="cover-caption">
<div id="container" class="container">
<div class="row">
<div class="col-sm-10 offset-sm-1 text-center">
<h1 class="display-3">Welcome to Bootstrap 4</h1>
<div class="info-form">
<form action="" class="form-inline justify-content-center">
<div class="form-group">
<label class="sr-only">Name</label>
<input type="text" class="form-control" placeholder="Jane Doe">
</div>
<div class="form-group">
<label class="sr-only">Email</label>
<input type="text" class="form-control" placeholder="[email protected]">
</div>
<button type="submit" class="btn btn-success ">okay, go!</button>
</form>
</div>
<br>
<a href="#nav-main" class="btn btn-secondary-outline btn-sm" role="button">↓</a>
</div>
</div>
</div>
</div>
</section>
</code></pre> |
32,837,195 | How to get list elements by index in elixir | <pre><code>{status, body} = File.read("/etc/hosts")
if status == :ok do
hosts = String.split body, "\n"
hosts = Enum.map(hosts, fn(host) -> line_to_host(host) end)
else
IO.puts "error reading: /etc/hosts"
end
</code></pre>
<p>I have the following elixir function where I read the /etc/hosts file and try to split it line by line using <code>String.split</code>.</p>
<p>Then I map through the line list of hosts and call line_to_host(host) for each. The line_to_host method splits the line by <code>" "</code> and then I want to set the <code>from</code> and <code>to</code> variable:</p>
<pre><code>def line_to_host(line) do
data = String.split line, " "
from = elem(data, 0) // doesn't work
to = elem(data, 1) // doesn't work either
%Host{from: from, to: to}
end
</code></pre>
<p>I looked through stackoverflow, the elixir docs and googled about how to get an list element at a specific index.
I know there is <code>head/tail</code> but there has to be a better way of getting list elements.</p>
<p><code>elem(list, index)</code> does exactly what I need but unfortunately it's not working with <code>String.split</code>.</p>
<p>How to get list/tuple elements by ID in elixir</p> | 32,837,669 | 2 | 2 | null | 2015-09-29 06:34:45.377 UTC | 4 | 2022-07-19 17:30:21.913 UTC | 2015-09-29 07:09:10.127 UTC | null | 1,268,652 | null | 1,268,652 | null | 1 | 45 | arrays|list|elixir | 37,122 | <p>You can use pattern matching for that:</p>
<pre><code>[from, to] = String.split line, " "
</code></pre>
<p>Maybe you want to add <code>parts: 2</code> option to ensure you will get only two parts in case there is more than one space in the line:</p>
<pre><code>[from, to] = String.split line, " ", parts: 2
</code></pre>
<p>There is also <a href="https://hexdocs.pm/elixir/Enum.html#at/3" rel="noreferrer"><code>Enum.at/3</code></a>, which would work fine here but is unidiomatic. The problem with <code>Enum.at</code> is that due to the list implementation in Elixir, it needs to traverse the entire list up to the requested index so it can be very inefficient for large lists.</p>
<hr />
<p><em>Edit: here's the requested example with <code>Enum.at</code>, but I would not use it in this case</em></p>
<pre><code>parts = String.split line, " "
from = Enum.at(parts, 0)
to = Enum.at(parts, 1)
</code></pre> |
10,557,316 | What is the best way to return a list<t> via a method? | <p>Suppose I have a method that returns a list of String names.</p>
<pre><code>public List<String> buildNamesList(){
List<String> namesList = new List<String>();
//add several names to the list
return namesList;
}
</code></pre>
<p>Now if I have a method that needs that namesList would returning it like so be the best way?</p>
<pre><code>public void someMethod(){
List<String> namesList = new List<String>();
namesList = buildNamesList();
//traverse namesList
}
</code></pre> | 10,557,349 | 4 | 1 | null | 2012-05-11 19:14:51.13 UTC | 2 | 2012-05-29 20:43:05.223 UTC | 2012-05-29 20:43:05.223 UTC | null | 1,039,608 | null | 1,345,632 | null | 1 | 1 | c#|.net|c#-4.0|collections | 58,015 | <p>If you are creating a new list in your buildNamesList method, I would just say: </p>
<pre><code>var namesList = buildNamesList();
</code></pre> |
10,808,324 | ROW NUMBER() OVER | <p>I came across a somewhat special syntax, could you help in figuring out what it means? Thank you.</p>
<pre><code>SELECT ROW NUMBER() OVER (ORDER BY Product.ProductID) FROM Product;
</code></pre>
<p>Also, this fails.
I'm particularly interested in the <code>ROW NUMBER() OVER</code> bit. It's the first time I've encountered the OVER keyword, too. </p>
<p>Please let me know if you need the full example. I shortened it a bit for the sake of clarity. </p> | 10,808,870 | 2 | 1 | null | 2012-05-29 23:57:02.85 UTC | null | 2014-10-07 11:05:52.96 UTC | 2012-05-30 01:30:16.357 UTC | null | 369 | null | 1,278,820 | null | 1 | 11 | sql-server|tsql | 56,945 | <p>The ROW_NUMBER() function requires the OVER(ORDER BY) expression to determine the order that the rows are numbered. The default order is ascending but descending can also be used. This function is useful for a variety of things like keeping track of rows when iterating through a set of records since T-SQL does not allow a cursor to be retrieved outside of T-SQL.
@tunimise fasipe is correct, you are missing the _ </p> |
7,269,076 | Spin UIImageView continuously | <p>I am having a problem while trying to rotate <code>UIImageview</code> continuously with a ball's image inside. I would like this ball to spin continuously on its center axis.
I have tried using <code>CGAffineTransform</code> but it didn't work.</p>
<p>Please help!</p> | 12,112,975 | 2 | 1 | null | 2011-09-01 10:32:10.46 UTC | 10 | 2016-07-18 21:16:12.857 UTC | 2011-09-01 10:48:28.2 UTC | null | 50,122 | null | 923,290 | null | 1 | 16 | iphone|objective-c|ios|cocoa-touch|animation | 11,768 | <p>This may be an old Q but it's near the top of search results for the topic. Here's a more cut and dry solution: (make sure to import QuartzCore/QuartzCore.h) </p>
<pre><code>CABasicAnimation *rotation;
rotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
rotation.fromValue = [NSNumber numberWithFloat:0];
rotation.toValue = [NSNumber numberWithFloat:(2*M_PI)];
rotation.duration = 1.1; // Speed
rotation.repeatCount = HUGE_VALF; // Repeat forever. Can be a finite number.
[yourView.layer addAnimation:rotation forKey:@"Spin"];
</code></pre>
<p>Then, to <s>stop</s> remove/reset the animation: (see comments for how to stop-in-place)</p>
<pre><code>[yourView.layer removeAnimationForKey:@"Spin"];
</code></pre>
<p>In swift:</p>
<pre><code>let rotation = CABasicAnimation(keyPath: "transform.rotation")
rotation.fromValue = 0
rotation.toValue = 2 * M_PI
rotation.duration = 1.1
rotation.repeatCount = Float.infinity
view.layer.addAnimation(rotation, forKey: "Spin")
</code></pre> |
7,533,146 | How do I select literal values in an sqlalchemy query? | <p>I have a query which looks like this:</p>
<pre><code>query = session.query(Item) \
.filter(Item.company_id == company_id) \
.order_by(Item.id)
</code></pre>
<p>It's a pretty basic query. In addition to pulling out the values for the Item, I want to append an additional value into the mix, and have it returned to me. In raw SQL, I would do this:</p>
<pre><code>SELECT *, 0 as subscribed
FROM items
WHERE company_id = 34
ORDER BY id
</code></pre>
<p>How can I manually add that value via sqlalchemy?</p> | 7,546,802 | 2 | 0 | null | 2011-09-23 18:12:02.56 UTC | 8 | 2018-06-10 20:29:07.717 UTC | 2018-06-10 20:29:07.717 UTC | null | 918,959 | null | 609,079 | null | 1 | 60 | python|sqlalchemy | 43,201 | <p>You'll need to use a <a href="http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.literal_column" rel="noreferrer"><code>literal_column</code></a>, which looks a bit like this:</p>
<pre><code>sqlalchemy.orm.Query(Item, sqlalchemy.sql.expression.literal_column("0"))
</code></pre>
<p>Beware that the <code>text</code> argument is inserted into the query without any transformation; this may expose you to a SQL Injection vulnerability if you accept values for the text parameter from outside your application. If that's something you need, you'll want to use <a href="http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.bindparam" rel="noreferrer"><code>bindparam</code></a>, which is about as easy to use; but you will have to invent a name:</p>
<pre><code>sqlalchemy.orm.Query(Item, sqlalchemy.sql.expression.bindparam("zero", 0))
</code></pre> |
23,033,473 | Error: Most middleware (like json) is no longer bundled with Express and must be installed separately. Please see | <p>i move my source window to ubuntu :</p>
<p>Error: Most middleware (like json) is no longer bundled with Express and must be installed separately. Please see <a href="https://github.com/senchalabs/connect#middleware">https://github.com/senchalabs/connect#middleware</a>.</p>
<p>this is my source thank you</p>
<pre><code>var http = require('http');
var fs = require('fs');
var express = require('express');
var mysql = require('mysql');
var ejs = require('ejs');
var app = express();
app.use(express.bodyParser());
app.use(app.router);
</code></pre> | 23,043,351 | 3 | 1 | null | 2014-04-12 17:00:27.537 UTC | 5 | 2019-02-18 11:18:17.243 UTC | 2015-10-06 05:51:37.487 UTC | null | 3,527,287 | null | 3,527,287 | null | 1 | 39 | mysql|json|node.js|express | 45,018 | <p>There are a number of changes with express 4.x. Like the error says, all of the middleware has been removed.</p>
<p>Update your package.json to include the "new" packages, a basic list can be found <a href="https://github.com/senchalabs/connect#middleware">here</a> and a full list <a href="https://github.com/expressjs">here</a></p>
<p>Using your code from above, you would just need the following:</p>
<pre><code>// package.json
{
"dependencies":
{
"express":"*",
"body-parser":"*"
}
}
</code></pre>
<p>Then update your source to reflect the new changes:</p>
<pre><code>// app.js
var http = require('http'),
fs = require('fs'),
express = require('express'),
bodyParser = require('body-parser'),
mysql = require('mysql'),
ejs = require('ejs');
var app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
</code></pre>
<p>Note that app.use(app.router) has been removed as well.</p> |
31,547,657 | How can I solve system of linear equations in SymPy? | <p>Sorry, I am pretty new to sympy and python in general.</p>
<p>I want to solve the following underdetermined linear system of equations:</p>
<pre><code>x + y + z = 1
x + y + 2z = 3
</code></pre> | 31,547,816 | 5 | 3 | null | 2015-07-21 19:12:00.323 UTC | 8 | 2020-01-27 13:34:04.07 UTC | 2015-07-21 19:36:41.41 UTC | null | 2,496,982 | null | 5,140,585 | null | 1 | 48 | python|math|sympy | 53,873 | <p>SymPy recently got a new Linear system solver: <code>linsolve</code> in <code>sympy.solvers.solveset</code>, you can use that as follows:</p>
<pre><code>In [38]: from sympy import *
In [39]: from sympy.solvers.solveset import linsolve
In [40]: x, y, z = symbols('x, y, z')
</code></pre>
<p><strong>List of Equations Form:</strong> </p>
<pre><code>In [41]: linsolve([x + y + z - 1, x + y + 2*z - 3 ], (x, y, z))
Out[41]: {(-y - 1, y, 2)}
</code></pre>
<p><strong>Augmented Matrix Form:</strong></p>
<pre><code>In [59]: linsolve(Matrix(([1, 1, 1, 1], [1, 1, 2, 3])), (x, y, z))
Out[59]: {(-y - 1, y, 2)}
</code></pre>
<p><strong>A*x = b Form</strong></p>
<pre><code>In [59]: M = Matrix(((1, 1, 1, 1), (1, 1, 2, 3)))
In [60]: system = A, b = M[:, :-1], M[:, -1]
In [61]: linsolve(system, x, y, z)
Out[61]: {(-y - 1, y, 2)}
</code></pre>
<p><strong>Note</strong>: Order of solution corresponds the order of given symbols.</p> |
31,314,245 | A timeout occured after 30000ms selecting a server using CompositeServerSelector | <p>I try to deploy my Mongo database in Mongolabs, everything works fine, and I create a new database. Please see my connectionstring.</p>
<pre><code> public DbHelper()
{
MongoClientSettings settings = new MongoClientSettings()
{
Credentials = new MongoCredential[] { MongoCredential.CreateCredential("dbname", "username", "password") },
Server = new MongoServerAddress("ds011111.mongolab.com", 11111),
//ConnectTimeout = new TimeSpan(30000)
};
Server = new MongoClient(settings).GetServer();
DataBase = Server.GetDatabase(DatabaseName);
}
</code></pre>
<p>but when I try to connect the database it's shows error like:</p>
<p><img src="https://i.stack.imgur.com/CwR69.png" alt="enter image description here"></p> | 31,468,224 | 11 | 4 | null | 2015-07-09 10:01:32.99 UTC | 3 | 2022-04-11 21:56:57.68 UTC | 2018-06-10 13:34:28.97 UTC | null | 472,495 | null | 1,115,885 | null | 1 | 30 | c#|mongodb|replication|mlab|nosql | 65,279 | <p>I am replacing the connection string method in like below. </p>
<pre><code>new MongoClient("mongodb://username:[email protected]:11111/db-name")
</code></pre>
<p>Now it's solved.</p>
<p>Please see the answer from Paul Lemke.</p> |
37,613,611 | multiple inputs on logstash jdbc | <p>I am using logstash jdbc to keep the things syncd between mysql and elasticsearch. Its working fine for one table. But now I want to do it for multiple tables. Do I need to open multiple in terminal</p>
<pre><code>logstash agent -f /Users/logstash/logstash-jdbc.conf
</code></pre>
<p>each with a select query or do we have a better way of doing it so we can have multiple tables being updated.</p>
<p>my config file</p>
<pre><code>input {
jdbc {
jdbc_driver_library => "/Users/logstash/mysql-connector-java-5.1.39-bin.jar"
jdbc_driver_class => "com.mysql.jdbc.Driver"
jdbc_connection_string => "jdbc:mysql://localhost:3306/database_name"
jdbc_user => "root"
jdbc_password => "password"
schedule => "* * * * *"
statement => "select * from table1"
}
}
output {
elasticsearch {
index => "testdb"
document_type => "table1"
document_id => "%{table_id}"
hosts => "localhost:9200"
}
}
</code></pre> | 37,613,839 | 3 | 2 | null | 2016-06-03 11:47:57.607 UTC | 14 | 2019-11-11 18:49:34.437 UTC | null | null | null | null | 295,189 | null | 1 | 17 | jdbc|elasticsearch|logstash|logstash-configuration | 23,208 | <p>You can definitely have a single config with multiple <code>jdbc</code> input and then parametrize the <code>index</code> and <code>document_type</code> in your <code>elasticsearch</code> output depending on which table the event is coming from.</p>
<pre><code>input {
jdbc {
jdbc_driver_library => "/Users/logstash/mysql-connector-java-5.1.39-bin.jar"
jdbc_driver_class => "com.mysql.jdbc.Driver"
jdbc_connection_string => "jdbc:mysql://localhost:3306/database_name"
jdbc_user => "root"
jdbc_password => "password"
schedule => "* * * * *"
statement => "select * from table1"
type => "table1"
}
jdbc {
jdbc_driver_library => "/Users/logstash/mysql-connector-java-5.1.39-bin.jar"
jdbc_driver_class => "com.mysql.jdbc.Driver"
jdbc_connection_string => "jdbc:mysql://localhost:3306/database_name"
jdbc_user => "root"
jdbc_password => "password"
schedule => "* * * * *"
statement => "select * from table2"
type => "table2"
}
# add more jdbc inputs to suit your needs
}
output {
elasticsearch {
index => "testdb"
document_type => "%{type}" # <- use the type from each input
hosts => "localhost:9200"
}
}
</code></pre> |
28,385,666 | Numpy: use reshape or newaxis to add dimensions | <p>Either <code>ndarray.reshape</code> or <code>numpy.newaxis</code> can be used to add a new dimension to an array. They both seem to create a view, is there any reason or advantage to use one instead of the other?</p>
<pre><code>>>> b
array([ 1., 1., 1., 1.])
>>> c = b.reshape((1,4))
>>> c *= 2
>>> c
array([[ 2., 2., 2., 2.]])
>>> c.shape
(1, 4)
>>> b
array([ 2., 2., 2., 2.])
>>> d = b[np.newaxis,...]
>>> d
array([[ 2., 2., 2., 2.]])
>>> d.shape
(1, 4)
>>> d *= 2
>>> b
array([ 4., 4., 4., 4.])
>>> c
array([[ 4., 4., 4., 4.]])
>>> d
array([[ 4., 4., 4., 4.]])
>>>
</code></pre>
<p>`</p> | 28,385,957 | 2 | 1 | null | 2015-02-07 18:15:44.737 UTC | 16 | 2018-11-25 21:34:29.083 UTC | null | null | null | null | 2,823,755 | null | 1 | 24 | python|numpy | 24,017 | <p>I don't see evidence of much difference. You could do a time test on very large arrays. Basically both fiddle with the shape, and possibly the strides. <code>__array_interface__</code> is a nice way of accessing this information. For example:</p>
<pre><code>In [94]: b.__array_interface__
Out[94]:
{'data': (162400368, False),
'descr': [('', '<f8')],
'shape': (5,),
'strides': None,
'typestr': '<f8',
'version': 3}
In [95]: b[None,:].__array_interface__
Out[95]:
{'data': (162400368, False),
'descr': [('', '<f8')],
'shape': (1, 5),
'strides': (0, 8),
'typestr': '<f8',
'version': 3}
In [96]: b.reshape(1,5).__array_interface__
Out[96]:
{'data': (162400368, False),
'descr': [('', '<f8')],
'shape': (1, 5),
'strides': None,
'typestr': '<f8',
'version': 3}
</code></pre>
<p>Both create a view, using the same <code>data</code> buffer as the original. Same shape, but reshape doesn't change the <code>strides</code>. <code>reshape</code> lets you specify the <code>order</code>.</p>
<p>And <code>.flags</code> shows differences in the <code>C_CONTIGUOUS</code> flag.</p>
<p><code>reshape</code> may be faster because it is making fewer changes. But either way the operation shouldn't affect the time of larger calculations much. </p>
<p>e.g. for large <code>b</code></p>
<pre><code>In [123]: timeit np.outer(b.reshape(1,-1),b)
1 loops, best of 3: 288 ms per loop
In [124]: timeit np.outer(b[None,:],b)
1 loops, best of 3: 287 ms per loop
</code></pre>
<hr>
<p>Interesting observation that: <code>b.reshape(1,4).strides -> (32, 8)</code></p>
<p>Here's my guess. <code>.__array_interface__</code> is displaying an underlying attribute, and <code>.strides</code> is more like a property (though it may all be buried in C code). The default underlying value is <code>None</code>, and when needed for calculation (or display with <code>.strides</code>) it calculates it from the shape and item size. <code>32</code> is the distance to the end of the 1st row (4x8). <code>np.ones((2,4)).strides</code> has the same <code>(32,8)</code> (and <code>None</code> in <code>__array_interface__</code>.</p>
<p><code>b[None,:]</code> on the other hand is preparing the array for broadcasting. When broadcasted, existing values are used repeatedly. That's what the <code>0</code> in <code>(0,8)</code> does. </p>
<pre><code>In [147]: b1=np.broadcast_arrays(b,np.zeros((2,1)))[0]
In [148]: b1.shape
Out[148]: (2, 5000)
In [149]: b1.strides
Out[149]: (0, 8)
In [150]: b1.__array_interface__
Out[150]:
{'data': (3023336880L, False),
'descr': [('', '<f8')],
'shape': (2, 5),
'strides': (0, 8),
'typestr': '<f8',
'version': 3}
</code></pre>
<p><code>b1</code> displays the same as <code>np.ones((2,5))</code> but has only 5 items.</p>
<p><code>np.broadcast_arrays</code> is a function in <code>/numpy/lib/stride_tricks.py</code>. It uses <code>as_strided</code> from the same file. These functions directly play with the shape and strides attributes.</p> |
2,100,272 | get json using php | <p>I need to get the json data from,
<a href="http://vortaro.us.to/ajax/epo/eng/" rel="noreferrer">http://vortaro.us.to/ajax/epo/eng/</a> + 'word'+ "/?callback=?"
working example (not enough reputation)</p>
<p>I know how to do it in javascript, But I need my php file to get this data, It needs to be server side, Thanks I'm new I have spent all day trying to figure this out. fopen and fread isn't working, </p>
<pre><code><?php
$vorto = $_GET['vorto']; // Get the Word from Outer Space and Search for it!
if (isset($vorto))
{
echo $vorto;
} else {
$Help = "No Vorto -> add ?vorto=TheWordYouWant to the end of this website";
echo $Help;
}
$url1 = "http://vortaro.us.to/ajax/epo/eng/";
$url2 = "/?callback=?";
$finalurl= $url1 . $vorto . $url2;
/*
PLEASE HELP
$v1 = fopen($finalurl ,"r");
echo $v1;
$frv1 = fread($v1,filesize($v1));
echo $frv1 ;
*/
?>
</code></pre> | 2,100,310 | 3 | 0 | null | 2010-01-20 09:34:17.27 UTC | 2 | 2015-12-12 14:16:29.89 UTC | 2010-01-20 09:37:19.243 UTC | null | 254,537 | null | 254,537 | null | 1 | 21 | php|json | 69,708 | <p><a href="http://be2.php.net/file_get_contents" rel="noreferrer">file_get_contents()</a> can be used on a URL. A simple and convenient way to handle http page download.</p>
<p>That done, you can use <a href="http://be2.php.net/manual/en/function.json-decode.php" rel="noreferrer">json_decode()</a> to parse the data into something useful.</p> |
8,814,811 | Remove blank values from array using C# | <p>How can I remove blank values from an array?</p>
<p>For example:</p>
<pre><code>string[] test={"1","","2","","3"};
</code></pre>
<p>in this case, is there any method available to remove blank values from the array using C#?</p>
<p>At the end, I want to get an array in this format:</p>
<pre><code>test={"1","2","3"};
</code></pre>
<p>which means 2 values removed from the array and eventually I get 3.</p> | 8,814,841 | 5 | 1 | null | 2012-01-11 05:55:28.52 UTC | 11 | 2021-08-12 10:12:44.963 UTC | 2020-11-04 01:11:13.113 UTC | null | 1,402,846 | null | 941,939 | null | 1 | 85 | c# | 151,557 | <p>If you are using .NET 3.5+ you could use LINQ (Language INtegrated Query).</p>
<pre><code>test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray();
</code></pre> |
734,255 | What is the difference between a site and an app in Django? | <p>I know a site can have many apps but all the examples I see have the site called "mysite". I figured the site would be the name of your site, like StackOverflow for example. </p>
<p>Would you do that and then have apps like "authentication", "questions", and "search"? Or would you really just have a site called mysite with one app called StackOverflow?</p> | 734,321 | 4 | 0 | null | 2009-04-09 13:35:00.037 UTC | 9 | 2010-04-19 04:21:29.2 UTC | null | null | null | null | 31,169 | null | 1 | 26 | python|django | 4,891 | <p>Django actually has 3 concepts here:</p>
<ul>
<li><p><strong>Project</strong> (I think this is what you're calling site): This is the directory that contains all the apps. They share a common runtime invocation and can refer to each other.</p></li>
<li><p><strong>App</strong>: This is a set of views, models, and templates. Apps are often designed so they can be plugged into another project.</p></li>
<li><p><strong>Site</strong>: You can designate different behaviour for an app based on the site (ie: URL) being visited. This way, the same "App" can customize itself based on whether or not the user has visited 'StackOverflow.com' or 'RackOverflow.com' (or whatever the IT-targeted version will be called), even though it's the same codebase that's handling the request.</p></li>
</ul>
<p>How you arrange these is really up to your project. In a complicated case, you might do:</p>
<pre><code>Project: StackOverflowProject
App: Web Version
Site: StackOverflow.com
Site: RackOverflow.com
App: XML API Version
Site: StackOverflow.com
Site: RackOverflow.com
Common non-app settings, libraries, auth, etc
</code></pre>
<p>Or, for a simpler project that wants to leverage an open-source plugin:</p>
<pre><code>Project: StackOverflowProject
App: Stackoverflow
(No specific use of the sites feature... it's just one site)
App: Plug-in TinyMCE editor with image upload
(No specific use of the sites feature)
</code></pre>
<p>Aside from the fact that there needs to be a Project, and at least one app, the arrangement is very flexible; you can adapt however suits best to help abstract and manage the complexity (or simplicity) of your deployment.</p> |
909,791 | Asynchronous processing or message queues in PHP (CakePHP) | <p>I am building a website in CakePHP that processes files uploaded though an XML-RPC API and though a web frontend. Files need to be scanned by ClamAV, thumbnails need to be generated, et cetera. All resource intensive work that takes some time for which the user should not have to wait. So, I am looking into asynchronous processing with PHP in general and CakePHP in particular.</p>
<p>I came across the <a href="http://blogs.bigfish.tv/adam/2009/02/16/new-cakephp-multitask-plugin/" rel="noreferrer">MultiTask plugin</a> for CakePHP that looks promising. I also came across various message queue implementations such as <a href="https://www.dropr.org/" rel="noreferrer">dropr</a> and <a href="http://xph.us/software/beanstalkd/" rel="noreferrer">beanstalkd</a>. Of course, I will also need some kind of background process, probably implemented using a Cake Shell of some kind. I saw MultiTask using <a href="http://pear.php.net/package/PHP_Fork/docs" rel="noreferrer">PHP_Fork</a> to implement a multithreaded PHP daemon.</p>
<p>I need some advice on how to fit all these pieces together in the best way.</p>
<ul>
<li>Is it a good idea to have a long-running daemon written in PHP? What should I watch out for?</li>
<li>What are the advantage of external message queue implementations? The MultiTask plugin does not use an external message queue. It rolls it's own using a MySQL table to store tasks.</li>
<li>What message queue should I use? dropr? beanstalkd? Something else?</li>
<li>How should I implement the backend processor? Is a forking PHP daemon a good idea or just asking for trouble?</li>
</ul>
<p>My current plan is either to use the MultiTask plugin or to edit it to use beanstald instead of it's own MySQL table implementation. Jobs in the queue can simply consist of a task name and an array of parameters. The PHP daemon would watch for incoming jobs and pass them out to one of it's child threads. The would simply execute the CakePHP Task with the given parameters.</p>
<p>Any opinion, advice, comments, gotchas or flames on this?</p> | 940,459 | 4 | 1 | null | 2009-05-26 09:27:37.457 UTC | 28 | 2015-09-12 13:48:25.467 UTC | 2014-08-23 15:40:15.59 UTC | null | 1,267,663 | null | 103,202 | null | 1 | 33 | php|multithreading|cakephp|asynchronous|message-queue | 20,244 | <p>I've had excellent results with <a href="http://kr.github.com/beanstalkd/" rel="nofollow noreferrer">BeanstalkD</a> and a back-end written in PHP to retrieve jobs and then act on them. I wrapped the actual job-running in a bash-script to keep running if even if it exited (unless I do a '<code>exit(UNIQNUM);</code>', when the script checks it and will actually exit). In that way, the restarted PHP script clears down any memory that may have been used, and can start afresh every 25/50/100 jobs it runs.</p>
<p>A couple of the advantages of using it is that you can set priorities and delays into a BeanstalkD job - "run this at a lower priority, but don't start for 10 seconds". I've also queued a number of jobs up at the some time (run this now, in 5 seconds and again after 30 secs).</p>
<p>With the appropriate network configuration (and running it on an accessible IP address to the rest of your network), you can also run a beanstalkd deamon on one server, and have it polled from a number of other machines, so if there are a large number of tasks being generated, the work can be split off between servers. If a particular set of tasks needs to be run on a particular machine, I've created a 'tube' which is that machine's hostname, which should be unique within our cluster, if not globally (useful for file uploads). I found it worked perfectly for image resizing, often returning the finished smaller images to the file system before the webpage itself that would refer to it would refer to the URL it would be arriving at.</p>
<p>I'm actually about to start writing a series of articles on this very subject for my blog (including some techniques for code that I've already pushed several million live requests through) - My URL is linked from my <a href="https://stackoverflow.com/users/6216/topbit">user profile</a> here, on Stackoverflow.</p>
<p>(I've written a <a href="http://www.phpscaling.com/tag/beanstalkd/" rel="nofollow noreferrer">series of articles</a> on the subject of Beanstalkd and queuing of jobs)</p> |
771,861 | Insert SQL command with Datetime in MS-Access | <p>I am trying the following query in MS-Access 2007, but it fails on the time field.</p>
<pre><code>INSERT INTO LOG (
EMPLOYEECODE, STATUSID, LOCATIONID, TIME, DURATION,
SHIFTID, LATECOMING, EARLYGOING, LOGDATE, STATIONID
)
VALUES (
1, 1, 0, '4/21/2009 2:25:53 PM', 0,
8, 0, 1, '1/1/2009', 1
)
</code></pre>
<p>The <code>TIME</code> field is defined as a datetime.</p>
<p>Without the <code>TIME</code> field, the query works fine! </p>
<p>I've tried a number of different things, such as enclosing the datetime in hashes, quotes etc. However, the query still fails on the time field.</p>
<hr>
<p>Thank you guys! That almost got me fully there. I still kept getting the syntax error for the insert statement, but then on further googling, I realized that <code>TIME</code> might be a reserved keyword, so putting it on box brackets as <code>[TIME]</code> worked!</p> | 771,902 | 1 | 0 | null | 2009-04-21 09:48:00.59 UTC | 2 | 2017-06-20 16:58:50.003 UTC | 2015-04-29 12:32:27.86 UTC | null | 12,892 | null | 63,605 | null | 1 | 14 | ms-access|ms-access-2007 | 106,895 | <p>Date & Time input in access use <strong>#</strong>, since access can't do auto conversion from char/text into date or time in SQL Query (or access call it query), and you better use international standard for inputting date time which was <strong>YYYY-MM-DD HH:NN:SS</strong> (4-digit year, 2-digit month, 2-digit day, 2-digit hour, 2-digit minute, 2-digit second)</p>
<p>so for <strong>4/21/2009 2:25:53 PM</strong> use <strong>#2009-04-21 14:25:53#</strong></p>
<p>or if it still fail, you can use <strong>#'2009-04-21 14:25:53'#</strong></p>
<p>Edit: Above might be working if you enable ANSI 92 or using ADO/OLEDB as database interface, thanks David for pointing out</p>
<p>I suggest you use YYYY-MM-DD HH:NN:SS format and try it with single quotes (') before use # like i said above</p> |
19,547,419 | Errors in Windows - DWORD (GetLastError) vs HRESULT vs LSTATUS | <p>I'm doing some programming in Win32 + WTL, and I'm confused with the available types of errors.</p>
<p>In general, I want to check for an error, and feed it to AtlGetErrorDescription (which calls FormatMessage).</p>
<p>My questions are:</p>
<ol>
<li><p>What's the difference between:</p>
<ul>
<li><code>DWORD</code>, returned by <code>GetLastError</code>.</li>
<li><code>HRESULT</code>, returned by e.g. the <code>CAtlFile</code> wrapper, which uses <code>HRESULT_FROM_WIN32</code> to convert from <code>DWORD</code>.</li>
<li><code>LSTATUS</code>, returned by e.g. <code>RegCreateKeyEx</code>.</li>
</ul></li>
<li><p>Which types of errors can I feed to <code>FormatMessage</code>? Its signature indicates it accepts <code>HRESULT</code>, but there are lots of examples where the return value of <code>GetLastError</code> is directly passed to <code>FormatMessage</code>.</p></li>
</ol> | 19,548,610 | 1 | 0 | null | 2013-10-23 16:37:13.157 UTC | 9 | 2014-10-13 16:43:41.267 UTC | 2014-10-13 16:43:41.267 UTC | null | 2,604,492 | null | 2,604,492 | null | 1 | 23 | winapi|error-handling|wtl | 9,998 | <p>They just reflect different APIs used in Windows:</p>
<ul>
<li><p>GetLastError() returns a winapi error code. A simple number starting at 1. They are usually mapped from an underlying native api error code. Like ERROR_FILE_NOT_FOUND is mapped from the STATUS_OBJECT_NAME_NOT_FOUND file system driver error code. Winapi error codes are declared in the WinError.h SDK header file. You can count on getting a descriptive string from FormatMessage() with the FORMAT_MESSAGE_FROM_SYSTEM option.</p></li>
<li><p>An HRESULT is a COM error code. It is built up from three basic parts, the high bits indicate the severity, the middle bits encode the <em>facility</em> which indicates the source of the error, the low 16 bits encode an error number. The HRESULT_FROM_WIN32() macro is a helper macro to map a winapi error code to a COM error code. It just sets the severity to "fail", the facility code to 7 (winapi) and copies the error code into the low bits. There are a lot of possible COM error codes and only a few of them are convertible to a string by FormatMessage(). You should use the ISupportErrorInfo interface to ask if the COM server can provide a description of the error through IErrorInfo.</p></li>
<li><p>LSTATUS is obscure, RegCreateEx actually returns LONG, just the winapi error code. It does pop up in some shell wrapper functions, like SHGetValue(). It is often very unclear to me why the shell team does what it does.</p></li>
<li><p>Not mentioned in your question but worth noting are the error codes generated by the native api. They are documented in the ntstatus.h SDK header. The winapi is supposed to wrap the native api but these error codes do peek around the edges sometimes, particularly in exceptions. Most any programmer has seen the 0xc0000005 (STATUS_ACCESS_VIOLATION) exception code. 0xc00000fd matches this site's name. FormatMessage() can convert the common ones to a string as long as it wasn't a custom error code generated by a driver. There are several apis that use these kind of error codes, even though they run in user mode. Common examples are WIC and Media Foundation, otherwise without a strong hint why they preferred it this way. Getting a string for such an error code requires using FormatMessage with the FORMAT_MESSAGE_FROM_HMODULE option.</p></li>
</ul> |
3,139,477 | jQuery: Check if character is in string | <p>I want the simplest way to check if an underscore (_) is in a variable using jQuery and do something if is not..</p>
<pre><code>if ( '_ is not in var') {
// Do
}
</code></pre>
<p>Thanks!</p> | 3,139,485 | 2 | 0 | null | 2010-06-29 09:41:54.777 UTC | 4 | 2020-08-27 22:05:46.997 UTC | null | null | null | null | 63,651 | null | 1 | 25 | jquery|variables | 92,751 | <pre><code>var str = "i am a string with _";
if (str.indexOf('_') == -1) {
// will not be triggered because str has _..
}
</code></pre>
<p>and as spender said below on comment, jQuery is not a requirement..
<a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/String/indexOf" rel="noreferrer"><code>indexOf</code></a> is a native javascript</p> |
57,891,050 | How run build task automatically before debugging in Visual Studio Code? | <p>In VS Code I have to run the build task first and then start debugging, while in CLion I just click debug, then it builds automatically if necessary and starts debugging. Is there a way to automate this in VS Code as well?</p> | 57,892,509 | 2 | 0 | null | 2019-09-11 14:10:13.767 UTC | 9 | 2022-03-09 04:44:15.527 UTC | 2020-08-07 12:36:35.697 UTC | null | 2,019,689 | null | 9,835,695 | null | 1 | 34 | visual-studio-code | 16,722 | <h2>Adding a build task to the Launch.Json</h2>
<hr />
<p>What you are looking for is probably how to link a build task to your debug config. I'll try to illustrate the process below.</p>
<p><a href="https://i.stack.imgur.com/CGWpS.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CGWpS.png" alt="debug configs" /></a></p>
<p>To access your build configs, go to the Debug bar on the side (1), and press the gear icon to access your launch.json config file (2). You will need to add a pre-launch task under your configurations in that launch.json file, and link it to your build task (3).</p>
<h2>Defining the Build Task in Tasks.Json</h2>
<hr />
<p><a href="https://i.stack.imgur.com/8istp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8istp.png" alt="tasks.json file" /></a></p>
<p>Then, you will need to set up your build task, by running it with ctrl-shift-b.</p>
<p>If it already exists (as implied in your post), you can find it in your .vs-code folder in the tasks.json file. If you open that task.json file, you will find the build task in the list. All you need to do now is to take the 'label' of that task and place it in your launch.json in that pre-launch config.</p>
<p>Good luck!</p>
<h2>Appendix</h2>
<hr />
<p>Appendix added with examples for clean build and running configs in parallel following a shared pre-launch build.</p>
<p>Q: What to do if the build task fails, but the launch process starts with the old binary?</p>
<p>A: Potential solution given by @JoKing: add a new task that deletes the binary and execute this task before each build by requiring it in the build task with the "dependsOn" option. An example is given below for how it might look in the tasks.json file, <a href="https://github.com/Microsoft/vscode/issues/31731" rel="noreferrer">source</a></p>
<pre><code> "tasks": [
{
"taskName": "build",
"command": "tsc",
"group": {
"kind": "build",
"isDefault": true
},
"dependsOn": [
"build client",
"build server"
]
},
{
"taskName": "build client",
"command": "tsc",
"args": [
"-w",
"-p",
"${workspaceRoot}/src/typescript/client"
]
},
{
"taskName": "build server",
"command": "tsc",
"args": [
"-w",
"-p",
"${workspaceRoot}/src/typescript/server"
]
}
]
</code></pre>
<p>Q: I have multiple configurations, but want to run build task to run once before all the configurations, is it possible?</p>
<p>A: I have not personally set this up before, but <a href="https://code.visualstudio.com/docs/editor/debugging#_compound-launch-configurations" rel="noreferrer">compound launch configurations</a> may be what you are looking for. The example from that page has two configurations, 'Server' and 'Client', which can be launched in parallel while following the prelaunchTask ('defaultBuildTask').</p>
<pre><code>{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Server",
"program": "${workspaceFolder}/server.js"
},
{
"type": "node",
"request": "launch",
"name": "Client",
"program": "${workspaceFolder}/client.js"
}
],
"compounds": [
{
"name": "Server/Client",
"configurations": ["Server", "Client"],
"preLaunchTask": "${defaultBuildTask}"
}
]
}
</code></pre> |
2,322,413 | How do I escape the ERB tag in ERB | <p>I have a simple <code>fixture.yml</code> file:</p>
<pre><code>label:
body: "<%= variable %>"
</code></pre>
<p>The issue is that the ERB code is parsed as part of loading the fixture, whereas I actually want the body to be literally "<%= variable %>" (un-interpolated).</p>
<p>How do I escape the ERB tag?</p> | 2,322,435 | 1 | 0 | null | 2010-02-23 22:58:18.043 UTC | 17 | 2017-12-13 08:09:25.707 UTC | 2017-12-13 08:09:25.707 UTC | null | 3,787,051 | null | 200,394 | null | 1 | 85 | ruby-on-rails|unit-testing|erb|fixture | 18,281 | <p>Add a second <code>%</code> to the opening tag:</p>
<pre><code>label:
body: "<%%= variable %>"
</code></pre>
<p>The <code><%%</code> sequence is <a href="http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/classes/ERB.html" rel="noreferrer">valid ERB</a>, rendered as a literal <code><%</code>.</p> |
20,263,600 | Validation to allow space character only when followed by an alphabet | <p>I am trying to validate the textbox which has to allow space character only when followed by any alphabetic character. My code fails when only a space character is inserted. What is the mistake in my code. Suggestions pls..</p>
<p><strong>javascript :</strong></p>
<pre><code>function validate() {
var firstname = document.getElementById("FirstName");
var alpha = /^[a-zA-Z\s-, ]+$/;
if (firstname.value == "") {
alert('Please enter Name');
return false;
}
else if (!firstname.value.match(alpha)) {
alert('Invalid ');
return false;
}
else
{
return true;
}
}
</code></pre>
<p><strong>view:</strong></p>
<pre><code> @Html.TextBoxFor(m => m.FirstName, new { @class = "searchbox" })
<button type="submit" onclick="return validate();">Submit</button>
</code></pre>
<p><strong>Conditions I applied :</strong> <br/>
Eg: Arun Chawla - condition success <br/>
Eg: _ - condition fails (should not allow space character alone)</p> | 20,267,218 | 5 | 0 | null | 2013-11-28 10:31:12.617 UTC | 1 | 2021-11-11 00:33:42.087 UTC | 2013-11-28 12:35:25.95 UTC | null | 1,298,342 | null | 1,298,342 | null | 1 | 1 | javascript|jquery|asp.net|validation | 54,821 | <p>try following regex </p>
<pre><code> var alpha = /^[a-zA-Z-,]+(\s{0,1}[a-zA-Z-, ])*$/
</code></pre>
<p>First part forces an alphabetic char, and then allows space.</p> |
29,837,398 | Why does the lifetime name appear as part of the function type? | <p>I believe that this function declaration tells Rust that the lifetime of the function's output is the same as the lifetime of it's <code>s</code> parameter:</p>
<pre><code>fn substr<'a>(s: &'a str, until: u32) -> &'a str;
^^^^
</code></pre>
<p>It seems to me that the compiler only needs to know this(1):</p>
<pre><code>fn substr(s: &'a str, until: u32) -> &'a str;
</code></pre>
<p>What does the annotation <code><'a></code> after the function name mean? Why does the compiler need it, and what does it do with it?</p>
<hr>
<p>(1): I know it needs to know even less, due to lifetime elision. But this question is about specifying lifetime explicitly.</p> | 29,851,211 | 3 | 0 | null | 2015-04-24 01:55:57.687 UTC | 12 | 2020-01-01 16:36:49.097 UTC | 2015-04-24 02:10:45.957 UTC | null | 238,886 | null | 238,886 | null | 1 | 24 | rust|lifetime | 2,457 | <p>Let me expand on the previous answers…</p>
<blockquote>
<p>What does the annotation <'a> after the function name mean?</p>
</blockquote>
<p>I wouldn't use the word "annotation" for that. Much like <code><T></code> introduces a generic <em>type</em> parameter, <code><'a></code> introduces a generic <em>lifetime</em> parameter. You can't use any generic parameters without introducing them first and for generic functions this introduction happens right after their name. You can think of a generic function as a family of functions. So, essentially, you get one function for every combination of generic parameters. <code>substr::<'x></code> would be a specific member of that function family for some lifetime <code>'x</code>.</p>
<p>If you're unclear on when and why we have to be explicit about lifetimes, read on…</p>
<p>A lifetime parameter is always associated with all reference types. When you write</p>
<pre><code>fn main() {
let x = 28374;
let r = &x;
}
</code></pre>
<p>the compiler knows that x lives in the main function's scope enclosed with curly braces. Internally, it identifies this scope with some lifetime parameter. For us, it is unnamed. When you take the address of <code>x</code>, you'll get a value of a specific reference type. A reference type is kind of a member of a two dimensional family of reference types. One axis is the type of what the reference points to and the other axis is a lifetime that is used for two constraints:</p>
<ol>
<li>The lifetime parameter of a reference type represents an upper bound for how long you can hold on to that reference</li>
<li>The lifetime parameter of a reference type represents a lower bound for the lifetime of the things you can make the reference point to.</li>
</ol>
<p>Together, these constraints play a vital role in Rust's memory safety story. The goal here is to avoid dangling references. We would like to rule out references that point to some memory region we are not allowed to use anymore because that thing it used to point to does not exist anymore.</p>
<p>One potential source of confusion is probably the fact that lifetime parameters are invisible most of the time. But that does not mean they are not there. References <em>always</em> have a lifetime parameter in their type. But such a lifetime parameter does not have to have a name and most of the time we don't need to mention it anyways because the compiler can assign names for lifetime parameters automatically. This is called "lifetime elision". For example, in the following case, you don't <em>see</em> any lifetime parameters being mentioned:</p>
<pre><code>fn substr(s: &str, until: u32) -> &str {…}
</code></pre>
<p>But it's okay to write it like this. It's actually a short-cut syntax for the more explicit</p>
<pre><code>fn substr<'a>(s: &'a str, until: u32) -> &'a str {…}
</code></pre>
<p>Here, the compiler automatically assigns the same name to the "input lifetime" and the "output lifetime" because it's a very common pattern and most likely exactly what you want. Because this pattern is so common, the compiler lets us get away without saying anything about lifetimes. It <em>assumes</em> that this more explicit form is what we meant based on a couple of "lifetime elision" rules (which are at least documented <a href="https://github.com/rust-lang/rfcs/blob/master/text/0141-lifetime-elision.md" rel="noreferrer">here</a>)</p>
<p>There are situations in which <em>explicit</em> lifetime parameters are <em>not</em> optional. For example, if you write</p>
<pre><code>fn min<T: Ord>(x: &T, y: &T) -> &T {
if x <= y {
x
} else {
y
}
}
</code></pre>
<p>the compiler will complain because it will interpret the above declaration as</p>
<pre><code>fn min<'a, 'b, 'c, T: Ord>(x: &'a T, y: &'b T) -> &'c T { … }
</code></pre>
<p>So, for each reference a separate lifetime parameter is introduced. But no information on how the lifetime parameters relate to each other is available in this signature. The user of this generic function could use <em>any</em> lifetimes. And that's a problem inside its body. We're trying to return either <code>x</code> or <code>y</code>. But the type of <code>x</code> is <code>&'a T</code>. That's not compatible with the return type <code>&'c T</code>. The same is true for <code>y</code>. Since the compiler knows nothing about how these lifetimes relate to each other, it's not safe to return these references as a reference of type <code>&'c T</code>.</p>
<p>Can it ever be safe to go from a value of type <code>&'a T</code> to <code>&'c T</code>? Yes. It's safe if the lifetime <code>'a</code> is equal <em>or greater</em> than the lifetime <code>'c</code>. Or in other words <code>'a: 'c</code>. So, we <em>could</em> write this</p>
<pre><code>fn min<'a, 'b, 'c, T: Ord>(x: &'a T, y: &'b T) -> &'c T
where 'a: 'c, 'b: 'c
{ … }
</code></pre>
<p>and get away with it without the compiler complaining about the function's body. But it's actually <em>unnecessarily</em> complex. We can also simply write</p>
<pre><code>fn min<'a, T: Ord>(x: &'a T, y: &'a T) -> &'a T { … }
</code></pre>
<p>and use a single lifetime parameter for everything. The compiler is able to deduce <code>'a</code> as the minimum lifetime of the argument references at the call site just because we used the same lifetime name for both parameters. And this lifetime is precisely what we need for the return type.</p>
<p>I hope this answers your question. :)
Cheers!</p> |
19,231,506 | How to access string as character value | <p><a href="http://play.golang.org/p/ZsALO8oF3W">http://play.golang.org/p/ZsALO8oF3W</a></p>
<p>I want to traverse a string and return the character values. How do I, not return the numeric values per each letter, and return the actual characters?</p>
<p>Now I am getting this</p>
<pre><code> 0 72 72
1 101 101
2 108 108
3 108 108
4 111 111
</code></pre>
<p>My desired output would be</p>
<pre><code> 0 h h
1 e e
2 l l
3 l l
4 o o
package main
import "fmt"
func main() {
str := "Hello"
for i, elem := range str {
fmt.Println(i, str[i], elem)
}
for elem := range str {
fmt.Println(elem)
}
}
</code></pre>
<p>Thanks,</p> | 19,232,071 | 3 | 0 | null | 2013-10-07 17:59:10.893 UTC | 7 | 2018-11-25 08:31:15.877 UTC | 2018-11-25 08:31:15.877 UTC | null | 13,860 | user2671513 | null | null | 1 | 30 | go | 44,804 | <blockquote>
<p><a href="http://golang.org/ref/spec#For_statements">For statements</a></p>
<p>For a string value, the "range" clause iterates over the Unicode code
points in the string starting at byte index 0. On successive
iterations, the index value will be the index of the first byte of
successive UTF-8-encoded code points in the string, and the second
value, of type rune, will be the value of the corresponding code
point. If the iteration encounters an invalid UTF-8 sequence, the
second value will be 0xFFFD, the Unicode replacement character, and
the next iteration will advance a single byte in the string.</p>
</blockquote>
<p>For example,</p>
<pre><code>package main
import "fmt"
func main() {
str := "Hello"
for _, r := range str {
c := string(r)
fmt.Println(c)
}
fmt.Println()
for i, r := range str {
fmt.Println(i, r, string(r))
}
}
</code></pre>
<p>Output:</p>
<pre><code>H
e
l
l
o
0 72 H
1 101 e
2 108 l
3 108 l
4 111 o
</code></pre> |
18,857,352 | Remove very last character in file | <p>After looking all over the Internet, I've come to this.</p>
<p>Let's say I have already made a text file that reads:
<code>Hello World</code></p>
<p>Well, I want to remove the very last character (in this case <code>d</code>) from this text file.</p>
<p>So now the text file should look like this: <code>Hello Worl</code></p>
<p>But I have no idea how to do this.</p>
<p>All I want, more or less, is a single backspace function for text files on my HDD.</p>
<p>This needs to work on Linux as that's what I'm using.</p> | 18,857,381 | 8 | 0 | null | 2013-09-17 18:34:15.09 UTC | 7 | 2021-07-26 10:50:08.357 UTC | 2020-01-25 01:07:06.733 UTC | null | 3,750,257 | null | 2,681,562 | null | 1 | 49 | python|file|text | 74,047 | <p>Use <a href="https://docs.python.org/3/library/io.html#io.IOBase.seek" rel="noreferrer"><code>fileobject.seek()</code></a> to seek 1 position from the end, then use <a href="https://docs.python.org/3/library/io.html#io.IOBase.truncate" rel="noreferrer"><code>file.truncate()</code></a> to remove the remainder of the file:</p>
<pre><code>import os
with open(filename, 'rb+') as filehandle:
filehandle.seek(-1, os.SEEK_END)
filehandle.truncate()
</code></pre>
<p>This works fine for single-byte encodings. If you have a multi-byte encoding (such as UTF-16 or UTF-32) you need to seek back enough bytes from the end to account for a single codepoint. </p>
<p>For variable-byte encodings, it depends on the codec if you can use this technique at all. For UTF-8, you need to find the first byte (from the end) where <code>bytevalue & 0xC0 != 0x80</code> is true, and truncate from that point on. That ensures you don't truncate in the middle of a multi-byte UTF-8 codepoint:</p>
<pre><code>with open(filename, 'rb+') as filehandle:
# move to end, then scan forward until a non-continuation byte is found
filehandle.seek(-1, os.SEEK_END)
while filehandle.read(1) & 0xC0 == 0x80:
# we just read 1 byte, which moved the file position forward,
# skip back 2 bytes to move to the byte before the current.
filehandle.seek(-2, os.SEEK_CUR)
# last read byte is our truncation point, move back to it.
filehandle.seek(-1, os.SEEK_CUR)
filehandle.truncate()
</code></pre>
<p>Note that UTF-8 is a superset of ASCII, so the above works for ASCII-encoded files too.</p> |
38,911,588 | Replace first occurrence of substring in a string in SQL | <p>I have to fetch data from a @temp table which has something like "or ccc or bbb or aaa" I want to replace the first occurrence into space to get something like this " ccc or bbb or aaa". I am trying stuff and replace but they don't seem to get me the desired result</p>
<p>What I have tried:</p>
<pre><code>DECLARE @stringhere as varchar(500)
DECLARE @stringtofind as varchar(500)
set @stringhere='OR contains or cccc or '
set @stringtofind='or'
select STUFF('OR contains or cccc or ',PATINDEX('or', 'OR contains or cccc or '),0 ,' ')
</code></pre> | 38,911,646 | 4 | 3 | null | 2016-08-12 06:47:08.833 UTC | 4 | 2020-06-05 20:39:21.537 UTC | 2016-08-12 08:24:30.9 UTC | null | 472,495 | null | 3,331,798 | null | 1 | 26 | sql|sql-server|sql-server-2012 | 46,532 | <p>You can use a combination of <code>STUFF</code> and <code>CHARINDEX</code> to achieve what you want:</p>
<pre><code>SELECT STUFF(col, CHARINDEX('substring', col), LEN('substring'), 'replacement')
FROM #temp
</code></pre>
<p><code>CHARINDEX('substring', col)</code> will return the index of the <em>first</em> occurrence of <code>'substring'</code> in the column. <code>STUFF</code> then replaces this occurrence with <code>'replacement'</code>.</p> |
22,389,184 | Recursive power function: approach | <p>I'm programming for a while now(beginner), and recursive functions are a somewhat abstract concept for me. I would not say I'm stuck, program works fine, I'm just wondering if the function itself could be written without the pow function in the code (but still doing exactly what the problem suggests)</p>
<p>Problem:
<a href="http://prntscr.com/30hxg9" rel="nofollow">http://prntscr.com/30hxg9</a></p>
<p>My solution:</p>
<pre><code>#include<stdio.h>
#include<math.h>
int power(int, int);
int main(void)
{
int x, n;
printf("Enter a number and power you wish to raise it to: ");
scanf_s("%d %d", &x, &n);
printf("Result: %d\n", power(n, x));
return 0;
}
int power(int x, int n)
{
if (n == 0) return 1;
if (n % 2 == 0) return pow(power(x, n / 2), 2);
else return x * power(x, n - 1);
}
</code></pre>
<p>I've tried doing this: power(power(x, n - 1), 2);
but execution failed, and I'm still backtracking why.</p> | 22,389,695 | 9 | 0 | null | 2014-03-13 19:39:30.153 UTC | 3 | 2019-11-23 11:07:14.907 UTC | 2017-12-15 19:51:03.873 UTC | null | 856,164 | null | 2,047,912 | null | 1 | 6 | c|recursion|pow | 70,188 | <p>When rewriting your function, don't lose sight of the main benefit of recursion in this case, which is to reduce the number of multiplication operations required. For example, if n = 8, then it is much more efficient to compute x * x as val1, then val1 * val1 as val2, and the final answer as val2 * val2 (3 multiplications) than to compute x * x * x * x * x * x * x * x (7 multiplications).</p>
<p>This difference is trivial for small integers but matters if you put this operation inside a big loop, or if you replace the integers with very large number representations or maybe ginormous matrices.</p>
<p>Here's one way to get rid of the pow() function without getting rid of the recursion efficiency:</p>
<pre><code>#include<stdio.h>
#include<math.h>
int power(int, int);
int main(void)
{
int x, n;
printf("Enter a number and power you wish to raise it to: ");
scanf_s("%d %d", &x, &n);
printf("Result: %d\n", power(x, n));
return 0;
}
int power(int x, int n)
{
int m;
if (n == 0) return 1;
if (n % 2 == 0) {
m = power(x, n / 2);
return m * m;
} else return x * power(x, n - 1);
}
</code></pre> |
19,789,709 | "Operation must use an updateable query" error in MS Access | <p>I am getting an error message: "Operation must use an updateable query" when I try to run my SQL. From my understanding, this happens when joins are used in update/delete queries in MS Access. However, I'm a little confused because I have another query almost identical in my database which works fine.</p>
<p>This is my troublesome query:</p>
<pre><code>UPDATE [GS] INNER JOIN [Views] ON
([Views].Hostname = [GS].Hostname)
AND ([GS].APPID = [Views].APPID)
SET
[GS].APPID = [Views].APPID,
[GS].[Name] = [Views].[Name],
[GS].Hostname = [Views].Hostname,
[GS].[Date] = [Views].[Date],
[GS].[Unit] = [Views].[Unit],
[GS].[Owner] = [Views].[Owner];
</code></pre>
<p>As I said before, I am confused because I have another query similar to this, which runs perfectly. This is that query:</p>
<pre><code>UPDATE [Views] INNER JOIN [GS] ON
[Views].APPID = [GS].APPID
SET
[GS].APPID = [Views].APPID,
[GS].[Name] = [Views].[Name],
[GS].[Criticial?] = [Views].[Criticial?],
[GS].[Unit] = [Views].[Unit],
[GS].[Owner] = [Views].[Owner];
</code></pre>
<p>What is wrong with my first query? Why does the second query work when the first doesn't?</p> | 19,790,931 | 12 | 0 | null | 2013-11-05 13:06:26.963 UTC | 6 | 2020-11-19 23:23:04.21 UTC | 2013-11-05 18:02:42.023 UTC | null | 168,868 | null | 1,779,136 | null | 1 | 37 | ms-access | 214,134 | <p>Whether this answer is universally true or not, I don't know, but I solved this by altering my query slightly.</p>
<p>Rather than joining a select query to a table and processing it, I changed the select query to create a temporary table. I then used that temporary table to the real table and it all worked perfectly.</p> |
48,534,980 | Mount local directory into pod in minikube | <p>I am running minikube v0.24.1. In this minikube, I will create a Pod for my nginx application. And also I want to pass data from my local directory.</p>
<p>That means I want to mount my local <code>$HOME/go/src/github.com/nginx</code> into my Pod</p>
<p>How can I do this?</p>
<pre><code>apiVersion: v1
kind: Pod
metadata:
name: nginx
spec:
containers:
- image: nginx:0.1
name: nginx
volumeMounts:
- mountPath: /data
name: volume
volumes:
- name: volume
hostPath:
path: /data
</code></pre> | 48,535,001 | 8 | 1 | null | 2018-01-31 05:22:25.777 UTC | 10 | 2022-01-12 00:23:25.107 UTC | null | null | null | null | 3,427,852 | null | 1 | 64 | kubernetes|minikube | 67,505 | <p>You can't mount your local directory into your Pod directly.</p>
<p>First, you need to mount your directory <code>$HOME/go/src/github.com/nginx</code> into your minikube.</p>
<pre><code>$ minikube start --mount-string="$HOME/go/src/github.com/nginx:/data" --mount
</code></pre>
<p>Then If you mount <code>/data</code> into your Pod using hostPath, you will get you local directory data into Pod.</p>
<p>There is <strong>another way</strong></p>
<p>Host's <code>$HOME</code> directory gets mounted into minikube's <code>/hosthome</code> directory. Here you will get your data</p>
<pre><code>$ ls -la /hosthome/go/src/github.com/nginx
</code></pre>
<p>So to mount this directory, you can change your Pod's hostPath</p>
<pre><code>hostPath:
path: /hosthome/go/src/github.com/nginx
</code></pre> |
23,529,783 | Remove unit testing from Xcode project? | <p>When I created my iOS project in Xcode 5 I clicked the option to add testing to the project. Is it possible to remove all that testing stuff, just as though I hadn't clicked the option to begin with?</p> | 23,529,853 | 2 | 2 | null | 2014-05-07 22:46:33.643 UTC | 10 | 2020-06-03 19:21:04.917 UTC | 2017-05-21 12:05:17.49 UTC | null | 3,681,880 | null | 2,985,425 | null | 1 | 53 | ios|xcode|unit-testing | 24,905 | <p>I suggest to <strong>make test</strong> in your project.</p>
<p>But in any case, you might to leave there the target. </p>
<p>Otherwise, if you want delete at any cost, you have just to <strong>click on your project settings</strong> and click on this icon:</p>
<p><img src="https://i.stack.imgur.com/pMLNJ.png" alt="enter image description here"></p>
<p>You will see your <strong>targets</strong> and you will can delete the <strong>test target</strong>. At this point you might want <strong>delete the test classes</strong> too: on the folder hierarchy, select these and just press backspace, confirming the deletion.</p> |
25,504,851 | How to enable CORS on Firefox | <p>How can I allow <a href="https://en.wikipedia.org/wiki/Cross-origin_resource_sharing" rel="nofollow noreferrer">CORS</a> on Firefox?</p>
<p>I easily managed it on Chrome and Internet Explorer, but I am totally failing at it with Firefox. I edited the following <em>about:config</em> entry</p>
<pre><code>security.fileuri.strict_origin_policy = false
</code></pre>
<p>This attempt has been posted several times here and is told on other sites too, but it doesn't have any effect. I read the Mozilla guide to <a href="https://en.wikipedia.org/wiki/Same-origin_policy" rel="nofollow noreferrer">same-origin policies</a>:</p>
<p><em><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS" rel="nofollow noreferrer">Cross-Origin Resource Sharing (CORS)</a></em></p>
<p>but it just explains CORS and the related topics. A workaround to enable it on Firefox is not listed.</p>
<p>Is there a definitive solution?</p>
<p>PS: FORCECORS does not work either somehow...</p> | 25,507,329 | 5 | 1 | null | 2014-08-26 11:33:32.56 UTC | 6 | 2021-08-17 02:47:54.287 UTC | 2021-08-17 02:37:17.997 UTC | null | 63,550 | null | 3,869,169 | null | 1 | 44 | firefox|cors|same-origin-policy | 128,087 | <p>Do nothing to the browser. <a href="http://caniuse.com/#feat=cors" rel="noreferrer">CORS is supported</a> by default on all modern browsers (and since Firefox 3.5).</p>
<p>The server being accessed by JavaScript has to give the site hosting the HTML document in which the JS is running permission via CORS HTTP response headers.</p>
<hr>
<p><code>security.fileuri.strict_origin_policy</code> is used to give JS in local HTML documents access to your entire hard disk. Don't set it to <code>false</code> as it makes you vulnerable to attacks from downloaded HTML documents (including email attachments).</p> |
51,859,725 | VSCode system-wide installation warning | <p>These days, anytime I start VSCode, I get this warning </p>
<p><em>You are running the system-wide installation of Code, while having the user-wide distribution installed as well. Make sure you're running the Code version you expect.</em></p>
<p>Please how do I fix that?</p> | 51,861,154 | 6 | 2 | null | 2018-08-15 13:31:59.1 UTC | 7 | 2019-03-26 11:37:14.897 UTC | 2019-03-26 11:37:14.897 UTC | null | 2,631,715 | null | 5,138,921 | null | 1 | 38 | visual-studio-code|vscode-settings | 13,236 | <p><strong>UPDATE</strong> (Recommended by @Fabio Turati)</p>
<p>Just uninstalling the older one <strong>without</strong> the (USER) extension, it seems working. If not, then uninstall the one left and reinstall vscode.</p>
<p><strong>additional reading:</strong></p>
<p>You installed the new one (with USER extension) before uninstalling the older one. So now you have both, and this is why you get that message. You need to uninstall them both, then reinstall vs code. Make sure you add a shortcut on desktop, it took me a few more minutes to find the .exe of vs code. No worries you don't lose anything by uninstalling...</p>
<p>cheers !</p> |
29,393,562 | Rails and jsonb type "jsonb" does not exist | <pre><code>psql --version
psql (PostgreSQL) 9.4.1
rails -v
Rails 4.2.0
</code></pre>
<p>I added a jsonb column through migration like that </p>
<pre><code>class AddPreferencesToUsers < ActiveRecord::Migration
def change
add_column :users, :preferences, :jsonb, null: false, default: '{}'
add_index :users, :preferences, using: :gin
end
end
</code></pre>
<p>I get this error :</p>
<pre><code>PG::UndefinedObject: ERROR: type "jsonb" does not exist
LINE 1: SELECT 'jsonb'::regtype::oid
</code></pre>
<p>any help ?</p> | 29,423,224 | 1 | 2 | null | 2015-04-01 14:31:34.543 UTC | 4 | 2015-04-02 22:00:24.507 UTC | 2015-04-01 14:43:35.4 UTC | null | 2,392,106 | null | 2,392,106 | null | 1 | 36 | ruby-on-rails|postgresql|jsonb | 25,000 | <p>After looking around I discovered that my postgresql version is not 9.4 by running the right command </p>
<pre><code>postgres=# SHOW SERVER_VERSION;
server_version
----------------
9.1
</code></pre>
<p>So I had simply to upgrade my postgresql to 9.4.</p>
<p>By the way I followed <a href="http://www.gab.lc/articles/migration_postgresql_9-3_to_9-4">this article</a> to do the upgrading which I found very handy.</p>
<p>Now :</p>
<pre><code>postgres=# SHOW SERVER_VERSION;
server_version
----------------
9.4.1
</code></pre>
<p>Hope this help someone in the same situation.</p> |
4,623,667 | AbstractWizardFormController using Annotated @Controllers | <p>In Spring Framework , <code>AbstractWizardFormController</code> seems deprecated. How to implement multiple pages form in the Spring MVC Framework. (I am not using webflow)</p>
<p>any example or pointer would help considering my limited knowledge in Spring.</p> | 4,624,451 | 1 | 0 | null | 2011-01-07 08:12:33.54 UTC | 29 | 2014-10-17 10:18:17.217 UTC | 2011-01-07 10:43:13.45 UTC | null | 1 | null | 150,252 | null | 1 | 31 | java|spring|spring-mvc|spring-annotations | 16,366 | <p>A @Controller is a more flexible way to define a form / wizard. You are supposed to map methods to requests based on requested path / request parameters / request method. So instead of defining a list of views and processing the request based on some required "step" parameter, you can define the steps of your wizard as you wish (also the command object will be handled more transparently). Here's how you can get to emulate a classic AWFC functionality (this is only meant to be an example, there's a lot more you can do).</p>
<pre><code>@Controller
@RequestMapping("/wizard.form")
@SessionAttributes("command")
public class WizardController {
/**
* The default handler (page=0)
*/
@RequestMapping
public String getInitialPage(final ModelMap modelMap) {
// put your initial command
modelMap.addAttribute("command", new YourCommandClass());
// populate the model Map as needed
return "initialView";
}
/**
* First step handler (if you want to map each step individually to a method). You should probably either use this
* approach or the one below (mapping all pages to the same method and getting the page number as parameter).
*/
@RequestMapping(params = "_step=1")
public String processFirstStep(final @ModelAttribute("command") YourCommandClass command,
final Errors errors) {
// do something with command, errors, request, response,
// model map or whatever you include among the method
// parameters. See the documentation for @RequestMapping
// to get the full picture.
return "firstStepView";
}
/**
* Maybe you want to be provided with the _page parameter (in order to map the same method for all), as you have in
* AbstractWizardFormController.
*/
@RequestMapping(method = RequestMethod.POST)
public String processPage(@RequestParam("_page") final int currentPage,
final @ModelAttribute("command") YourCommandClass command,
final HttpServletResponse response) {
// do something based on page number
return pageViews[currentPage];
}
/**
* The successful finish step ('_finish' request param must be present)
*/
@RequestMapping(params = "_finish")
public String processFinish(final @ModelAttribute("command") YourCommandClass command,
final Errors errors,
final ModelMap modelMap,
final SessionStatus status) {
// some stuff
status.setComplete();
return "successView";
}
@RequestMapping(params = "_cancel")
public String processCancel(final HttpServletRequest request,
final HttpServletResponse response,
final SessionStatus status) {
status.setComplete();
return "canceledView";
}
}
</code></pre>
<p>I tried to vary the method signatures so that you can get an idea about the flexibility I mentioned. Of course, there's a lot more to it: you can make use of request method (GET or POST) in the <code>@RequestMapping</code>, you can define a method annotated with <code>@InitBinder</code>, etc.</p>
<p><strong>EDIT:</strong> I had an unmapped method which I fixed (by the way, you need to make sure you don't have ambiguous mappings -- requests that could be mapped to more than one method -- or unmapped requests -- requests that cannot be mapped to any method). Also have a look at @SessionAttributes, @SessionStatus and @ModelAttribute, which are also needed for fully simulating the behaviour of the classic AWFC (I edited the code already to make this clear).</p> |
25,049,923 | Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no object at index 3 in section at index 0' | <p>Hi I'm having a hard time fixing this error.</p>
<blockquote>
<p>Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no object at index 3 in section at index 0'</p>
</blockquote>
<p>That error exist when I delete all my Entity in coredata and refetch it.</p>
<p><strong>CALL API</strong></p>
<pre><code>self.fetchedResultsController = nil;
[NSFetchedResultsController deleteCacheWithName:nil];
[api requestForMenuCategory:@"details" managedObjectContext:self.managedObjectContext delegate:self];
</code></pre>
<p><strong>EXECUTE WHEN API IS DONT FETCHING DATA</strong></p>
<pre><code> if (![self.fetchedResultsController performFetch:&error]) {
NSLog(@"%@",[error description]);
}
else{
NSLog(@"NUMBER OF FETCH %d",[[_fetchedResultsController fetchedObjects] count]);
[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
[self.tableView reloadData];
}
</code></pre>
<p>Number of fetch says it's 0 but I dont' know why I still have a data in my tableview and after awhile it crashes </p>
<p><strong>EDIT</strong></p>
<p>Here's my number of row in section and I don't have number of section since default is 1 when not implemented</p>
<pre><code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[_fetchedResultsController fetchedObjects] count];
</code></pre>
<p>}</p>
<p><strong>EDIT 2</strong></p>
<pre><code>*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no object at index 3 in section at index 0'
*** First throw call stack:
(
0 CoreFoundation 0x00df65e4 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x042a08b6 objc_exception_throw + 44
2 CoreData 0x03310cae -[NSFetchedResultsController objectAtIndexPath:] + 398
3 DogDuck 0x0014c692 -[TestMenuViewController configureCell:atIndexPath:] + 146
4 DogDuck 0x0014c583 -[TestMenuViewController tableView:cellForRowAtIndexPath:] + 227
5 UIKit 0x01e2361f -[UITableView _createPreparedCellForGlobalRow:withIndexPath:] + 412
6 UIKit 0x01e236f3 -[UITableView _createPreparedCellForGlobalRow:] + 69
7 UIKit 0x01e07774 -[UITableView _updateVisibleCellsNow:] + 2378
8 UIKit 0x01e05b1f -[UITableView _setNeedsVisibleCellsUpdate:withFrames:] + 171
9 UIKit 0x01e1b111 -[UITableView _rectChangedWithNewSize:oldSize:] + 490
10 UIKit 0x01e1b6dd -[UITableView setBounds:] + 279
11 UIKit 0x01daac17 -[UIScrollView setContentOffset:] + 690
12 UIKit 0x01e1c1d1 -[UITableView setContentOffset:] + 314
13 UIKit 0x01dc7cae -[UIScrollView(UIScrollViewInternal) _adjustContentOffsetIfNecessary] + 2622
14 UIKit 0x01daad82 -[UIScrollView setContentInset:] + 143
15 UIKit 0x01e1c302 -[UITableView setContentInset:] + 280
16 DogDuck 0x00133be6 -[EGORefreshTableHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:] + 310
17 DogDuck 0x0014c2a8 -[TestMenuViewController doneLoading] + 440
18 DogDuck 0x00006192 __66-[BoogieAPI requestForMenuCategory:managedObjectContext:delegate:]_block_invoke + 1266
19 Foundation 0x02ce2695 __67+[NSURLConnection sendAsynchronousRequest:queue:completionHandler:]_block_invoke_2 + 151
20 Foundation 0x02c42945 -[NSBlockOperation main] + 88
21 Foundation 0x02c9b829 -[__NSOperationInternal _start:] + 671
22 Foundation 0x02c18558 -[NSOperation start] + 83
23 Foundation 0x02c9daf4 __NSOQSchedule_f + 62
24 libdispatch.dylib 0x048ac4b0 _dispatch_client_callout + 14
25 libdispatch.dylib 0x0489a75e _dispatch_main_queue_callback_4CF + 340
26 CoreFoundation 0x00e5ba5e __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 14
27 CoreFoundation 0x00d9c6bb __CFRunLoopRun + 1963
28 CoreFoundation 0x00d9bac3 CFRunLoopRunSpecific + 467
29 CoreFoundation 0x00d9b8db CFRunLoopRunInMode + 123
30 GraphicsServices 0x0524c9e2 GSEventRunModal + 192
31 GraphicsServices 0x0524c809 GSEventRun + 104
32 UIKit 0x01d34d3b UIApplicationMain + 1225
33 DogDuck 0x000027cd main + 125
34 DogDuck 0x00002745 start + 53
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
</code></pre>
<p><strong>ADDITIONAL NOTE</strong>
Cell for row is being called but fetchedobject is 0 </p> | 25,051,056 | 2 | 3 | null | 2014-07-31 02:29:40.547 UTC | 10 | 2018-06-14 18:38:29.793 UTC | 2015-11-23 12:35:02.903 UTC | null | 247,679 | null | 1,636,421 | null | 1 | 13 | ios|core-data|nsfetchedresultscontroller | 10,780 | <p>The problem is inside your <code>configureCell:atIndexPath</code> method. Unfortunately the implementation that is provided in the Core Data Xcode templates has a few bugs. Your crash is one of them.</p>
<p>The <code>NSFetchedResultsController</code> method <code>objectAtIndexPath:</code> is not very safe to call. If you give it an NSIndexPath that is out of range it will crash with the very exception you are seeing. This is mentioned in the class reference:</p>
<blockquote>
<p>If indexPath does not describe a valid index path in the fetch results, an exception is raised.</p>
</blockquote>
<p>This is just like access to an array: whenever you access an array by an index, you should do a bounds check first. A bounds check for <code>objectAtIndexPath:</code> would look like:</p>
<pre><code>id result = nil;
if ([[self.fetchedResultsController sections] count] > [indexPath section]){
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:[indexPath section]];
if ([sectionInfo numberOfObjects] > [indexPath row]){
result = [self.fetchedResultsController objectAtIndexPath:indexPath];
}
}
</code></pre>
<p>And that's a bit complicated, but necessary. That solves the exception.</p>
<p>The reason you are getting an exception is that the state of the NSFetchedResultsController is getting out of sync with the state of the tableview. When your crash happens the tableView just asked your delegate methods (<code>numberOfSectionsInTableView</code> and <code>tableView:numberOfRowsInSection:</code> for the number of rows and sections. When it asked that, the NSFetchedResultsController had data in it, and gave positive values (1 section, 3 rows). But in-between that happening and your crash, the entities represented by the NSFetchedResultsController were deleted from the NSManagedObjectContext. Now <code>cellForRowAtIndexPath:</code> is being called with an outdated <code>indexPath</code> parameter. </p>
<p>It looks like <code>egoRefreshScrollViewDataSourceDidFinishedLoading</code> is causing the tableView to be rebuilt by adjusting the content view of the scroll view - and <code>cellForRowAtIndexPath:</code> to be called - <em>before</em> you refetch and reload your tableView. That needs to happen before whatever <code>egoRefreshScrollViewDataSourceDidFinishedLoading</code> is doing. <code>egoRefreshScrollViewDataSourceDidFinishedLoading</code> is causing <code>cellForRowAtIndexPath:</code> to be called with stale index paths.</p>
<p>The real problem may lie in your <code>NSFetchedResultsControllerDelegate</code> methods. When your entities are being deleted, those should be getting called to remove items from the tableView. That does not seem to be happening here.</p>
<p>The short version though, move your <code>[self.tableView reloadData];</code> up one line:</p>
<pre><code>[self.tableView reloadData];
[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
</code></pre> |
39,637,675 | What is the difference between @types.coroutine and @asyncio.coroutine decorators? | <p>Documentations say:</p>
<blockquote>
<p>@asyncio.coroutine</p>
<p>Decorator to mark generator-based coroutines. This enables the generator use yield from to call async def coroutines, and also
enables the generator to be called by async def coroutines, for
instance using an await expression.</p>
</blockquote>
<p>_</p>
<blockquote>
<p>@types.coroutine(gen_func) </p>
<p>This function transforms a generator
function into a coroutine function which returns a generator-based
coroutine. The generator-based coroutine is still a generator
iterator, but is also considered to be a coroutine object and is
awaitable. However, it may not necessarily implement the <code>__await__()</code>
method.</p>
</blockquote>
<p>So is seems like purposes is the same - to flag a generator as a coroutine (what <code>async def</code>in Python3.5 and higher does with some features).</p>
<p>When need to use <code>asyncio.coroutine</code> when need to use <code>types.coroutine</code>, what is the diffrence?</p> | 49,477,233 | 2 | 2 | null | 2016-09-22 11:23:13.613 UTC | 12 | 2020-09-01 07:38:53.913 UTC | null | null | null | null | 3,411,682 | null | 1 | 25 | python|asynchronous|python-3.5 | 3,094 | <p>The difference is if you have a yield statement or not.
Here's the code:</p>
<pre><code>from types import coroutine as t_coroutine
from asyncio import coroutine as a_coroutine, ensure_future, sleep, get_event_loop
@a_coroutine
def a_sleep():
print("doing something in async")
yield 1
@t_coroutine
def t_sleep():
print("doing something in types")
yield 1
async def start():
sleep_a = a_sleep()
sleep_t = t_sleep()
print("Going down!")
loop = get_event_loop()
loop.run_until_complete(start())
</code></pre>
<p>In this example everything seem same - here's the debugging info from pycharm (we're standing on the "Going down!" line). Nothing is printed in console yet, so the functions didn't start yet.</p>
<p><a href="https://i.stack.imgur.com/eIqZb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/eIqZb.png" alt="PyCharm Debug"></a></p>
<p>But <strong>if we remove the <code>yield</code></strong>, the <code>types</code> version will start function instantly!</p>
<pre><code>from types import coroutine as t_coroutine
from asyncio import coroutine as a_coroutine, ensure_future, sleep, get_event_loop
@a_coroutine
def a_sleep():
print("doing something in async")
@t_coroutine
def t_sleep():
print("doing something in types")
async def start():
sleep_a = a_sleep()
sleep_t = t_sleep()
print("Going down!")
loop = get_event_loop()
loop.run_until_complete(start())
</code></pre>
<p>Now we have <code>doing something in types</code> in console printed. And here's the debug info:</p>
<p><a href="https://i.stack.imgur.com/DF4tM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DF4tM.png" alt="new debug info"></a></p>
<p>As you can see <strong>it starts right after call</strong>, if there is no result and returns None.</p>
<hr>
<p>As for usage, you should use <code>asyncio</code> version always. If you need to run it like <em>fire and forget</em> (running instantly and getting results later) - use <code>ensure_future</code> function.</p> |
39,068,983 | PHP 7 interfaces, return type hinting and self | <p><strong>UPDATE</strong>: PHP 7.4 now <a href="https://www.php.net/manual/en/language.oop5.variance.php" rel="noreferrer">does support covariance and contravariance</a> which addresses the major issue raised in this question. </p>
<hr>
<p>I have run into something of an issue with using return type hinting in PHP 7. My understanding is that hinting <code>: self</code> means that you intend for an implementing class to return itself. Therefore I used <code>: self</code> in my interfaces to indicate that, but when I tried to actually implement the interface I got compatibility errors. </p>
<p>The following is a simple demonstration of the issue I've run into: </p>
<pre><code>interface iFoo
{
public function bar (string $baz) : self;
}
class Foo implements iFoo
{
public function bar (string $baz) : self
{
echo $baz . PHP_EOL;
return $this;
}
}
(new Foo ()) -> bar ("Fred")
-> bar ("Wilma")
-> bar ("Barney")
-> bar ("Betty");
</code></pre>
<p>The expected output was: </p>
<blockquote>
<p>Fred
Wilma
Barney
Betty</p>
</blockquote>
<p>What I actually get is: </p>
<blockquote>
<p>PHP Fatal error: Declaration of Foo::bar(int $baz): Foo must be compatible with iFoo::bar(int $baz): iFoo in test.php on line 7</p>
</blockquote>
<p>The thing is Foo is an implementation of iFoo, so as far as I can tell the implementation should be perfectly compatible with the given interface. I could presumably fix this issue by changing either the interface or the implementing class (or both) to return hint the interface by name instead of using <code>self</code>, but my understanding is that semantically <code>self</code> means "return the instance of the class you just called the method on". Therefore changing it to the interface would mean in theory that I could return any instance of something that implements the interface when my intent is for the invoked instance is what will be returned. </p>
<p>Is this an oversight in PHP or is this a deliberate design decision? If it's the former is there any chance of seeing it fixed in PHP 7.1? If not then what is the correct way of return hinting that your interface expects you to return the instance you just called the method on for chaining? </p> | 39,070,492 | 4 | 5 | null | 2016-08-21 21:21:01.853 UTC | 14 | 2021-11-29 11:53:59.337 UTC | 2020-02-17 01:25:04.697 UTC | null | 93,540 | null | 477,127 | null | 1 | 97 | php|interface|return-type|php-7|type-hinting | 57,930 | <p>editorial note: the answer below is outdated. as php PHP7.4.0, the following is perfectly legal:</p>
<pre><code><?php
Interface I{
public static function init(?string $url): self;
}
class C implements I{
public static function init(?string $url): self{
return new self();
}
}
$o = C::init("foo");
var_dump($o);
</code></pre>
<ul>
<li>3v4l: <a href="https://3v4l.org/VYbGn" rel="nofollow noreferrer">https://3v4l.org/VYbGn</a></li>
</ul>
<p>original answer:</p>
<p><code>self</code> does not refer to the instance, it refers to the current class. There is no way for an interface to specify that the same <em>instance</em> must be returned - using <code>self</code> in the manner you're attempting would only enforce that the returned instance be of the same class.</p>
<p>That said, return type declarations in PHP must be invariant while what you're attempting is covariant.</p>
<p>Your use of <code>self</code> is equivalent to:</p>
<pre><code>interface iFoo
{
public function bar (string $baz) : iFoo;
}
class Foo implements iFoo
{
public function bar (string $baz) : Foo {...}
}
</code></pre>
<p>which is not allowed.</p>
<hr />
<p>The <a href="https://wiki.php.net/rfc/return_types" rel="nofollow noreferrer">Return Type Declarations RFC</a> has <a href="https://wiki.php.net/rfc/return_types#variance_and_signature_validation" rel="nofollow noreferrer">this to say</a>:</p>
<blockquote>
<p>The enforcement of the declared return type during inheritance is invariant; this means that when a sub-type overrides a parent method then the return type of the child must exactly match the parent and may not be omitted. If the parent does not declare a return type then the child is allowed to declare one.</p>
<p>...</p>
<p>This RFC originally proposed covariant return types but was changed to invariant because of a few issues. It is possible to add covariant return types at some point in the future.</p>
</blockquote>
<hr />
<p>For the time being at least the best you can do is:</p>
<pre><code>interface iFoo
{
public function bar (string $baz) : iFoo;
}
class Foo implements iFoo
{
public function bar (string $baz) : iFoo {...}
}
</code></pre> |
6,892,148 | Adding arrays to multi-dimensional array within loop | <p>I am attempting to generate a multi-dimensional array with each sub array representing a row I want to insert into my DB. The reason for this is so I can use CodeIgniters batch_insert function to add each row to the DB.</p>
<p>I am attempting to create each sub array within a loop and insert it into a multidimensional array. Google suggested using array_merge, but after using 'print_r' on the multidimensional array with the code below, only the last sub-array is being displayed. </p>
<p>Here is my code:</p>
<pre><code>$allplayerdata = array(); //M-D container array
for ($i = 1; $i <= 11; $i++)
{
$playerdata = array(
'player_id' => $this->input->post('player' . $i),
'goals' => $this->input->post('playergoals' . $i),
'player_num' => $i,
'fixture_id' => $this->input->post('fixture_id')
);
//Merge each player row into same array to allow for batch insert
$allplayerdata = array_merge($allplayerdata, $playerdata);
}
print_r($allplayerdata);
</code></pre>
<p>Can anyone spot where I'm going wrong? Help is appreciated!</p> | 6,892,188 | 2 | 0 | null | 2011-07-31 20:37:01.67 UTC | 5 | 2017-04-21 09:35:39.183 UTC | 2016-05-12 07:36:21.33 UTC | null | 4,900,669 | null | 841,749 | null | 1 | 21 | php|arrays|codeigniter|multidimensional-array | 74,685 | <p>This is because <code>array_merge</code> is not the right operation for this situation. Since all the <code>$playerdata</code> arrays have the same keys, the values are overridden. </p>
<hr>
<p>You want to use <code>array_push</code> to append to an array. This way you will get an array of <code>$playerdata</code> arrays.</p>
<pre><code>array_push($allplayerdata, $playerdata);
</code></pre>
<p>Which is equivalent to adding an element with the square bracket syntax</p>
<pre><code>$allplayerdata[] = $playerdata;
</code></pre>
<hr>
<ul>
<li><a href="http://php.net/manual/en/function.array-merge.php" rel="noreferrer"><code>array_merge</code> - Merge one or more arrays</a></li>
<li><a href="http://php.net/manual/en/function.array-push.php" rel="noreferrer"><code>array_push</code> - Push one or more elements onto the end of array</a></li>
<li><a href="http://php.net/manual/en/language.types.array.php#language.types.array.syntax.modifying" rel="noreferrer">Creating/modifying with square bracket syntax</a></li>
</ul> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.