pid
int64
2.28k
41.1M
label
int64
0
1
text
stringlengths
1
28.3k
37,263,185
0
<p>I humbly propose that you're using the wrong data structure. Notice that if you have an array column that has unique values between 1 and N (an index column) you could encode the same data simply by re-ordering your other columns. Once you're re-ordered your data, not only can you drop the "index" column but now it becomes easier to operate on the remaining data. Let me demonstrate:</p> <pre><code>import numpy as np N = 5 a = np.array([[1, 5], [2,6], [3,3], [4,2]]) b = np.array([[3, 1], [4,2], [1,8], [2,4]]) a_trans = np.ones(N) a_trans[a[:, 0]] = a[:, 1] b_trans = np.ones(N) b_trans[b[:, 0]] = b[:, 1] c = a_trans / b_trans print c </code></pre> <p>Depending on the nature of your problem, you can sometimes use an implicit index from the beginning, but sometimes an explicit index can be very useful. If you need an explicit index, consider using something like <code>pandas.DataFrame</code> with better support for index operations.</p>
34,956,492
0
using pusher npm in reactnative app <p>I'm trying to get a basic reactnative app with chat feature going. Found a pusher npm on <a href="https://www.npmjs.com/package/pusher" rel="nofollow">https://www.npmjs.com/package/pusher</a></p> <p>Did install the module to the project with:</p> <pre><code>npm install pusher --save </code></pre> <p>As soon as I add to a react component following line of code</p> <pre><code>var Pusher = require('pusher'); </code></pre> <p>the xcode project stops compiling with following stack trace:</p> <pre><code>bundle: Created ReactPackager uncaught error Error: UnableToResolveError: Unable to resolve module crypto from /Users/dmitry/hacks/tentags/TenTags/node_modules/request/lib/helpers.js: Invalid directory /Users/node_modules/crypto at ResolutionRequest.js:356:15 at tryCallOne (/Users/dmitry/hacks/tentags/TenTags/node_modules/promise/lib/core.js:37:12) at /Users/dmitry/hacks/tentags/TenTags/node_modules/promise/lib/core.js:123:15 at flush (/Users/dmitry/hacks/tentags/TenTags/node_modules/asap/raw.js:50:29) at nextTickCallbackWith0Args (node.js:452:9) at process._tickCallback (node.js:381:13) See logs /var/folders/gq/zxnwqjwd75d_2rhgbzzc_0n00000gn/T/react-packager.log at SocketClient._handleMessage (SocketClient.js:139:23) at BunserBuf.&lt;anonymous&gt; (SocketClient.js:53:42) at emitOne (events.js:77:13) at BunserBuf.emit (events.js:169:7) at BunserBuf.process (/Users/dmitry/hacks/tentags/TenTags/node_modules/bser/index.js:289:10) at /Users/dmitry/hacks/tentags/TenTags/node_modules/bser/index.js:244:12 at nextTickCallbackWith0Args (node.js:452:9) at process._tickCallback (node.js:381:13) Command /bin/sh failed with exit code 1 </code></pre> <p>What am I doing wrong? Is pusher npm only meant to work in react.js web apps? Can I not use pusher npm as is in ractnative app? I know, maybe naive questions, but I'm very new to reactnative and the whole JS, Node, npm business. </p>
3,684,933
0
<p>SVN supports multiple protocols for accessing repositories, including HTTP, SSH, and even its own SVN protocol. Port 3690 is the default port for the SVN protocol. You can specify the protocol to use in the repository URL. For example. http:// or svn://.</p> <p>To use ssh, try using something like: svn+ssh://username@hostname/path/to/repository</p> <p>Search for "ssh" in TortoiseSVN help for more information.</p>
14,823,269
0
<p>Yes, you're correct that sadly Intellisense is gone for C++/CLI in VS 2010. It's back in VS 2012 and for VS 2010, I recommend <a href="http://www.wholetomato.com" rel="nofollow">Visual Assist</a> if you can afford it.</p>
40,222,894
0
<p>To overcome the "<em>ERROR: query has no destination for result data</em>" error you don't need dynamic SQL.</p> <p>You can <a href="https://www.postgresql.org/docs/current/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-SQL-ONEROW" rel="nofollow">select into a variable directly</a>:</p> <pre><code>select parentid into parent from account where childid = child_id; </code></pre> <hr> <p>But you can simplify your function by using a <a href="https://www.postgresql.org/docs/current/static/queries-with.html" rel="nofollow">recursive CTE</a> and a SQL function. That will perform a lot better especially with a large number of levels:</p> <pre><code>create or replace function build_mp(child_id text) returns text[] language sql as $$ with recursive all_levels (childid, parentid, level) as ( select childid, parentid, 1 from account where childid = child_id union all select c.childid, c.parentid, p.level + 1 from account c join all_levels p on p.parentid = c.childid ) select array_agg(childid order by level) from all_levels; $$; </code></pre>
12,695,965
0
How to perform a $_POST for this example below? <p>I have a multiple row of buttons in my javascript code which goes from A-Z:</p> <pre><code>&lt;?php $a = range("A","Z"); ?&gt; &lt;table id="answerSection"&gt; &lt;tr&gt; &lt;?php $i = 1; foreach($a as $key =&gt; $val){ if($i%7 == 1) echo"&lt;tr&gt;&lt;td&gt;"; echo"&lt;input type=\"button\" onclick=\"btnclick(this);\" value=\"$val\" id=\"answer".$val."\" name=\"answer".$val."Name\" class=\"answerBtns answers answerBtnsOff\"&gt;"; if($i%7 == 0) echo"&lt;/td&gt;&lt;/tr&gt;"; $i++; } ?&gt; &lt;/tr&gt; </code></pre> <p>Below is the javascript function where it turns on and off each individual button:</p> <pre><code>function btnclick(btn) { $(btn).toggleClass("answerBtnsOff"); $(btn).toggleClass("answerBtnsOn"); return false; } </code></pre> <p>I want to perform a $_POST so that it posts all of the buttons which has been turned on. Does anyone know how the post method should be written for this?</p>
35,974,432
1
Django NoReverseMatch at / <p>I am trying to add user uploadable images in my web app using Pillow. I created a Django Upload model and registered it in Admin. As soon as I added a photo using admin console I get the following error. Initially the website was working all fine</p> <p>The Error</p> <pre><code>NoReverseMatch at / Reverse for 'thing_detail' with arguments '()' and keyword arguments '{u'slug': ''}' not found. 1 pattern(s) tried: ['things/(?P&lt;slug&gt;[-\\w]+)/$'] Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.8.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'thing_detail' with arguments '()' and keyword arguments '{u'slug': ''}' not found. 1 pattern(s) tried: ['things/(?P&lt;slug&gt;[-\\w]+)/$'] Exception Location: /usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py in _reverse_with_prefix, line 496 Python Executable: /usr/bin/python Python Version: 2.7.6 Python Path: ['/home/shashank/development/hellowebapp/hellowebapp', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client'] Server time: Sun, 13 Mar 2016 18:54:31 +0000 </code></pre> <p>Urls.py</p> <pre><code>from collection.backends import MyRegistrationView from django.conf.urls import include, url from django.contrib import admin from collection import views from django.conf import settings from django.views.generic import TemplateView from django.contrib.auth.views import ( password_reset, password_reset_done, password_reset_confirm, password_reset_complete ) urlpatterns = [ url(r'^$', views.index, name='home'), url(r'^about/$',TemplateView.as_view(template_name='about.html'),name='about'), url(r'^contact/$',TemplateView.as_view(template_name='contact.html'),name='contact'), url(r'^things/(?P&lt;slug&gt;[-\w]+)/$','collection.views.thing_detail',name='thing_detail'), url(r'^things/(?P&lt;slug&gt;[-\w]+)/edit/$','collection.views.edit_thing',name='edit_thing'), url(r'^things/(?P&lt;slug&gt;[-\w]+)/edit/weight$','collection.views.edit_weight',name='edit_weight'), url(r'^things/(?P&lt;slug&gt;[-\w]+)/delete/weight$','collection.views.remove_weight',name='remove_weight'), #WORKING url(r'^things/(?P&lt;pk&gt;\d+)/remove/$', 'collection.views.remove_weight', name='remove_weight'), url(r'^things/$',TemplateView.as_view(template_name='weight_removed.html'),name='weight_removed'), url(r'^(?P&lt;slug&gt;[\w\d-]+)/(?P&lt;pk&gt;\d+)/$','collection.views.remove_weight',name='remove_weight'), #url(r'^edit/(?P&lt;slug&gt;\d+)/weights$', 'collection.views.AddWeight',name='AddWeight'), # the new password reset URLs url(r'^accounts/password/reset/$',password_reset,{'template_name':'registration/password_reset_form.html'},name="password_reset"), url(r'^accounts/password/reset/done/$',password_reset_done,{'template_name':'registration/password_reset_done.html'},name="password_reset_done"), url(r'^accounts/password/reset/(?P&lt;uidb64&gt;[0-9A-Za-z]+)-(?P&lt;token&gt;.+)/$',password_reset_confirm,{'template_name':'registration/password_reset_confirm.html'},name="password_reset_confirm"), url(r'^accounts/password/done/$',password_reset_complete,{'template_name':'registration/password_reset_complete.html'},name="password_reset_complete"), #setup additional registeration page url(r'^accounts/register/$',MyRegistrationView.as_view(),name='registration_register'), url(r'^accounts/create_thing/$','collection.views.create_thing',name='registration_create_thing'), url(r'^accounts/',include('registration.backends.default.urls')), url(r'^admin/', include(admin.site.urls)), ] if settings.DEBUG: urlpatterns += [ url(r'^media/(?P&lt;path&gt;.*)$','django.views.static.serve',{'document_root': settings.MEDIA_ROOT,}), ] </code></pre> <p>Models .py</p> <pre><code>from django.db import models from django.contrib.auth.models import User from django.db import models from django.utils import timezone class Thing(models.Model): name = models.CharField(max_length=255) description = models.TextField() slug = models.SlugField(unique=True) user = models.OneToOneField(User, blank=True, null=True) class Weight(models.Model): date = models.DateTimeField(default=timezone.now) weight_value = models.CharField(max_length=255) thingRA = models.ForeignKey(Thing,related_name="weights") class Meta: order_with_respect_to = 'thingRA' ordering = ['date'] def get_image_path(instance, filename): return '/'.join(['thing_images', instance.thing.slug, filename]) class Upload(models.Model): thing = models.ForeignKey(Thing, related_name="uploads") image = models.ImageField(upload_to=get_image_path) </code></pre> <p>Admin.py</p> <pre><code>from django.contrib import admin # import your model from collection.models import Thing, Weight, Upload class ThingAdmin(admin.ModelAdmin): model = Thing list_display = ('name', 'description',) prepopulated_fields = {'slug': ('name',)} # and register it admin.site.register(Thing, ThingAdmin) class WeightAdmin(admin.ModelAdmin): model = Weight list_display = ('date','weight_value',) admin.site.register(Weight, WeightAdmin) class UploadAdmin(admin.ModelAdmin): list_display = ('thing', ) list_display_links = ('thing',) # and register it admin.site.register(Upload, UploadAdmin) </code></pre> <p>Base.html</p> <pre><code>{% load staticfiles %} &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt; {% block title %} WEB PAGE BY SHASHANK {% endblock title %} &lt;/title&gt; &lt;link rel="stylesheet" href="{% static 'css/style.css' %}" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="page"&gt; &lt;div id="logo"&gt; &lt;h1&gt;&lt;a href="/" id="logoLink"&gt;S PORTAL&lt;/a&gt;&lt;/h1&gt; &lt;/div&gt; &lt;div id="nav"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="{% url 'home' %}"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="{% url 'about' %}"&gt;About&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="{% url 'contact' %}"&gt;Contact&lt;/a&gt;&lt;/li&gt; {% if user.is_authenticated %} &lt;li&gt;&lt;a href="{% url 'auth_logout' %}"&gt;Logout&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="{% url 'thing_detail' slug=user.thing.slug %}"&gt;My Profile&lt;/a&gt;&lt;/li&gt; {% else %} &lt;li&gt;&lt;a href="{% url 'auth_login' %}"&gt;Login&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="{% url 'registration_register' %}"&gt;Register&lt;/a&gt;&lt;/li&gt; {% endif %} &lt;/ul&gt; &lt;/div&gt; {% block content %}{% endblock content %} &lt;div id="footer"&gt; &lt;p&gt; Webpage made by &lt;a href="/" target="_blank"&gt;SHASHANK&lt;/a&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>View.py</p> <pre><code>from django.shortcuts import render,redirect,get_object_or_404 from collection.models import Thing, Weight from collection.forms import ThingForm, WeightForm, ThingWeightFormSet from django.template.defaultfilters import slugify from django.contrib.auth.decorators import login_required from django.http import Http404 from django.views.decorators.csrf import csrf_protect from django.views.generic import ListView, CreateView, UpdateView from django import forms def index(request): things = Thing.objects.all() return render(request,'index.html',{'things':things,}) def thing_detail(request, slug): # grab the object... thingRA = Thing.objects.get(slug=slug) weights = thingRA.weights.all().order_by('-date') # and pass to the template return render(request, 'things/thing_detail.html', {'thing': thingRA, 'weights':weights,}) def edit_thing(request, slug): # grab the object thing = Thing.objects.get(slug=slug) # set the form we're using form_class = ThingForm # if we're coming to this view from a submitted form if request.method == 'POST': # grab the data from the submitted form and apply to # the form form = form_class(data=request.POST, instance=thing) if form.is_valid(): # save the new data form.save() return redirect('thing_detail', slug=thing.slug) # otherwise just create the form else: form = form_class(instance=thing) # and render the template return render(request, 'things/edit_thing.html', {'thing': thing,'form': form,}) def create_thing(request): form_class = ThingForm if request.method == 'POST': form = form_class(request.POST) if form.is_valid(): thing = form.save(commit=False) thing.user = request.user thing.slug = slugify(thing.name) thing.save() slug = slugify(thing.name) return redirect('thing_detail', slug=thing.slug) else: form = form_class() return render(request,'things/create_thing.html', {'form': form,}) def edit_weight(request, slug): thing = get_object_or_404(Thing, slug=slug) if request.method == "POST": form = WeightForm(request.POST) if form.is_valid(): weight = form.save(commit=False) weight.thingRA = thing weight.save() return redirect('thing_detail', slug=thing.slug) else: form = WeightForm() return render(request, 'things/edit_weight.html', {'form': form}) """WORKING WEIGHT def remove_weight(request, pk): weight = get_object_or_404(Weight, pk=pk) thing_pk = weight.thingRA.pk weight.delete() return redirect('weight_removed') """ def remove_weight(request, pk, slug): weight = get_object_or_404(Weight, pk=pk) thing = get_object_or_404(Thing, slug=slug) thing_pk = weight.thingRA.pk weight.delete() return redirect('thing_detail', slug=slug) @login_required def edit_thing(request, slug): # grab the object... thing = Thing.objects.get(slug=slug) # make sure the logged in user is the owner of the thing if thing.user != request.user: raise Http404 # set the form we're using... form_class = ThingForm # if we're coming to this view from a submitted form, if request.method == 'POST': # grab the data from the submitted form and # apply to the form form = form_class(data=request.POST, instance=thing) if form.is_valid(): # save the new data form.save() return redirect('thing_detail', slug=thing.slug) # otherwise just create the form else: form = form_class(instance=thing) # and render the template return render(request, 'things/edit_thing.html', {'thing': thing,'form': form,}) </code></pre>
113,486
0
<p>It's a good practice. Unless you use ViewState values on postbacks, or they are required by some complex control itself it's good idea to save on ViewState as part of what will be sent to the client.</p>
12,869,937
0
How can I access a link with a div id directly in jQuery Mobile? <p>Suppose I have a link, say, <code>http://www.example.com/index.html#xyz</code>. When I open it in browser with <code>www.example.com/index.html</code> it works fine, but when I have a link targeting <code>#xyz</code> on the same page it loads a new <code>data-role=content</code> page through ajax. </p> <p>Now my query is if I access the same URL directly as <code>http://www.example.com/index.html#xyz</code>, it loads the <code>www.example.com/index.html</code> and not the specific <code>#xyz</code> page. </p> <p>Is there any way to make this work? </p> <p>NOTE: The <code>#xyz</code> page content is loaded dynamically.</p>
14,626,552
0
<p>This is called "hoisting" <code>SlowVariabele</code> out of the loop.</p> <p>The compiler can do it only if it can prove that the value of <code>SlowVariabele</code> is the same every time, and that evaluating <code>SlowVariabele</code> has no side-effects.</p> <p>So for example consider the following code (I assume for the sake of example that accessing through a pointer is "slow" for some reason):</p> <pre><code>void foo1(int *SlowVariabele, int *result) { for (int i = 0; i &lt; *SlowVariabele; ++i) { --*result; } } </code></pre> <p>The compiler cannot (in general) hoist, because for all it knows it will be called with <code>result == SlowVariabele</code>, and so the value of <code>*SlowVariabele</code> is changing during the loop.</p> <p>On the other hand:</p> <pre><code>void foo2(int *result) { int val = 12; int *SlowVariabele = &amp;val; for (int i = 0; i &lt; *SlowVariabele; ++i) { --*result; } } </code></pre> <p>Now at least in principle, the compiler <em>can</em> know that <code>val</code> never changes in the loop, and so it can hoist. Whether it actually does so is a matter of how aggressive the optimizer is and how good its analysis of the function is, but I'd expect any serious compiler to be capable of it.</p> <p>Similarly, if <code>foo1</code> was called with pointers that the compiler can determine (at the call site) are non-equal, and if the call is inlined, then the compiler could hoist. That's what <code>restrict</code> is for:</p> <pre><code>void foo3(int *restrict SlowVariabele, int *restrict result) { for (int i = 0; i &lt; *SlowVariabele; ++i) { --*result; } } </code></pre> <p><code>restrict</code> (introduced in C99) means "you must not call this function with <code>result == SlowVariabele</code>", and allows the compiler to hoist.</p> <p>Similarly:</p> <pre><code>void foo4(int *SlowVariabele, float *result) { for (int i = 0; i &lt; *SlowVariabele; ++i) { --*result; } } </code></pre> <p>The strict aliasing rules mean that <code>SlowVariable</code> and <code>result</code> must not refer to the same location (or the program has undefined behaviour anyway), and so again the compiler can hoist.</p>
20,802,831
0
<p>Short answer: The Class <code>com.ku.aajakobazzar.MainActivity</code> is not in your project dependencies accordingly.</p>
15,289,290
0
<p>There is 2 options for you:</p> <ol> <li>If your condition can be expressed in If Controller, then use standard <a href="http://jmeter.apache.org/usermanual/component_reference.html#Test_Action" rel="nofollow">Test Action</a> Component to stop test</li> <li>If you want to stop test when response time or error rate increases some threshod, then use custom <a href="http://code.google.com/p/jmeter-plugins/wiki/AutoStop" rel="nofollow">AutoStop</a> Component</li> </ol>
18,914,585
0
Losing data when sending by UDP <p>I've written a UDP send/receive function to send a struct and listen for another struct back. The bytes have to be sent in a particular order, but this is working OK as I'm using <code>#pragma pack(1)</code>. The only problem that I'm having now is that if any <code>Null</code> values (<code>0x00</code>) appear in the struct, the rest of the data after the <code>Null</code> disappears.</p> <p>I guess there's something fairly simple that I'm doing wrong, but here is my code:</p> <pre><code>typedef u_int8_t NN; typedef u_int8_t X; typedef int32_t S; typedef u_int32_t U; typedef char C; typedef struct{ X test; NN test2[2]; C test3[4]; S test4; } Test; int main(int argc, char** argv) { Test t; memset( &amp;t, 0, sizeof(t)); t.test = 0xde; t.test2[0]=0xad; t.test2[1]=0x00; t.test3[0]=0xbe; t.test3[1]=0xef; t.test3[2]=0xde; t.test3[3]=0xca; t.test4=0xde; LogOnResponse response; udp_send_receive(&amp;t, &amp;response); return 0; } </code></pre> <p>And here is my send/receive function:</p> <pre><code>int send_and_receive(void* message, void* reply, int do_send, int expect_reply) { struct sockaddr_in serv_addr; int sockfd, i, slen=sizeof(serv_addr); int buflen = BUFLEN; void* buf = NULL; struct timeval tv; int n_timeouts=1; int recv_retval; // printf("Message Size: %d\n", strlen(message)); if ( (strlen(message)) &gt;= BUFLEN) err("Message too big"); buf = malloc(buflen); if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1) err("socket"); tv.tv_sec = timeout_seconds; tv.tv_usec = timeout_microseconds; if( setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO,&amp;tv,sizeof(tv)) &lt; 0 ){ err("Setting Timout"); } bzero(&amp;serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); if (inet_aton(IP_ADDRESS, &amp;serv_addr.sin_addr)==0) err("inet_aton() failed\n"); //---Timeout Send/Receive loop do{ if(do_send == TRUE){ strcpy(buf, message); if (sendto(sockfd, buf, buflen, 0, (struct sockaddr*)&amp;serv_addr, slen)==-1) err("sendto()"); } if (expect_reply == TRUE){ if( (recv_retval = recvfrom(sockfd, buf, buflen, 0, (struct sockaddr*)&amp;serv_addr, &amp;slen)) == -1){ itercount++; } } }while ((itercount &lt; itermax) &amp;&amp; (recv_retval == -1)); if ( itercount != itermax ){ memcpy(reply, buf, BUFLEN); } else{ reply=NULL; } close(sockfd); free(buf); return 0; } void udp_send_receive(void* message, void* reply) { send_and_receive(message, reply, TRUE, TRUE); } </code></pre> <p>Running the above code and capturing the packets with <code>WireShark</code> shows:</p> <p><code>Data: DEAD000000000000000000....</code></p> <p>I'd like it to show:</p> <p><code>Data: DEAD00BEEFDECADE</code></p> <p>I'd really appreciate some pointers on this.</p>
31,152,731
0
<p>Here, I am storing all the names ending with 'x' in <code>namex_list</code> instead of using the <code>list</code>(also a built-in variable) variable you used before.</p> <p>Also, i am assigning <code>namex_list</code> as an empty list before the while condition and printing the <code>namex_list</code> at the end outside of <code>while</code>.</p> <pre><code>namex_list = [] while True: name = input("Enter your name: ") if name == "": break if name.endswith("x"): namex_list.append(name) print (namex_list) </code></pre> <p>Also, <code>name == namex</code> does not check what you are trying to achieve because of the comparison between string values and boolean values.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; name1 = 'abc' &gt;&gt;&gt; name2 = 'abcx' &gt;&gt;&gt; namex1 = name1.endswith('x') &gt;&gt;&gt; namex2 = name2.endswith('x') &gt;&gt;&gt; namex1 False &gt;&gt;&gt; namex2 True &gt;&gt;&gt; name1 == namex1 False &gt;&gt;&gt; name2 == namex2 False </code></pre> <p>You should use an <code>if</code> instead to achieve what you are trying to achieve in your code above:</p> <pre><code>if name.endswith("x"): </code></pre>
32,199,622
0
<p>This is rather crude but it should work. On the form :-</p> <pre><code>&lt;input type="checkbox" name="room101" value="1"&gt;Camera 101 &lt;input type="checkbox" name="room102" value="1"&gt;Camera 102 </code></pre> <p>In the PHP code :-</p> <pre><code>$room101 = (int) $_POST['room101']; $room102 = (int) $_POST['room102']; </code></pre> <p>The two variables will have either 1 (Selected) or 0 (Not selected)</p> <p>You could make the two variables an array if there are lots of cameras.</p>
28,013,028
0
<p>For Your requirement. For creation of microposts. do something like this.</p> <pre><code>artist=Artist who is logged in artist.artist_micro_posts.build(attributes) artist.save </code></pre> <p>For creating comments to microposts</p> <pre><code>micro_posts= Micropost Id micro_post.artist_micropost_comments.build(:artist_id=logged in person) micro_post.save </code></pre>
2,427,125
0
<p>I've been using the Mozex extension for Firefox for years.</p> <ul> <li><a href="http://mozex.mozdev.org/" rel="nofollow noreferrer">http://mozex.mozdev.org/</a></li> </ul> <p>Once installed, on the "Textarea" tab, assign a hot-key and enter the command to run. For example:</p> <pre><code>gnome-terminal -e "/usr/bin/vim %t" </code></pre> <p>When the hot-key is pressed, Mozex will create a temporary file and replace the "%t" above with its name.</p> <p>If there's more than one text area on a page it will allow you to pick which one you want to edit.</p> <p>Mozex provides a lot more functionality than just text area editing. If you want to "view source" with Vim, you can do that too.</p>
37,725,413
0
<p>This is just a quick hack. I don't have enough information to refine the code. But is should definitely point you in the right direction. <br /> Your code was trying to connect to the Excel Spreadsheet. The proper way is to connect to your database and use conn.execute to run your queries. </p> <pre><code>Sub TransferSpreadsheet() Dim destinationTable As String, rangeAddress As String, SqlQuery As String Dim conn Set conn = CreateObject("ADODB.Connection") conn.Provider = "OLEDB;Provider=Microsoft.ACE.OLEDB.12.0;" conn.Open "C:\Users\tinzina\Datafiles\Spotlights.accdb" destinationTable = "TempTable" rangeAddress = getTableAddress("Sheet1") ExportExceltoAccessTable ThisWorkbook.Name, conn, destinationTable ' SqlQuery is the name of a "Saved Query" in your database 'The "Saved Query" will insert the records from TempTable into whatever table you want SqlQuery = "" conn.Execute SqlQuery End Sub Private Sub ExportExceltoAccessTable(conn, destinationTable, rangeAddress) On Error Resume Next conn.Execute "DROP TABLE " &amp; destinationTable &amp; ";" On Error GoTo 0 SqlQuery = "SELECT * INTO " &amp; destinationTable &amp; " FROM [Excel 8.0;HDR=YES;DATABASE=" &amp; ThisWorkbook.FullName &amp; "]." &amp; rangeAddress conn.Execute SqlQuery End Sub Public Function getTableAddress(wsSheetName) Dim r As range Set r = Worksheets(wsSheetName).UsedRange getTableAddress = "[" &amp; r.Worksheet.Name &amp; "$" &amp; r.Address(False, False) &amp; "]" End Function </code></pre> <p>Let me know if you have any questions</p>
12,354,482
0
<p>You can make use of onreadystatechange event: <a href="http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp" rel="nofollow">http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp</a></p>
23,510,811
0
<p>Use a case expression to get an order key:</p> <pre><code>select * from book_history order by case status when 1 then 100 -- any small value would do here when 0 then 200 -- any medium value would do here when 2 then 300 -- any big value would do here end; </code></pre>
13,815,683
0
how to minify a whole folder content using grunt.js <p>Instead of mention every <code>js</code> seperatly, is this the way to minify and concatinate a whole js folder?</p> <pre><code>module.exports = function(grunt) { grunt.initConfig({ min: { dist: { src: ['scripts/*.js'], dest: 'dist/built.min.js' } } }); }; </code></pre>
1,246,931
0
<p>Set the delegate of the text field to you controller class, implement the <code>UITextFieldDelegate</code> protocol and put your formatting code in the <code>textField:shouldChangeCharactersInRange:replacementString:</code> method.</p>
1,550,960
0
<p>The hashmaps work really well if the hashing function gives you a very uniform distribution of the hashvalues of the existing keys. With really bad hash function it can happen so that hash values of your 20 values will be the same, which will push the retrieval time to O(n). The binary search on the other hand guaranties you O(log n), but inserting data is more expensive.</p> <p>All of this is very incremental, the bigger your dataset is the less are the chances of a bad key distribution (if you are using a good, proven hash algorithm), and on smaller data sets the difference between O(n) and O(log n) is not much to worry about.</p>
4,565,391
0
<p>It largely depends on your overall technology stack. If you're already set up with nHibernate and there's no external motivating factor (business reason, etc), then there's no true need to move over to EF4. However, if you're almost exclusively using the MS technology stack, then moving to EF4 will further that effort.</p> <p>That said, Spring.NET and nHibernate have a great, mature history of interoperability, and it's tough to fix what isn't broken. I'm in the process of building up a Domain Model using POCOs with EF4 and Spring.NET and can attest there are a lot of learning opportunities and instances of "OK, how am I going to do THAT?". But it's certainly doable and while there aren't many resources out there specifically of using EF4 and Spring.NET, there is good guidance in the general realm of EF4 and DDD.</p> <p>Dunno if that helped at all, but it's my two cents on the topic.</p>
21,981,408
0
sas macros for incrementing date <p>My codes are:</p> <pre><code>libname " Cp/mydata" options ; %let yyyymmdd=20050210; %let offset=0; %let startrange=0; %let endrange=0; /* MACRO FOR INCREMENTING THE DATE */ %macro base(yyyymmdd=, offset=); %local date x ds; /* declare macro variables with local scope */ %let date=%sysfunc(mdy(%substr(&amp;yyyymmdd,5,2) ,%substr(&amp;yyyymmdd,7,2) ,%substr(&amp;yyyymmdd,1,4))); /* convert yyyymmdd to SAS date */ %let loopout=100;/* hardcoded - number of times to check whether ds exists */ %do x=&amp;offset %to &amp;loopout; /* begin loop */ /* convert &amp;date to yyyymmdd format */ %let ds=AQ.CO_%sysfunc(intnx(day,&amp;date,&amp;offset),yymmddn8.); %if %sysfunc(exist( &amp;ds )) %then %do; %put &amp;ds exists!; &amp;ds /* write out the dataset, if it exists */ %let x=&amp;loopout; /* exit loop */ %end; %else %do; %put &amp;ds does not exist - checking subsequent day; %let date=&amp;date+1; %end; %end; %mend; %macro loop(yyyymmdd=, startrange=, endrange=); %local date x ds; %let date=%sysfunc(mdy(%substr(&amp;yyyymmdd,5,2) ,%substr(&amp;yyyymmdd,7,2) ,%substr(&amp;yyyymmdd,1,4))); data x; set set %base(yyyymmdd=&amp;yyyymmdd, offset=0) /* loop through each specific dataset, checking first whether it exists.. */ %do x=&amp;startrange %to &amp;endrange; %let ds=AQ.CO_%sysfunc(intnx(day,&amp;date,&amp;x),yymmddn8.); %if %sysfunc(exist( &amp;ds )) %then %do; &amp;ds %end; %end; ; run; %mend; </code></pre> <p>This was the error generated when I tried to run this macro.</p> <p>data temp;</p> <p>58 set %loop(yyyymmdd=&amp;yyyymmdd, startrange=&amp;startrange, 58 ! endrange=&amp;endrange); </p> <p>ERROR: File WORK.DATA.DATA does not exist.</p> <p>ERROR: File WORK.X.DATA does not exist.</p> <p>AQ.CO_20050210 does not exist - checking subsequent day</p> <p>AQ.CO_20050211 does not exist - checking subsequent day</p> <p>AQ.CO_20050212 exists!</p> <p>NOTE: The system stopped processing this step because of errors.</p> <p>I want help on two things:</p> <p>1) Here, I'm trying to increment my date by 1 or 2 or so on if that date is not there in my original dataset. Please help to make this macro work fine.</p> <p>2)I would like to have another column ie work.date in my data that will have 0 or 1(1 if the specified date yyyymmdd exist in our original data and 0 if I'm incrementing). Please make the specified changes in my macro. Thanks in advance!!</p>
39,883,988
0
<p>SPOOL is a SQLPlus command, so you can not use it in a PlSQL block dynamically.</p> <p>One way could be creating at runtime a second script, dynamically built based on your query, and then run it to do the job. For example:</p> <pre><code>conn ... set serveroutput on set feedback off variable fullpath varchar2(20); variable filename varchar2(10); variable extension varchar2(5); variable sep varchar2(1); /* spool to a fixed file, that will contain your dynamic script */ spool d:\secondScript.sql begin select 'filename', 'd:\', 'txt', '|' into :filename, :fullpath, :extension, :sep from dual; /* write the second script */ dbms_output.put_line('set colsep ' || :sep); dbms_output.put_line('spool ' || :fullpath || :filename || '.' || :extension); dbms_output.put_line('select 1, 2, 3 from dual;'); dbms_output.put_line('spool off'); end; / spool off /* run the second script */ @d:\secondscript.sql </code></pre> <p>This gives:</p> <pre><code>SQL&gt; sta C:\firstScript.sql Connected. set colsep | spool d:\filename.txt select 1, 2, 3 from dual; 1| 2| 3 ----------|----------|---------- 1| 2| 3 </code></pre> <p><strong>d:\filename.txt</strong>:</p> <pre><code> 1| 2| 3 ----------|----------|---------- 1| 2| 3 </code></pre>
1,487,275
0
Programmatically switch the ID generator in NH mapping file <p>So I'm currently attempting to do a promotion of objects from one database to another in my app. Basically I want to allow the user to click a button and promote changes from staging to production, as it were.</p> <p>To do this, I really want to keep the IDs the same in order to help with debugging. So for example if the object has an ID of 6 in the staging db, I want it to have that same ID on production. To do this, we turned off identity on our production db and just made those primary key columns with non-null integers.</p> <p>In my staging mapping file, my IDs are mapped using the "identity" generator, but for production I want them to be "assigned". Is it possible to programmatically change this, perhaps using an interceptor or something similar?</p> <p>Thanks in advance!</p>
20,497,315
0
template template parameters with container and default allocator: can I make my declaration more compact? <p>I was looking at this interesting thread: <a href="http://stackoverflow.com/a/16596463/2436175">http://stackoverflow.com/a/16596463/2436175</a></p> <p>My specific case concerns declaring a templated function using a std container of cv::Point_ and cv::Rect_ from opencv. I want to template against: </p> <ul> <li>the type of std container I will use</li> <li>the basic data types to complete the definition of cv::Point_ and cv::Rect_</li> </ul> <p>I ended up with the following declaration:</p> <pre><code>template &lt;typename T, template &lt;typename, typename&gt; class Container_t&gt; void CreateRects(const Container_t&lt;cv::Point_&lt;T&gt;,std::allocator&lt;cv::Point_&lt;T&gt; &gt; &gt;&amp; points, const T value, Container_t&lt;cv::Rect_&lt;T&gt;,std::allocator&lt;cv::Rect_&lt;T&gt; &gt; &gt;&amp; rects) { } </code></pre> <p>which compiles fine with this:</p> <pre><code>void dummy() { const std::vector&lt;cv::Point_&lt;double&gt; &gt; points; std::vector&lt;cv::Rect_&lt;double&gt; &gt; rects; CreateRects(points,5.0,rects); } </code></pre> <p>(I have also seen that I can also use, for example, <code>CreateRects&lt;double&gt;(points,5,rects)</code>)</p> <p>I was wondering if there existed any way to make my declaration more compact, e.g. without the need to specify 2 times the default allocator.</p>
22,157,950
0
<p>You cannot write to the install directory without explicit permission from the user.</p> <p>Here is the protocol instead:</p> <ul> <li>At first startup, check to see if there is a file in the local data folder (<code>ApplicationDataContainer</code>), if not, read in the file from the install directory.</li> <li>Write out a copy of the file to the local app data folder (Check out guides on <code>ApplicationDataContainer</code> for more info there)</li> <li>Edit this file freely.</li> </ul>
16,819,408
0
<p>You are not referencing the <code>$id</code> variable, but rather a string text <code>id</code> which breaks the query statement. Add a dollar sign to reference the variable, and if it's anything but an integer, wrap it in single quotes, too.</p> <p><code>$query = "UPDATE utilizatori SET username = '$username', {...}, ip = '$ip' where id= '$id' ";</code></p>
27,343,768
0
Debugging runtime pl/sql errors <p>I’m new in pl/sq.</p> <p>So, I’m trying to call pl/sql stored procedure from Java, but appears error:</p> <pre><code>wrong number or types of arguments in call to ‘searchuser’. </code></pre> <p>Where can I find most specific exception?</p> <p>Is there some error logs or errors table in oracle? How can I debug these kind of problems?</p> <p>Thanks!</p>
7,468,556
0
<p>Your solution is just fine. As long as you are only using 1 column for each "joined" table, and has no multiple matching rows, it is fine. In some cases, even better than joining. (the db engine could anytime change the direction of a join, if you are not using tricks to force a given direction, which could cause performance suprises. It is called query optimiyation, but as far as you really know your database, you should be the one to decide how the query should run).</p>
349,755
0
<p>Well, of the three you've listed, NHibernate has been around the longest. If you want to work with something which has a proven track record, that's probably a safe place to begin. </p> <p>It is pretty even across the four metrics (scale/learning curve/ease of use and performance) although you might find there is more information available due to it being around longer than the other two.</p> <p>LINQ to SQL has been released longer than the Entity Framework, but only runs against SQL Server flavours. It works very well as a fit-for-purpose ORM, but is not a feature-rich as the Entity Framework (which provides eSql amongst other things).</p> <p>LINQ to SQL is pretty easy to grasp (depending on your knowledge of LINQ) and more recently the quality of the generated queries has improved (since the earlier betas). I'm not sure how well it scales, or performs, but you'd have to think it's on par with an average developer's handwritten T-SQL (okay now that's a wild assumption!). It's pretty straightforward, and generates a very nice model for you within Visual Studio.</p> <p>There are other <a href="http://www.devart.com/dotconnect/linq.html" rel="nofollow noreferrer">(2) alternatives</a> for non-SQL Server databases support</p> <p>The Entity Framework is the newest of the three and as a result, still has some issues to be corrected (hopefully in the next version). It will work with a number of providers (it's not limited to SQL Server) and has additional goodness such as eSQL and <a href="http://msdn.microsoft.com/en-us/data/cc765425.aspx" rel="nofollow noreferrer">(1) Table-Per-Type inheritance</a>. It can be a bit tricky to learn at first, but once you've done one or two solutions with it, it gets predictable and easier to implement.</p> <p>Due to it being the latest, it'll take a bit more in terms of learning curve (also there's more to learn), and the performance is.. less than desirable (at present) but it does offer some interesting benefits (especially the support for multiple providers).</p> <p>I guess my question in reply is - are you just evaluating or do you need to produce a workable (production-ready) ORM solution? </p> <p>The Entity Framework probably isn't quite ready for serious production work (outside of smaller solutions) which leaves you with LINQ to SQL or NHibernate. If you're only going to be working with SQL Server databases, LINQ to SQL is an interesting option. Otherwise, NHibernate is probably the best bet for serious work.</p> <p>(1) [ <a href="http://msdn.microsoft.com/en-us/data/cc765425.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/data/cc765425.aspx</a> ] (2) [ <a href="http://www.devart.com/dotconnect/linq.html" rel="nofollow noreferrer">http://www.devart.com/dotconnect/linq.html</a> ]</p>
22,084,574
0
multi line js regular expression <pre><code>var Text = "start abc\ndef\nghi\njkl"; var regexAT = new RegExp("start([\s\S]*)", ''); var match = regexAT.exec(Text); alert(match[1]); </code></pre> <p>my limited js skills tell me that match[1] should contain:</p> <pre><code>abc\ndef\nghi\njkl </code></pre> <p>however match[1] is null, any tips?</p> <p><a href="http://jsfiddle.net/XE44B/" rel="nofollow">http://jsfiddle.net/XE44B/</a></p>
19,501,614
0
<p>If you know the name of the menu inside drupal you can render it this way:</p> <p><strong>Example of page.tpl.php:</strong></p> <pre><code>&lt;div id="menu"&gt; &lt;?php if (isset($secondary_menu)) { ?&gt;&lt;?php print theme('links', $secondary_menu, array('class' =&gt; 'links', 'id' =&gt; 'subnavlist')); ?&gt;&lt;?php } ?&gt; &lt;?php if (isset($main_menu)) { ?&gt;&lt;?php print theme('links', $main_menu, array('class' =&gt; 'links', 'id' =&gt; 'navlist')) ?&gt;&lt;?php } ?&gt; &lt;/div&gt; </code></pre> <p>For more information on how to convert a drupal 6 theme to drupal 7 I would recommend going through this tutorial:</p> <p><a href="https://drupal.org/node/254940#menus" rel="nofollow">https://drupal.org/node/254940#menus</a></p>
9,887,031
0
<p>O.K, I got my mistake!!! I've used the <code>@InjectMocks</code> but initialized the same variable in the init() method... So what happened was that mockito injected the mock objects to my variable - but seconds later I ran it over - initializing that very same variable!!!</p>
16,608,976
0
<p>I use it this way:</p> <p>So it is not necessary to wait the specific time to end.</p> <pre><code>public void run(){ try { //do something try{Thread.sleep(3000);}catch(Exception e){} //do something }catch(Exception e){} } </code></pre>
19,117,076
0
Animate control with respecting parents/container <p>I have a control that I move with help of animation from the bottom to the final position. My problem is now that I want to change the behaviour of the animation, so that it respects the outer container (DarkGray).</p> <p>The orange Ractangle should only be visible on the white background and not on the darkgray Grid!</p> <p><strong>Code:</strong></p> <p>MainWindow.xaml:</p> <pre><code>&lt;Grid Background="DarkGray"&gt; &lt;Grid Margin="50" Background="White"&gt; &lt;Rectangle x:Name="objectToMove" VerticalAlignment="Bottom" Fill="Orange" Height="50" Width="50"/&gt; &lt;Button Height="20" Width="40" Margin="20" Content="Move" Click="Button_Click" VerticalAlignment="Top"/&gt; &lt;/Grid&gt; &lt;/Grid&gt; </code></pre> <p>MainWindow.xaml.cs:</p> <pre><code>private void Button_Click(object sender, RoutedEventArgs e) { var target = objectToMove; var heightOfControl = target.ActualHeight; var trans = new TranslateTransform(); target.RenderTransform = trans; var myAnimation = new DoubleAnimation(heightOfControl, 0, TimeSpan.FromMilliseconds(600)); trans.BeginAnimation(TranslateTransform.YProperty, myAnimation); } </code></pre> <p>Current:<br> <img src="https://i.stack.imgur.com/sNscV.png" alt="Snapshot of the running code snippets"></p> <p>Desired solution:<br> <img src="https://i.stack.imgur.com/69eVr.png" alt="Should be like this"></p>
1,416,068
0
<p>when creating the hashed password you should use "double" salt</p> <p>Create a salt (random md5 or sha1) then use format something like sha1("--$password--$salt--") and then store hashed password and salt in database. </p> <p>Then, when authenticating you recreate the hash from --$pass--$salt-- string and compare it to the pass stored in db.</p>
21,581,178
0
How to add MFC application project to Win32 application project in Visual C++ 2008 <p>I've spent most of my day trying to figure out why this error is occurring but it continues to mystify me.</p> <p>I created a console application in Visual C++ and created one MFC application.Now, I want to add them into single project such way that when i compile the project ,it should open the console then will open Dialog box depending upon my commands......</p> <p>I've added afx headers files,set configuration settings.</p> <p>I want to know where to start whether starting point would in winmain() or int main()? Is there any examples.? Give me some links to know. the solution Thank you in advance.</p>
17,777,437
0
<p>The sql <a href="http://www.w3schools.com/sql/sql_func_max.asp" rel="nofollow">max</a> function returns the largest value of the selected column, in your case since your data type is a <code>nvarchar</code> the <em>largest</em> value is what is alphabetically larger, which in this case is <code>7/2/2013</code> (since the "2" is greater then the "1" in "13").</p> <p>What you need to do is basically what <a href="http://stackoverflow.com/users/328193/david">@David</a> mentioned, either chance the data type of the column or if it isn't feasible then you can cast it in your query as a <code>datetime</code></p> <p>For example</p> <pre><code>select max(cast([P_Date] as datetime)) from [BalDB].[dbo].[tab_Product] </code></pre>
14,319,160
0
<p>The image is 1200px wide. So on a 1900 resolution the image doesn't stretch and is smaller :). If you use background-size: 100%; It should stretch.</p> <p>As for mobile: <a href="http://stackoverflow.com/questions/8011085/keep-image-on-top-while-scrolling">This question is the same issue as you with solution.</a></p>
12,324,924
0
URLConnection.getInputStream: specifying byte range start but no end <p>My goal is to read only the bytes from a file on a remote server starting at a particular byte position in the file without unnecessary data transfer. My concern is that without specifying an end byte, the entire file from the start byte is put into a buffer before any reads occur. </p> <p>When one specifies a byte range in this fashion:</p> <pre><code>urlConn.setRequestProperty("Range","bytes="+byteRangeStart+"-") </code></pre> <p>and then subsequently obtains an InputStream, will that InputStream contain all the bytes of the file from byteRangeStart to the end of the file meaning that all the data is transferred when the InputStream is obtained or are bytes only transferred when the InputStream is read from?</p>
18,323,891
0
<p>You just need to cast first, before attempting to call <code>execute</code>:</p> <pre><code>return ((Commands)type).execute(cmdParams); </code></pre> <p>The way you have it written, it's attempting to call <code>execute</code> on the un-casted type, and then to cast the result to <code>Commands</code>.</p>
22,632,670
0
<p>You can try this XPath to get text node after <code>&lt;a&gt;</code> element :</p> <pre><code>nodeValue = hd.DocumentNode .SelectSingleNode("//div[@class='resum_card']/p/a/following-sibling::text()"); </code></pre> <p>Note: simply use single slash (<code>/</code>) instead of double (<code>//</code>) to select element that is direct child of current element. It is better performance wise.</p>
3,714,659
0
<p>Try this (inside your for loop): </p> <p><strong>Updated:</strong> </p> <pre><code>var joiners; for ... { joiners += pings[i].joining_profiles[q].name + " "; var newText = RTRIM(joiners).split(" ").join(","); } </code></pre>
27,127,242
0
seekg, fail on large files <p>I have a very large (950GB) binary file in which I store 1billion of sequences of float points.</p> <p>A small example of the type of file I have with sequences of length 3 could be:</p> <pre><code>-3.456 -2.981 1.244 2.453 1.234 0.11 3.45 13.452 1.245 -0.234 -1.983 -2.453 </code></pre> <p>Now, I want to read a particular sequence (let's say the sequence with index=2, therefore the 3rd sequence in my file) so I use the following code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;stdlib.h&gt; using namespace std; int main (int argc, char** argv){ if(argc &lt; 4){ cout &lt;&lt; "usage: " &lt;&lt; argv[0] &lt;&lt; " &lt;input_file&gt; &lt;length&gt; &lt;ts_index&gt;" &lt;&lt; endl; exit(EXIT_FAILURE); } ifstream in (argv[1], ios::binary); int length = atoi(argv[2]); int index = atoi(argv[3]); float* ts = new float [length]; in.clear(); **in.seekg(index*length*sizeof(float), in.beg);** if(in.bad()) cout &lt;&lt; "Errore\n"; **// for(int i=0; i&lt;index+1; i++){** in.read(reinterpret_cast&lt;char*&gt; (ts), sizeof(float)*length); **// }** for(int i=0; i&lt;length; i++){ cout &lt;&lt; ts[i] &lt;&lt; " "; } cout &lt;&lt; endl; in.close(); delete [] ts; return 0; } </code></pre> <p>The problem is that when I use seekg this read fails for some indexes and I get a wrong result. If I read the file in a sequential manner (without using seekg) and print out the wanted sequence instead, I always get the correct result.</p> <p>At the beginning I thought about an overflow in seekg (since the number of bytes can be very big), but I saw seekg takes in input a streamoff type which is huge (billions of billions).</p>
24,469,610
0
<p>Not every MATLAB function can be converted to C code.</p> <p>For a list of supported function see <a href="http://www.mathworks.com/help/simulink/ug/functions-supported-for-code-generation--alphabetical-list.html" rel="nofollow">here</a>.</p> <p>If you wish to use MATLAB functions that are not on the list, you should write your own version in MATLAB (if possible, in your case I doubt it) or in C.</p>
11,990,232
0
<p>As <a href="http://stackoverflow.com/users/1366455/tolgap">tolgap</a> pointed in his comment, the fact that you have something about "br" looks like your page is sending back a PHP error, with its HTML formatting (hence the BR) instead of the JSON string. You should try and fix that error first.</p>
5,789,787
0
<p>Two simple options would be to either provide your user with some dictionary where they can register type mappings, or alternatively just provide them with a container interface that provides all of the services you think you're likely to require and allow users to supply their own wrapped containers. Apologies if these don't quite fit your scenario, I primarily use Unity, so I don't know if Ninject, etc. do fancy things Unity doesn't.</p>
35,652,416
0
<p>To add new profile question you have to utilize admin panel. Just go to URL <strong>www.yoursitename.com/admin/users/profile-questions</strong></p> <p>On this page you will get options for add <strong>Sections</strong> and <strong>Profile questions</strong>. Fill up the form and save using submit button.</p> <p>Regarding your query, To add a question with answer as drop down or list, you need to add them with <strong>Answer type field as drop down</strong>.</p> <p>Once you create new question if your site supports multiple language then you have to put corresponding value in <strong>yoursite.com/admin/settings/languages</strong></p> <p>FYI: new questions are stored under base section.</p>
5,375,542
0
Jquery .post() return array <p>Sorry for the bad title, but I don't know how to name this. My problem is that whenever I pass a value from a select box I trigger this jquery event in order to check on the check boxes. Bassically I echo $res[]; at selecctedgr.php. Do I need to use json? and how can I do this?</p> <p>Mainpage:</p> <pre><code>$("#group_name").change(function(){ var groupname = $("#group_name").val(); var selectedGroup = 'gr_name='+ groupname; $.post("selectedgr.php", {data: selectedGroup}, function(data){ $.each(data, function(){ $("#" + this).attr("checked","checked"); }); },"json"); }); </code></pre> <p>PHP (selectedgr.php):</p> <pre><code>&lt;?php include_once '../include/lib.php'; $gr_name=mysql_real_escape_string($_POST['gr_name']); $sqlgr = "SELECT * FROM PRIVILLAGE WHERE MAINGR_ID=".$gr_name; $resultgr = sql($sqlgr); while($rowgr = mysql_fetch_array($resultgr)){ $res[] = $rowgr['ACT_ID']; } echo $res[]; ?&gt; </code></pre>
7,640,083
0
<p>Possibly not the most relevant answer to your original question but since I got redirected to this page while looking for a way to control the formatting of DateTime properties in the serialisation someone else might find it useful.</p> <p>I found that by adding the following to your app.config/web.config instructs the .NET serialisation to format DateTime properties consistently:</p> <pre><code> &lt;system.xml.serialization&gt; &lt;dateTimeSerialization mode="Local" /&gt; &lt;/system.xml.serialization&gt; </code></pre> <p>Ref: <a href="http://msdn.microsoft.com/en-us/library/ms229751(v=VS.85).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms229751(v=VS.85).aspx</a></p>
22,202,811
0
<p>It really depends on how you store data, you want to delete. If you just want to hide deleted element from page, you can do that with javascript. eg.:</p> <pre><code>$(document).on("click", ".alert", function(e) { bootbox.confirm("?", function(result) { $(this).hide(200); // animated }); }); </code></pre> <p>If you store data you show in database, you should use ajax to request for example php that erase data from database.</p>
29,527,705
0
<p>You need to save the information in parse. First off I would start by setting a variable for PFUser.currentUser(). So something like: </p> <pre><code>var UserInfo = PFUser.currentUser() </code></pre> <p>Then you need to save your info in the background. So right before your dismissViewController, user this:</p> <pre><code>UserInfo.saveInBackgroundWithBlock { (success:Bool, error:NSError!) -&gt; Void in } </code></pre>
32,016,580
0
<p>In:</p> <pre><code>template &lt;typename T&gt; void Method1(T&amp;&amp; a); </code></pre> <p><code>T&amp;&amp;</code> is a <em>forwarding-reference</em>, rather than an <em>rvalue reference</em>.</p> <p>Now, the call:</p> <pre><code>classA.Method1(a); </code></pre> <p>deduces <code>T</code> to be <code>double&amp;</code>. The explicit instantiation you provide:</p> <pre><code>template void ClassA::Method1&lt;double&gt;(double&amp;&amp;); </code></pre> <p>is only for <em>rvalue</em> expressions. This is why it compiles and links when you turn <code>a</code> into an <em>xvalue</em> (a kind of an rvalue) with <code>std::move</code>.</p> <p>Try the following explicit instantiation:</p> <pre><code>template void ClassA::Method1&lt;double&amp;&gt;(double&amp;); </code></pre> <p>Still, you don't cover all possibilities a forwarding reference can take, so better move the implementation of <code>Method1</code> to a header file with the class definition.</p>
21,602,882
0
Error:Object [object Object] has no method 'msdropdown' <p>I am new to jQuery if somebody could tell me what i should do to get rid of this error?</p> <pre><code>$(document).ready(function () { debugger; $.ajax({ type: 'POST', url: rootUrl + 'SchedulingProfile/GetVisitTypes', contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { var markup = ''; for (var x = 0; x &lt; data.length; x++) { markup += "&lt;option value='" + data[x].Id + "' title='../images/trans.png' label='background-color:#" + data[x].VisitTypeColor + "'&gt;" + data[x].VisitTypeName + "&lt;/option&gt;"; } $('#ddlAnnualVisitType').html(markup).show(); try { oHandler = $(".mydds").msDropDown().data("dd"); //oHandler.visible(true); $("#ver").html($.msDropDown.version); } catch (e) { alert("Error: " + e.message); } } }); }); </code></pre> <p>Error:Object [object Object] has no method <code>'msdropdown'</code></p>
24,673,698
0
unexpected EOF while looking for matching `'' while using sed <p>Yes this question has been asked many times, and in the answer it is said to us <code>\</code> escape character before the single quote.</p> <p>In the below code it isn't working:</p> <pre><code>LIST="(96634,IV14075295,TR14075685')" LIST=`echo $LIST | sed 's/,/AAA/g' ` echo $LIST # Output: (96634AAAIV14075295AAATR14075685') # Now i want to quote the list elements LIST=`echo $LIST | sed 's/,/\',\'/g' ` # Giving error # exit 0 </code></pre> <p><strong>Error :</strong></p> <pre><code>line 7: unexpected EOF while looking for matching `'' line 8: syntax error: unexpected end of file </code></pre>
17,863,081
0
remove character columns from a numeric data frame <p>I have a data frame like the one you see here. </p> <pre><code> DRSi TP DOC DN date Turbidity Anions 158 5.9 3371 264 14/8/06 5.83 2246.02 217 4.7 2060 428 16/8/06 6.04 1632.29 181 10.6 1828 219 16/8/06 6.11 1005.00 397 5.3 1027 439 16/8/06 5.74 314.19 2204 81.2 11770 1827 15/8/06 9.64 2635.39 307 2.9 1954 589 15/8/06 6.12 2762.02 136 7.1 2712 157 14/8/06 5.83 2049.86 1502 15.3 4123 959 15/8/06 6.48 2648.12 1113 1.5 819 195 17/8/06 5.83 804.42 329 4.1 2264 434 16/8/06 6.19 2214.89 193 3.5 5691 251 17/8/06 5.64 1299.25 1152 3.5 2865 1075 15/8/06 5.66 2573.78 357 4.1 5664 509 16/8/06 6.06 1982.08 513 7.1 2485 586 15/8/06 6.24 2608.35 1645 6.5 4878 208 17/8/06 5.96 969.32 </code></pre> <p>Before I got here i used the following code to remove those columns that had no values at all or some NA's. </p> <pre><code> rem = NULL for(col.nr in 1:dim(E.3)[2]){ if(sum(is.na(E.3[, col.nr]) &gt; 0 | all(is.na(E.3[,col.nr])))){ rem = c(rem, col.nr) } } E.4 &lt;- E.3[, -rem] </code></pre> <p>Now I need to remove the "date" column but not based on its column name, rather based on the fact that it's a character string. </p> <p>I've seen here (<a href="http://stackoverflow.com/questions/6286313/remove-an-entire-column-from-a-data-frame-in-r">remove an entire column from a data.frame in R</a>) already how to simply set it to NULL and other options but I want to use a different argument. </p>
5,497,517
0
How do i repeat my table / RadListView x times? <p>I have made one html-table that contain a RadListView (with use of LayoutTemplate and ItemTemplate), and it works fine.</p> <p>It's a Property-table with two columns ("CadastralNummer", "CadastralSomething"). (The table has as many rows as the property has cadastrals)</p> <p>Now comes the tricky part for me!</p> <p>I now have a list of properties, instead of just one. How do repeat my table for every property below each other?</p> <p>If it can help, here's my code for one table:</p> <pre><code>&lt;table border="0" cellspacing="2" cellpadding="0" width="75%"&gt; &lt;thead&gt; &lt;tr&gt; &lt;td style="width: 25%;"&gt; CadastralNummer &lt;/td&gt; &lt;td style="width: 25%;"&gt; CadastralSomething &lt;/td&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;telerik:RadListView runat="server" ID="RadListViewProperty" AllowPaging="false" DataKeyNames="PropertyNR" OverrideDataSourceControlSorting="true" ItemPlaceholderID="ListViewContainer" OnItemDataBound="RadListViewProperty_ItemDataBound"&gt; &lt;LayoutTemplate&gt; &lt;asp:PlaceHolder runat="server" ID="listViewContainer" /&gt; &lt;/LayoutTemplate&gt; &lt;ItemTemplate&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td style="vertical-align: top;"&gt; &lt;asp:Label ID="lblCadastralNummer" runat="server" /&gt; &lt;/td&gt; &lt;td style="vertical-align: top;"&gt; &lt;asp:Label ID="lblCadastralSomething" runat="server" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/ItemTemplate&gt; &lt;/telerik:RadListView&gt; &lt;/table&gt; </code></pre>
3,894,291
0
<p>The sign bit is the most significant bit on any two's-complement machine (like the x86), and thus will be in the last byte in a little-endian format</p> <p>Just cause i didn't want to be the one not including ASCII art... :)</p> <pre><code>+---------------------------------------+---------------------------------------+ | first byte | second byte | +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+ | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+ ^--- lsb msb / sign bit -----^ </code></pre> <p>Bits are basically represented "backwards" from how most people think about them, which is why the high byte is last. But it's all consistent; "bit 15" comes after "bit 0" just as addresses ought to work, and is still the most significant bit of the most significant byte of the word. You don't have to do any bit twiddling, because the hardware talks in terms of bytes at all but the lowest levels -- so when you read a byte, it looks exactly like you'd expect. Just look at the most significant bit of your word (or the last byte of it, if you're reading a byte at a time), and there's your sign bit.</p> <p>Note, though, that two's complement doesn't exactly designate a particular bit as the "sign bit". That's just a very convenient side effect of how the numbers are represented. For 16-bit numbers, -x is equal to 65536-x rather than 32768+x (which would be the case if the upper bit were strictly the sign).</p>
28,757,540
0
<p>Try this:</p> <pre><code>$.getScript("{{ STATIC_URL }}js/jquery.json.js").done(function( script, textStatus ) { $.getScript("{{ STATIC_URL }}js/jquery.inplaceeditform.js").done(function( script, textStatus ) { var options = {"getFieldUrl": "/inplaceeditform/get_field/", "saveURL": "/inplaceeditform/save/", "successText": "Successfully saved", "eventInplaceEdit": "click", "disableClick": true, "autoSave": true, "unsavedChanges": "You have unsaved changes!", "enableClass": "enable", "fieldTypes": "input, select, textarea", "focusWhenEditing": true}; var inplaceManager = $(".inplaceedit:not(.enable)").inplaceeditform(options); inplaceManager.enable(); }); }); </code></pre>
39,443,978
0
<p>As I know, we can use Azure blob storage to store your files. Azure blob Storage containers provide three access level: Full public read access, Public read access for blobs only, no public read access. Refer to <a href="https://azure.microsoft.com/en-us/documentation/articles/storage-manage-access-to-resources/" rel="nofollow">this article</a> for more details. For your scenario, please save private files in “no public read access”, and save public file in “Public read access for blobs only”. So that the user cannot access your private files but can read your public files. If you want to share private files to others, please try SAS as LoekD mentioned. If you want to expired the SAS token in server side. Please try to use SAS policy to do it. Read <a href="https://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-shared-access-signature-part-1/" rel="nofollow">this article</a> for more details. </p>
14,522,770
0
<p>This is not really a programming question so it should be on superuser.</p> <p>Short answer -</p> <p>reboot the system.</p> <p>If the system comes back up, try:</p> <pre><code>find / -mtime -3 -size +100000 -exec ls -ls {} \; | sort -n </code></pre> <p>The largest newest files will be at the bottom of the list. If you can see that the file is not part of an app- a data file for example- remove it. You need at least 5% free space on /.</p> <p>Long term you must add more disk space, like double or triple what you have.</p>
14,090,987
0
<pre><code>$dir = realpath(dirname(__FILE__)."/../"); </code></pre> <p>This would be the directory you are looking for. Require files relative to that.</p> <p>To output a different file look at <a href="http://php.net/manual/en/function.readfile.php" rel="nofollow">readfile</a> which outputs straight to the buffer or perhaps use <a href="http://php.net/manual/en/function.file-get-contents.php" rel="nofollow">file_get_contents</a> which can be held in a variable.</p>
19,645,176
0
Mule: apply filters and transformers according to HTTP method with REST router (and error handling) <p>I am struggling a little to satisfy my use-case with the Mule REST module. I'd like to have different transformations according to templateUri and HTTP method.</p> <p>Here is my configuration:</p> <pre><code> &lt;flow name="http-interface"&gt; &lt;http:inbound-endpoint address="http://localhost:8555" exchange-pattern="request-response"/&gt; &lt;rest:router templateUri="/schedule"&gt; &lt;rest:post&gt; &lt;mxml:schema-validation-filter schemaLocations="xsd/scheduler.xsd" returnResult="true"/&gt; &lt;mxml:jaxb-xml-to-object-transformer jaxbContext-ref="jaxb-context"/&gt; &lt;vm:outbound-endpoint path="addjob"/&gt; &lt;/rest:post&gt; &lt;/rest:router&gt; &lt;choice-exception-strategy&gt; &lt;catch-exception-strategy when="exception.causedBy(org.mule.api.routing.filter.FilterUnacceptedException)"&gt; &lt;logger level="ERROR" message="FilterUnacceptedException #[message]"/&gt; &lt;set-payload value="An error occurred while validating request. Please check the XML payload"/&gt; &lt;set-property propertyName="http.status" value="400"/&gt; &lt;/catch-exception-strategy&gt; &lt;catch-exception-strategy when="exception.causedBy(java.lang.NullPointerException)"&gt; &lt;logger level="ERROR" message="NullPointerException #[message]"/&gt; &lt;set-payload value="An error occurred while validating request. Please check the XML payload"/&gt; &lt;set-property propertyName="http.status" value="400"/&gt; &lt;/catch-exception-strategy&gt; &lt;/choice-exception-strategy&gt; &lt;/flow&gt; </code></pre> <p>When invalid XML is posted to the endpoint, I am getting a NullPointerException in NestedProcessorChain.processWithExtraProperties. Hence the nasty catch for this exception (not ideal).</p> <p>My IDE gives schema validation errors both for rest:router in flow and the mxml filter/transformer in the rest:post element. I can remove the first by putting rest:router inside the inbound-endpoint. Results are the same, and most examples don't have this</p> <p>I tried moving the filter/transformation to a separate flow on a VM endpoint. Validation is clean, but then I can't figure out how to get the HTTP error code and response back to the client.</p> <p>Any help much appreciated, Alfie.</p>
32,444,602
0
<p>You have used <code>/if</code> which sounds plausible, but actually it needs to be <code>/id</code> for a dump file:</p> <pre><code>symchk /os /id "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll" /su "SRV*e:\debug\symbols*http://msdl.microsoft.com/download/symbols" SYMCHK: FAILED files = 0 SYMCHK: PASSED + IGNORED files = 1 </code></pre> <p>The output is the same, but the symbol folder contains the PDBs now.</p> <hr> <p>It is similar in WinDbg:</p> <ul> <li>choose <code>File | Open Crash Dump ...</code> or press <kbd>Ctrl</kbd>+<kbd>D</kbd></li> <li>for the file name filter, instead of <code>Crash Dump Files</code> select <code>All files</code></li> <li><p>choose the DLL or EXE of your interest. WinDbg will e.g. say</p> <pre><code>Loading Dump File [C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll] </code></pre> <p>although it is not really a dump file</p></li> <li>issue the typical commands <code>.symfix</code> and <code>.reload</code>. If symbols are present on the symbol server, they will be downloaded.</li> </ul> <p>Looking at what you're "debugging", you'll see that it's the DLL:</p> <pre><code>0:000&gt; | . 0 id: f0f0f0f0 examine name: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll 0:000&gt; || . 0 Image file: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll 0:000&gt; lm start end module name 00000001`80000000 00000001`80988000 clr (pdb symbols) e:\debug\symbols\clr.pdb\5706A2AA257A45FDAC5776EDDC7BBA542\clr.pdb </code></pre> <p>And also some other commands work:</p> <pre><code>0:000&gt; x clr!* 00000001`80123e28 clr!SafeHandle::Init (&lt;no parameter info&gt;) 00000001`808f5e80 clr!HillClimbingLogSize = &lt;no type information&gt; 00000001`80064af0 clr!IsTimerSpecialThread (&lt;no parameter info&gt;) ... 0:000&gt; u clr!SafeHandle::Init clr!SafeHandle::Init: 00000001`80123e28 4883ec28 sub rsp,28h 00000001`80123e2c 488b059d4b7c00 mov rax,qword ptr [clr!g_Mscorlib+0x10 (00000001`808e89d0)] 00000001`80123e33 488b80e0070000 mov rax,qword ptr [rax+7E0h] 00000001`80123e3a 4885c0 test rax,rax ... </code></pre>
16,953,360
0
<p>Or you can try <strong>CGI.unescapeHTML</strong> method.</p> <pre><code>CGI.unescapeHTML "&amp;lt;p&amp;gt;This is a Paragraph.&amp;lt;/p&amp;gt;" =&gt; "&lt;p&gt;This is a Paragraph.&lt;/p&gt;" </code></pre>
26,244,873
0
<p><strong>Your question:</strong> Why would this happen?</p> <p><strong>A:</strong> Because <code>.divError</code> is in a stacking context and the root of that stacking context has a <code>z-index</code> (<em>calculated</em> or <em>explicitly declared</em>) lower than the root of the stacking context of the rest of the content that is 'over' <code>.divError</code>.</p> <p>If you want to know how to 'solve' this, the DOM tree leading to and surrounding the <code>updPanelContent</code> and positioning and z-index applied to those elements is needed.</p>
41,020,685
0
No-except without passing argument <p>Can you say how can I assertion, is function noexcept(without passing arguments)? Thanks.</p>
12,706,388
0
<p>Just add position: relative; to each of the styles, as stated here: <a href="http://www.w3schools.com/cssref/pr_pos_z-index.asp" rel="nofollow">http://www.w3schools.com/cssref/pr_pos_z-index.asp</a></p> <p>(They can both have relative positioning)</p>
4,367,468
0
<p>haven't use a no-xml configuration yet, but with the config file it would look like:</p> <pre><code>&lt;MsmqTransportConfig InputQueue="WorkerQueueForCurrentService" ErrorQueue="ErrorQueue" NumberOfWorkerThreads="1" MaxRetries="5"/&gt; &lt;UnicastBusConfig&gt; &lt;MessageEndpointMappings&gt; &lt;add Messages="AssemblyName1" Endpoint="PublisherQueue1" /&gt; &lt;add Messages="AssemblyName2.Message1, AssemblyName2" Endpoint="PublisherQueue2" /&gt; &lt;add Messages="AssemblyName2.Message3, AssemblyName2" Endpoint="PublisherQueue2" /&gt; &lt;/MessageEndpointMappings&gt; &lt;/UnicastBusConfig&gt; </code></pre> <p>so your worker queue for the current service is "WorkerQueueForCurrentService" and it subscribes to different messages that are published on the queues "PublisherQueue1" and "PublisherQueue2". i have included a sample for the subscription of a whole messageassembly (see add messages line 1) and for specific messages in a given messageassembly (see add messages line 2 and line 3).</p> <p>Kristian kristensens answer is not correct. the input queue is relevant for every service that uses nservicebus. regardless of whether it's an publisher or an subscriber. a publisher receives subscription notices on the input queue and the subscriber sets the input queue as the destination queue for a subscription notice that is sent to the publisher.</p> <p>if you want to programmatically subscribe to messages like mrnye says you would need a messageendpointmapping. so if you do bus.subscribe nservicebus looks into his messageendpointmappings and tries to extract the publisher queue name where this message gets published.</p> <p>messageendpointmappings are used for both:<br> - the lookup of which messages gets published where<br> and<br> - the destination queue where messages are sent which you bus.send()</p> <p>hope this clears some things up :-)</p>
40,648,515
0
ERM: Key attribute for relation <p>My question is the following: Can relations have key attributes like shown in the following figure? <a href="https://i.stack.imgur.com/il3tg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/il3tg.png" alt=""></a></p> <p>For me it doesn't make sense, however I have found them like in <a href="https://i.stack.imgur.com/il3tg.png" rel="nofollow noreferrer">1</a>. If it is possilbe, how should I "resolve" them in the relational schema?</p> <p>I found a similar the question on [2] but it seems to focus on how to handle attributes during the transformation of the ERM to the relational schema.</p> <p><a href="https://i.stack.imgur.com/il3tg.png" rel="nofollow noreferrer">1</a> <a href="https://www.wu.ac.at/fileadmin/wu/_processed_/csm_erm_cardinalities2_84a65dbc2b.png" rel="nofollow noreferrer">https://www.wu.ac.at/fileadmin/wu/<em>processed</em>/csm_erm_cardinalities2_84a65dbc2b.png</a></p> <p>[2] <a href="http://stackoverflow.com/questions/9700196/relationship-attributes-in-er-diagrams">relationship attributes in ER diagrams</a></p>
27,922,197
0
<p>I have a feeling there is an easier way but meanwhile, assuming you want to the count of <code>2</code> for <code>Rejected</code> to be of <code>System</code>s <code>S102</code> and <code>S103</code> and assuming Status is in <code>C1</code> and no blank row: </p> <p>Add a helper column (say D, labelled say <code>SR</code>) with: </p> <pre><code>=A2&amp;B2 </code></pre> <p>copied down to suit. Create a PivotTable from all four columns, with <code>System</code> for ROWS, Max of <code>Revision</code> for Sigma VALUES. Assuming the PT is in F:G starting Row1, add: </p> <pre><code> =INDEX(C:C,MATCH(F2&amp;G2,D:D,0)) </code></pre> <p>in H2 and copy down to suit. In I2: </p> <pre><code>=COUNTIF(H:H,H2) </code></pre> <p>in I3: </p> <pre><code>=COUNTIF(H:H,H3) </code></pre> <p>or change H2 and H3 in the formulae to "Accepted" and "Rejected".</p>
13,278,830
0
Valid SQL using temp tables returning no result set <p>I've been searching google and stack overflow for the past several hours, and can't seem to find an exact match on this issue. I'm relatively new to java, so please correct me if I'm just doing something incredibly silly!</p> <p>Issue: When executing a try-with-resource query (statement.executeQuery(stmt)) I am getting a 'Statement did not return a result set'</p> <p>I can guarantee this is valid SQL, and when run through SSMS the query works - and when using the select...into...from style syntax, this query works as well [in java]. The select...into...from is not a viable option though as it creates performance issues (23 second query turns into a 5+ minute query due to resource utilization)</p> <p>Proof of concept: SQL file: c:\test.sql</p> <pre><code>set nocount on create table #test (loannum int) insert into #test (loannum) select 1 select * from #test drop table #test </code></pre> <p>This query is used to make a cached result set so that I can pass the data around other functions without leaving an open connection to the database...</p> <p><strong>Note: SQLInfo in the below is just "C:\test.sql"</strong> &lt; snip></p> <pre><code>try(BufferedReader in = new BufferedReader(new FileReader(SQLInfo))) { String str; StringBuffer sb = new StringBuffer(); while((str = in.readLine()) != null) { sb.append(str + System.getProperty("line.separator")); } _stmt = sb.toString(); } </code></pre> <p>&lt; /snip></p> <p>which is later used in the below... &lt; snip></p> <pre><code>try (Connection connection = DriverManager.getConnection(CONNECTION); Statement statement = connection.createStatement(); ResultSet resultset = statement.executeQuery(_stmt) ) { crs.populate(resultset); return crs; } catch (SQLException e) { e.printStackTrace(); } return crs; </code></pre> <p>&lt; /snip></p> <p>What I'm expecting, is a cached result set that will be used in a defaulttablemodel to display a "loannum" field, and value of 1 -- what I really get is the following error: "com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set..."</p> <p>If I modify the SQL to the following:</p> <pre><code>set nocount on select 1 as loannum into #test select * from #test drop table #test </code></pre> <p>I get the expected return result of "loannum" with value of 1.</p> <p>It appears to have something to do with the create table statement in the executeQuery method, but it's a temporary table! Is there any way to make the above to work with the create table (value type, value type, value type) insert into... method?</p> <p>**Note: I've attempted to use the .execute(String) method, and parse through the return results. It appears to have the same issue, but it's entirely possible I'm implementing it incorrectly.</p> <p>**Secondary note: The defaulttablemodel works fine, and returns information to a JTable that displays on screen. This dynamically allocates the column names, and displays the associated values. I can provide a sample of this code if needed, but i don't think it's relevant to the issue as this is failing on simply creating the resultset, rather then when it's trying to assign the information to the table model.</p> <p>[Editing this in]: Stored procedures on SQL side are not a viable option in this instance. This is a query against a data warehouse that does not allow stored procs as company policy (I've pushed back, and have been smacked down) - As a result, I'm working on this ... hackish solution.</p> <p>Hopefully somebody has some insight into this issue!</p>
26,778,850
0
<p>XPath 1.0 was specified in 1999 and defines the <code>contains</code> function. <a href="http://www.w3.org/TR/xpath20/" rel="nofollow">XPath 2.0</a> was specified in 2007 and <a href="http://www.w3.org/TR/xquery-operators/#func-lower-case" rel="nofollow">defines the <code>lower-case</code> function</a>. The latest version is <a href="http://www.w3.org/TR/xpath-30/" rel="nofollow">XPath 3.0</a>. If you want to use the <code>lower-case</code> function then you need to use an XPath 2.0 or 3.0 implementation or alternatively an XQuery 1.0 or 3.0 implementation as XPath is basically a subset of XQuery. I suspect that you are using an XPath 1.0 implementation and simply get an error that the function <code>lower-case</code> is not known.</p>
4,489,232
0
Java Server socket stuck on accept call (Android Client, Java Server) <p>Below I have put a fragment of code to help understand my problem. I have a server code, works fine for the first time the client loads and sends a packet. After the first packet is received, the server is stuck on "accept".</p> <p>I have wireshark configured for this port, and the server is getting those packets. I just wonder why accept wont return more than once. Its driving me nuts.</p> <p>Server Code</p> <pre><code> public class DAPool implements Runnable { private ServerSocket serverSocket; private ArrayList&lt;DA&gt; pool; private LinkedList&lt;Socket&gt; clientConnQ; public DAPool(int newPoolSize, int serverPort) { try { serverSocket = new ServerSocket(serverPort, 500, InetAddress.getByName("127.0.0.1")); } catch (IOException e) { e.printStackTrace(); return; } poolSize = newPoolSize; clientConnQ = new LinkedList&lt;Socket&gt;(); pool = new ArrayList&lt;DA&gt;(poolSize); DA deviceThread; for (int threads = 0; threads &lt; poolSize; threads++) { deviceThread = new DA(); connPool.add(deviceThread); deviceThread.start(); } } public void run() { while (true) { Socket incomingSocket; try { incomingSocket = serverSocket.accept(); } catch (IOException e) { e.printStackTrace(); return; } insertNewConnToQ(incomingSocket); } } private class DA extends Thread { private Socket clientSocket; private ObjectInputStream inputObjectStream; public DA() { } public void run() { while (true) { while (clientConnQ.isEmpty()) { synchronized (clientConnQ) { try { clientConnQ.wait(); } catch (InterruptedException ignored) { ignored.printStackTrace(); } } } synchronized (clientConnQ) { clientSocket = (Socket) clientConnQ.removeFirst(); try { inputObjectStream = new ObjectInputStream(clientSocket.getInputStream()); } catch (IOException e) { e.printStackTrace(); return; } // Do something useful here } } } } } </code></pre> <p>Client Code</p> <pre><code>public class SendQueue extends Thread { LinkedList&lt;Message&gt; requestQ; Message sendRequest, requestMessage; Socket clientSocket; OutputStream outputStream; ObjectOutputStream objectOutputStream; public SendQueue(Socket newClientSocket) { requestQ = new LinkedList&lt;Message&gt;(); clientSocket = newClientSocket; } public void run() { while (true) { synchronized (requestQ) { while (requestQ.isEmpty()) { try { requestQ.wait(); } catch (InterruptedException ignored) { ignored.printStackTrace(); } } sendRequest = requestQ.removeFirst(); } try { outputStream = clientSocket.getOutputStream(); objectOutputStream = new ObjectOutputStream(outputStream); objectOutputStream.writeObject(sendRequest); objectOutputStream.flush(); outputStream.flush(); } catch (IOException e) { e.printStackTrace(); } catch (RuntimeException e) { e.printStackTrace(); } } } public int sendRequest(Message message) { synchronized (requestQ) { requestQ.addLast(message); requestQ.notify(); } return 0; } } </code></pre>
29,190,731
0
<p>Your code will give the ArrayIndexOutOfBoundsException if usrSet is greater than 1. If your intention is to just make a copy of an array, I am not sure why you are doing so many things. Probably the below code may suffice:</p> <p><code> String[] deckCards = new String[setLength]; for(int j = 0; j &lt; cards.length; j++){ temp = cards[j]; deckCards[j]= temp; }</code></p> <p>If you are at liberty to use other api, try exploring java.util.Arrays</p>
37,800,052
0
<p>Bear in mind that audiences only begin accumulating members <em>after</em> you define them. So, after you define this audience, once at least 10 LOGIN events are logged with a sign_up_method which includes "CEO", you will see your results in Firebase Analytics. More on audiences in the <a href="https://support.google.com/firebase/answer/6317509?hl=en&amp;ref_topic=6317489" rel="nofollow">Firebase Help Center</a>.</p>
6,122,070
0
How to get tasklist information from cmd, without using "tasklist" command <p>Anyone knows how to extract the tasklist information using cmd, but without using "tasklist /svc" command? </p>
35,633,658
0
lsqr result strongly depends on weights <p>I need to solve</p> <pre><code>argmin||W*FT^-1(Ax)-W*p|| </code></pre> <p>using lsqr. p is image, x is k-space matrix, A is a matrix and W is a weighting matrix. In order to pass them to matlab lsqr, I vectorized p, x and W. This is my code:</p> <pre><code>b=W.*p; x=lsqr(@(x1,modo)FUNC(x1,W_vector,A,modo),b,tol,maxit); X_k_lsqr=reshape(x,dim(1),dim(2),dim(3)); X_lsqr=real(ifftn(X_k_lsqr)).*MASK(:,:,:,1); </code></pre> <p>%% Auxiliary function</p> <pre><code>function [result modo]=FUNC(x1,W_vector,A,modo) %Computes y=A*x for modo='notransp' %Computes y=A'*x for modo='transp' switch modo case 'notransp' res=A*x1; R1=reshape(res,norient,dim(1)*dim(2)*dim(3)); for co=1:norient R2(:,:,:,co)=reshape(R1(co,:),dim(1),dim(2),dim(3)); FR(:,:,:,co)=ifftn(R2(:,:,:,co)); aux=FR(:,:,:,co); R3(co,:)=aux(:).'; end result=W.*R3(:); case 'transp' RR1=reshape(x1./(W+eps),norient,dim(1)*dim(2)*dim(3)); for co=1:norient RR2(:,:,:,co)=reshape(RR1(co,:),dim(1),dim(2),dim(3)); FRR(:,:,:,co)=fftn(RR2(:,:,:,co)); aux=FRR(:,:,:,co); RR3(co,:)=aux(:).'; end result=A'*RR3(:); end end </code></pre> <p>As W appears in both terms of the minimization problem, I would have expected the image I obtain as a result to be almost independent on W values. The image looks qualitatively the same if I change W, but its values strongly depend on W. I don't know if something is wrong with my code. Should I actually obtain almost the same values for different W? Thank you very much for your help.</p> <p>EDIT: I added an initial guess and now the result does not depend on W. Does anyone know why?</p>
12,213,252
0
<p>Try this:</p> <pre><code>Uri uri = Uri.parse("https://www.google.com"); startActivity(new Intent(Intent.ACTION_VIEW, uri)); </code></pre> <p>or if you want then web browser open in your activity then do like this:</p> <pre><code>WebView webView = (WebView) findViewById(R.id.webView1); WebSettings settings = webview.getSettings(); settings.setJavaScriptEnabled(true); webView.loadUrl(URL); </code></pre> <p>and if you want to use zoom control in your browser then you can use:</p> <pre><code>settings.setSupportZoom(true); settings.setBuiltInZoomControls(true); </code></pre>
17,667,061
0
<p>Looking at <a href="http://hg.python.org/cpython/file/v2.7.4/Lib/ctypes/__init__.py#l243" rel="nofollow">the source</a>, <code>__repr__</code> will only show the contents of the string if</p> <ol> <li>It is running on Windows; and</li> <li><a href="http://msdn.microsoft.com/en-us/library/aa366714.aspx" rel="nofollow"><code>IsBadStringPtr</code></a> returns <code>TRUE</code>.</li> </ol> <p>They probably want to show a string representation if possible, since that's a rather useful thing to show, but not crash your program if it points somewhere unexpected. <code>IsBadStringPtr</code> only exists on Windows, necessitating the first check. Frankly, I'm surprised they'd use it, as it's clearly marked obsolete, and <a href="https://blogs.msdn.com/b/oldnewthing/archive/2006/09/27/773741.aspx" rel="nofollow">for good reasons</a>.</p>
21,745,915
0
cassandra performance and speed with multiple insertion? <p>I am new to cassandra and migrating my application from Mysql to cassandra.As i read of cassandra it says it reduces the read and write time compared to Mysql.when i tried a simple example with single node using hector, reading operation is quite faster compared to Mysql,and if i tried to insert a single column it is very fast compared to mysql.But when i tried to insert a single row with multiple columns its taking long time compared to mysql. Is there anyway to improve Write performance or please let me know if i am wrong with my way of coding.</p> <p>My sql code is <code>INSERT into energy_usage(meter_id,reading_datetime,reading_date,reading_time,asset_id,assetid) VALUES('164','2012-12-07 00:30:00','2012-12-07','00:00:00','1','1') " </code> my cassandra code is</p> <pre><code>Mutator&lt;String&gt; mutator = HFactory.createMutator(keyspaceOperator, StringSerializer.get()); mutator.addInsertion("888999", DYN_CF, HFactory.createStringColumn("assetid","1")). addInsertion("888999", DYN_CF, HFactory.createStringColumn("meterid", "164")). addInsertion("888999", DYN_CF, HFactory.createStringColumn("energyusage","10")). addInsertion("888999", DYN_CF, HFactory.createStringColumn("readdate","2012-12-07")). addInsertion("888999", DYN_CF, HFactory.createStringColumn("readdatetime","2012-12-07 00:30:00")); mutator.execute(); </code></pre>
29,281,992
0
<p>Difference is crucial. Relocation address is addend to all relocs in section. So if it differ with load address, nothing will really work in this section -- all relocs inside section will be resolved to wrong values.</p> <p>So why do we need technique like this? Not so much applications, but suppose (<a href="http://ftp.gnu.org/old-gnu/Manuals/ld-2.9.1/html_node/ld_22.html" rel="nofollow">from here</a>) you do have on your architecture extremely fast memory at 0x1000</p> <p>Then you may take two sections to have relocation address 0x1000:</p> <pre><code>.text0 0x1000 : AT (0x4000) { o1/*.o(.text) } __load_start_text0 = LOADADDR (.text0); __load_stop_text0 = LOADADDR (.text0) + SIZEOF (.text0); .text1 0x1000 : AT (0x4000 + SIZEOF (.text0)) { o2/*.o(.text) } __load_start_text1 = LOADADDR (.text1); __load_stop_text1 = LOADADDR (.text1) + SIZEOF (.text1); . = 0x1000 + MAX (SIZEOF (.text0), SIZEOF (.text1)); </code></pre> <p>Now at runtime go ahead and when you need text1, manage it by yourself to be copied on right address from its actual load address:</p> <pre><code>extern char __load_start_text1, __load_stop_text1; memcpy ((char *) 0x1000, &amp;__load_start_text1, &amp;__load_stop_text1 - &amp;__load_start_text1); </code></pre> <p>And then use it, <strong>as it was loaded</strong> here naturally. This technique is called overlays.</p> <p>I think, example is pretty clear.</p>
4,731,669
0
which files are need to create .ipa for my application which is done in xcode <p>I am creating a simple application in xcode </p> <p>Now i need to create ipa for that file.</p> <p>By google i found some info regarding this.</p> <p>create a folder named Payload and copy the app file,Zip the fine and rename zip to .ipa.</p> <p>But i have a doubt in the this path users/username/library/application support/iphone simulator/4.1/Applications </p> <p>i found a folder named with random alphabets and numbers.</p> <p>In that i found documents,library,tmp folders along with my application.app.</p> <p>is i need to copy all the 3 folders into payload or just my application.app is enough.</p> <p>And i did n't get my icon in over the .ipa.</p> <p>How can i get it.</p> <p>can any one pls help me.</p> <p>Thank u in advance. </p>
22,851,901
0
Route specific page to controller in ASP.NET MVC <p>If I have a page on my site (extension could be ".html", whatever:</p> <p><a href="http://tempuri.org/mypage.asp" rel="nofollow">http://tempuri.org/mypage.asp</a></p> <p>I want this page to invoke a specific web api controller and action. Can anyone help with configuring this in the route mapping? Thanks.</p>
38,752,559
0
<p>Alright so it's nothing related to the CardView. Just buttons on Android 5.1 (Lollipop)+ Try these two rules with your class and it will work. You won't need <code>border-color: transparent</code> with this either.</p> <p><code> border-width: 0.1; background-color: transparent; </code></p>
16,689,064
0
<p>It's because you use <a href="http://underscorejs.org/#without" rel="nofollow">http://underscorejs.org/#without</a>, which creates a copy of the array instead of just removing the item. When you remove an item a new array will be linked to the scope, and the new array is not linked with array in the isolate scope.</p> <p>To solve this problem you can use splice instead, which removes the item from the original array:</p> <pre class="lang-js prettyprint-override"><code>$scope.removeSkill = function() { $scope.profile.skills.splice(_.indexOf($scope.profile.skills, this.skill),1); }; </code></pre> <p>...</p> <pre><code>$scope.removeItem = function() { $scope.list.splice(_.indexOf($scope.list, this.item),1); }; </code></pre> <p>Updated plunker: <a href="http://jsfiddle.net/jtjf2/" rel="nofollow">http://jsfiddle.net/jtjf2/</a></p>
11,971,345
0
<p>tinyMCE <a href="http://www.tinymce.com/wiki.php/Configuration%3avalid_elements" rel="nofollow">valid_elements</a> option allows to specify wide range of rules to 'normalize' the document: it's powerful, but it's quite strict in its syntax. Particularly speaking, one shouldn't use whitespace as additional separator of the rules. </p> <p>For example, to restrict valid elements to <code>&lt;p&gt;</code> and <code>&lt;br /&gt;</code> only, this line should be used:</p> <pre><code>... valid_elements: 'p,br' // not valid_elements: 'p, br' ... </code></pre>
24,316,986
0
<p>The following method should give you a string array of zero's and one's, representing the specified image:</p> <pre><code>private static string ConvertToString(Bitmap image) { StringBuilder result = new StringBuilder(); StringBuilder imageLine = new StringBuilder(); // Iterate each pixel from top to bottom for (int y = 0; y &lt; image.Height; y++) { // Iterate each pixel from left to right for (int x = 0; x &lt; image.Width; x++) { Color pixelColour = image.GetPixel(x, y); // Determine how "dark" the pixel via the Blue, Green, and Red values // (0x00 = dark, 0xFF = light) if (pixelColour.B &lt;= 0xC8 &amp;&amp; pixelColour.G &lt;= 0xC8 &amp;&amp; pixelColour.R &lt;= 0xC8) { imageLine.Append("1"); // Dark pixel } else { imageLine.Append("0"); // Light pixel } } // Add line of zero's and one's to end results result.AppendLine(imageLine.ToString()); imageLine.Clear(); } return result.ToString(); } </code></pre> <p>This is based on <a href="http://www.c-sharpcorner.com/UploadFile/hscream/ImagetoBinary02132007164649PM/ImagetoBinary.aspx" rel="nofollow">the link you provided</a>, but I've amended the code in a few places, like how the comparison of the pixel values was previously also based on the Alpha, and the string representations of the values.</p> <p>The following console application code should output the result, but I wouldn't recommend it for large images; maybe output to a text file instead?</p> <pre><code>using System; using System.Drawing; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { // Read image into memory var img = new Bitmap(@"C:\Temp\MickyMouse.png"); // Modify width of console buffer to keep each line of characters "on one line" Console.SetBufferSize(img.Width + 10, img.Height + 10); Console.WriteLine(ConvertToString(img)); Console.ReadLine(); } private static string ConvertToString(Bitmap image) { // Code from above } } } </code></pre> <p>You'll need to add a reference to <code>System.Drawing</code> to the project in order for it to compile.</p>
18,809,594
0
<p>Google's JavaScript CDN serves jQuery's source map as <code>application/json</code>.</p> <p><img src="https://i.stack.imgur.com/ThAEV.png" alt="enter image description here"></p>
10,546,310
0
<p>You should not use <code>gcnew</code> inside the array initializer:</p> <pre><code>array&lt;String^&gt;^ arr = gcnew array&lt;String^&gt; { "Madam I'm Adam.", "Don't cry for me,Marge and Tina.", "Lid off a daffodil.", "Red lost Soldier.", "Cigar? Toss it in a can. It is so tragic." }; </code></pre>
23,014,509
0
<p>Simplest solution is to use the dynamic array and call the <code>.reserve</code> method before doing any appends. Then it will preallocate the space and future appends will be cheap.</p> <pre><code>void main() { MyStruct[] structs; structs.reserve(256); // prealloc memory foreach(id; 0 .. 256) structs ~= MyStruct(id); // won't reallocate } </code></pre> <p>That's how I'd do it with dynamic arrays, writing to individual members I don't think will ever work with immutability involved like this.</p> <p>BTW if you wanted a static array, calling reserve won't work, but you can explicitly initialize it.... to <code>void</code>. That'll leave the memory completely random, but since you explicitly requested it, the disabled default constructor won't stop you. (BTW this is prohibited in <code>@safe</code> functions) But in this case, those immutable members will leave it garbage forever unless you cast away immutability to prepare it soo.. not really workable, just a nice thing to know if you ever need it in the future.</p>
40,517,681
0
Howto set Outlook MailItem Property Category <p>I am trying to set the category of the currently selected outlook mail item to a value.</p> <p>The following seems to be setting it but it isnt updating the GUI of Outlook.</p> <pre><code>Option Explicit Public Sub SaveMessageAsMsg() Dim oMail As Outlook.MailItem Dim objItem As Object Dim sPath As String Dim dtDate As Date Dim sName As String Dim enviro As String Dim oPA As PropertyAccessor Dim arrErrors As Variant Dim i As Integer enviro = CStr(Environ("USERPROFILE")) For Each objItem In Application.ActiveExplorer.Selection If objItem.MessageClass = "IPM.Note" Then Set oMail = objItem Debug.Print oMail.Categories oMail.Categories = "99 - Archive" Debug.Print oMail.Categories End If Next </code></pre> <p>End Sub</p>
24,859,414
0
Customize Gii Code Generator For Internal Use <p>I am new to yii.I want to use Gii Code Generator in my application for generate model and CRUD dynamically.Like i am giving rights to choose field for their form.They enter details for fields and click button for generate form at that time in back hand i want to generate table for that all field, model and crude for that.I can generate table in back hand but when i want to generate model and crude i have show interface of gii. I can't hide it from User so please help me out if any one knew how to generate all in back hand.please.</p>
40,920,415
0
<p>In addition to the above answer, using <code>newAPIHadoopRDD</code> means that, you get all the data from HBase and from then on, its all core spark. You would not get any HBase specific API like Filters etc. And the current spark-hbase, only snapshots are available. </p>
22,715,611
0
<p>I've come up with an alternate solution that to me seems safer than LombaX's. It uses the fact that both events come in with the same timestamp to reject the subsequent event.</p> <pre><code>@interface RFNavigationBar () @property (nonatomic, assign) NSTimeInterval lastOutOfBoundsEventTimestamp; @end @implementation RFNavigationBar - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { // [rfillion 2014-03-28] // UIApplication/UIWindow/UINavigationBar conspire against us. There's a band under the UINavigationBar for which the bar will return // subviews instead of nil (to make those tap targets larger, one would assume). We don't want that. To do this, it seems to end up // calling -hitTest twice. Once with a value out of bounds which is easy to check for. But then it calls it again with an altered point // value that is actually within bounds. The UIEvent it passes to both seem to be the same. However, we can't just compare UIEvent pointers // because it looks like these get reused and you end up rejecting valid touches if you just keep around the last bad touch UIEvent. So // instead we keep around the timestamp of the last bad event, and try to avoid processing any events whose timestamp isn't larger. if (point.y &gt; self.bounds.size.height) { self.lastOutOfBoundsEventTimestamp = event.timestamp; return nil; } if (event.timestamp &lt;= self.lastOutOfBoundsEventTimestamp + 0.001) { return nil; } return [super hitTest:point withEvent:event]; } @end </code></pre>
3,335,710
0
<p>easiest way is to add a new web config file to the admin section</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;configuration&gt; &lt;system.web&gt; &lt;authorization&gt; &lt;deny users="*" /&gt; &lt;allow roles="Admin" /&gt; &lt;/authorization&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre>
8,365,074
0
Image taken from ImageList looks different than taken straight from resource <p>I have a form with two buttons. </p> <p>To one of them I assigned an image (a 16 x 16, 32 bit depth <code>png</code>) by setting the <code>Image</code> property from VS's properties editor (using the <code>Import...</code> button).</p> <p>I also have an <code>ImageList</code> (16 x 16 <code>ImageSize</code> and <code>Depth32Bit</code> <code>ColorDepth</code>) to which I assigned the same image as to the first button also from the properties editor -> <code>Images</code> and then <code>Add</code>. Then I assigned this image to my second button this way:</p> <pre><code>button2.Image = imageList.Images[0]; </code></pre> <p>And this is how the images look (2x the actual size): </p> <p><img src="https://i.stack.imgur.com/RVhED.png" alt="enter image description here"></p> <p>Is it possible to have my second button look like my first one by using an <code>ImageList</code>? The reason why I use an <code>ImageList</code> is because when checking performance, the line of code that loaded the image from the resource was a hot spot according to VS's Performance Wizard. </p> <p>My application will have a list of controls, each of which have a bunch of buttons with images, so I want them to load as fast as possible. So what I have is a static <code>ImageList</code> from which each of these controls get their images.</p>