title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
Apache Drill > sqlline: how to run a sql script containing variable | <p>I am a newbie of Apache Drill, and I need to run a SQL script through sqlline. In most SQL client, it is allowed to use some variables in sqlline, so hereby I would like to ask that is it possible to use variables in sqlline of Apache Drill?</p> | 1 |
How to convert a Vagrantfile to a Dockerfile | <p>I'm trying to use the following Vagrantfile to make a Dockerfile for learning purposes. So far this is what I've come up with:</p>
<p>From Udacity: "Intro to Relational Databases", this is my Vagrantfile:</p>
<pre><code># -*- mode: ruby -*-
# vi: set ft=ruby :
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.provision "shell", path: "pg_config.sh"
# config.vm.box = "hashicorp/precise32"
config.vm.box = "ubuntu/trusty32"
config.vm.network "forwarded_port", guest: 8000, host: 8000
config.vm.network "forwarded_port", guest: 8080, host: 8080
config.vm.network "forwarded_port", guest: 5000, host: 5000
end
</code></pre>
<p>pg_config.sh:</p>
<pre><code>apt-get -qqy update
apt-get -qqy install postgresql python-psycopg2
apt-get -qqy install python-flask python-sqlalchemy
apt-get -qqy install python-pip
pip install bleach
pip install oauth2client
pip install requests
pip install httplib2
pip install redis
pip install passlib
pip install itsdangerous
pip install flask-httpauth
su postgres -c 'createuser -dRS vagrant'
su vagrant -c 'createdb'
su vagrant -c 'createdb forum'
su vagrant -c 'psql forum -f /vagrant/forum/forum.sql'
vagrantTip="[35m[1mThe shared directory is located at /vagrant\nTo access your shared files: cd /vagrant(B[m"
echo -e $vagrantTip > /etc/motd
wget http://download.redis.io/redis-stable.tar.gz
tar xvzf redis-stable.tar.gz
cd redis-stable
make
make install
</code></pre>
<hr>
<p>This is my attempt at converting to a Dockerfile:</p>
<pre><code># Set the base image to Ubuntu
FROM ubuntu:14.04
# Update the repository sources list
RUN apt-get update
# Add the packages
RUN \
apt-get -qqy install postgresql python-psycopg2 && \
apt-get -qqy install python-flask python-sqlalchemy && \
apt-get -qqy install python-pip && \
pip install bleach && \
pip install oauth2client && \
pip install requests && \
pip install httplib2 && \
pip install redis && \
pip install passlib && \
pip install itsdangerous && \
pip install flask-httpauth && \
su postgres -c 'createuser -dRS vagrant' && \
su vagrant -c 'createdb' && \
su vagrant -c 'createdb forum' && \
su vagrant -c 'psql forum -f /vagrant/forum/forum.sql' && \
vagrantTip="[35m[1mThe shared directory is located at /vagrant\nTo access your shared files: cd /vagrant(B[m" && \
echo -e $vagrantTip > /etc/motd && \
wget http://download.redis.io/redis-stable.tar.gz && \
tar xvzf redis-stable.tar.gz && \
cd redis-stable && \
make && \
make install
# Expose the default port
EXPOSE 5000
</code></pre>
<p>After running </p>
<pre><code>docker build -t fullstack-vm .
</code></pre>
<p>I received the following errors:</p>
<pre><code>debconf: unable to initialize frontend: Dialog
debconf: (TERM is not set, so the dialog frontend is not usable.)
debconf: falling back to frontend: Readline
debconf: unable to initialize frontend: Readline
debconf: (This frontend requires a controlling tty.)
debconf: falling back to frontend: Teletype
dpkg-preconfigure: unable to re-open stdin:
</code></pre>
<p>What needs to be corrected in the Dockerfile for this to run properly?</p> | 1 |
Use VLC to fetch SDP file once using RTSP | <h2>Context</h2>
<ul>
<li>Most RTP streams (from e.g. an IP camera) need some information from a SDP to be able to decode them. </li>
<li>SDP is usually fetched just in time, usually from a RTSP URL but other means are possible (e.g. HTTP).</li>
</ul>
<h2>Specific case</h2>
<p>We have a situation where an RTP stream (from a camera, UDP sent at all time whether anyone listens or not) will be played using VLC, but providing VLC an RTSP URL to fetch SDP just in time is not an option. </p>
<p>There <em>is</em> a RTSP service yet we need to query it in advance and dump the resulting SDP file to feed it to VLC later. Doing a RTSP query just-in-time is useless anyway since the stream exists at all times.</p>
<h2>How to do that with VLC?</h2>
<h3>Search before you post</h3>
<p>Of course I've been searching Google, videolan wiki and StackExchange.</p>
<p>Information is difficult to find because when people talk about streaming, RTSP, RTP, they are generally usig VLC to <em>generate</em> a RTP stream, or output a SDP that VLC generates because it does the encoding, etc.
It's not the case here. The SDP to dump comes from the serveur with a single RTSP query.</p>
<h3>Question</h3>
<p>Basically, I'm looking for a command-line like:</p>
<pre><code>vlc --sout...something...rtsp://sourceIP:Port/...something...out...myfile.sdp
</code></pre>
<p>That would dump the SDP in <code>myfile.sdp</code>.</p>
<p>Then, later, running vlc with the <code>myfile.sdp</code> as argument is expected to play the stream.</p> | 1 |
Python Tools for Visual Studio Inline Graphics | <p>This one should be simple, but I've been searching all over and it seems to be so simple that nobody else has encountered the problem yet :)</p>
<p>I just installed Python (2.7 Anaconda distribution) and Python Tools for Visual Studio with Visual Studio 2015 Community. It all appears to be working, but I would like to use the inline graphics feature and can't get it to work. This code should (I think) do it, but instead shows nothing in the interactive window and pulls up a new blank window for the plot.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
plt.ion()
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C,S = np.cos(X), np.sin(X)
plt.plot(X,C)
plt.plot(X,S)
</code></pre>
<p>Do I need to configure something else before the inline graphics will work?</p> | 1 |
How to disable the navigation bar slide animation when going fullscreen? | <p>I have an activity that goes to another full screen activity. However, when transitioning from this activity to my full screen activity, the navigation bar slides down instead of disappearing instantly. I've inflated a full-screen window in the second activity, but because of the slow sliding animation, it resizes 1 second later after the animation has completed instead of being inflated to full-screen immediately. Therefore, I need the animation to disappear instantly. I've tried </p>
<p><code><item name="android:windowAnimationStyle">@null</item></code></p>
<p>and </p>
<pre><code>overridePendingTransition(0, 0);
</code></pre>
<p>and</p>
<pre><code>Transition fade = new Fade();
fade.excludeTarget(android.R.id.navigationBarBackground, true);
getWindow().setEnterTransition(fade);
</code></pre>
<p>with no luck. </p>
<p>On the Windows side, I've tried</p>
<pre><code>WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
WindowManager.LayoutParams.FLAG_FULLSCREEN
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
</code></pre>
<p>How I hide the navbar: <code>View.SYSTEM_UI_FLAG_HIDE_NAVIGATION</code></p> | 1 |
Can I search/get file by using File ID in Dropbox V2 API? | <p>I'm using Dropbox V2 APIs (C#) to get files/folders from Dropbox account. I am able to fetch particular file/folder by using its specific path. I wanted to know whether there is any way I can fetch file/folder by using ID?</p> | 1 |
Django forms - Select a valid choice. That choice is not one of the available choices | <p>In my form I have select box but when after submit i getting error on this field: "Select a valid choice. That choice is not one of the available choices." I'm using exactly code in other form and there everything works fine but not in this form :(</p>
<p><strong>forms.py:</strong></p>
<pre><code>BLANK_CHOICE = (('', '---------'),)
class ClientCreateForm(forms.ModelForm):
class Meta:
model = Client
fields = ('name', 'address', 'zip_code', 'city', 'country', 'forwarding_address',
'forwarding_zip_code', 'forwarding_city', 'forwarding_country')
def __init__(self, *args, **kwargs):
super(ClientCreateForm, self).__init__(*args, **kwargs)
self.fields['country'].choices = CountriesShortcut.objects.all().values_list('id', 'name')
self.fields['forwarding_country'].choices = BLANK_CHOICE + tuple(
CountriesShortcut.objects.all().values_list('id', 'name'))
</code></pre>
<p><strong>Models.py</strong></p>
<pre><code>class CountriesShortcut(models.Model):
name = models.CharField(max_length=80, unique=True)
class Meta:
ordering = ['id']
def __init__(self):
self.code
class Client(models.Model):
id = models.OneToOneField(User, on_delete=models.CASCADE, unique=True, primary_key=True)
name = models.CharField(max_length=256, unique=True)
address = models.CharField(max_length=64)
zip_code = models.CharField(max_length=10, help_text='Zip Code')
city = models.CharField(max_length=64)
country = models.ForeignKey(CountriesShortcut, related_name='country', blank=True, null=True)
forwarding_address = models.CharField(max_length=64, blank=True)
forwarding_zip_code = models.CharField(max_length=10, blank=True)
forwarding_city = models.CharField(max_length=64, blank=True)
forwarding_country = models.ForeignKey(CountriesShortcut, related_name='forwarding_country', blank=True, null=True)
def __str__(self):
re = self.name + ' [' + str(self.id) + ']'
return re
</code></pre>
<p>Can you give me some advice?</p>
<p><strong>Traceback showed after changed to queryset:</strong></p>
<pre><code>Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/panel/client/create/
Django Version: 1.8.8
Python Version: 3.5.1
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'core',
'client',
'registration',
'avatar',
'filer',
'mptt',
'easy_thumbnails',
'reversion')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Template error:
In template C:\Users\loc\PycharmProjects\CRM\templates\panel\client\form.html, error at line 131
__init__() takes 1 positional argument but 3 were given
121 : <div class="col-sm-3">
122 : {{ form_client.city }}
123 : {% if form_client.errors.city %}
124 : <p class="help-block">
125 : {{ form_client.errors.city }}
126 : {{ form_client.non_field_errors.city }}
127 : </p>
128 : {% endif %}
129 : </div>
130 : <div class="col-sm-3">
131 : {{ form_client.country }}
132 : {% if form_client.errors.country %}
133 : <p class="help-block">
134 : {{ form_client.errors.country }}
135 : {{ form_client.non_field_errors.country }}
136 : </p>
137 : {% endif %}
138 : </div>
139 : </div>
140 : </div>
141 : </div>
Traceback:
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\core\handlers\base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
File "C:\Users\loc\PycharmProjects\CRM\core\views.py" in client_create
111. return render(request, 'panel/client/form.html', dict)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\shortcuts.py" in render
67. template_name, context, request=request, using=using)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\template\loader.py" in render_to_string
99. return template.render(context, request)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\template\backends\django.py" in render
74. return self.template.render(context)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\template\base.py" in render
210. return self._render(context)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\template\base.py" in _render
202. return self.nodelist.render(context)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\template\base.py" in render
905. bit = self.render_node(node, context)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\template\debug.py" in render_node
79. return node.render(context)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\template\loader_tags.py" in render
135. return compiled_parent._render(context)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\template\base.py" in _render
202. return self.nodelist.render(context)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\template\base.py" in render
905. bit = self.render_node(node, context)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\template\debug.py" in render_node
79. return node.render(context)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\template\loader_tags.py" in render
65. result = block.nodelist.render(context)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\template\base.py" in render
905. bit = self.render_node(node, context)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\template\debug.py" in render_node
79. return node.render(context)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\template\debug.py" in render
92. output = force_text(output)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\utils\encoding.py" in force_text
90. s = six.text_type(s)
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\utils\html.py" in <lambda>
399. klass.__str__ = lambda self: mark_safe(klass_str(self))
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\forms\forms.py" in __str__
537. return self.as_widget()
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\forms\forms.py" in as_widget
593. return force_text(widget.render(name, self.value(), attrs=attrs))
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\forms\widgets.py" in render
513. options = self.render_options(choices, [value])
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\forms\widgets.py" in render_options
539. for option_value, option_label in chain(self.choices, choices):
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\forms\models.py" in __iter__
1107. for obj in queryset:
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\db\models\query.py" in iterator
255. obj = model_cls.from_db(db, init_list, row[model_fields_start:model_fields_end])
File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\db\models\base.py" in from_db
489. new = cls(*values)
Exception Type: TypeError at /panel/client/create/
Exception Value: __init__() takes 1 positional argument but 3 were given
</code></pre> | 1 |
How to label countries, not regions, using maps.text in the R maps package | <p>There don't appear to be any examples in the documentation for the maps package or on stack overflow of anyone trying to plot text or other information in place of a country name, rather than regions within a country.</p>
<pre><code>library(maps)
test <- structure(list(countries = structure(c(3L, 4L, 2L, 1L), .Label = c("France",
"Germany", "Italy", "UK"), class = "factor"), value = c(20, 13,
42, 6)), .Names = c("countries", "value"), row.names = c(NA,
-4L), class = "data.frame")
map.text("world", c("France", "Germany", "Italy", "UK"))
</code></pre>
<p><a href="https://i.stack.imgur.com/cQGtU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cQGtU.png" alt="Map with all regions labelled, rather than just the country names"></a></p>
<p>I plan on replacing the country names with the values. The solution might look something like</p>
<pre><code>map.text("world",test$countries, labels=test$values)
</code></pre>
<p>but I can't figure out how to get it to leave out all the unnecessary region labels.</p> | 1 |
Load dynamic html with nodejs | <p>I'm pretty new with NodeJs.<br />
I'm trying to download some html from a website in order to parse it and present some information for debug.<br />
I try with success with http module (<a href="https://stackoverflow.com/questions/5801453/in-node-js-express-how-do-i-download-a-page-and-gets-its-html">see this post</a>), but in this way when I print chunk:</p>
<pre><code>var req = http.request(options, function(res) {
res.setEncoding("utf8");
res.on("data", function (chunk) {
console.log(chunk);
});
});
</code></pre>
<p>I don't get all html that is loaded dynamically with ajax for instance:</p>
<pre><code><div class="container">
::before
<div class="row">
::before
....
</div>
</code></pre>
<p>Are there any other <a href="https://www.npmjs.com/browse/keyword/crawler" rel="nofollow noreferrer">module</a> that can help me on this goal?</p>
<p>Thanks!</p>
<h1>update</h1>
<p>I would like to share with you my success (thanks to @oKonyk).</p>
<ul>
<li>npm install phantomjs</li>
<li>create your script</li>
<li>use the same code suggested by @oKonyk</li>
</ul>
<p>note that if you're running your script locally, you need to set this options:</p>
<pre><code>options = { 'web-security': 'no' };
phantom.create({parameters: options}, function() {});
</code></pre> | 1 |
Python PyUSB HID Feature Report | <p>I am accessing a USB HID Device using python hidapi from a Mac OSX 10.10.5 doing:</p>
<pre><code>import hid
import time
hidraw = hid.device(0x1a67, 0x0004)
hidraw.open(0x1a67, 0x0004)
# Rpt, GnS, Tgt, Size, Index LSB, Index MSB, Data
# Blink 4 pulses
hidraw.send_feature_report([0x00, 0x00, 0x00,0x01, 0x01, 0x00, 0x03])
hidraw.get_feature_report(33,33)
time.sleep(3)
</code></pre>
<p>The HID Feature Report works nicely without problems.
However, I am trying to port this code to PyUSB and trying to do the same thing (on a RaspberryPi)</p>
<pre><code>import usb.core
import usb.util
# find our device
dev = usb.core.find(idVendor=0xfffe, idProduct=0x0004)
# was it found?
if dev is None:
raise ValueError('Device not found')
# get an endpoint instance
for interface in dev.get_active_configuration():
if dev.is_kernel_driver_active(interface.bInterfaceNumber):
# Detach kernel drivers and claim through libusb
dev.detach_kernel_driver(interface.bInterfaceNumber)
usb.util.claim_interface(dev, interface.bInterfaceNumber)
# set the active configuration. With no arguments, the first
# configuration will be the active one
dev.set_configuration()
ret = dev.ctrl_transfer(0x00, 0x00, 0x01, 0x01, [0x00, 0x03])
</code></pre>
<p>But I get a Broken Pipe when executed with root permissions. It is not very clear how to map the parameters that I used in the send_feature_report of Hidapi to how it is actually used from ctrl_transfer in PyUSB.</p>
<p>Any help on how this mapping should be made?</p>
<p>Thanks !!!</p>
<ul>
<li><a href="http://libusb.sourceforge.net/api-1.0/group__syncio.html" rel="nofollow">http://libusb.sourceforge.net/api-1.0/group__syncio.html</a></li>
<li><a href="https://github.com/walac/pyusb/blob/master/docs/tutorial.rst" rel="nofollow">https://github.com/walac/pyusb/blob/master/docs/tutorial.rst</a></li>
</ul> | 1 |
how can reorder column in DataTable in vb.net? | <p>Importing data from Excel to VisualBasic, I am using the following code to reorder the columns:</p>
<pre><code> Dim new_postion As Integer = dt_Excel.Columns.Count - 1
For i As Integer = 0 To dt_Excel.Columns.Count - 1
dt_Excel.Columns(i).SetOrdinal(new_postion)
new_postion = new_postion - 1
Next
DGV_Excel.DataSource = dt_Excel
</code></pre>
<p>but when I show the data in DataGridView it's still in the same order.</p> | 1 |
Use TrackBar to Zoom In/out of Picturebox Proportionately | <p>I'm using WinForms. In my form i have a picturebox that i want to zoom in and out using the track bar. My picturebox is set to zoom-mode. I want the image and picturebox to be proportion height/width when i drag the bar. How can i accomplish this?</p>
<pre><code> private void Open_btn_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
Image bmp;
bmp = new Bitmap(openFileDialog1.FileName);
if (bmp == null)
{
MessageBox.Show("Loading image failed", "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
}
else
{
pictureBox1.Image = bmp;
openFileDialog1.Dispose();
}
}
}
private void zoomSlider_Scroll(object sender, EventArgs e)
{
if(TrackBar1.Value == 1)
{
pictureBox1.Height += 50;
pictureBox1.Width += 50;
}
if(TrackBar1.Value == 2)
{
pictureBox1.Height += 100;
pictureBox1.Width += 100;
}
if(TrackBar1.Value == 3)
{
pictureBox1.Height += 200;
pictureBox1.Width += 200;
}
//This is not exactly what i had in mind...
}
</code></pre>
<p><a href="https://i.stack.imgur.com/6b5WS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6b5WS.png" alt="enter image description here"></a></p> | 1 |
Listening to the focus event in angular using $on | <p>I am using the swiper widget by <a href="http://www.idangero.us/swiper/#.Vqiziip96Uk" rel="nofollow">Idangero</a>, which allows me to pagify a form. However, since it loads all the controls up front, it is possible to tab into a field on the next page. I want to prevent this and I have found this <a href="https://jsfiddle.net/6rtskL5g/1/" rel="nofollow">jsfiddle</a> that changes the page when tabbing.</p>
<p>It, however, uses regular javascript to listen to the focus event <code>$('form')[0].addEventListener('focus'...</code> I want to convert this to a more angular version using the $rootscope.$on (I also want it to blur out of the field instead of changing the page, but I think I can handle that) anyone know how to do this?</p>
<p>I'd rather not use the ng-focus directive because then I have to add it to the controls at the bottom and top of every page.</p> | 1 |
How to cancel Alamofire.upload | <p>I am uploading images on server via <code>Alamofire.upload</code> as multipart data. Unlike <code>Alamofire.request</code> it's not returning <code>Request</code> object, which I usually use to cancel requests. </p>
<p>But it's very reasonable to be able to cancel such a consuming requests like uploading. What are the options for this in Alamofire?</p> | 1 |
How can I analyze a confusion matrix? | <p>When I print out scikit-learn's confusion matrix, I receive a very huge matrix. I want to analyze what are the true positives, true negatives etc. How can I do so?
This is how my confusion matrix looks like. I wish to understand this better.</p>
<pre><code>[[4015 336 0 ..., 0 0 2]
[ 228 2704 0 ..., 0 0 0]
[ 4 7 19 ..., 0 0 0]
...,
[ 3 2 0 ..., 5 0 0]
[ 1 1 0 ..., 0 0 0]
[ 13 1 0 ..., 0 0 11]]
</code></pre> | 1 |
How to set a default value to a DateTime parameter | <p>In my MVC application I want to set default values to the <code>DateTime</code> parameter.</p>
<pre><code>[HttpPost]
public ActionResult BudgetVSActualTabular(DateTime startDate)
{
var Odata = _db.sp_BudgetedVsActualTabular(startDate).ToList();
string[] monthName = new string[12];
for (int i = 0; i < 12;i++ )
{
DateTime date = startDate;
date = date.AddMonths(i);
monthName[i] = date.ToString("MMMM") + " " + date.Year.ToString();
}
ViewBag.startDate = new SelectList(_db.DaymonFinancialYears, "startDate", "DateRange");
var MonthName = monthName.ToList();
ViewBag.Bdata = Odata;
ViewBag.Cdata = MonthName;
return View();
}
</code></pre> | 1 |
Data Type of field from sequelize model | <p>Is it possible to get the datatype of a given field from a sequelize model. Assume we have a module defined like so</p>
<pre><code>User = sequelize.define 'User',
{
id:
type: DataTypes.UUID
primaryKey: true
defaultValue: DataTypes.UUIDV4
firstName:
type: DataTypes.STRING
allowNull: false
middleName:
type: DataTypes.STRING
allowNull: true
defaultValue: null
lastName:
type: DataTypes.STRING
allowNull: true
defaultValue: null
}
</code></pre>
<p>I need to say figure out the data type for firstName. Is there any method within model which can achieve this?</p> | 1 |
Removing Big, old Files that do not belong in git | <p>Long story short, there are very big files (like iso files-big) that were pushed into git. Not during my time with the group, but they've been treating the repo like an SVN-VC. </p>
<p>Anywho, how can i removed iso's from the repo and its history, to lighten the repo.</p>
<p>Or </p>
<p>Would it be easier to just move the code to a new repo, losing it's repo?</p> | 1 |
RecyclerView how to make cyclic | <p>I have RecyclerView with elements, for example from 1 to 10. Can somebody help? Thanks!</p>
<p>1 2 3 4 5 6 7 8 9 10 //On create</p>
<p>and when I scroll i want to make something like this:</p>
<p>9 10 1 2 3 4 5 6 7 8 //On Scroll</p>
<p>5 6 7 8 9 10 1 2 3 4</p> | 1 |
Is it possible to configure cucumber to run the same test with different spring profiles? | <p>I have an application where I'm running a trial with different technologies. I have a set of interfaces implemented with each technology and I use spring profiles to decide which technology to run. Each of the technologies has its own Spring java config annotated with the profile they are active for.</p>
<p>I run my cucumber tests defining which profile is the active one but this forces me to manually change the string every time I want to test a different profile, making it impossible to run automated tests for all of them. Is there anyway in cucumber to provide a set of profiles so tests are run once for each of them?</p>
<p>Thanks!</p> | 1 |
C: Signal handling and semaphores | <p>I'm trying to better understand semaphores and all that jazz and for that I'm programming a server and clients that communicate using shared memory and semaphores. It works pretty well and everything, but I'm not sure I understand how signal handling properly works in this case. This is some sample code from my server. I realize it may be a bit redundant to check both, but I kinda would like to understand the weird behaviour I'm experiencing:</p>
<pre><code>sig_atomic_t running = 1;
while(running == 1) {
if (sem_wait(server) == -1) {
//exit and print error A
}
if(running == 0) {
//exit and print error B
}
/* do server stuff */
if (sem_post(client) == -1) {
//exit and print error
}
}
</code></pre>
<p>server is the server semaphore name, client is the client semaphore name (which doesn't really matter in this case). running (which is actually global) is the variable I use in my signal handler:</p>
<pre><code>static void init_signalhandler() {
struct sigaction sa;
sa.sa_handler = terminate;
if(sigemptyset(&(sa.sa_mask)) == -1) {
bail_out(EXIT_FAILURE, "sigemptyset error");
}
if(sigaction(SIGINT, &sa, NULL) == -1) {
bail_out(EXIT_FAILURE, "sigaction1 error");
}
if(sigaction(SIGTERM, &sa, NULL) == -1) {
bail_out(EXIT_FAILURE, "sigaction2 error");
}
}
static void terminate(int e) {
running = 0;
sem_post(server);
}
</code></pre>
<p>Where bail_out is a custom error printing/exiting function.</p>
<p>Basically no matter what I do, whenever I start up the server, it gets to the <code>sem_wait(server)</code> part. If I try to kill it by sending SIGINT, sometimes, it prints error A, and other times, it prints error B. This appears to be completely random. It kinda forces me to use the running variable though, since sometimes, the semaphore gets passed, while at other times, it does not.</p> | 1 |
Matlab interp2 extrapolation | <p>I am doing a 2-D interpolation using <code>interp2</code>. For some data values, the
interp2 command returns NaN because one of the dimensions are outside
of the range defined by the vector of known values.</p>
<p>Its possible to extrapolate with the <code>interp1</code> command. However, Is
there a way to do this for <code>interp2</code>?</p>
<p>Thanks</p>
<p>Here is the code in which I am using the interp2 command:</p>
<pre><code>function [Cla] = AirfoilLiftCurveSlope(obj,AFdata,Rc,M)
% Input:
% AFdata: Airfoil coordinates.
% Rc: Local Reynolds number.
% M: Mach number for Prandtle Glauert compressibility correction.
% Output:
% Cla: 2 dimensional lift curve slopea applicable to linear region of lift polar.
load('ESDU84026a.mat');
xi = size(AFdata);
if mod(xi(1,1),2) == 0
%number is even
AFupper = flipud(AFdata(1:(xi(1,1)/2),:));
AFlower = AFdata(((xi(1,1)/2)+1):end,:);
else
%number is odd
AFupper = flipud(AFdata(1:floor((xi(1,1)/2)),:));
AFlower = AFdata((floor(xi(1,1)/2)+1):end,:);
end
t_c = Airfoil.calculateThickness(AFdata(:,2));
Y90 = ((interp1(AFupper(:,1),AFupper(:,2),0.9,'linear')) - (interp1(AFlower(:,1),AFlower(:,2),0.9,'linear')))*100;
Y99 = ((interp1(AFupper(:,1),AFupper(:,2),0.99,'linear')) - (interp1(AFlower(:,1),AFlower(:,2),0.99,'linear')))*100;
Phi_TE = (2 * atan( ( (Y90/2) - (Y99/2) )/9))*180/pi; % Degrees
Tan_Phi_Te = ( (Y90/2) - (Y99/2) )/9;
Cla_corr = interp2(Tan_Phi,Rc_cla,cla_ratio,Tan_Phi_Te,Rc,'linear');
beta =sqrt((1-M^2)); % Prandtle Glauert correction
Cla_theory = 2*pi + 4.7*t_c*(1+0.00375 * Phi_TE); % per rad
Cla = (1.05/beta) * Cla_corr * Cla_theory; % per rad
if isnan(Cla) == 1 %|| Cla > 2*pi
Cla = 2*pi;
end
end
</code></pre> | 1 |
How to map a local ip to a hostname? | <p>I am running IIS express through visual studio 2015. It launches <a href="http://localhost:60355/" rel="nofollow">http://localhost:60355/</a></p>
<p>I setup a proxy through the node module IISexpress-proxy to forward port 8000 to 60355</p>
<p>Now I can access my web app remotely by typing my IP:port (192.xxx.xxx.x:8000)</p>
<p>I would like to know how I can map a hostname to my ip so I can type:</p>
<blockquote>
<p><a href="http://mydev:8000" rel="nofollow">http://mydev:8000</a></p>
</blockquote>
<p>and it loads up the site I'm serving through visual studio. Thanks!</p> | 1 |
Groovy SQL: Shall I manually close the Mysql connection | <p>I have a grails service that calls stored procedures using Groovy SQL.
I am using <code>dataSource</code> for initializing the connection.
My question is: Do I need to manually close the connection or will it be handled by Groovy or GORM (since I am using <code>def dataSource</code>)?</p>
<p>Here is how my service is structured.</p>
<pre><code>class MyService {
static transactional = Boolean.FALSE
private static final String STATEMENT_ONE_SQL = "{ call sp_One(?) }"
private static final String STATEMENT_TWO_SQL = "{ call sp_Two(?,?) }"
def dataSource
Sql sql
@PostConstruct
def initSql() {
sql = new Sql(dataSource)
}
List<GroovyRowResult> callSpOne(Integer id) {
List<GroovyRowResult> results = sql.rows(STATEMENT_ONE_SQL, [id])
return results
}
List<GroovyRowResult> callSpTwo(Integer id, String name) {
List<GroovyRowResult> results = sql.rows(STATEMENT_TWO_SQL, [id, name])
return results
}
</code></pre> | 1 |
How to handle inline table-valued function that returns a table using ado.net | <p>I have implemented Inline table valued function in sql. I am trying to read the table values returned from Inline table valued function in C# using ado.net. Please help. I am attaching code here.</p>
<h2>Sql function:-</h2>
<pre><code>CREATE FUNCTION fun
(
@lname varchar(50)
)
RETURNS TABLE
AS
RETURN
(
select fp.accntname,ld.BU,fp.salesop,idt.isdormant from legacy_system as ls
inner join fourth_page as fp on ls.accountname=fp.accountname
inner join linked as ld on fp.productid=ld.productid
inner join isdormant as idt on idt.productid=ld.productid
inner join legacy_system as l on ls.productid=idt.productid
where l.legacyname in(@lname)
)
GO
</code></pre>
<h2>C# code:-</h2>
<pre><code> [HttpPost]
public void call_stored_procedure(List<string> lyname)
{
Console.WriteLine(lyname);
string dogCsv = string.Join(",", lyname.Select(i => "'" + i + "'"));
Console.WriteLine(dogCsv);
using (SqlConnection connection = new SqlConnection("data source=.; database=Srivatsava; integrated security=SSPI"))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "select dbo.fun(@lname)";
command.Parameters.AddWithValue("@lname", dogCsv);
command.CommandType = CommandType.Text;
String s=command.ExecuteScalar().ToString();
Console.WriteLine(s);
connection.Close();
}
}
}
</code></pre> | 1 |
ORA-01780: string literal required | <p>When i invoke below procedure i get 'string literal required' exception, can any one help please, i'm sure that i'm writing (Execute Immediate) in wrong form : </p>
<pre><code>PROCEDURE ADD_TAB_COL_COMMENT (
P_TAB_NAME IN VARCHAR,
P_COL_NAME IN VARCHAR,
P_COMMENT IN VARCHAR,
P_LEVEL IN NUMBER
)
IS
BEGIN
IF(P_LEVEL = 1)THEN
EXECUTE IMMEDIATE 'COMMENT ON TABLE ' || P_TAB_NAME || ' IS ' || P_COMMENT;
ELSIF(P_LEVEL = 2)THEN
EXECUTE IMMEDIATE 'COMMENT ON COLUMN ' || P_TAB_NAME ||'.'|| P_COL_NAME || ' IS ' || P_COMMENT;
END IF;
END ADD_TAB_COL_COMMENT ;
</code></pre> | 1 |
List file that have changed since last commit with GitPython | <p>I need to have the Python script read in the files that have changed since the last Git commit. Using <a href="https://github.com/gitpython-developers/GitPython" rel="noreferrer">GitPython</a>, how would I get the same output as running from cli:</p>
<pre><code>$ git diff --name-only HEAD~1 HEAD
</code></pre>
<p>I can do something like the following, however, I only need the file names:</p>
<pre><code>hcommit = repo.head.commit
for diff_added in hcommit.diff('HEAD~1').iter_change_type('A'):
print(diff_added)
</code></pre> | 1 |
Paging is reset when data is updated with Angular-DataTables | <p>We have a Web form using Angular DataTables (DataTables 1.10.10 / angular-datatables - v0.5.3). We are feeding the data with a JSON coming from the backend. The table is configured with paging, and data feeding the table is reloaded manually every 10 secs. This is all working fine, when I select a different page from 1st one and the table get refreshed then paging is reset. I tried the different params of the draw(<a href="https://datatables.net/reference/api/draw()" rel="noreferrer">https://datatables.net/reference/api/draw()</a>) method but did not make any difference..
Many thanks in advance!!</p>
<p>My HTML table:</p>
<pre><code><table datatable="ng" id="datatable1" dt-options="dtOptions" dt-column-defs="dtColumnDefs" class="table table-striped table-hover" dt-instance="dtInstance">
</code></pre>
<p><code><tr ng-repeat="session in data.serverData[data.selectedAgent]" class="gradeX"></code></p>
<p>This is our controller:</p>
<pre><code>App.controller("ReportAgentSessionsListController", [
"$scope", "$http", "sessionsListData", "$timeout", "DTOptionsBuilder", "DTColumnDefBuilder", function ($scope, $http, sessionsListData, $timeout, DTOptionsBuilder, DTColumnDefBuilder, DTInstances) {
$scope.dtOptions = DTOptionsBuilder.newOptions().withPaginationType("simple_numbers").withDisplayLength(25).withOption("retrieve", true).withOption('order', [0, 'desc']);
$scope.dtColumnDefs = [
DTColumnDefBuilder.newColumnDef(0),
DTColumnDefBuilder.newColumnDef(1),
DTColumnDefBuilder.newColumnDef(2),
DTColumnDefBuilder.newColumnDef(3).notSortable(),
];
// Get original request params
$scope.dateData = JSON.parse(sessionsListData.config.data);
var timer; // used for auto-refresh
var vm = this;
$scope.cduInterval = 1000;
$scope.counter = 0;
$scope.dtInstance = {};
$scope.data = {};
$scope.data.serverData = [];
var formatServerData = function(serverData) {
$scope.agentsList = Object.keys(serverData);
// If no agent has been selected
if (!$scope.data.selectedAgent) {
$scope.data.selectedAgent = $scope.agentsList[0];
}
// Format data
for (var key in serverData) {
if (serverData.hasOwnProperty(key)) {
for (var i = 0; i < serverData[key].length; i++) {
var data = serverData[key][i];
data.waitTime = numeral(data.waitTime).format("00:00:00");
data.handleTime = numeral(data.handleTime).format("00:00:00");
data.revenue = numeral(data.revenue).format("$0,0.00");
}
}
}
$scope.data.serverData = serverData;
// This does not do anything apparently
if ($scope.dtInstance.DataTable) {
$scope.dtInstance.DataTable.draw('full-hold');
}
};
var scheduleTimeout = function () {
var getFreshDataInterval = 1000;
timer = $timeout(getFreshData, getFreshDataInterval);
};
// Request a new set of data from the server
var getFreshData = function () {
if ($scope.counter++ % 10 == 0) { // Requests to server will be done every 10th request (10 secs)
var response = $http({
abp: true,
url: abp.appPath + "Report/GetTeamSessionsByTimeInterval",
method: "POST",
data: sessionsListData.config.data
}).then(function (response) {
formatServerData(response.data);
if (timer) {
scheduleTimeout();
}
});
}
else {
if (timer) {
scheduleTimeout();
}
}
};
// Is currentdate between the date ranges being displayed
var isTodayInRage = function (currentdate) {
..
}
formatServerData(sessionsListData.data);
if (isTodayInRage(userCurrentDate)) {
// Date range includes Today (local time)
scheduleTimeout();
}
$scope.selectAgent = function(agent) {
$scope.data.selectedAgent = agent;
};
$scope.$on("$destroy", function () {
if (timer) {
$timeout.cancel(timer);
}
});
}]);
</code></pre> | 1 |
Preventing DDOS attack, for Django app with nginx reverse proxy + gunicorn | <p>I am writing a Django app which uses an nginx reverse proxy + gunicorn as a webserver in production. </p>
<p>I want to include the capability to stop DDOS attacks from a certain IP (or pool of IPs). This as to be at the nginx level, rather than any deeper in the code. Do I need a web application firewall? If so, how do I integrate it.</p>
<p>My project's nginx file located at sites-available has:</p>
<pre><code>server {
listen 80;
charset utf-8;
underscores_in_headers on;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/sarahm/djangoproject/djangoapp;
}
location /static/admin {
root /home/sarahm/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/contrib/admin/static/;
}
location / {
proxy_pass_request_headers on;
proxy_buffering on;
proxy_buffers 8 24k;
proxy_buffer_size 2k;
include proxy_params;
proxy_pass http://unix:/home/sarahm/djangoproject/djangoapp/djangoapp.sock;
}
error_page 500 502 503 504 /500.html;
location = /500.html {
root /home/sarahm/djangoproject/djangoapp/templates/;
}
}
</code></pre>
<p>Let me know if I should include more information, and what that information should be.</p> | 1 |
ScrollView allows dragging content. How can this be disabled? | <p>The content of a QML <code>ScrollView</code> can be dragged using the mouse or touch gestures. The same is true for the content of <code>ListView</code>s, at least in the example I have.
And it is even possible to do so when the content fits into the <code>ScrollView</code> and no scrollbars are displayed. In this case, after releasing the mouse button, the content item moves back to it's original place. Is there any way to disable this?</p> | 1 |
How to test in functional test if event has been dispatched | <p>I am testing a controller action using a functional test in Symfony. In this test I am doing something like this:</p>
<pre><code>$client->request(
'PUT',
'/api/nodes/',
$data
);
</code></pre>
<p>Afterwards I would like to test if a certain event has been dispatched. I already tried to enable the profiler previously (and set the config accordingly) and check the data in the <code>EventDataCollector</code>:</p>
<pre><code>$client->enableProfiler();
$client->request(
'PUT',
'/api/nodes/' . $data[0]['id'] . '?webspace=sulu_io&language=en',
$data[0]
);
/** @var EventDataCollector $eventDataCollector */
$eventDataCollector = $client->getProfile()->getCollector('events');
</code></pre>
<p>This works as expected, but the problem is that the <code>$eventDataCollector</code> only contains data about the events for which some listeners have actually been executed. Fortunately there is an event listener executed in this specific case, but I would like that to work also without any event listeners attached, since I can't say for sure that this situation will continue to be like that.</p>
<p>So my question is if there is a way to test if a event is dispatched, which is save, even if there wasn't a event listener attached.</p> | 1 |
unrecognized expression on browserLink | <p>I get some mistake about <em>" browserLink "</em> <strong>see this below</strong></p>
<pre class="lang-html prettyprint-override"><code><div ng-show="optList.editing && optList.BANKRUPT_FLG != 'Y' && (optList.OPT != 'TF' || (optList.OPT == 'TF' && optList.ONCESMART_ID == '-1'))">
<input />
</div>
</code></pre>
<p><a href="https://i.stack.imgur.com/IqbQ4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IqbQ4.png" alt="enter image description here" /></a></p>
<p>It's Ok..</p>
<p>But</p>
<pre class="lang-html prettyprint-override"><code><div ng-show="optList.editing && optList.BANKRUPT_FLG != 'Y' && (optList.OPT != 'TF' || (optList.OPT == 'TF' && optList.ONCESMART_ID == '-1'))">
<input type="text"/>
</div>
</code></pre>
<p><a href="https://i.stack.imgur.com/fmpao.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fmpao.png" alt="enter image description here" /></a></p>
<p>When i add <code>type="text"</code> on input tag i will get</p>
<blockquote>
<p><strong>Uncaught Error: Syntax error, unrecognized expression:</strong></p>
<p>div:has(input[type='text'])[ng-show='optList.editing && optList.BANKRUPT_FLG != 'Y' && (optList.OPT != 'TF' || (optList.OPT == 'TF' && optList.ONCESMART_ID == '-1'))']</p>
<p><a href="https://i.stack.imgur.com/hCeuk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hCeuk.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/iDGAy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iDGAy.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/Vx8mn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vx8mn.png" alt="enter image description here" /></a></p>
</blockquote>
<p>Can someone tell me , How to solve this error please ?</p>
<p><strong>FYI</strong> :
Google Chrome (48.0.2564.97)<br>
Microsoft Visual Studio Professional 2015 (14.0.23107.156)<br>
Web Essentials 2015.1 (1.0.203)</p> | 1 |
Flask-Login: login user and redirect to home page after registration | <p>Using flask login, trying to login the user after the user registers.
user_login() works for my login route, however after registration, it redirects to the login route, not the intended home page. So my question is, can login_user() only work in a 'login' route?</p>
<p>Here is a basic version of what I have now:</p>
<pre><code>class User(flask_login.UserMixin):
def __init__(self, userName, email, firstName):
self.userName = userName
self.id = email
self.email = email
self.firstName = firstName
@login_manager.user_loader
def user_loader(email):
""" code to get userdata from database """
user = User(userName,email,firstName)
return user
@app.route('/register', methods=['GET','POST'])
def register():
if request.method == 'GET':
return render_template('register.html')
elif request.method == 'POST':
""" code for creating user from form data """
#create session for user
user = User(userName,email,firstName)
flask_login.login_user(user)
return redirect(url_for('home'))
@app.route('/login', methods=['GET','POST'])
def login():
if request.method == 'GET':
return render_template('login.html')
elif request.method == 'POST':
""" code for authorizing a user """
user = User(userName,email,firstName)
flask_login.login_user(user)
return flask.redirect(flask.url_for('home'))
else:
return render_template('login.html')
@app.route('/home')
@flask_login.login_required
def home():
return render_template('home.html')
</code></pre>
<p>UPDATE:
I wasn't loading my user correctly in my user_loader</p> | 1 |
How to run spring-boot as a service in linux | <p>I am trying to run a spring-boot application as a service in linux box so that I can start and stop it as a jenkins job. </p>
<p>As per the suggestions in for this question <a href="https://stackoverflow.com/questions/21503883/spring-boot-application-as-a-service">Spring Boot application as a Service</a> I created the soft link </p>
<pre><code>$sudo link -s /opt/jenkins/workspace/myapp/myapp.jar /etc/init.d/myapp
</code></pre>
<p>Now when I am trying to run it from the jenkins command prompt I get command not found</p>
<pre><code>$ sudo /etc/init.d/myapp start
sudo: /etc/init.d/myapp: command not found
</code></pre>
<p>I am using spring boot 1.3 and java8</p> | 1 |
Set focus in a QTableView | <p>I have a <code>QMainWindow</code> containing a <code>QTableView</code> as its centralwidget.</p>
<p>I populate this <code>QTableView</code> by setting a model (which is derived from <code>QAbstractTableModel</code>). </p>
<p>The selection behavior for the <code>QTableView</code> is set to <code>QAbstractItemView::SelectRows</code>. This means that if I click in a cell, the entire row is selected (and is highlighted).</p>
<p>I would like to be able to focus/highlight a row in the <code>QTableView</code> programatically. In other words, I would like to focus/highlight a row without the user clicking on it. How can this be done, do I 'fake' a click in a cell? </p> | 1 |
Adding filter entries to the git config file | <p>If I run:</p>
<pre><code>git config foo.bar hello
</code></pre>
<p>It adds the following to my repo's local .git\config file:</p>
<pre><code>[foo]
bar = hello
</code></pre>
<p>But now suppose that I want to add the following to that same config (which is what's used by <a href="https://git-lfs.github.com/" rel="noreferrer">lfs</a>, but that's beyond the point):</p>
<pre><code>[filter "lfs"]
clean = git-lfs clean %f
smudge = git-lfs smudge %f
required = true
</code></pre>
<p><strong>Question: Is there a git command that will add this?</strong></p>
<p>I have not been able to make <code>git config</code> work here, because the key would need to be something like <code>filter "lfs".clean</code> which it doesn't view as a valid key.</p> | 1 |
NullValueHandling.Ignore influences deserialization into [ExtensionData] despite matching class member | <p>My server responses consists of a set of known and unknown properties. For the known ones, I created a DTO class with members for each property. The unknown properties shall be put inside a dictionary annotated with the <code>[ExtensionData]</code> attribute:</p>
<pre><code>[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class Dto
{
[JsonExtensionData]
private readonly Dictionary<string, object> unknownProperties = new Dictionary<string, object>();
public IDictionary<string, object> UnknownProperties
{
get
{
return new ReadOnlyDictionary<string, object>(this.unknownProperties);
}
}
[JsonProperty(Required = Required.Default, PropertyName = "KNOWN_PROPERTY")]
public string KnownProperty { get; private set; }
}
</code></pre>
<p><code>Null</code> is allowed as value for <code>KnownProperty</code>. If I try to deserialize a JSON object that contains <code>KNOWN_PROPERTY : null</code>, this property is also contained in the dictionary <code>UnknownProperties</code>, if I configure the serializer with <code>NullValueHandling.Ignore</code>. This is done even though a class member exists for <code>KNOWN_PROPERTY</code>:</p>
<pre><code>static void Main(string[] args)
{
string jsonString = @"{
KNOWN_PROPERTY : null,
UNKNOWN_PROPERTY : null
}";
JsonSerializer serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore
});
using (var textReader = new StringReader(jsonString))
{
Dto dto = serializer.Deserialize<Dto>(new JsonTextReader(textReader));
foreach (var pair in dto.UnknownProperties)
{
Console.WriteLine("{0}: {1}", pair.Key, pair.Value == null ? "null" : pair.Value.ToString());
}
}
}
</code></pre>
<p>Output:</p>
<pre><code> KNOWN_PROPERTY : null
UNKNOWN_PROPERTY : null
</code></pre>
<p>If I configure the serializer with <code>NullValueHandling.Include</code> or set a value for <code>KNOWN_PROPERTY</code> in the JSON string, the dictionary contains only <code>UNKNOWN_PROPERTY</code>, as expected.</p>
<p>For my understanding <code>[ExtensionData]</code> is not working correctly if <code>NullValueHandling</code> is set to ignore, since the <a href="http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonExtensionDataAttribute.htm" rel="nofollow">documentation</a> states the extension is used only if no matching class member is found. </p>
<p>Is the behavior I'm seeing intended? Can I do something to avoid this? Because I don't like to send null values to the server, I'd like to stick to the currently set <code>NullValueHandling</code>.</p>
<p>I'm using Json.NET 8.0.2</p> | 1 |
Cassandra cqlsh Connection error : 'Unable to connect to any servers',.cql_version '3.4.0' is not supported by remote | <p>I was trying to connect to my remote cassandra DB via <code>cqlsh</code> ,</p>
<pre><code>Connection error: ('Unable to connect to any servers', {'XX.XX.XX.XX': ProtocolError("cql_version '3.4.0' is not supported by remote (w/ native protocol). Supported versions: [u'3.2.1']",)})
</code></pre>
<p>I installed Planet Cassandra version 3.2.1 from this <a href="http://www.planetcassandra.org/cassandra/#tablepress-3_wrapper" rel="nofollow noreferrer">link</a> .</p>
<p>I run the command : <code>nodetool version</code> it is showing <code>3.2.1</code> version.</p>
<p>I found similar question <a href="https://stackoverflow.com/questions/33002404/cassandra-cqlsh-unable-to-connect-to-any-servers">here</a> , but that didn't help me. </p> | 1 |
DownloadManager IllegalStateException creating a download in DIRECTORY_DOWNLOADS | <p>Firstly, there are a lot of questions on this subject, but none reflect my issue. I have for example read <a href="https://stackoverflow.com/questions/17112142/android-downloadmanager-illegalstateexception-unable-to-create-directory">this</a> and <a href="https://stackoverflow.com/questions/26802707/why-get-java-lang-illegalstateexception-unable-to-create-directory-error">this</a>.</p>
<p>The issue that I have, is that in an <em>extremely</em> small number of cases, my function to <code>setDestinationInExternalPublicDir</code> results in the following stack trace:</p>
<pre><code>Fatal Exception: java.lang.RuntimeException: Unable to start receiver com.onlinetvrecorder.otrapp2.listeners.DownloadUpdateReceiver: java.lang.IllegalStateException: Unable to create directory: /mnt/sdcard/Download
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2274)
at android.app.ActivityThread.access$1500(ActivityThread.java:131)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4791)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(NativeStart.java)
Caused by java.lang.IllegalStateException: Unable to create directory: /mnt/sdcard/Download
at android.app.DownloadManager$Request.setDestinationInExternalPublicDir(DownloadManager.java:496)
at com.myapp.Utils.download(SourceFile:752)
at com.myapp.Receiver.onReceive(SourceFile:20)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2267)
at android.app.ActivityThread.access$1500(ActivityThread.java:131)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4791)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(NativeStart.java)
</code></pre>
<p>I am using a standard <code>Environment</code> constant to tell the <code>DownloadManager</code> where to save the file.</p>
<pre><code>android.app.DownloadManager dm = (android.app.DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse("url.to.file.ext"));
request.setMimeType("mime/type");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
Utils.setDownloadRequestVisibility(request, android.app.DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "file.ext");
request.setTitle(context.getString(R.string.download));
dm.enqueue(request);
</code></pre>
<p>As previously stated, there are perhaps not even 1% of users getting this error. What could be causing it?</p> | 1 |
Asp.Net MVC C# [Authorize(Roles"")] not working | <p>I am trying to make role based authorization with my custom manager. I have User Table and Roles Table. The models looks like this</p>
<pre><code>public class Account : EntityModel
{
public string Username { get; set; }
public string PasswordHash { get; set; }
public string Email { get; set; }
public Account()
: base("1", Suid.NewSuid())
{
Roles = new List<String>();
}
public static IEnumerable<Account> GetAll()
{
return TableHelper.GetAll<Account>();
}
public List<String> Roles { get; set; }
public Account Save()
{
TableHelper.Save<Account>(this);
return this;
}
}
</code></pre>
<p>Roles Model looks like this</p>
<pre><code>public class Role : EntityModel
{
public string Name { get; set; }
public String Id
{
get
{
return this.RowKey;
}
set
{
this.RowKey = value;
}
}
public Role()
: base("1", Suid.NewSuid())
{
}
public static IEnumerable<Role> GetAll()
{
return TableHelper.GetAll<Role>();
}
public static Role Get(string x)
{
return TableHelper.Get<Role>("1", x);
}
}
</code></pre>
<p>I am able to add Role Id in <code>User.Roles</code> list. So I create a role named <code>admin</code> and add it to the users list. It is added successfully.</p>
<p>Then I try this on one of my controllers</p>
<pre><code>[Authorize(Roles = "admin")]
</code></pre>
<p>but it doesn't work. Am I missing something?</p> | 1 |
How to mock Auth in a Laravel 5.2 Model | <p>I'm trying to write some unit tests for a brand new mini app. I usually write functional tests so this is me branching out to try and do it properly with mocking and stubs and all those things that make it just about the code.</p>
<p>The model looks like this :</p>
<pre><code><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Auth;
class myModel extends Model
{
public static function getUser()
{
$user = \Auth::user();
return $user->adldapUser->cn[0];
}
}
</code></pre>
<p>And the test :</p>
<pre><code>class MyModelTest extends TestCase
{
public function testGetUser()
{
$mockResult = new StdClass();
$mockResult->adldapUser = new stdClass();
$mockResult->adldapUser->cn=array("test");
$auth = $this->getMock('Auth');
$auth
->method('user')
->will($this->returnValue($mockResult));
$this->assertEquals('test',\App\MyModel::getUser());
}
}
</code></pre>
<p>But when I run the unit test I get the following error message :</p>
<p>There was 1 error:</p>
<blockquote>
<p>1) MyModelTest::testGetUser ErrorException: Trying to get property of
non-object</p>
<p>/home/aidan/web/vagrant-web-dev/src/apps/orcid/app/MyModel.php:61
/home/aidan/web/vagrant-web-dev/src/apps/orcid/tests/MyModelTest.php:18</p>
</blockquote>
<p>and if I post out $user it's NULL.</p>
<p>What am I doing wrong here?</p> | 1 |
Align placeholder inside text field HTML | <p>I want to move my placeholder in upper-left corner.</p>
<p><a href="https://i.stack.imgur.com/oDEVf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oDEVf.png" alt="enter image description here"></a></p>
<p>I want something like on the image.</p>
<p>I've tried</p>
<pre><code>::-webkit-input-placeholder {
left: 0px;
up: 0px;
}
</code></pre>
<p>But it doesn't work. I know HTML well, but I never did something like this.</p> | 1 |
Best way to detect editText inputType in Android? | <p>I developed a simple keyboard.</p>
<p>It's a T9 keyboard that is conceived specifically for phones with an hardware keyboard.</p>
<p>When I want to write something into a standard EditText I have no problem, but when i try to write numbers inside an ediText with <code>android:inputType="phone"</code> or <code>android:inputType="number"</code> the keyboard still tries to write letters.</p>
<p>My question is: What is the best and simplest way to detect if the editText I have focus on is Number-only, Text-only, etc. from my custom Keyboard?
How can I detect the inputType from my Keyboard?</p>
<p>I hope someone of you already solved this problem in the past and can help...thank you in advance! </p> | 1 |
Extracting Content from Webpage with ParsedHtml | <p>I've been trying to use the invoke-Webrequest and the "ParsedHtml.getElements" </p>
<pre><code>ParsedHtml.getElementsByTagName("div") | Where{ $_.className -eq 'pricingContainer-priceContainer' } ).innerText
</code></pre>
<p>to try to get the value <code>$8.29</code> but using it on the below code produces no result. What am I doing wrong?</p>
<pre><code><div class="pricingContainer pricingContainer--grid u-ngFade noCenterTag" ng-class="::{'noCenterTag': !showCenterTag}" ng-if="::featuresEnabled">
<!-- ngIf: ::(product.IsOnSpecial && !product.HideWasSavedPrice) -->
<div class="pricingContainer-priceContainer">
<span class="pricingContainer-priceAmount" ng-class="::specialClass">$8.29</span>
<!-- ngIf: ::product.CupPrice --><span ng-if="::product.CupPrice" class="pricingContainer-priceCup">
$5.19 / 100G
</span><!-- end ngIf: ::product.CupPrice -->
</div>
</div>
</code></pre> | 1 |
How to display multiple strings into one Toast? | <p>I made some strings that I could display using a Toast but I'm having trouble figuring out how to make them appear at the same time as a single Toast. So far I have this:</p>
<pre><code>String text = input.getText().toString();
String text2= input2.getText().toString();
String text3 = input3.getText().toString();
Toast.makeText(getApplicationContext(),"Name: " + text,Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"Age: " + text2,Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"Occupation: " + text3,Toast.LENGTH_SHORT).show();
</code></pre>
<p>When I run the emulator, it shows the Toasts one at a time. Is there a way to display the name, age, and occupation at the same time?</p> | 1 |
How can I assign a name of this combobox(Name = Combobox1) and range it to a fixed position (Cell C4)? | <pre><code>With ActiveSheet.OLEObjects.Add(ClassType:="Forms.ComboBox.1",Link:=False, DisplayAsIcon:=False, Left:=50, Top:=80, Width:=100, Height:=15)
With .Object
.AddItem "Yes"
.AddItem "No"
End With
End With
</code></pre>
<p><strong>How Can I assign a name and fix the position of it (based on the code above)?</strong></p> | 1 |
Magento keeps redirecting to default website for a multisite store | <p>We have 3 website in a Magento store.
Here's what I've done.</p>
<ol>
<li>I have downloaded the code from the live site to my local machine</li>
<li><p>set up the vhost for the 3 websites </p>
<pre><code>created site1(2 & 3).com.conf and enabled them
</code></pre></li>
<li>Added the corresponding lines to /etc/hosts </li>
<li><p>In my .htaccess I have the code that manages the 3 websites</p>
<pre><code>SetEnvIf Host www\.site1\.com MAGE_RUN_CODE=site1
SetEnvIf Host www\.site1\.com MAGE_RUN_TYPE=website
SetEnvIf Host ^site1\.com MAGE_RUN_CODE=site1
SetEnvIf Host ^site1\.com MAGE_RUN_TYPE=website
SetEnvIf Host www\.site2\.com MAGE_RUN_CODE=site2
SetEnvIf Host www\.site2\.com MAGE_RUN_TYPE=website
SetEnvIf Host ^site2\.com MAGE_RUN_CODE=site2
SetEnvIf Host ^site2\.com MAGE_RUN_TYPE=website
SetEnvIf Host www\.site3\.com MAGE_RUN_CODE=site3
SetEnvIf Host www\.site3\.com MAGE_RUN_TYPE=website
SetEnvIf Host ^site3\.com MAGE_RUN_CODE=site3
SetEnvIf Host ^site3\.com MAGE_RUN_TYPE=website
</code></pre></li>
</ol>
<p>Everything is working fine on the live server but on my local machine when I type www.site1.com or www.site2.com I'm automatically redirected to www.site2.com as it's the default website.</p>
<p>I'm on Ubuntu 14.04 I've just set up the whole environment (apache2, php5, mysql) as my machine was formatted last week.</p>
<p>Thanks,</p> | 1 |
Why is document.body not a HTMLBodyElement? | <p>Visual Studio, hint that <code>document.body</code> is a <code>HTMLElement</code>, and not a <code>HTMLBodyElement</code>, why is that? - I haven't had any luck searching for an answer.</p>
<pre><code>class Test {
documentBody1: HTMLBodyElement;
documentBody2: HTMLElement;
constructor(){
this.documentBody1 = document.body; //wrong
this.documentBody2 = document.body; //right
}
}
</code></pre> | 1 |
nginx redirect multiple servers to SSL | <p>I have this code. I just want each of the server_name in the list to redirect to its own name https. But, if I do <a href="http://beta.example.com" rel="noreferrer">http://beta.example.com</a>, it redirects to <a href="https://api.example.com" rel="noreferrer">https://api.example.com</a> (or whatever the first item in the list is)</p>
<pre><code>server {
listen 80;
server_name api.example.com beta.example.com apibeta.example.com nodebeta.example.com app.example.com;
return 301 https://$server_name$request_uri;
}
</code></pre> | 1 |
What does CommandLineRunner do in this case? | <p>I'm completely new to Spring & not very experienced in Java admittedly. I am trying to go through the <a href="http://spring.io/guides/tutorials/bookmarks/" rel="nofollow">Building REST services with Spring</a> tutorial on the spring.io website. I came across the following code segment and I'm confused as to what it actually does.</p>
<pre><code>@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
@Bean
CommandLineRunner init(AccountRepository accountRepository,
BookmarkRepository bookmarkRepository) {
return (evt) -> Arrays.asList(
"jhoeller,dsyer,pwebb,ogierke,rwinch,mfisher,mpollack,jlong".split(","))
.forEach(
a -> {
Account account = accountRepository.save(new Account(a,
"password"));
bookmarkRepository.save(new Bookmark(account,
"http://bookmark.com/1/" + a, "A description"));
bookmarkRepository.save(new Bookmark(account,
"http://bookmark.com/2/" + a, "A description"));
});
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
</code></pre>
<p>I looked up CommandLineRunner on Spring Boot docs, and it says it's an interface that gets implemented if you want to execute some code when the application starts. But to my limited knowledge, CommandLineRunner is not getting implemented by anything in the above code segment. Also, I have no clue where the init() method came from or what it really is.</p>
<p>Additionally, I downloaded the complete code from their <a href="https://github.com/spring-guides/tut-bookmarks.git" rel="nofollow">github repo</a> but I'm not quite sure how to actually run it. I read earlier today that <code>SpringApplication.run()</code> makes it so that you don't have to deploy anything to an external service like Tomcat. But when I tried <code>java -jar ./jarFileName</code> for the Application class (seemed like a natural choice since it had main() ), it gave an error.</p>
<p>Any help would be appreciated.</p> | 1 |
How to Rejoin a player to a room using PUN Unity3D? | <p>I am building a multiplayer game using PUN where two player in a room will play with each other.
While playing if network seems very slow of a player, he/she automatically disconnected from Photon server.
I want to give a waiting time to respond the disconnected player and meanwhile he can again join the room and continue his game.</p>
<p>How can I do this?
Any kind of help is highly appreciated. TIA</p> | 1 |
Writing in HINDI in android studio string.xml | <p>I am trying to learn/build my first few apps on android using android studio. Apart from default language, I wanted to add support for HINDI language. I have created strings.xml file required for hindi and I have verified that whatever string I put in this file is displayed correctly when HINDI language is selected on Android device. To try this, I just wrote different sting in English characters, because I am unable to figure out how to write in HINDI in android studio.</p>
<p>For eg. I want something like this in my hindi strings.xml</p>
<pre><code><string name="customer_name">क्रुपया अपना नाम लिखे</string>
</code></pre>
<p>Currently I just have this in my XML:</p>
<pre><code><string name="customer_name">Please enter your name</string>
</code></pre>
<p>Could someone please provide on what should I do to type directly in hindi language in android studio xml?</p> | 1 |
how to loop through 3 lists and get 3 columns in Python? | <p>I have three lists list1 is "Car Models" list2 is "price per galon (mpg)" and list3 is "total price for one year". I'm able to loop through the 3 columns, but I don't know how to get 3 columns one after the other. Please someone help me. Thank you in advance!!</p>
<p>Heres my code:</p>
<pre><code>modelName = ['Toyota', 'Nissan', 'Honda']
fuelEfficiency = [15.0, 20.0, 30.0]
for i in range(len(modelName)):
print (modelName[i])
for i in range(len(fuelEfficiency )):
print (fuelEfficiency[i])
priceGas = 2.41
totalCost1 = (10000 * priceGas)/15.0
totalCost2 = (10000 * priceGas)/20.0
totalCost3 = (10000 * priceGas)/30.0
print (totalCost1)
print (totalCost2)
print (totalCost3)
</code></pre>
<p>The output I want is this:</p>
<pre><code>MODEL COST(MPG) TOTALCOST
Toyota 15.0 1606.66
Nissan 20.0 1205.0
Honda 30.0 803.33
</code></pre> | 1 |
BabylonJS, how to rotate mesh instead of the camera? | <p><a href="http://babylonjs-playground.com/#A83GX#0" rel="nofollow">http://babylonjs-playground.com/#A83GX#0</a></p>
<p>Hi All,</p>
<p>I have been playing with babylonjs for a couple of days now and excited about it. But why would I be here if I don't have a problem.</p>
<p>Attached the playground link, right now an arcrotatecamera rotates around a mesh. It gives an illusion that the mesh itself is being rotated, but when I move the object away from (0,0,0) it starts to show that the camera is rotating and not the object. Instead of such a camera hack, I would like to rotate the mesh itself from wherever it is, I googled and found a couple of topics in the babylonjs forum, but the solutions are not as smooth or eased as the camera solution. It will be great if someone can help me on this. Cheers and thanks for your help in advance.</p> | 1 |
Electron: Close w X vs right click dock and quit | <p>In my Electron app, I would like to do something that is done very often in other OSX apps. That is... I would like to NOT close the app of the red X is clicked in the top right. But, if they right click the app icon in the dock, and say Quit, then I would like to quit the app. How do I do this?</p>
<p>I have tried using the <code>onbeforeunload</code> event from the rendererProcess, as well as the <code>browserWindow.on("close", fn)</code> event to try and prevent this. The problem is that they both file the <code>onbeforeunload</code> event. And I can't tell the different between the red X being clicked and the dock icon being right clicked and told to quit. Any help would be nice. Has anyone else done this in Electron for OSX?</p> | 1 |
cjson.decode() of a multi layer JSON | <p>I want to decode a multi layered json object into a table and print the value of "temp".</p>
<pre class="lang-Lua prettyprint-override"><code>p=666
d=23.42
payload='{"d":
{"pres":'..(p)..',"temp":'..(d)..'}
}'
t = cjson.decode(payload)
</code></pre>
<p>My first idea was something like this: </p>
<pre class="lang-Lua prettyprint-override"><code>print(t["d"]["temp"])
</code></pre>
<p>But this did not work. How can I improve this code so that it correctly decodes using Lua-CJson?</p> | 1 |
Set android-gradle packagingOptions in the new experimental plugin | <p>What is the equivalent to the andriod.packagingOptions in the android gradle experimental plugin? </p>
<p>In the current "stable" version it works as follows:</p>
<pre><code>android{
packagingOptions{
exclude 'META-INF/notice.txt'
exclude 'META-INF/license.txt'
}
}
</code></pre>
<p>I tried mapping it inside the new android block but it didn't work. Also haven't found anything related to it on the documentation</p> | 1 |
json formatting with moshi | <p>Does anyone know a way to get moshi to produce a multi-line json with indentation ( for human consumption in the context of a config.json )
so from:</p>
<pre><code>{"max_additional_random_time_between_checks":180,"min_time_between_checks":60}
</code></pre>
<p>to something like this:</p>
<pre><code>{
"max_additional_random_time_between_checks":180,
"min_time_between_checks":60
}
</code></pre>
<p>I know other json-writer implementations can do so - but I would like to stick to moshi here for consistency </p> | 1 |
Iterating over columns and rows in pandas dataframe | <p>I am trying to iterate through a dataframe that I have and use the values inside of the cells, but I need to use the names of the columns and rows that the cells come from. Because of that I am currently doing something like the following:</p>
<pre><code>df=pandas.DataFrame(data={"C1" : [1,2,3,4,5], "C2":[1,2,3,4,5]},
index=["R1","R2","R3","R4","R5"])
for row in df.index.values:
for column in df.columns.values:
if (df[row][column] > 3:
if row in df2[column]:
print("data is present")
</code></pre>
<p>I need to use the row and column names because I am using them to look values up in another data frame that has related information. I know that for loops take forever in pandas, but I haven't been able to find any examples of how to iterate over both the row and the column and the same time. This: </p>
<pre><code>df.applymap()
</code></pre>
<p>wont work because it only gives the value in the cell, without keeping reference to which row and column the cell was in, and this:</p>
<pre><code>df.apply(lambda row: row["column"])
</code></pre>
<p>wont work because I need get the name of the column without knowing it before. Also this:</p>
<pre><code>df.apply(lambda row: someFunction(row))
</code></pre>
<p>wont work because apply uses a Series object which only has the row name, rather than the row and column names.</p>
<p>Any insight would be helpful! I am currently running the for loop version but it takes forever and also hogs CPU cores.</p> | 1 |
How to display flash messages, on successful ajax, at the top of my page, without refreshing? | <p>My bookmarks index page is essentially a single page application. When I submit the form for a new bookmark at the bottom of my page, I want the page to not have to refresh and display <code>"Bookmark successfully created!"</code> in the form of a flash message at the top of the page. </p>
<p>In my <code>application.html.erb</code> file, I am rendering flash messages: </p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Text Me Later</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<%= render partial: 'layouts/nav' %>
<% flash.each do |key, value| %>
<% if key == "notice" %>
<%= content_tag :div, value, class: "text-center alert alert-warning" %>
<% elsif key == "alert" %>
<%= content_tag :div, value, class: "text-center alert alert-danger" %>
<% else %>
<%= content_tag :div, value, class: "text-center alert alert-success" %>
<% end %>
<% end %>
<div class="container">
<%= yield %>
<%= debug(params) if Rails.env.development? %>
</body>
</html>
</code></pre>
<p>The <code>create</code> method in my <code>bookmarks_controller</code>:</p>
<pre><code>def create
@bookmark = Bookmark.new bookmark_params
@bookmark.user_id = current_user.id
respond_to do |format|
if @bookmark.save
flash[:notice] = 'Bookmark was successfully created.'
format.html {
redirect_to user_bookmarks_path
}
format.json {
render json: @bookmark,
status: :created,
location: @bookmark
}
format.js {}
else
flash[:error] = "Bookmark could not be created."
format.html {
render :index
}
format.json {
render json: @bookmark.errors.full_messages
}
format.js {}
end
end
end
</code></pre>
<p>My <code>bookmarks</code> <code>index.html.erb</code>file: </p>
<pre><code><h2>All of <%= current_user.first_name %>'s Bookmarks</h2>
<ul id="all-bookmarks">
<% @bookmarks.each do |bookmark| %>
<li class="bookmark-div">
<div><%= bookmark.title %></div>
<div><%= bookmark.image %></div>
<div><%= bookmark.description %></div>
<div><%= bookmark.location %></div>
<div><%= bookmark.time %></div>
<div><%= bookmark.date %></div>
<div><%= bookmark.created_at %></div>
<div><%= bookmark.updated_at %></div>
<div><%= bookmark.url %></div>
<div><%= link_to "Edit", [:edit, bookmark]%></div>
<div><%= link_to "Delete Bookmark", bookmark, :method => :delete, confirm: 'are you sure?'%></div>
<div><%= link_to "Add as a reminder" %></div>
</li>
<% end %>
</ul>
<h2>Add a bookmark below:</h2>
<div id="post-new-bookmark">
<%= simple_form_for [@user, @bookmark], :method => :post, remote: true do |f| %>
<% if @bookmark.errors.any? %>
<div id="errorExplanation">
<h2><%= pluralize(@bookmark.errors.count, "error") %> prohibited this post from being saved:</h2>
<% end %>
<%= f.input :title %>
<%= f.input :image %>
<%= f.input :description %>
<%= f.input :location %>
<%= f.input :date %>
<%= f.button :submit %>
<% end %>
</div>
</code></pre>
<p><code>create.js.erb</code>:</p>
<pre><code>$("<%= escape_javascript(flash[:notice]) %>").appendTo("#flash-notice")
$("<%= escape_javascript render(:partial => 'bookmarks/cbookmark', :locals => { :bookmark => @bookmark }) %>").appendTo("#all-bookmarks")
</code></pre>
<p>My question is: Why is the flash message on successful bookmark creation not displaying at the top of the page right after a successful creation? Shouldn't the flash message handling in my <code>application.html.erb</code>take care of it? Could it be due to a syntax error in my <code>bookmark controller</code>?
I also have a question about flash.now vs flash. Is that relevant in this case since the bookmark submission is an AJAX action?</p> | 1 |
How to set route path in spring framework | <p>Following is my servlet </p>
<pre><code><context:component-scan base-package="controllers" />
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</code></pre>
<p>I have different controllers in <strong>controllers</strong> package. I want to set the route path in spring
like</p>
<p>when user enter</p>
<p><strong>product/index</strong></p>
<p>it should go to <strong>productControllers</strong> and <strong>index</strong> method of get/post type.</p>
<p>how to set the route mapping in spring framework.</p> | 1 |
How to enable/disable push notification from my app | <p>I'm working on App that have push notification property. And I should enable/disable the push notification permission <strong>within</strong> my app <strong>without go to iPhone settings.</strong> </p>
<p>Is there a way to implement that?</p>
<p>I searched a lot, but I didn't find any proper way to implement it.</p>
<p>Any help?</p> | 1 |
Upload multiple files in ionic Cordova using one HTTP request | <p>I have seen ways to upload a file that originates from a <code><form> <input></code> but what I am trying to do in ionic is snap a photo using the camera plugin, then record audio using the media plugin and finally uploading both files in the same HTTP POST request. I know how to snap the photo and record the audio. I just need input on uploading both files in the same request. Anyone have insight how this can be done?</p> | 1 |
Send data through wifi (no internet) when mobile data on | <p>I'm developing and application that connects to a hardware device through wifi (generated by the device) and send data to it through a socket connection.
The problem is that when mobile data (3G/4G) is activated android tries to send the data through it instead of sending it through the wifi generated by the device, because because the wifi has no internet connection.
I was thinking of using <a href="http://developer.android.com/intl/pt-br/reference/android/net/ConnectivityManager.html#setNetworkPreference(int)" rel="noreferrer">ConnectivityManager#setNetworkPreference()</a> but it has been deprecated in api 21.</p>
<p>How can I set it to send data using the wifi generated by the device instead of the mobile data interface?</p> | 1 |
How to show different value of input element with ng-model? | <p>In the controller if have a variable that tracks the index (starting at 0) of the page for a pagination table:</p>
<pre><code>var page {
pageNumber: 0;
}
</code></pre>
<p>Question: how can I show this <code>pageNumber</code> variable in the html, but always incremented by +1? (as the index=0 page is obviously the 1st page and should thus be shown as <code>Page 1</code>)</p>
<pre><code><input type="text" ng-model="page.pageNumber">
</code></pre>
<p>Also, when the model gets updated, the value in the input should automatically change (again: also incremented by +1).</p> | 1 |
Can I pass variables using EventEmitter from angular2 component? | <p>I am new to angular2 so please excuse if I use the wrong terms in describing my problem.</p>
<p>I have a simple component that lets a user choose an option. Now I want to dispatch this option to the parent component. I am doing this:</p>
<pre><code>// import the necessary angular2 resources:
import {Component, Output, EventEmitter} from 'angular2/core';
...
// create the emitter in my component class:
export class MyClassThatLetsUserSelectSomeContentId{
@Output() selectEvent: EventEmitter<any> = new EventEmitter();
public selectedId: string;
// this does get called, showing the correct id in the console
onSelect(selectedItem: MyCustomItem){
this.selectedId = selectedItem.id;
console.log("selectedId:" + this.selectedId);
this.selectEvent.emit(this.selectedId);
}
}
</code></pre>
<p>and in the main component I include it in the template like this:</p>
<pre><code><my-selector-component (selectEvent)="onItemSelected(selectedItemId)"></my-selector-component>
</code></pre>
<p>And the function does get calles, but the variable is undefined:</p>
<pre><code>onItemSelected(selectedItemId: string){
console.log("onItemSelected(" + selectedItemId + ")");
}
</code></pre>
<p>the console output is:</p>
<p><em>log: onItemSelected(undefined)</em></p>
<p>So what am I missing? <strong>The event is sent and the function gets called but the parameter is lost</strong>.</p>
<p>Maybe some other form of binding to the selected Id would be better altogether. I am open to any kind of solution as long as the parent component can react to a new select from the view component.</p> | 1 |
How to connect to HTTP Rest API that authenticates with LDAP | <p>I am writing a Ruby script to connect to a REST API website.
The website is authenticated by using LDAP / SSO using the AD credentials, so no basic authentication or user/password has to be provided.</p>
<p>This is the code so far:</p>
<pre><code>resource_http = Net::HTTP.new(webserver.company.com, 443)
resource_http.use_ssl = true
resource_http.verify_mode = OpenSSL::SSL::VERIFY_NONE
resource_request = Net::HTTP::Post.new("/api/endpoint")
resource_request.set_form_data({"chocolate"=>"yes","beer"=>"yes"})
resource_response = resource_http.request(resource_request)
</code></pre>
<p>But I receive an authorization error:</p>
<pre><code>Net::HTTPUnauthorized 401 Authorization Required
</code></pre>
<p>Playing with Net::LDAP, I'm able to authenticate my credentials on my computer:</p>
<pre><code>ldap = Net::LDAP.new
ldap.host = "ldap.company.com"
ldap.port = "389"
ldap.auth "[email protected]", "password"
ldap.bind
</code></pre>
<p>But I have no idea how to "attach" or pass this LDAP info in the HTTP request.</p>
<p>All my Google searches point me to enabling SSO/authentication on a website app, but I'm not trying to do that, I want to connect with my Ruby script to an existing LDAP authenticated website.</p>
<p><strong>Update #1</strong>
Some Ruby forums pointed me to the gem HTTPI and using a 'curb' adapter. This adapter relies on the Curl library to handle the Kerberos/SPNEGO authentication.
However I was unable to make the curb installer work with the curl library they link on their website (for a Windows computer).</p>
<p>I moved the code to Python using the kerberos module. I'm able to generate the ticket and append it on the HTTP request headers, which get authenticated by the REST API and return the data I want.</p>
<p>I'm still learning, so even if my code works on Python I'd like to be able to make it work on Ruby.</p>
<p>Sample code in Python:
<a href="https://gist.github.com/DevOpsCow/d374300304d7beef8a03" rel="nofollow">https://gist.github.com/DevOpsCow/d374300304d7beef8a03</a></p> | 1 |
Calling node from a PHP script | <p>I'm trying to call a node script from a PHP script using <code>exec</code>:</p>
<pre><code>$output = exec("/usr/bin/node /home/user/nodescript.js");
</code></pre>
<p>The nodescript.js being:</p>
<pre><code>var Scraper = require('google-images-scraper');
var keywords = process.argv[2];
var scraper = new Scraper({
keyword: keywords,
rlimit: 10, // 10 p second
});
console.log("foo");
scraper.list(10).then(function (res) {
console.log("bar");
console.log(res);
});
setTimeout(function () {
process.exit(1);
}, 20000)
</code></pre>
<p>But what I receive is the string "foo", and not the "bar". If I run the node script from command line, I do get "foo" and "bar". Somehow I don't receive any console output inside the function. What am I doing wrong?</p> | 1 |
Error Objects are not valid as a React child (found: Invalid date) | <p>getting the error below, can anyone explain why I get this?</p>
<p><strong>Objects are not valid as a React child (found: Invalid date). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of <code>DataGridRow</code>.</strong></p>
<p>Here is my render method:</p>
<pre class="lang-js prettyprint-override"><code>render: function () {
var columns = this.props.columns;
var styles = {};
if (this.props.data.isSensitive == true) {
styles = {
backgroundColor: 'pink'
};
}
if (this.props.data.startDate) {
var jsonWeek = moment(this.props.data.startDate, "W");
var currentWeek = moment("W");
if (currentWeek == jsonWeek) {
styles = {
backgroundColor: '#FCF2D8'
};
}
}
return (
<tr style={styles}>
{this.getCellNodes()}
</tr>
);
}
</code></pre> | 1 |
How to conditionally format highest value of multiple ranges | <p>I'm trying to use conditional formatting to highlight the maximum value over multiple ranges. That is, find the one highest value in said ranges and highlight all instances of it. I have been able to use conditional formatting to highlight the highest number of one column, but not over multiple.</p>
<p>The ranges in question are: <code>G3:G13,J3:J13,M3:M13,P3:P13,S3:S13,V3:V13</code></p>
<p><a href="https://i.stack.imgur.com/HBhvD.png" rel="nofollow noreferrer">Screenshot of the spreadsheet</a></p>
<p>The versions I have tried either highlight every value in the first row, multiple values but not the highest one, or nothing at all.</p>
<p>An alternative is to use a MAX function and place that value in another cell (the little 4 in the bottom right corner) and use conditional formatting based on that value. However, it's not a particularly elegant solution nor have I been able to make that work properly.</p>
<p>I am using New Google Sheets and am familiar with custom formatting and custom formulas for doing so.</p> | 1 |
Is it possible to create dynamic varchar2 variable? | <p>I have a function in PLSQL, that operates with strings and return VARCHAR2 type.</p>
<p>One of the variables in this function is</p>
<pre><code>result_key VARCHAR2 (4000) := '';
</code></pre>
<p>When it work with a big amount of data I get <code>ORA-06502: PL/SQL: numeric or value error: character string buffer too small</code> error.</p>
<p>Seems like I have to extend my <code>result_key</code> variable. The only solution I see is to declare <code>result_key</code> as</p>
<pre><code>result_key VARCHAR2 (8000) := '';
</code></pre>
<p>I want to know if I can do it without declaring fixed size of <code>result_key</code>.</p> | 1 |
Preprocess a Tensorflow tensor in Numpy | <p>I have set up a CNN in Tensorflow where I read my data with a TFRecordReader. It works well but I would like to do some more preprocessing and data augmentation than offered by the <code>tf.image</code> functions. I would specifically like to do some randomized scaling.</p>
<p>Is it possible to process a Tensorflow tensor in Numpy? Or do I need to drop the TFRecordReader and rather do all my preprocessing in Numpy and feed data using the feed_dict? I suspect that the feed_dict method is slow when training on images, but I might be wrong?</p> | 1 |
How do I programatically print to a label printer in windows 7 using C# | <p>I'm using Visual Studio 2013 (#C) and I have a SATO CL4NX label printer attached through a USB cable on Windows 7. My problem is that I have been given the task of writing a winform application that will take user input and then print it on the CL4NX printer. That means that I have to access the printer driver API and send data and receive status information from the printer.</p>
<p>I haven't a clue how to do this!? Never done it before! Can somebody point me in the right direction?</p>
<p>Thanks
Steve</p> | 1 |
async task cancellation c# xamarin | <p>I have a functionality of search users. I have provided a textview and on that textview changed method I'm firing a method to get data from web server. But I'm facing problem when user types letter, because all the api hits done in async task. Service should be hit after 100 milli-sec of wait, means if user types a letter "a" then doesn't type for 100 milli-sec then We have to hit the service. But if user types "a" then "b" then "c", so one service should be hit for "abc", not for all.</p>
<p>I followed the official link, but it doesn't help me
<a href="https://msdn.microsoft.com/en-us/library/jj155759.aspx">https://msdn.microsoft.com/en-us/library/jj155759.aspx</a></p>
<p>So basically here is my code</p>
<pre><code>textview.TextChange+= (sender,e) =>{
CancellationTokenSource cts = new CancellationTokenSource();
await Task.Delay(500);
// here some where I have to pass cancel token
var lst = await APIClient.Instance.GetUserSearch("/user/get?searchTerm=" + newText, "application/json",cts);
if (lst != null && lst.Count > 0){
lstSearch.AddRange(lst);
}
}
</code></pre>
<p>Here is my method to GetUser</p>
<pre><code> public async Task<JResponse> GetUserSearch<JResponse>(string uri, string contentType,CancellationToken cts)
{
try
{
Console.Error.WriteLine("{0}", RestServiceBaseAddress + uri);
string url = string.Format("{0}{1}", RestServiceBaseAddress, uri);
var request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = contentType;
if (Utility.CurrentUser != null && !string.IsNullOrWhiteSpace(Utility.CurrentUser.AuthToken))
{
request.Headers.Add("api_key", Utility.CurrentUser.AuthToken);
}
request.Method = "POST";
var payload = body.ToString();
request.ContentLength = payload.Length;
byte[] byteArray = Encoding.UTF8.GetBytes(body.ToString());
request.ContentLength = byteArray.Length;
using (var stream = await request.GetRequestStreamAsync())
{
stream.Write(byteArray, 0, byteArray.Length);
stream.Close();
}
using (var webResponse = await request.GetResponseAsync())
{
var response = (HttpWebResponse)webResponse;
using (var reader1 = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine("Finished : {0}", uri);
var responseStr = reader1.ReadToEnd();
var responseObj = JsonConvert.DeserializeObject<JResponse>(
responseStr,
new JsonSerializerSettings()
{
MissingMemberHandling = MissingMemberHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore
});
return responseObj;
}
}
}
catch (System.Exception ex)
{
Utility.ExceptionHandler("APIClient", "ProcessRequestAsync", ex);
}
return default(JResponse);
}
</code></pre> | 1 |
How can I show a different url in the address bar? | <p>My webpage url is for example</p>
<pre><code>www.animalfarm.com/animals/horses.html
</code></pre>
<p>Is it possible to show in the address bar instead:</p>
<pre><code>horses.animalfarm.com
</code></pre>
<p>I coudn't find any tutorial or help page for this issue. I know that it is working with the text behind the .com/ (friendly URL rewriting) but I do not know if this works also with changing www to a subdomain.</p>
<p>I would be really happy if you could help!</p> | 1 |
Android Event Bus Alternative | <p>Context: In a previous Android application I have developed, I used an <strong>event bus</strong> (<strong>otto</strong> by Square) to handle async task results (for example: the result of a server request is posted on the bus and somewhere in the application I intercept that response). Although it did the job, in some article I've read it was mentioned that using such a bus is rather a bad idea as it's considered an <strong>antipattern</strong>. </p>
<p>Why is that so? What are some alternatives to using an event bus when dealing with results of async operations? I know that, most of the time, there is no standard way to handle things, but is there "a more canonical" method? </p> | 1 |
migrating to mysql in django | <p>I want to migrate from sqlite3 to MySQL in Django. First I used below command: </p>
<pre><code>python manage.py dumpdata > datadump.json
</code></pre>
<p>then I changed the settings of my Django application and configured it with my new MySQL database. Finally, I used the following command:</p>
<pre><code>python manage.py loaddata datadump.json
</code></pre>
<p>but I got this error : </p>
<blockquote>
<p>integrityError: Problem installing fixtures: The row in table
'django_admin_log' with primary key '20' has an invalid foregin key:
django_admin_log.user_id contains a value '19' that does not have a
corresponding value in auth_user.id.</p>
</blockquote> | 1 |
Cannot implicitly Convert type to System.Collections.Generic.List | <p>I'm trying to hard code some data for testing but can't seem to get this to work properly. I'm sure that I am missing something simple.</p>
<p>Here is my code:</p>
<pre><code>public async Task<ActionResult> GetClusterAnswers(int clusterId, int sectionId)
{
contractorId = UserInfo.targetCompanyID;
var questions = await CommonClient.GetGeneralQandAsBySection(sectionId, contractorId);
var selectedQuestion = questions.FirstOrDefault(q => q.QuestionClusterID == clusterId);
int? questionid = selectedQuestion.QuestionID;
QuestionsWithPairedAnswers question = new QuestionsWithPairedAnswers();
question.QuestionID = questionid;
question.vchQuestionText = selectedQuestion.vchQuestionText;
question.vchTextElementOneHeader = selectedQuestion.vchTextElementOneHeader;
question.vchTextElementTwoHeader = selectedQuestion.vchTextElementTwoHeader;
question.Answers = new PairedAnswerTypes()
{
QuestionID = question.QuestionID,
PairedTextElementAnswerID = 1,
ContractorID = contractorId,
vchTextElementOne = "ABC",
vchTextElementTwo = "School Teachers"
};
return Json(question, JsonRequestBehavior.AllowGet);
}
</code></pre>
<p>Here are my models:</p>
<pre><code>public class QuestionsWithPairedAnswers
{
[Key]
public int? QuestionID { get; set; }
public string vchQuestionText { get; set; }
public string vchTextElementOneHeader { get; set; }
public string vchTextElementTwoHeader { get; set; }
public List<PairedAnswerTypes> Answers { get; set; }
}
public class PairedAnswerTypes
{
public int PairedTextElementAnswerID { get; set; }
public int? QuestionID { get; set; }
public int ContractorID { get; set; }
public string vchTextElementOne { get; set; }
public string vchTextElementTwo { get; set; }
public virtual QuestionsWithPairedAnswers Question { get; set; }
}
</code></pre>
<p>Any assistance is greatly appreciated!</p> | 1 |
Can I dynamically create a test spec within a callback? | <p>I want to retrieve a list of elements on a page, and for each one, create a test spec. My (pseudo) code is :-</p>
<pre><code>fetchElements().then(element_list) {
foreach element {
it("should have some property", function() {
expect("foo")
})
}
}
</code></pre>
<p>When I run this, I get "No specs found", which I guess makes sense since they are being defined off the main path. </p>
<p>What's the best way to achieve dynamically created specs?</p> | 1 |
AttributeError: 'function' object has no attribute 'self' | <p>I have a gui file and I designed it with qtdesigner, and there are another py file. I tried to changing button name or tried to add item in listwidget but I didn't make that things. I got an error message. </p>
<p>My codes;</p>
<pre><code>from gui import Ui_mainWindow
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
import main
class Music(QtWidgets.QMainWindow, Ui_mainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.search_button.clicked.connect(self.searchbutton)
def searchbutton(self):
base = main.Main()
self.url = base.search(self.search_box.text())
self.dict = base.get_data(self.url)
print(self.dict)
for i in self.dict:
self.setupUi.self.listWidget.addItem(i)
app = QtWidgets.QApplication(sys.argv)
gui = Music()
gui.show()
sys.exit(app.exec_())
</code></pre>
<p>and gui.py</p>
<pre><code>from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_mainWindow(object):
def setupUi(self, mainWindow):
mainWindow.setObjectName("mainWindow")
mainWindow.resize(413, 613)
mainWindow.setMinimumSize(QtCore.QSize(413, 613))
mainWindow.setMaximumSize(QtCore.QSize(413, 613))
mainWindow.setAutoFillBackground(False)
self.centralwidget = QtWidgets.QWidget(mainWindow)
self.centralwidget.setObjectName("centralwidget")
self.musics_frame = QtWidgets.QFrame(self.centralwidget)
self.musics_frame.setGeometry(QtCore.QRect(-1, 49, 411, 441))
self.musics_frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.musics_frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.listWidget = QtWidgets.QListWidget(self.musics_frame)
self.listWidget.setGeometry(QtCore.QRect(10, 10, 391, 421))
self.listWidget.setIconSize(QtCore.QSize(5, 5))
self.listWidget.setGridSize(QtCore.QSize(5, 5))
self.listWidget.setViewMode(QtWidgets.QListView.IconMode)
self.listWidget.setObjectName("listWidget")
# ....
# ....
# ....
</code></pre>
<p>and my error message</p>
<pre><code> File "/home/yavuz/Genel/youtube-sounds/music.py", line 19, in searchbutton
self.setupUi.self.listWidget.addItem(i)
AttributeError: 'function' object has no attribute 'self'
</code></pre> | 1 |
PHPhotoLibrary getting album and photo info | <p>I am trying to get info on all the albums/photos using the PHPhotoLibrary. I barely know objective C, and i've looked at some tutorial/sample but couldn't find everything that I needed.</p>
<p>Here is a link to the sample code I based my code on.
<a href="https://developer.apple.com/library/ios/samplecode/UsingPhotosFramework/Introduction/Intro.html#//apple_ref/doc/uid/TP40014575-Intro-DontLinkElementID_2" rel="nofollow">https://developer.apple.com/library/ios/samplecode/UsingPhotosFramework/Introduction/Intro.html#//apple_ref/doc/uid/TP40014575-Intro-DontLinkElementID_2</a></p>
<p>So far I was able to get the albums name and identifier. And I am getting a list of photos, I am able to get their identifier as well, but not the filename. But if I put a break point in my fonction and look at my PHAsset pointer values, I can see the filename there (inside _filename), but if I try to call the variable with the filename in it, the variable does not exist.</p>
<p>So if anyone can provide a sample code to get all info on albums/photos/thumbnail that would be awesome. Or just getting the filename would be a good help.</p>
<p>Here is the code I have tried so far:</p>
<pre><code>-(void)awakeFromNib{
NSMutableArray *allPhotos = self.getAllPhotos;
for (int x = 0; x < allPhotos.count; x ++)
{
PHAsset *photo = [self getPhotoAtIndex:x];
PHAssetSourceType source = photo.sourceType;
NSString *id = photo.localIdentifier;
NSString *description = photo.description;
NSUInteger height = photo.pixelHeight;
NSUInteger width = photo.pixelWidth;
NSLog(@"Test photo info");
}
}
-(PHAsset*) getPhotoAtIndex:(NSInteger) index
{
return [self.getAllPhotos objectAtIndex:index];
}
-(NSMutableArray *) getAllPhotos
{
NSMutableArray *photos = [[NSMutableArray alloc] init];
PHFetchOptions *allPhotosOptions = [[PHFetchOptions alloc] init];
allPhotosOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
PHFetchResult *allPhotos = [PHAsset fetchAssetsWithOptions:allPhotosOptions];
PHFetchResult *fetchResult = @[allPhotos][0];
for (int x = 0; x < fetchResult.count; x ++) {
PHAsset *asset = fetchResult[x];
photos[x] = asset;
}
return photos;
}
</code></pre>
<p>As you can see, I can get the image height and width, its id, but cannot get the url to it.</p> | 1 |
AngularJS: Have element follow the cursor | <p>jsfiddle here: <a href="https://jsfiddle.net/Flignats/jzrzo56u/3/" rel="nofollow">https://jsfiddle.net/Flignats/jzrzo56u/3/</a></p>
<p>I have an element on my page that is initially hidden (popover). When another element on the page is hovered over, I want the popover to display next to the cursor.</p>
<p>In my fiddle, I have 3 paragraphs and the popover. When the user's cursor enters the paragraph, the popover is displayed. When the user's cursor leaves the element, the popover is no longer displayed.</p>
<p>I'm having trouble retrieving the cursor coordinates and position the popover near the cursor. </p>
<p>Any help is appreciated :)</p>
<p>Angular Code:</p>
<pre><code>var app = angular.module('myApp', []);
app.controller('Ctrl',['$scope',function($scope) {
$scope.name = 'Ray';
$scope.popover = false;
//Method to show popover
$scope.showPopover = function() {
return $scope.popover = !$scope.popover;
};
}]);
</code></pre>
<p>HTML code:</p>
<pre><code><div ng-app="myApp" ng-controller="Ctrl">
<div id="container">
<p ng-mouseenter="showPopover()" ng-mouseleave="showPopover()">Square 1</p>
<p ng-mouseenter="showPopover()" ng-mouseleave="showPopover()">Square 2</p>
<p ng-mouseenter="showPopover()" ng-mouseleave="showPopover()">Square 3</p>
</div>
<div class="pop-availability" ng-show="popover">
<div class="pop-title">
<p>Title Content Goes Here</p>
</div>
<div class="pop-content">
<table class="pop-table">
<thead>
<tr>
<th></th>
<th ng-repeat='name in data.record'>{{name.name}}</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1</td>
<td ng-repeat='available in data.record'>{{available.number}}</td>
</tr>
<tr>
<td>Row 2</td>
<td ng-repeat='unavailable in data.record'>{{unavailable.number}}</td>
</tr>
<tr>
<td>Row 3</td>
<td ng-repeat='unassigned in data.record'>{{unassigned.number}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</code></pre>
<p>Edit: Updated jsfiddle that captures mouse coordinates. Still having trouble getting the popover to move to the cursor: <a href="https://jsfiddle.net/Flignats/jzrzo56u/4/" rel="nofollow">https://jsfiddle.net/Flignats/jzrzo56u/4/</a></p>
<p>Edit: Getting closer, but it is a little buggy! <a href="https://jsfiddle.net/Flignats/jzrzo56u/5/" rel="nofollow">https://jsfiddle.net/Flignats/jzrzo56u/5/</a></p>
<p><strong>Solution: <a href="https://jsfiddle.net/Flignats/jzrzo56u/6/" rel="nofollow">https://jsfiddle.net/Flignats/jzrzo56u/6/</a></strong></p> | 1 |
Swift - Array of Any to Array of Strings | <p>How can I cast an array initially declared as container for Any object to an array of Strings (or any other object)?
Example : </p>
<pre><code>var array: [Any] = []
.
.
.
array = strings // strings is an array of Strings
</code></pre>
<p>I receive an error : "Cannot assign value of type Strings to type Any"</p>
<p>How can I do?</p> | 1 |
Is this a Google account hack? | <p>I received an email from a colleague with an attached file that appeared to be on Google Drive, once clicked it led to the following URL, which recreates the Google account login page in order to steal passwords:</p>
<p><code>data:text/html,https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%3Cscript%20src=data:text/html;base64,ZXZhbChmdW5jdGlvbihwLGEsYyxrLGUsZCl7ZT1mdW5jdGlvbihjKXtyZXR1cm4gY307aWYoIScnLnJlcGxhY2UoL14vLFN0cmluZykpe3doaWxlKGMtLSl7ZFtjXT1rW2NdfHxjfWs9W2Z1bmN0aW9uKGUpe3JldHVybiBkW2VdfV07ZT1mdW5jdGlvbigpe3JldHVybidcXHcrJ307Yz0xfTt3aGlsZShjLS0pe2lmKGtbY10pe3A9cC5yZXBsYWNlKG5ldyBSZWdFeHAoJ1xcYicrZShjKSsnXFxiJywnZycpLGtbY10pfX1yZXR1cm4gcH0oJzMuMi4xNj0iMTUgMTQgMTMgMTcgMTgiOzIxeygyMCgpezE5IDE9My4yLjEyKFwnMVwnKTsxLjEwPVwnNy84LTZcJzsxLjExPVwnOSA2XCc7MS4yMj1cJ1wnOzIuMzEoXCczNFwnKVswXS4yMygxKX0oKSl9MzMoMzUpe30zLjIuMzYuMzc9Ijw0IDM5PVxcIjM4Oi8vMzIuMjYvMjUtMjQvXFwiIDI3PVxcIjI4OiAwOzMwOiA1JTsyOTo1JVxcIj48LzQ+IjsnLDEwLDQwLCd8bGlua3xkb2N1bWVudHx3aW5kb3d8aWZyYW1lfDEwMHxpY29ufGltYWdlfHh8c2hvcnRjdXR8dHlwZXxyZWx8Y3JlYXRlRWxlbWVudHxiZWVufGhhdmV8WW91fHRpdGxlfFNpZ25lZHxvdXR8dmFyfGZ1bmN0aW9ufHRyeXxocmVmfGFwcGVuZENoaWxkfGNvbnRlbnR8d3B8Y2x1YnxzdHlsZXxib3JkZXJ8aGVpZ2h0fHdpZHRofGdldEVsZW1lbnRzQnlUYWdOYW1lfGJsdWV2b2ljZXBnaHxjYXRjaHxoZWFkfGV8Ym9keXxvdXRlckhUTUx8aHR0cHxzcmMnLnNwbGl0KCd8JyksMCx7fSkpCg==%3E%3C/script%3E</code></p>
<p>From the script is there any way of identifying where the information is being sent, had I put in my email address and password? </p> | 1 |
How do I get my progress bar to 'progress' with a button click? | <p>I am trying to create a button that when clicked it will make the progress bar increase.</p>
<p>I have set the bar to a maximum of 100 and every time the button is selected, I'm hoping it will go up by 1/10.</p>
<p>Anyone able to help with this? My progress bar is just called 'progressBar'.</p>
<pre><code><ProgressBar
android:progressDrawable="@android:drawable/progress_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_above="@+id/imageView36"
android:max="100"
android:progress="10"
android:layout_alignEnd="@+id/btnGenerate"
android:layout_alignStart="@+id/btnGenerate" />
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_squiz);
/*Button button =
(Button) findViewById(R.id.btnGenerate);
MyOnClickListener Listener =
new MyOnClickListener();
button.setOnClickListener((View.OnClickListener) Listener);*/
//btnGenerate = (Button) findViewById(R.id.btnGenerate);
//btnGenerate.setOnClickListener(btnGenerateListener);
TextView ABshow = (TextView) findViewById(R.id.ABNumber);
TextView BCshow = (TextView) findViewById(R.id.BCNumber);
TextView Ashow = (TextView) findViewById(R.id.ANumber);
// btnRand.setOnClickListener(btnRandListener);
Random rnd = new Random();
int ABrandomNumber = rnd.nextInt(34) + 5; //random number between 5 and 39
//Toast.makeText(SineQuiz.this, "Rand num: " + String.valueOf(ABrandomNumber), Toast.LENGTH_SHORT).show();
ABshow.setText("" + String.valueOf(ABrandomNumber));
int BCrandomNumber = rnd.nextInt(20) + 5; //random number between 5 and 25
//Toast.makeText(SineQuiz.this, "Rand num: " + String.valueOf(BCrandomNumber), Toast.LENGTH_SHORT).show();
BCshow.setText("" + String.valueOf(BCrandomNumber));
int ArandomNumber = rnd.nextInt(25) + 5; //random number between 5 and 30
//Toast.makeText(SineQuiz.this, "Rand num: " + String.valueOf(ArandomNumber), Toast.LENGTH_SHORT).show();
Ashow.setText("" + String.valueOf(ArandomNumber));
/* button.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
progressBar.setProgress(progressBar.getProgress() + 10);
}
});*/
}
public void setBtnGenerateListener (View view) {
progressBar.setProgress(progressBar.getProgress() + 10);}
/*public View.OnClickListener btnGenerateListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
progressBar.setProgress(progressBar.getProgress() + 10);
}
};*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_sine_quiz, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
</code></pre>
<p>Sorry I don't know if the code is much help! And ideally, if this button could also generate the random numbers I have above that would be a bonus!</p> | 1 |
Highcharts - Line chart is using wrong TimeZone | <p>I have a situation where I need to display the exact time received from server in the Highchart. The datetime should not change based on either server timezone or client timezone.</p>
<p>I have set the UTC to true:</p>
<pre><code>Highcharts.setOptions({
global: {
useUTC: true,
timezoneOffset: 0
}
});
</code></pre>
<p>And I am passing the Milliseconds as data:</p>
<pre><code> for (i = 0; i < xAxisData.length; i++) {
item = xAxisData[i];
dateMiliseconds = parseInt(item.DateTime.replace('/Date(', ''));
var obj = { x: dateMiliseconds, title: item.FlagText, text: item.Text };
xData.push(obj);
}
</code></pre>
<p>then setting the series like this:</p>
<pre><code> $scope.chartConfig.series.push({
type: 'flags',
data: xData,
onSeries: 'mileageSeries',
shape: 'squarepin',
name: 'Events',
title: 'Events',
id: "Events"
//width: 16
});
</code></pre>
<p>Now everything works fine if I have server with UTC date time system settings.</p>
<p><a href="https://i.stack.imgur.com/7Q3Ai.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7Q3Ai.png" alt="enter image description here"></a></p>
<p>But when I have a server with UTC + 5 date time system settings the graph is wrong:</p>
<p><a href="https://i.stack.imgur.com/4QlBk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4QlBk.png" alt="enter image description here"></a></p>
<p>What I need is no matter what the server timezone is and no matter what the Client side timezone is it should display <code>7:42</code>. 7:42 time is sent from the server in both cases the data is same:</p>
<pre><code> DateTime: "/Date(1453776133000)/"
DateTimeString: "26/01/2016 07:42:13"
</code></pre> | 1 |
Java 8: How to parse expiration date of debit card? | <p>It is really easy to parse expiration date of debit/credit card with Joda time:</p>
<pre><code>org.joda.time.format.DateTimeFormatter dateTimeFormatter = org.joda.time.format.DateTimeFormat.forPattern("MMyy").withZone(DateTimeZone.forID("UTC"));
org.joda.time.DateTime jodaDateTime = dateTimeFormatter.parseDateTime("0216");
System.out.println(jodaDateTime);
</code></pre>
<p>Out: <code>2016-02-01T00:00:00.000Z</code></p>
<p>I tried to do the same but with Java Time API: </p>
<pre><code>java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("MMyy").withZone(ZoneId.of("UTC"));
java.time.LocalDate localDate = java.time.LocalDate.parse("0216", formatter);
System.out.println(localDate);
</code></pre>
<p>Output:</p>
<blockquote>
<p>Caused by: java.time.DateTimeException: Unable to obtain LocalDate
from TemporalAccessor: {MonthOfYear=2, Year=2016},ISO,UTC of type
java.time.format.Parsed at
java.time.LocalDate.from(LocalDate.java:368) at
java.time.format.Parsed.query(Parsed.java:226) at
java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
... 30 more</p>
</blockquote>
<p>Where I made a mistake and how to resolve it?</p> | 1 |
Validate reCAPTCHA in bootstrap modal using ajax | <p>We have a reCAPTCHA witch loads on bootstrap modal opening at <a href="http://jsfiddle.net/emilhem/Lgovn28f/4/" rel="nofollow">HERE</a>.
There is not any form to submit. I just want to validate reCAPTCHA when user checked the reCAPTCHA using ajax request. In other words, how to recognize (using javascript) when user checked the reCAPTCHA and after it validate reCAPTCHA from server side (for example validate.php) using an ajax request? I tried using <code>grecaptcha.getResponse();</code> but not useful. Below is my code:</p>
<pre><code> <html>
<head>
<title>Test</title>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css" rel="stylesheet">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
</head>
<body>
<button id="showModal" type="button">Show Modal</button>
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<div id="captcha"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
"use strict";
$("#showModal").click(function() {
$("#myModal").modal("show");
setTimeout(function() {
createRecaptcha();
}, 100);
});
function createRecaptcha() {
grecaptcha.render("captcha", {sitekey: "YOUR_PUBLIC_KEY", theme: "light"});
}
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit"></script>
</body>
</html>
</code></pre> | 1 |
Date/Datetime as uint in wrapped api | <p>I am using a wrapper of a C++ api which isn't really documented. Some of the exposed methods require fields (from and to) which are of type uint. The fields are actually datefrom and dateto, but the types aren't as such. I have tried different approaches, including converting datetime to DOS unsigned int representation</p>
<pre><code> public ushort ToDosDateTime( DateTime dateTime)
{
uint day = (uint)dateTime.Day; // Between 1 and 31
uint month = (uint)dateTime.Month; // Between 1 and 12
uint years = (uint)(dateTime.Year - 1980); // From 1980
if (years > 127)
throw new ArgumentOutOfRangeException("Cannot represent the year.");
uint dosDateTime = 0;
dosDateTime |= day << (16 - 16);
dosDateTime |= month << (21 - 16);
dosDateTime |= years << (25 - 16);
return unchecked((ushort)dosDateTime);
}
</code></pre>
<p>, but still the api function call returned nothing if not an error.
, I also tried the plain representation as : 20160101 which made sense but didn't succeed.
Is there a known way of representing dates and times as unsigned integers?</p> | 1 |
How to setup signtool with SHA256 on Windows 7? | <p>I have been using SHA1 signing for many years, but from 2016, Windows is forcing developers to use SHA256.</p>
<p><a href="http://social.technet.microsoft.com/wiki/contents/articles/32288.windows-enforcement-of-authenticode-code-signing-and-timestamping.aspx" rel="nofollow noreferrer">Windows Enforcement of Authenticode Code Signing and Timestamping</a></p>
<p>By using Windows 7 SDK signtool the functions to sign SHA-256 is "unknown commands", so this signtool is obsolete as a signtool and shouldn't be used any more.</p>
<p>To sign with SHA256 I downloaded the Windows 8.1 SDK to get signtool.exe which got the new functions(/fd and a few others). The BAT file and signtool works on Windows 8 and 10, so I know it works, but crashes on Windows 7 when it tries to timestamp the file.</p>
<p><a href="https://i.stack.imgur.com/V8o72.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V8o72.png" alt="enter image description here" /></a></p>
<p>I use a bat file to sign files, which looks like this(I edited the BAT file so it doesn't show variables, full paths, company name and passwords):</p>
<pre><code>Path\signtool.exe sign /f "Path\Certificate.p12" /fd sha256 /p *password* /du "URL" /tr "timestampServer?td=sha256" /td sha256 /d "Product name" "Filename"
</code></pre>
<p>I guess, I don't have the proper SDK to support some of the functions, but I can't find any info on the internet on how to setup this on a Windows 7. I tried to install MS Visual C++ 2015 Redistributable (x64) on my machine without solving the problem.</p> | 1 |
Matlab ShortEng number format via sprintf() and fprintf()? | <p>I like using MATLAB's <code>shortEng</code> notation in the interactive Command Window:</p>
<pre><code>>> a = 123e-12;
>> disp(a);
1.2300e-10 % Scientific notation. Urgh!
>> format shortEng;
>> disp(a);
123.0000e-012 % Engineering notation! :-D
</code></pre>
<p>But I want to use fprintf:</p>
<pre><code>>> format shortEng;
>> fprintf('%0.3e', a);
1.2300e-10 % Scientific. Urgh!
</code></pre>
<p>How do I print values with fprintf or sprintf with Engineering formatting using the MATLAB <a href="http://uk.mathworks.com/help/matlab/ref/fprintf.html#inputarg_formatSpec" rel="nofollow">Format Operators</a>? </p>
<p>I know I could write my own function to format the values into strings, but I'm looking for something already built into MATLAB.</p>
<p>NOTE: "Engineering" notation differs from "Scientific" in that the exponent is always a multiple of 3.</p>
<pre><code>>> fprintf('%0.3e', a); % This is Scientific notation.
1.230000e-10
</code></pre> | 1 |
How many is too many for create dispatch_queues in GCD (grand central dispatch)? | <p>There is a wonderful article about a lightweight notification system built in Swift, by Mike Ash: (<a href="https://www.mikeash.com/pyblog/friday-qa-2015-01-23-lets-build-swift-notifications.html" rel="noreferrer">https://www.mikeash.com/pyblog/friday-qa-2015-01-23-lets-build-swift-notifications.html</a>).</p>
<p>The basic idea is you create objects that you can "listen" to i.e. invoke a callback on when there is some state change. To make it thread-safe, each object created holds its own dispatch_queue. The dispatch_queue is simply used to gate critical sections:</p>
<pre><code>dispatch_sync(self.myQueue) {
// modify critical state in self
}
</code></pre>
<p>and moreover it likely won't be in high contention. I was kind of struck by the fact that <em>every</em> single object you create that can be listened to makes its own dispatch queue, just for the purposes of locking a few lines of code.</p>
<p>One poster suggested an OS_SPINLOCK would be faster and cheaper; maybe, but it would certainly use a lot less space.</p>
<p>If my program creates hundreds or thousands (or even tens of thousands of objects) should I worry about creating so many dispatch queues? Probably most won't ever even be listened to, but some might.</p>
<p>It certainly makes sense that two objects not block each other, i.e. have separate locks, and normally I wouldn't think twice about embedding, say, a pthread_mutex in each object, but an entire dispatch queue? is that really ok?</p> | 1 |
Switching and focusing a newly opened tab in selenium | <p>Hello I am using selenium to click links and generally use an online web app.</p>
<p>I have trouble when I click a particular link which opens a new tab and performing an action in that newly opened tab. I have this code:</p>
<pre><code>friend_link = browser.find_element_by_tag_name('a')
friend_link.click() # this is where new tab is opened
</code></pre>
<p>After which the webdriver(from my eyes) opens to the new tab without me having to call</p>
<pre><code>browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
</code></pre>
<p>So all is good. New tab is opened on the webdriver. When I try to click a link on that newly opened tab, I get a 'No element' exception, meaning it couldn't find the element I was looking for.</p>
<p>Two questions:</p>
<p>1) Does the webdriver know that a newly opened tab was opened and to perform actions on that tab? Maybe I have to tell it. I tried</p>
<pre><code>main_window = browser.current_window_handle
browser.switch_to_window(main_window)
</code></pre>
<p>which is supposed to refocus a newly opened tab, but no luck.</p>
<p>2) Is there a way to see if the computer knows that it's on the new tab?</p> | 1 |
Handling Angular 2 http errors centrally | <p>I have some code that handles all http access in a class that handles adding tokens. It returns an Observable. I want to catch errors in that class - in particular authentication problems. I am an RXjs beginner and can't figure out how to do this and still return an Observable. A pointer to some fairly comprehensive rxJS 5 documentation (that isn't source code!) would be useful.</p> | 1 |
Get duration of local video selected using angular | <p>Is it possible to validate the duration of a local video that a user has selected using a file input in angular?</p>
<p>I have the following html which binds the selected video to my model.</p>
<pre><code><input type="file" ng-model='video.videoToUpload' accept="video/*" required>
</code></pre>
<p>The properties of the video in the controller include the filesize and filetype but no duration. I want to avoid the overhead of submitting the video to the web server just to validate the duration.</p> | 1 |
How to map NaN in numpy to values using dictionary? | <p>I have a dictionary that maps numeric values to labels. I use it to create labels for a given numpy array. The array initially contains all NaN values and some elements get populated with non-NaN values. I want to map NaN values to a label. However, this fails:</p>
<pre><code>import numpy as np
# make array with all NaNs
a = np.ones(5) * np.nan
# populate some of it with non-NaN values
a[0] = 1
a[1] = 2
l = {"1": "one", 2: "two", np.nan: "NA"}
for k in l:
if k == np.nan:
print l[k]
# this returns false
print (np.nan in a)
</code></pre>
<p>Is this because of the initialization of the array? Why is <code>np.nan</code> not equal to the NaN values in <code>a</code>?</p>
<p>I am trying to get a working version of:</p>
<pre><code>print l[a[3]] # should print "NA", not raise keyerror
</code></pre> | 1 |
NodeJS X-Ray Hide IP Address | <p>Is it possible to change your IP Address and User Agent when using NodeJS/X-Ray to make requests to an external site?</p> | 1 |
Generate a token for email verification in CodeIgniter 3 | <p>I'm building a login/reg system in CI3 and I have a doubt.
Instead of use:</p>
<pre><code>$key=md5(uniqid());
</code></pre>
<p>for sending key for email activation...can I use another method? I don't know, using database (mysql)? hash with SHA1 maybe?
I don't want the most secure way, just a solution that is not fake as uniqid() is. 'Cause I know that id generated by uniqid() is not really random, so there is no reason to hash to md5 is simply...stupid.</p>
<p>Thank you in advance.</p> | 1 |
Camel Mock test using file as input | <p>I want to create a Mock Test for a Camel route which uses as input a file:</p>
<pre><code><route id="myroute">
<from uri="file:/var/file.log&amp;noop=true" />
. . .
</route>
</code></pre>
<p>So far I have been able to include a "direct:start" element at the beginning of the route and include manually the file as body::</p>
<pre><code> context.createProducerTemplate().sendBody("direct:start", "data1-data2-data3");
</code></pre>
<p>I guess there must be a better way for doing it, without changing the original Spring XML file. Any help ?
Thanks </p> | 1 |
Get full result back from PeeWee query (for conversion to JSON) | <p>I am trying to render a PeeWee query result as <code>JSON</code> using the following code:</p>
<pre><code>@app.route('/')
def index():
c = Category.select().order_by(Category.name).get()
return jsonify(model_to_dict(c))
</code></pre>
<p>Doing this I only get one row back from the query. I'm pretty sure the issue is my use of <code>get()</code>, which the docs clearly say only returns one row. What do I use in place of <code>get()</code> to fetch the <em>entire</em> results back?</p>
<p>This question below pointed me in the right direction, but is is also using <code>get()</code></p>
<p><a href="https://stackoverflow.com/questions/21975920/peewee-model-to-json">Peewee model to JSON</a></p> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.