title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
If statements in Racket | <p>I am trying to construct a function "number-crop" which takes three arguments x a b. If x is to the left of the closed interval [a, b] on the number line, then return a. If x is to the right of the interval, then return b. Otherwise, just return x. This is what I have: </p>
<pre><code>(define (number-crop x a b)
(if (max x a b) x b)
(if (min x a b) x a))
</code></pre>
<p>I am returned with the error, "define: expected only one expression for the function body, but found 1 extra part". I am new to Racket so I am still trying to understand how if statements work within the language.</p> | 1 |
How to get random row from file in JMeter | <p>I'm looking for way how to get random row from file in JMeter.
I would be appreciate for any suggestions.</p> | 1 |
Unable to deserialize ZonedDateTime using Jackson | <p>I am using Jersey with Jackson as JSON provider. I am able to serialize <code>ZonedDateTime</code> to JSON but when I want to deserialize it gives me error as follows.</p>
<p>Could you please help me tell the exact configuration required to get this deserialization work.</p>
<blockquote>
<p>Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class java.time.ZonedDateTime] from String value ('2016-01-21T21:00:00Z'); no single-String constructor/factory method</p>
</blockquote>
<p>My mapper configuration is as follows:</p>
<pre><code>@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
private final ObjectMapper MAPPER;
public ObjectMapperContextResolver() {
MAPPER = new ObjectMapper();
//This would add JSR310 (Datetime) support while converting date to JSON using JAXRS service
MAPPER.registerModule(new JavaTimeModule());
//Below line would disable use of timestamps (numbers),
//and instead use a [ISO-8601 ]-compliant notation, which gets output as something like: "1970-01-01T00:00:00.000+0000".
MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
}
@Override
public ObjectMapper getContext(Class<?> type) {
return MAPPER;
}
}
</code></pre> | 1 |
You are not logged in: You are not logged in. Please log in and try again | <p>I am using HybridAuth library in my codeigniter application. but when i click on login with facebook button it gives error "You are not logged in: You are not logged in. Please log in and try again.". Please help some to know why this error occured.</p> | 1 |
Get PublishProfile for an Azure WebApp using Powershell | <p>How can we get the PublishProfile for an Azure WebApp using Powershell?
I'm not looking for <code>Get-AzurePublishSettingsFile</code> cmdlet. That gives me the PublishSettings for the whole subscription.
I want the PublishSettings only for that particular Azure WebApp. </p>
<p>We can get this file when we click the following link on Azure Portal.
<a href="https://i.stack.imgur.com/arBM8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/arBM8.png" alt="enter image description here"></a></p>
<p>The content of the file is something like shown below.
<a href="https://i.stack.imgur.com/z8Axp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/z8Axp.png" alt="enter image description here"></a></p>
<p>Can someone please help me get this?</p>
<p>Thanks.</p> | 1 |
Qt Creator and QML Live Preview | <p>The problem now is that I don't know how I can use qml live preview?
I saw a video:
<a href="https://vimeo.com/145921618" rel="noreferrer">https://vimeo.com/145921618</a></p>
<p>I saw <a href="http://webcache.googleusercontent.com/search?q=cache:https://qt-project.org/forums/viewthread/35366" rel="noreferrer">this</a> post about erase this function for Qt Creator.
How i can implementlive coding into my app?</p> | 1 |
Regular expression for detecting first name and/or last name | <p>Please help me to build a pattern in the text input field like that,</p>
<pre><code><input name="BusinessOwner" type="text" id="BusinessOwner" pattern="?">
</code></pre>
<p>But the rule is that this input field only allow English <strong>Small letter</strong> and/or <strong>Capital letter</strong>(include/Exclude space) and no <strong>Numeric Digits</strong>. So according to the rule,</p>
<pre><code>Adam Smith => valid
adam => valid
AB CD => valid
abcd12 => Invalid
abcd 12 => Invalid
</code></pre>
<p>Please help me to build the pattern.</p> | 1 |
Why is change detection not working in my Angular 2 code? | <p>What am I doing wrong here. I have created a service that has one property that I am updating with <code>setInterval</code>. </p>
<p>I am injecting this service into a component and want the component to watch the property for changes to update the screen. But only the initial value for <code>numCount</code> is shown and it is never updated. </p>
<p>Example:</p>
<p>Here is a test service I created</p>
<pre class="lang-ts prettyprint-override"><code>export class TestService {
numCount: number;
constructor() {
this.numCount = 0;
var self = this;
setInterval(function() {
self.numCount++;
console.log('from service', self.numCount);
}, 500);
}
}
</code></pre>
<p>Here is the component</p>
<pre class="lang-ts prettyprint-override"><code>export class MyComponentView implements OnChanges {
displayString: string;
constructor(testService: TestService) {
this.displayString = testService.numCount.toString();
}
ngOnChanges(changes) {
console.log(changes); // nothing logs out, even though the testService.numCount is being incremented in the class.
}
}
</code></pre>
<p>If you see here, <code>testService.numCount</code> is being increased by one every half second. But when I display it on screen through the component, it does not update. How can I watch the data from the injected service so it updates on screen?</p>
<p>I am displaying the <code>displayString</code> on the screen and the number does not change.</p> | 1 |
Oozie shell action: exec and file tags | <p>I'm a newbie in Oozie and I've read some Oozie shell action examples but this got me confused about certain things.</p>
<p>There are examples I've seen where there is no <code><file></code> tag.</p>
<p>Some example, like in Cloudera <a href="http://blog.cloudera.com/blog/2013/03/how-to-use-oozie-shell-and-java-actions/" rel="noreferrer">here</a>, repeats the shell script in file tag:</p>
<pre><code><shell xmlns="uri:oozie:shell-action:0.2">
<exec>check-hour.sh</exec>
<argument>${earthquakeMinThreshold}</argument>
<file>check-hour.sh</file>
</shell>
</code></pre>
<p>While in <a href="https://oozie.apache.org/docs/4.1.0/DG_ShellActionExtension.html#Shell_Action" rel="noreferrer">Oozie's website</a>, writes the shell script (the reference <code>${EXEC}</code> from job.properties, which points to script.sh file) twice, separated by #.</p>
<pre><code><shell xmlns="uri:oozie:shell-action:0.1">
...
<exec>${EXEC}</exec>
<argument>A</argument>
<argument>B</argument>
<file>${EXEC}#${EXEC}</file>
</shell>
</code></pre>
<p>There are also examples I've seen where the path (HDFS or local?) is prepended before the <code>script.sh#script.sh</code> within the <code><file></code> tag.</p>
<pre><code><shell xmlns="uri:oozie:shell-action:0.1">
...
<exec>script.sh</exec>
<argument>A</argument>
<argument>B</argument>
<file>/path/script.sh#script.sh</file>
</shell>
</code></pre>
<p>As I understand, any shell script file can be included in the workflow HDFS path (same path where workflow.xml resides).</p>
<p>Can someone explain the differences in these examples and how <code><exec></code>, <code><file></code>, <code>script.sh#script.sh</code>, and the <code>/path/script.sh#script.sh</code> are used?</p> | 1 |
Need help overriding a WPF button style background color. | <p>I have the below code set for a custom button. But I want to change the background for a single button. </p>
<pre><code><Style x:Key="myButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Foreground" Value="White"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Rectangle x:Name="rectangle" Fill="#FF2F2FEA" Stroke="Black">
<Rectangle.Effect>
<DropShadowEffect ShadowDepth="3"/>
</Rectangle.Effect>
</Rectangle>
<ContentPresenter x:Name="contentPresenter" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Bottom" Margin="2.833,0,2.5,1.162" RenderTransformOrigin="0.5,0.5" Width="69.667"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</code></pre>
<p></p>
<p>The code below is meant to override the background color but doesn't. What am I missing? Thanks</p>
<pre><code><Style x:Key="SpecialButton" TargetType="Button" BasedOn="{StaticResource myButtonStyle}">
<Setter Property="Background" Value="PaleGreen" />
<Setter Property="Height" Value="19.96" />
</Style>
</code></pre> | 1 |
Parsoid doesn't start | <p>I installed parsoid from its official repository, and configured it correctly by adding my Mediawiki API to <code>/etc/mediawiki/parsoid/settings.js</code>. I also removed the Interwiki options from my <code>/usr/lib/parsoid/src/api/localsettings.js</code>file, because they seem to be replaced by the parsoidConfig.setMwApi option in the settings.js file.</p>
<p>When running <code>nodejs /usr/lib/parsoid/src/api/server.js</code> from the command promt, I get the following error message:</p>
<pre><code>[fatal][worker][4915] uncaught exception object is not a function
TypeError: object is not a function
at new ParsoidService (/usr/lib/parsoid/src/api/ParsoidService.js:43:12)
at Object.<anonymous> (/usr/lib/parsoid/src/api/server.js:203:12)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
[warning][master][4882] worker 4911 died (1), restarting.
</code></pre>
<p>When I run <code>service parsoid start</code> and <code>service parsoid status</code> I am always getting the information, that there is no parsoid process running.</p>
<p>Can someone explain me why Parsoid does not work?</p>
<p>EDIT:</p>
<p>localsettings.js</p>
<pre><code>/*
* This is a sample configuration file.
*
* Copy this file to localsettings.js and edit that file to fit your needs.
*
* Also see the file ParserService.js for more information.
*/
exports.setup = function( parsoidConfig ) {
// The URL here is supposed to be your MediaWiki installation root
//parsoidConfig.setInterwiki( 'localhost', 'http://domain.com/Wiki/api.php' );
//parsoidConfig.setInterwiki( 'foo', 'http://localhost/wikiarst/api.php' );
//parsoidConfig.setInterwiki( 'noconn', 'http://213.127.84.12:80/wikiarst/api.php' );
//parsoidConfig.setInterwiki( 'disney', 'http://disneychannel.wikia.com/api.php' );
// Use the PHP preprocessor to expand templates via the MW API (default true)
//parsoidConfig.usePHPPreProcessor = true;
// Use selective serialization (default false)
parsoidConfig.useSelser = true;
// parsoid cache url
//parsoidConfig.parsoidCacheURI = 'http://localhost:8000/';
//parsoidConfig.trace = true;
//parsoidConfig.traceFlags = 'selser,wts';
//parsoidConfig.traceFlags = 'selser';
//parsoidConfig.defaultAPIProxyURI = 'http://localhost/';
};
/* vim: set filetype=javascript noexpandtab ts=4 sw=4 cindent : */
</code></pre>
<p>settings.js</p>
<pre><code>/*
* This is a sample configuration file.
*
* Copy this file to localsettings.js and edit that file to fit your needs.
*
* Also see:
* - api/server.js for more information about passing config files via
* the commandline.
* - lib/mediawiki.ParsoidConfig.js all the properties
* that you can configure here. Not all properties are
* documented here.
*/
'use strict';
exports.setup = function(parsoidConfig) {
// Set your own user-agent string
// Otherwise, defaults to "Parsoid/<current-version-defined-in-package.json>"
//parsoidConfig.userAgent = "My-User-Agent-String";
// The URL of your MediaWiki API endpoint.
parsoidConfig.setMwApi({ prefix: 'localhost', uri: 'http://domain.com/Wiki/api.php' });
// To specify a proxy (or proxy headers) specific to this prefix (which
// overrides defaultAPIProxyURI) use:
/*
parsoidConfig.setMwApi({
prefix: 'localhost',
uri: 'http://localhost/w/api.php',
// set `proxy` to `null` to override and force no proxying.
proxy: {
uri: 'http://my.proxy:1234/',
headers: { 'X-Forwarded-Proto': 'https' } // headers are optional
}
});
*/
// We pre-define wikipedias as 'enwiki', 'dewiki' etc. Similarly
// for other projects: 'enwiktionary', 'enwikiquote', 'enwikibooks',
// 'enwikivoyage' etc. (default true)
//parsoidConfig.loadWMF = false;
// A default proxy to connect to the API endpoints.
// Default: undefined (no proxying).
// Overridden by per-wiki proxy config in setMwApi.
//parsoidConfig.defaultAPIProxyURI = 'http://proxy.example.org:8080';
// Enable debug mode (prints extra debugging messages)
//parsoidConfig.debug = true;
// Use the PHP preprocessor to expand templates via the MW API (default true)
//parsoidConfig.usePHPPreProcessor = false;
// Use selective serialization (default false)
parsoidConfig.useSelser = true;
// Allow cross-domain requests to the API (default '*')
// Sets Access-Control-Allow-Origin header
// disable:
//parsoidConfig.allowCORS = false;
// restrict:
//parsoidConfig.allowCORS = 'some.domain.org';
// Set to true for using the default performance metrics reporting to statsd
// If true, provide the statsd host/port values
/*
parsoidConfig.useDefaultPerformanceTimer = true;
parsoidConfig.txstatsdHost = 'statsd.domain.org';
parsoidConfig.txstatsdPort = 8125;
*/
// Alternatively, define performanceTimer as follows:
/*
parsoidConfig.performanceTimer = {
timing: function(metricName, time) { }, // do-something-with-it
count: function(metricName, value) { }, // do-something-with-it
};
*/
// How often should we emit a heap sample? Time in ms.
// This setting is only relevant if you have enabled
// performance monitoring either via the default metrics
// OR by defining your own performanceTimer properties
//parsoidConfig.heapUsageSampleInterval = 5 * 60 * 1000;
// Allow override of port/interface:
//parsoidConfig.serverPort = 8000;
//parsoidConfig.serverInterface = '127.0.0.1';
// The URL of your LintBridge API endpoint
//parsoidConfig.linterAPI = 'http://lintbridge.wmflabs.org/add';
// Require SSL certificates to be valid (default true)
// Set to false when using self-signed SSL certificates
//parsoidConfig.strictSSL = false;
// Use a different server for CSS style modules.
// Set to true to use bits.wikimedia.org, or to a string with the URI.
// Leaving it undefined (the default) will use the same URI as the MW API,
// changing api.php for load.php.
//parsoidConfig.modulesLoadURI = true;
// Suppress some warnings from the Mediawiki API
// (defaults to suppressing warnings which the Parsoid team knows to
// be harmless)
//parsoidConfig.suppressMwApiWarnings = /annoying warning|other warning/;
};
</code></pre> | 1 |
Can someone explain how to select Multiple Values from an Access 2016 Combo box Control | <p>I have a combo box control on a form that allows me to choose one option only from a list of options.</p>
<p>I would like to be able to choose multiple options from this list(similar to how a drop down menu works on an access table field)</p>
<p>I know it is possible from a list box but this takes up a lot of room on my form because the list box must stay open. </p>
<p>It says in this article <a href="https://support.office.com/en-us/article/Use-a-list-that-stores-multiple-values-c8d15127-3641-45fc-aa2d-a3943d355e89" rel="nofollow">https://support.office.com/en-us/article/Use-a-list-that-stores-multiple-values-c8d15127-3641-45fc-aa2d-a3943d355e89</a> that its possible but I cannot get it to work. The article describes how it works under this heading "Understand the technology behind check-box drop-down lists and check box lists".</p> | 1 |
How to set value into textarea attribute using nightwatch.js | <p>I am working on nighwatch.js for web ui testing, I want to set value to a textarea, and textarea has an attribute which has my actual text, I am writing full textarea and how I am setting in following.</p>
<pre><code><div class="textarea-description">
<textarea cols="50" class="myClass setText" data-def placeholder="text to be replaced using nightwatch"/>
</div>
</code></pre>
<p>I am trying to set value in above textarea's attribute <strong>data-def placeholder</strong> as following ways</p>
<pre><code>browser.setValue('.textarea-description textarea[type=text]','nightwatch'); or
browser.setValue('.textarea-description textarea[data-def placeholder=text]','nightwatch'); or
browser.setValue('.textarea-description textarea[type=data-def placeholder]','nightwatch');
</code></pre>
<p>but nothing is working.</p> | 1 |
Why apache throws Target WSGI script not found or unable to stat on Flask app? | <p>I want to setup my flask app for apache on my ubuntu server using wsgi. But after my setup, I get the following browser error:</p>
<pre><code>Not Found
The requested URL / was not found on this server.
</code></pre>
<p>The apache error log throws:</p>
<pre><code>Target WSGI script not found or unable to stat:
/var/www/html/appname/appname.wsgi
</code></pre>
<p>My wsgi file looks like this:</p>
<pre><code>#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/html/appname/")
from IdeaHound import app as application
application.secret_key = 'here_the_key'
</code></pre>
<p>and my apache config file looks like this:</p>
<pre><code><VirtualHost *:80>
ServerName server_ip_here
WSGIScriptAlias / /var/www/html/appname/appname.wsgi
<Directory /var/www/html/appname/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel info
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
</code></pre>
<p>The <strong>appname</strong> folder has the following structure:
appname</p>
<pre><code>--application.py
--appname.wsgi
--LICENSE
--README.md
--requirements.txt
--db_manage.py
--appname
----frontend
----__inity__.py
----__init__.pyc
----models
----__pycache__
----socket_interface
--AppName
----__init__.py
----static
----templates
--instance
----config.py
</code></pre>
<p>What am I missing here to make the webserver run correctly with Flask?</p> | 1 |
React Native MapView rotate map with camera heading | <p>I am trying to rotate a map in React Native's <strong><MapView></strong> but haven't been able to find a description on how to rotate a map according to the heading of the camera. The tutorial states:</p>
<blockquote>
<p>When this property is set to true and a valid camera is associated with the map, the camera’s heading angle is used to rotate the plane of the map around its center point. </p>
</blockquote>
<p>So I came as far as:</p>
<pre><code><MapView
style={styles.map}
onRegionChange={this._onRegionChange}
onRegionChangeComplete={this._onRegionChangeComplete}
region={this.state.mapRegion}
annotations={this.state.annotations}
rotateEnabled={true}
</code></pre>
<p>But there is no explanation on how a camera is associated with the map.</p>
<p>Can anyone help with this issue please? </p> | 1 |
Why HMAC sha256 return different value on PHP & Javascript | <p>I am trying to build a HMAC SHA256 string in Javascript using CryptoJS, my existing code is written in PHP using the Akamai library.</p>
<p>In some cases I am getting different results compared to PHP & I am unable to understand why it is giving me different results</p>
<pre><code> /*
<php> Using native hash_hmac
Generating key by concatenating char
*/
$signature1 = hash_hmac('SHA256', "st=1453362060~exp=1453363260~acl=/*", chr(63));
$signature2 = hash_hmac('SHA256', "st=1453362060~exp=1453363260~acl=/*", chr(63) . chr(23));
$signature3 = hash_hmac('SHA256', "st=1453362060~exp=1453363260~acl=/*", chr(63) . chr(23) . chr(253));
/*
here is result from php
signature1 : 3e086bb48ab9aafa85661f9ce1b7dac49befddf117ce2a42d93c92b6abe513ce ( matched: same as JavaScript)
signature2 : 3667dd414a50f68f7ce083e540f27f68f7d0f18617b1fb1e4788bffeaeab59f6( matched: same as JavaScript)
signature3 : dd5a20041661046fdee871c8b9e77b3190fbbf85937c098090a1d524719b6aa9 ( not matched: diff from JavaScript)
*/
/*
<JavaScript> using CryptoJS
Generating key by concatenating three char
*/
var signature1 = CryptoJS.HmacSHA256("st=1453362060~exp=1453363260~acl=/*", String.fromCharCode(63));
var signature2 = CryptoJS.HmacSHA256("st=1453362060~exp=1453363260~acl=/*", String.fromCharCode(63) + String.fromCharCode(23));
var signature3 = CryptoJS.HmacSHA256("st=1453362060~exp=1453363260~acl=/*", String.fromCharCode(63) + String.fromCharCode(23) + String.fromCharCode(253));
/*
here is result from JavaScript
signature1 : 3e086bb48ab9aafa85661f9ce1b7dac49befddf117ce2a42d93c92b6abe513ce ( matched: same as php)
signature2 : 3667dd414a50f68f7ce083e540f27f68f7d0f18617b1fb1e4788bffeaeab59f6 ( matched: same as php)
signature3 : 28075dc75de9f22f83e87772f09a89efb007f2e298167686832eff122ef6eb08 ( not matched: diff from php)
*/
</code></pre>
<p>First two HMAC values are matching but when I append the third char it produces different results, Can anyone please explain why this is. </p>
<p>here is<br>
<a href="http://codepad.org/qtKsIJtT" rel="noreferrer">PHPFiddle</a> &
<a href="http://jsfiddle.net/_anil/5c4yyeao/2/" rel="noreferrer">JSFiddle</a></p> | 1 |
Add images with text in select2 | <p>Well I am creating a select tag drop down with countries name as option and i want to add the respected countries flag with them:
I used this HTML</p>
<pre><code> <div class="form-group" id="abc">
<label class="col-md-2 control-label">Language: </label>
<div class="col-md-6">
<select class="select2me form-control" name = "locale" id="select_lang">
@foreach($languages as $lang)
<option value="{{$lang->locale}}" @if($lang->locale == $company->locale) selected="selected" @endif>{{$lang->language}}</option>
@endforeach
</select>
</div>
</code></pre>
<p>JAVASCRIPT USED:</p>
<pre><code> jQuery(document).ready(function() {
$.fn.select2.defaults.set("theme", "bootstrap");
$('.select2me').select2({
placeholder: "Select",
width: '100%',
allowClear: false
});
function format(state) {
if (!state.id) return state.text; // optgroup
return "<img class='flag' src='" + MyFILEPATH() + "flags/" + state.id.toLowerCase() + ".png'/>&nbsp;&nbsp;" + state.text;
}
$("#select_lang").select2({
placeholder: "Select a Country",
allowClear: true,
formatResult: format,
formatSelection: format,
escapeMarkup: function (m) {
return m;
}
});
});
</code></pre> | 1 |
Android Marshmallow (rooted): How to read / write any file | <p>I recently updated to Marshmallow (Cyanogmod CM13) and, due to the new permissions regime, a lot of my apps no longer work.</p>
<p>Note that these apps are not on the Play Store and are for my own personal use. So security is not much of a problem - I'll let my apps access whatever I want them to access.</p>
<p>The problem is how to achieve that.</p>
<p>I've tried doing a "su -c chmod" to modify the permissions but that does not work.</p>
<p>Other apps (eg Jota+) can browse to and write to a file. How do they do that? (Yes, I've tried searching but have not hit on the right search terms - if the answer is "out there".)</p>
<p><strong>EDIT</strong>: The sdcard has been "adopted" and all relevant files transferred to it.</p> | 1 |
How to use 'hasManyThrough' with more than 3 tables in Laravel? | <p>as stated in the <a href="https://laravel.com/docs/5.2/eloquent-relationships#has-many-through" rel="nofollow">docs</a> the current <strong>hasManyThrough</strong> can be used when u have something like <code>country > users > posts</code></p>
<p>which result in something like <code>Country::whereName('xx')->posts;</code>
which is great but what if i have more than that like</p>
<p><code>country > cities > users > posts</code>
or even</p>
<p><code>country > cities > towns > users > posts</code></p>
<p>how would you then implement something like that so you can write the same as above</p>
<p><code>Country::whereName('xx')->posts;</code> or <code>Town::whereName('xx')->posts;</code></p> | 1 |
How to enable routing in OS X El Capitan | <p>I've got a Linux VMware virtual machine (guest) configured with a NAT adapter on a 192.168.56.0 subnet. Its IP address is 192.168.56.128 and my Mac (host) got 192.168.56.1. Guest's default gateway is automatically set to 192.168.56.2 and is able to ping google. Host's Wi-Fi IP is 192.168.0.2,</p>
<p>I've configured my Wi-Fi router with following routing table to forward packets of 192.168.56.0 to 192.168.0.2 (my Mac)</p>
<pre><code>pi@raspberrypi ~ $ route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
default 172.16.4.1 0.0.0.0 UG 0 0 0 eth0
172.16.4.0 * 255.255.252.0 U 0 0 0 eth0
192.168.0.0 * 255.255.255.0 U 0 0 0 wlan0
192.168.56.0 192.168.0.2 255.255.255.255 UGH 0 0 0 wlan0
192.168.57.0 192.168.0.2 255.255.255.255 UGH 0 0 0 wlan0
</code></pre>
<p>But I'm unable to ping guest from any other device on the Wi-Fi network (192.168.0.0). So it's obvious that my Mac running OS X El Capitan is not forwarding the packets from 192.168.0.0 to 192.168.56.0</p> | 1 |
Laravel Eloquent Birthdays Query to get Date Column based on Date and Month only | <p>I have a <code>date()</code> column in mysql which has the Date of Birth in mysql’s <code>YYYY-MM-DD</code> format:</p>
<pre><code>$table->date('dob')->nullable();
</code></pre>
<p>I am trying to query this table so it lists all users who are having birthdays from today till next 7 days. I have something like this right now:</p>
<pre><code>$date = new Carbon;
$today = $date->format('Y-m-d');
$futureDays = $date->addDays(7)->format('Y-m-d');
$birthdays = SiteUsers::where('dob', '>=', $today)
->where('dob', '<=', $futureDays)
->orderBy('dob', 'ASC')
->get();
</code></pre>
<p>The problem with the above query is that it only lists the users having DOB with the exact dates in this year only which is not right. What I really want is to list the users having birthdays irrespective of the year they were born by matching only the ‘date’ and ‘month’ and ignoring the ‘year’.</p>
<p>I don’t know how to achieve that. Can someone help me out please…</p> | 1 |
How to store special characters in Hive? | <p>I've been playing around with Spark, Hive and Parquet, I have some data in my Hive table and here is how it looks like ( warning french language ahead ) : </p>
<pre><code>Bloqu� � l'arriv�e NULL
Probl�me de connexion Bloqu� en hub
</code></pre>
<p>Obviously there's something wrong here.</p>
<p>What I do is : I read a teradata table as a dataframe with spark, I store it as a parquet file and then I use this file to store it to hive, here's my create table script : </p>
<pre><code>CREATE TABLE `table`(
`lib` VARCHAR(255),
`libelle_sous_cause` VARCHAR(255),
)
STORED AS PARQUET
LOCATION
'hdfs://location';
</code></pre>
<p>I don't really know what cause this, it might be caused by some special encoding between Teradata > parquet or Parquet > Hive, I'm not sure.</p>
<p>Any help will be appreciated, thanks.</p> | 1 |
Instantiate a fragment with a Custom Object Array List | <p>I'm trying to instantiate a fragment "sending" a custom object array list, but I can't find the exact way to do it. I think I may have to use <code>Serializable</code> or <code>Parcelable</code> (as seen in another answer), but I'm not sure how to implement it even after reading that answer.</p>
<p>Can someone help me? Thanks in advance.</p>
<p>Code to instantiate</p>
<pre><code>Fragment f = new Fragment();
ArrayList<IconsCategory> category = Utils.getCategory();
ArrayList<IconItem> icons = category.getIconsArray();
f = IconsFragment.newInstance(icons);
return f;
</code></pre>
<p>Code in fragment to create the instance:
I know <code>args.putArrayList()</code> method doesn't exist, I just wrote it to show how I expect to be able to code it.</p>
<pre><code>public static IconsFragment newInstance(ArrayList<IconItem> list) {
IconsFragment fragment = new IconsFragment();
Bundle args = new Bundle();
args.putArrayList(list); // here's where the code is supposed to go
fragment.setArguments(args);
return fragment;
}
</code></pre>
<p>IconsCategory class:</p>
<pre><code>import java.util.ArrayList;
public class IconsCategory {
private String name;
private ArrayList<IconItem> iconsArray = new ArrayList<>();
public IconsCategory(String name, ArrayList<IconItem> iconsArray) {
this.name = name;
this.iconsArray = iconsArray;
}
public String getCategoryName() {
return this.name;
}
public ArrayList<IconItem> getIconsArray() {
return iconsArray.size() > 0 ? this.iconsArray : null;
}
}
</code></pre>
<p>IconItem class:</p>
<pre><code>public class IconItem {
private String name;
private int resId;
public IconItem(String name, int resId){
this.name = name;
this.resId = resId;
}
public String getName(){
return this.name;
}
public int getResId(){
return this.resId;
}
}
</code></pre> | 1 |
Insufficient privileges to complete the operation when using an Azure service principal to create Azure resources | <p>I would like to use a service principal account to run a Powershell script that creates Azure resources, as suggested in <a href="http://blog.davidebbo.com/2014/12/azure-service-principal.html" rel="nofollow">this article about doing so when provisioning via TeamCity</a></p>
<p>I am able to create the service principal and assign it the 'Owner' role on the subscription, so in theory it should have rights to do anything in the Azure account. (I will adjust the rights later to just what is required by the principal.) The commands are basically the following:</p>
<pre><code>Login-AzureRmAccount # using my Azure admin account
$azureAdApplication = New-AzureRmADApplication -DisplayName "Deploy" -HomePage "https://deploy" -IdentifierUris "https://deploy" -Password "password"
New-AzureRmADServicePrincipal -ApplicationId $azureAdApplication.ApplicationId
New-AzureRmRoleAssignment -RoleDefinitionName Owner -ServicePrincipalName $azureAdApplication.ApplicationId
$subscription = Get-AzureRmSubscription
$creds = Get-Credential
Login-AzureRmAccount -Credential $creds -ServicePrincipal -Tenant $subscription.TenantId
</code></pre>
<p>However, when I then run a Powershell script that provisions resources, I get the following warnings when creating a Key Vault: </p>
<ul>
<li>Insufficient privileges to complete the operation</li>
<li>Access policy is not set. No user or application have access permission to use this vault. Please use Set-AzureRmKeyVaultAccessPolicy to set access policies</li>
</ul>
<p>I don't get these warnings when creating the Key Vault via my own admin account. How do I give a service principal sufficient privileges to be able to create resources in an Azure subscription without getting permissions issues?</p> | 1 |
Java JNI error java.lang.UnsatisfiedLinkError: xxxx()V | <p>I have had a rough time with <code>JNI</code> today, basically what I want to do is integrate <code>OpenAlpr</code> to my <code>Java</code> project, I am using precompiled binaries which work perfectly when I run the <code>java_test.bat</code> file. At first Java kept on telling me it could not locate <code>openAlprJni</code> then I added the path to the <code>dlls</code> to my build path and system path, after which I started experiencing the <code>openAlprJni.Alpr.initialize(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V</code> which according to documentation means the library itself is not ok, but it is ok since the test program is running, I have looked at various forums and even talked to the author of <code>OpenAlpr</code> but still cannot resolve this issue, is there anybody here who has had a similar problem help me fix this? thanks in advance.</p> | 1 |
Escape table name in SQLite? | <p>I have table named References in SQLite, so I can't target it, it seems. SQLite studio I use to edit databases throws an error.</p>
<p>Is there a way to escape database name?</p>
<p>The query is:</p>
<pre><code>UPDATE References
SET DateTimeLastEdited = datetime('now', 'localtime')
WHERE NewsItemID = old.NewsItemID;
</code></pre>
<p>(This is part of the trigger I am making.)</p> | 1 |
Excessive console messages from Kafka Producer | <p>How do you control the console logging level of a Kafka Producer or Consumer? I am using the Kafka 0.9 API in Scala.</p>
<p>Every time <code>send</code> on the <code>KafkaProducer</code> is called, the console gives output like below. Could this indicate I do not have the <code>KafkaProducer</code> set up correctly, rather than just an issue of excessive logging?</p>
<pre><code>17:52:21.236 [pool-10-thread-7] INFO o.a.k.c.producer.ProducerConfig - ProducerConfig values:
compression.type = none
metric.reporters = []
metadata.max.age.ms = 300000
.
.
.
17:52:21.279 [pool-10-thread-7] DEBUG o.a.kafka.common.metrics.Metrics - Added sensor with name bufferpool-wait-time
17:52:21.280 [pool-10-thread-7] DEBUG o.a.kafka.common.metrics.Metrics - Added sensor with name buffer-exhausted-records
17:52:21.369 [pool-10-thread-7] DEBUG org.apache.kafka.clients.Metadata - Updated cluster metadata version 1 to Cluster(nodes = [Node(-1, localhost, 9092)], partitions = [])
17:52:21.369 [pool-10-thread-7] DEBUG o.a.kafka.common.metrics.Metrics - Added sensor with name connections-closed:client-id-producer-2
17:52:21.369 [pool-10-thread-7] DEBUG o.a.kafka.common.metrics.Metrics - Added sensor with name connections-created:client-id-producer-2
17:52:21.370 [pool-10-thread-7] DEBUG o.a.kafka.common.metrics.Metrics - Added sensor with name bytes-sent-received:client-id-producer-2
17:52:21.370 [pool-10-thread-7] DEBUG o.a.kafka.common.metrics.Metrics - Added sensor with name bytes-sent:client-id-producer-2
.
.
</code></pre>
<p>There are logging configurations in the <code>properties</code> files the Kafka server and Zookeeper look at, but I've assumed these do not affect Kafka clients. Changing some of the logging configurations in these files, and restarting the Kafka server and Zookeeper so those files are reloaded, has not solved the problem.</p>
<p>Thank you</p> | 1 |
AWS data into Excel? | <p>I have a client who has asked me to take a look at the spreadsheet that they use for manipulating AWS data in order to import sales invoices into Xero....I'm just wondering if it's possible to directly query AWS from Excel?...this would streamline the process by cutting out the manual AWS export plus I would be able to create a query that puts the data into the format that Xero needs to see.</p>
<p>...moving on from this, I guess the next logical step would be to create an API that Xero can hook up to....unless this is already a thing?</p>
<p>Darren</p> | 1 |
Following Manual Instructions for Bootstrap 3 forms getting yml config error | <p>I'm following directions directly from the manual. I've got this configuration setting in my config.yml</p>
<pre><code>twig:
form:
resources: ['bootstrap_3_layout.html.twig']
</code></pre>
<p>haven't got this far but in my base.html.twig i have...</p>
<pre><code> <link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"
integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r"
crossorigin="anonymous">
{% block stylesheets %}{% endblock %}
</code></pre>
<p>And of course the appropriate call for jquery and boostrap.js at bottom of base.html.twig</p>
<p>In any of my templates I have....</p>
<pre><code>{% extends 'base.html.twig' %}
{% form_theme form 'bootstrap_3_layout.html.twig' %}
{% block body %} //etc. etc.
</code></pre>
<p>I get the error:</p>
<pre><code>InvalidConfigurationException in ArrayNode.php line 317:
Unrecognized option "form" under "twig"
</code></pre>
<p>did they change the yml configuration settings and not update it in the manual?</p> | 1 |
Google Sheet script to automatically calculate a countdown | <p>I haven't coded in decades, and I'm looking for a way to automate my current "countdown" spreadsheet. I currently do things in an ugly, error-prone and roundabout way, a very small script should be able to make it much better.</p>
<p><b>Goal:</p></B>
- Type in a duration in hours (typically, between 0 and 1,000) in a cell</p>
- One cell below, get a running countdown of how many hours remain. </p>
<p><B>Current situation:</B></p>
I've got the sheet set up to auto-recalc every hour, which is fine
then a 4-cells setup, repeated over multiple columns to track several timers:</p></p></p>
<ul>
<li>1st cell (B2) is the input cell to type in the duration in hours</p></li>
<li>2nd cell (B3) is =now()+B2/24 , that calculates the expected date of completion resulting from B2</p></li>
<li>3rd cell (B4) contains a hard copy of B3's value so that recalcs don't change that "firm expected completion" date. I have to copy + pastevalue from B3 to B4 every time I modify B2, which is the main issue with that setup</p></li>
<li>4th cell (B5) is =(int(B4)-int(now()))*24+hour(B4)-hour(now()) and is the running countdown I watch out for. Had to use int() not day() otherwise I get bugs when the start and completion dates are not the same month. </p></li>
</ul>
<p><B>What I'd like: </p></p></B>
- To get rid of the 2 intermediate cells and the cumbersome + error-prone manual copy-pastevalue between them.</p>
- An auto-trigger script that directly fills in B5 (actually, that would change to B3) with the countdown, using a formula that's probably</p>
(int(B2+$datetime_of_B2_modification) - int(now() )*24 + hour(B2+$datetime_of_B2_modification) - hour(now)). </p>
B2 is a direct reference to B2's value, $datetime_of_B2_modification is a value that is calculated each time I modify B2, and only then (not when the sheet is recalced, not when I hover over B2 but don't actually modify it) and is then harcoded into B5's formula; now() is gSheet's actual function that returns now's datetime.</p>
- ideally, that autotrigger script automatically creates that formula one cell below the one were I enter the hours duration, ie I don't have to make a different script for every column in my spreadsheet, it creates the formula "one cell below", not at a fixed cell.</p></p></p>
<p>My decades-old skills are rusty, I've been struggling to get started but I'm going nowhere. If someone could magically whip up that script, I'd be very grateful !</p></p></p>
<p>Best regards, Olivier</p>
<p>Thinking of it, a script to automate the copy+pastevalue step w/o changing anything else would be a nice first step. Getting rid of the 2 extra rows isn't that critical, though it would be nice.</p>
<p><strong>Edit after 1st answer</strong>: I thing I need something along the lines of what's below; ?? lines are lines I know are wrong</p>
<pre><code>function onEdit(e)() {
if(!e) return;
var book = SpreadsheetApp.getActiveSpreadsheet();
var sheet = book.getActiveSheet()
var sourcecell = book.getActiveCell();
//check the edited cell is a valid source cell
?? var sourcecelladdress = right(getA1Notation(sourcecell),2) // need to get result such as: 'A1" or 'B1'...
if ('B2C2D2B8C8D8'.indexOf(sourcecelladress) =-1) return;
// check the cell has actually been modified
if (e.value = e.oldValue) return;
//OK, so we're in a valid source cell, and it HAS been modified
// now let's build the formula string
var sourcevalue = sourcecell.getValue()
var enddate = sourcevalue/24 + now()
var enddateday = int (endate) * 24
var endatetime = hour (enddate)
?? var countdownformula = '=' + (enddateday + enddatehour) + '- (int(now())*24) - hour(now())'
//and now let's put it in the destination cell
?? var destcell = sourcecell + ????? (one row down from active cell)
?? destcell.setformula(countdownformula)
}
</code></pre> | 1 |
AngularJs stop $interval for specific controller | <p>I was used $interval to run certain function in first controller. After redirect to second controller, still $interval registered function (implemented in first controller) was running. I want to stop $interval services without using destroy function. </p> | 1 |
Openstack-Devstack: Can't create instance, There are not enough hosts available | <p>I installed openstack via devstack on Ubuntu 14.04. I have got 8 gb of ram on my computer and i have created around 8 VM's which i don't use simultaneously as I use the VM differently.
Now i cannot create any more VM's. I get an error message</p>
<blockquote>
<p>No Valid Host was found.
there are not enough hosts available.</p>
</blockquote>
<p>Can someone advice what should i do?</p> | 1 |
Correct way to reuse ADODB.Command | <p>What is the correct way to call a sproc within a loop?</p>
<p>If I come in with something like this:</p>
<pre><code>Connection = CreateObject("ADODB.Connection")
DO UNTIL RS.EOF
SET cmd = Server.CreateObject ("ADODB.Command")
cmd.ActiveConnection = Connection
cmd.CommandText = "spMySproc"
cmd.CommandType = adCmdStoredProc
cmd.Parameters.Append cmd.CreateParameter ("@p1",adInteger,adParamInput, ,RS("Val1"))
cmd.Parameters.Append cmd.CreateParameter ("@p2",adInteger,adParamInput, ,RS("Val2"))
cmd.Execute
SET cmd = nothing
LOOP
</code></pre>
<p>Then on the second and subsequent iterations of the loop I get an error </p>
<blockquote>
<p>Procedure or function spMySproc has too many arguments specified.</p>
</blockquote> | 1 |
Installing gem error (EADDRNOTAVAIL) | <p>I am trying to install Redmine to a Windows Server 2012, following "<a href="http://coreboarder.com/blog/?p=465" rel="nofollow">How to MANUALLY install Redmine 3.x on Windows Server 2008 R2</a>". </p>
<p>After installing <a href="http://rubyinstaller.org/downloads/" rel="nofollow">http://rubyinstaller.org/downloads/</a> the next step is to install Bundler but I got the following error:</p>
<pre><code>C:\inetpub\wwwroot\redmine>ruby -v
ruby 2.2.4p230 (2015-12-16 revision 53155) [i386-mingw32]
C:\inetpub\wwwroot\redmine>gem list
*** LOCAL GEMS ***
bigdecimal (1.2.6)
io-console (0.4.3)
json (1.8.1)
minitest (5.4.3)
power_assert (0.2.2)
psych (2.0.8)
rake (10.4.2)
rdoc (4.2.0)
test-unit (3.0.8)
C:\inetpub\wwwroot\redmine>gem install bundler
ERROR: While executing gem ... (Errno::EADDRNOTAVAIL)
The requested address is not valid in its context. - connect(2) for "0.0.0.0
" port 53
C:\inetpub\wwwroot\redmine>
</code></pre>
<p>Any help would be appreciated.</p> | 1 |
canvas toDataURL() - operation is insecure | <p>I'm using fabric.js to draw annotations on page. Now I want to save anootated page as is, rather than to redraw all elements on server side using JSON.</p>
<p>I have main image loaded as:</p>
<pre><code>function redrawPage(src) {
var deferred = $q.defer();
fabric.Image.fromURL(src, function (img) {
zoom.reset();
transformation.reset();
mainImage = img;
mainImage.set({
left: 0,
top: 0
});
mainImage.hasRotatingPoint = true;
mainImage.selectable = false;
canvas.clear();
canvas.setWidth(mainImage.getWidth());
canvas.setHeight(mainImage.getHeight());
canvas.add(mainImage);
canvas.renderAll();
deferred.resolve();
});
return deferred.promise;
}
</code></pre>
<p>and when I want to send canvas image data to be stored as annotated version of original image, I get "Operation is insecure" error.</p>
<pre><code>function getImageData() {
var context = canvas.getContext('2d'),
imageData = context.getImageData(0, 0, canvas.width, canvas.height);
return imageData.data;
}
</code></pre>
<p>web server from which I load images is not allowing crossOrigin set to "Anonymus"</p> | 1 |
Extract the last element of a list for a split string | <p>I'm trying to take a regular expression and split it by a pre-determined character, and then extract the final value of the returned list.</p>
<p>For example, my string may take the form:</p>
<pre><code>name
WAYNE.ROONEY.226
ROSS.BARKLEY.HELLO.113
ADAM.A122
</code></pre>
<p>Pythonically, what I'm trying to do is:</p>
<pre><code>for x in list:
my_val = x.split('.')[-1] #Return the last element of the list when split on .
</code></pre>
<p>e.g. desired output:</p>
<pre><code>name value
WAYNE.ROONEY.226 226
ROSS.BARKLEY.HELLO.113 113
ADAM.A122 A122
</code></pre>
<p>Can anyone provide me any pointers in either Hive or Impala please?</p>
<p>If I can create this as a view, ideally, that would be perfect, but am also happy with generating actual output with it and then re-uploading to a table</p>
<p>Thank you!</p> | 1 |
XWPF - remove cell text | <p>I have a .docx file that contains a single table. I want to remove all text from rows 2 to the end.
However the method <code>myTable.getRow(somecounter).getCell(somecounter2).setText("")</code> doesn't work as it only concatenates " " to the existing value.
I also tried making a XWPFRun and doing <code>run.setText("")</code> created from <code>myTable.getRow(sc).getCell(sc2).getParagraphs().get(0).createRun()</code> but it doesn't work aswell.</p>
<p>Also tried the solution from <a href="https://stackoverflow.com/questions/28926195/apache-poi-xwpf-does-not-replace-but-concatenates">this thread</a>, no luck this time :(</p>
<p>Any ideas how to easily remove text from the cell?
My idea is to make a new table from scratch and fill it with content but it seems really arduous.</p> | 1 |
laravel5.2 Auth::guest() returns error "Class 'App\Http\Controllers\Auth' not found" | <p>I am trying to use the inbuilt <code>Auth</code> for login in <code>laravel</code> and register. These automatically generated pages work so well, now I use <code>Auth::guest()</code> to check if the user is authorized to return a view: index else to login page. </p>
<p>But it shows:</p>
<blockquote>
<p>Class 'App\Http\Controllers\Auth' not found".</p>
</blockquote>
<p><strong>Here's the code:</strong></p>
<pre><code><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
class StepsController extends Controller
{
public function step1()
{
if (Auth::guest())
{
return redirect('login');
}else {
return view('index');
}
}
}
</code></pre> | 1 |
How can I set an initial .focus() on a node in a d3.js sunburst chart? | <p>I'm working on making <a href="http://embed.plnkr.co/bOlEKo/" rel="nofollow">this sunburst chart</a> accessible/508 compliant. Does anyone have any idea on how I can make say, the center circle carry a default focus using the .focus() call? That way, whenever the chart is interacted with by the user limited to keyboard navigation, the starting point is always highlighting the center circle?</p>
<p>I'm fairly new to Accessibility Standards. But what i'm trying to accomplish is a bilateral keyboard navigation. Any suggestions would be greatly appreciated!</p> | 1 |
tensorflow build fails with "missing dependency" error | <p>I'm completely new to bazel and tensorflow so the solution to this may be obvious to someone with some experience. My bazel build of tensorflow fails with a "missing dependency" error message. Here is the relevant sequence of build commands and output:</p>
<pre><code>(tf-gpu)kss@linux-9c32:~/projects> git clone --recurse-submodules https://github.com/tensorflow/tensorflow tensorflow-nogpu
Cloning into 'tensorflow-nogpu'...
remote: Counting objects: 16735, done.
remote: Compressing objects: 100% (152/152), done.
remote: Total 16735 (delta 73), reused 0 (delta 0), pack-reused 16583
Receiving objects: 100% (16735/16735), 25.25 MiB | 911.00 KiB/s, done.
Resolving deltas: 100% (10889/10889), done.
Checking connectivity... done.
Submodule 'google/protobuf' (https://github.com/google/protobuf.git) registered for path 'google/protobuf'
Cloning into 'google/protobuf'...
remote: Counting objects: 30266, done.
remote: Compressing objects: 100% (113/113), done.
remote: Total 30266 (delta 57), reused 0 (delta 0), pack-reused 30151
Receiving objects: 100% (30266/30266), 28.90 MiB | 1.98 MiB/s, done.
Resolving deltas: 100% (20225/20225), done.
Checking connectivity... done.
Submodule path 'google/protobuf': checked out '0906f5d18a2548024b511eadcbb4cfc0ca56cd67'
(tf-gpu)kss@linux-9c32:~/projects> cd tensorflow-nogpu/
(tf-gpu)kss@linux-9c32:~/projects/tensorflow-nogpu> ./configure
Please specify the location of python. [Default is /home/kss/.venv/tf-gpu/bin/python]:
Do you wish to build TensorFlow with GPU support? [y/N]
No GPU support will be enabled for TensorFlow
Configuration finished
(tf-gpu)kss@linux-9c32:~/projects/tensorflow-nogpu> bazel build -c opt //tensorflow/tools/pip_package:build_pip_package
Sending SIGTERM to previous Bazel server (pid=8491)... done.
....
INFO: Found 1 target...
ERROR: /home/kss/.cache/bazel/_bazel_kss/b97e0e942a10977a6b42467ea6712cbf/external/re2/BUILD:9:1: undeclared inclusion(s) in rule '@re2//:re2':
this rule is missing dependency declarations for the following files included by 'external/re2/re2/perl_groups.cc':
'/usr/lib64/gcc/x86_64-suse-linux/4.8/include/stddef.h'
'/usr/lib64/gcc/x86_64-suse-linux/4.8/include/stdarg.h'
'/usr/lib64/gcc/x86_64-suse-linux/4.8/include/stdint.h'
'/usr/lib64/gcc/x86_64-suse-linux/4.8/include/x86intrin.h'
'/usr/lib64/gcc/x86_64-suse-linux/4.8/include/ia32intrin.h'
'/usr/lib64/gcc/x86_64-suse-linux/4.8/include/mmintrin.h'
'/usr/lib64/gcc/x86_64-suse-linux/4.8/include/xmmintrin.h'
'/usr/lib64/gcc/x86_64-suse-linux/4.8/include/mm_malloc.h'
'/usr/lib64/gcc/x86_64-suse-linux/4.8/include/emmintrin.h'
'/usr/lib64/gcc/x86_64-suse-linux/4.8/include/immintrin.h'
'/usr/lib64/gcc/x86_64-suse-linux/4.8/include/fxsrintrin.h'
'/usr/lib64/gcc/x86_64-suse-linux/4.8/include/adxintrin.h'.
Target //tensorflow/tools/pip_package:build_pip_package failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 144.661s, Critical Path: 1.18s
(tf-gpu)kss@linux-9c32:~/projects/tensorflow-nogpu>
</code></pre>
<p>The version of bazel I'm using is <code>release 0.1.4</code>, I'm running on openSUSE 13.2. I confirmed that the header files do exist which is probably expected:</p>
<pre><code>(tf-gpu)kss@linux-9c32:~/projects/tensorflow-nogpu> ll /usr/lib64/gcc/x86_64-suse-linux/4.8/include/stddef.h
-rw-r--r-- 1 root root 13619 Oct 6 2014 /usr/lib64/gcc/x86_64-suse-linux/4.8/include/stddef.h
</code></pre>
<hr>
<p><strong>Note for anyone who finds this question</strong>:</p>
<p>Use Damien's answer below except that you have to use <code>--crosstool_top</code> rather than <code>--crosstool</code>. Also if you are building for GPU acceleration you will also need to modify the <code>CROSSTOOL</code> file in the tensorflow repo like:</p>
<pre><code>(tf-gpu)kss@linux-9c32:~/projects/tensorflow-gpu> git diff third_party/gpus/crosstool/CROSSTOOL | cat
diff --git a/third_party/gpus/crosstool/CROSSTOOL b/third_party/gpus/crosstool/CROSSTOOL
index dfde7cd..b63f950 100644
--- a/third_party/gpus/crosstool/CROSSTOOL
+++ b/third_party/gpus/crosstool/CROSSTOOL
@@ -56,6 +56,7 @@ toolchain {
cxx_builtin_include_directory: "/usr/lib/gcc/"
cxx_builtin_include_directory: "/usr/local/include"
cxx_builtin_include_directory: "/usr/include"
+ cxx_builtin_include_directory: "/usr/lib64/gcc"
tool_path { name: "gcov" path: "/usr/bin/gcov" }
# C(++) compiles invoke the compiler (as that is the one knowing where
</code></pre> | 1 |
download file from localhost | <p>I want to put an image on my web and when clicked it will download a specific file. is this the correct script for this purpose ? but when I click there is no response.</p>
<pre><code><td><a href="file:download/D411.zip"><img src="images/download.png" title="Download"></a></td>
</code></pre>
<p>Thank you for the help</p> | 1 |
How to post complex XML using rest assured | <p>Using rest-assured we can easily perform GET, POST and other methods. In the example below we are sending a POST to an API that returns a JSON response. </p>
<pre><code>@Test
public void reserveARide()
{
given().
header("Authorization", "abcdefgh-123456").
param("rideId", "gffgr-3423-gsdgh").
param("guestCount", 2).
when().
post("http://someWebsite/reserveRide").
then().
contentType(ContentType.JSON).
body("result.message", equalTo("success"));
}
</code></pre>
<p>But I need to create POST request with complex XML body.
Body example:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<request protocol="3.0" version="xxx" session="xxx">
<info1 param1="xxx" version="xxx" size="xxx" notes="xxx"/>
<info2 param1="xxx" version="xxx" size="xxx" notes="xxx"/>
</request>
</code></pre>
<p>How can I do this?
Thank you in advance</p> | 1 |
Creating style alias in CSS on HTML page | <p>I am wanting to do selectively stop the line feeds associated with the < p> command on a dynamically built HTML page and am using a style to do this. I know that </p>
<pre><code> p {
display: inline
}
</code></pre>
<p>can do this, but I do not want to continually add this tag throughout the page.</p>
<p>Is there a method where I can create an alias of the p tag, or somehow create another tag that will invoke the style.</p>
<p>For instance (and I know that this code won't work), something like</p>
<pre><code> <style type="text/css">
stop-p-lf {
p {
display: inline
}
}
</style>
</code></pre>
<p>then in my HTML I just use the tag like this..</p>
<pre><code> <stop-p-lf>the next p tag will not line feed <p>
but the one after this</stop-p-lf> <p> will
</code></pre>
<p>I'm hoping to use these tags to ease readability and to reduce the amount of coding throughout the html.</p>
<p>Is there a way of doing this?</p> | 1 |
Django static templatetag not displaying SVG | <p>I'm trying to use django's <code>static</code> templatetag to display an SVG, but it doesn't seem to recognize the SVG as a valid image url. This is what I currently have:</p>
<h2>settings.py</h2>
<pre><code>import mimetypes
mimetypes.add_type("images/svg+xml", ".svg", True)
</code></pre>
<h2>landing.html</h2>
<pre><code>{% load staticfiles %}
<img src="{% static 'images/right-arrow.svg' %}" />
</code></pre>
<p>At least in my view.py, it recognizes the SVG mimetype:</p>
<h2>views.py</h2>
<pre><code>print(mimetypes.guess_type(static('images/right-arrow.svg')))
# returns ('images/svg+xml', None)
</code></pre>
<p>The SVG does display in a non-django page, and it will download the SVG if I try to open the SVG path in a new browser tab. </p>
<p>I'm currently using python 3.4 and django 1.8.4.</p> | 1 |
COPY NULL values in Postgresql using psycopg2 copy_from() | <p>This seems like a rather popular question, but all the answers around here did not help me solve the issue... I have a Postgresql 9.5 table on my OS X machine:</p>
<pre><code>CREATE TABLE test (col1 TEXT, col2 INT)
</code></pre>
<p>The following function uses the psycopg2 <a href="http://initd.org/psycopg/docs/cursor.html#cursor.copy_from" rel="noreferrer"><code>copy_from()</code></a> command:</p>
<pre><code>def test_copy(conn, curs, data):
cpy = BytesIO()
for row in data:
cpy.write('\t'.join([str(x) for x in row]) + '\n')
print cpy
cpy.seek(0)
curs.copy_from(cpy, 'test')
test_copy(connection, [('a', None), ('b', None)])
</code></pre>
<p>And will result in this error:</p>
<pre><code>ERROR: invalid input syntax for integer: "None"
CONTEXT: COPY test, line 1, column col2: "None"
STATEMENT: COPY test FROM stdin WITH DELIMITER AS ' ' NULL AS '\N'
</code></pre>
<p>I tried also <code>curs.copy_from(cpy, 'test', null='')</code>, <code>curs.copy_from(cpy, 'test', null='NULL')</code>. Any suggestions are greatly appreciated.</p> | 1 |
Need to transfer multiple files from client to server | <p>I'm recently working on a project in which I'm basically making a dropbox clone. The server and client are working fine but I'm having a slight issue. I'm able to transfer a single file from the client to the server but when I try to transfer all the files together it gives me an error after the transfer of the first file so basically my code is only working for a single file. I need to make it work for multiple files. Any help will be appreciated. Here's my code</p>
<p><strong>Server Code</strong></p>
<pre><code>import socket
import thread
import hashlib
serversock = socket.socket()
host = socket.gethostname();
port = 9000;
serversock.bind((host,port));
filename = ""
serversock.listen(10);
print "Waiting for a connection....."
clientsocket,addr = serversock.accept()
print("Got a connection from %s" % str(addr))
while True:
size = clientsocket.recv(1)
filesz = clientsocket.recv(1)
if filesz.isdigit():
size += filesz
filesize = int(size)
else:
filesize = int(size)
print filesize
for i in range(0,filesize):
if filesz.isdigit():
filename += clientsocket.recv(1)
else:
filename += filesz
filesz = "0"
print filename
file_to_write = open(filename, 'wb')
while True:
data = clientsocket.recv(1024)
#print data
if not data:
break
file_to_write.write(data)
file_to_write.close()
print 'File received successfully'
serversock.close()
</code></pre>
<p><strong>Client Code</strong></p>
<pre><code>import socket
import os
import thread
s = socket.socket()
host = socket.gethostname()
port = 9000
s.connect((host, port))
path = "C:\Users\Fahad\Desktop"
directory = os.listdir(path)
for files in directory:
print files
filename = files
size = bytes(len(filename))
#print size
s.send(size)
s.send(filename)
file_to_send = open(filename, 'rb')
l = file_to_send.read()
s.sendall(l)
file_to_send.close()
print 'File Sent'
s.close()
</code></pre>
<p><strong>Here's the error that I get</strong></p>
<pre><code>Waiting for a connection.....
Got a connection from ('192.168.0.100', 58339)
13
Betternet.lnk
File received successfully
Traceback (most recent call last):
File "server.py", line 22, in <module>
filesize = int(size)
ValueError: invalid literal for int() with base 10: ''
</code></pre> | 1 |
How to put R Markdown chunks in different HTML-tabs? | <p>I have an R markdown page with a lot of chunks. Is it possible to render an HTML-page in which the chunks appear in different tabs?</p>
<p>As an example I use this .Rmd file:</p>
<pre><code>---
title: "Example"
output: html_document
---
# Tab 1
```{r}
summary(cars)
```
# Tab 2
```{r, echo=FALSE}
plot(cars)
```
</code></pre>
<p>Now I want to render an HTML-page with the content of the two chunks in two different tabs. How can I do that?</p>
<p>This is how it basically has to look like.</p>
<p><a href="https://i.stack.imgur.com/mQ47g.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mQ47g.png" alt="enter image description here"></a></p> | 1 |
Disable Android WebView/WebViewClient Initiated favicon.ico Request | <p>How can I disable the Android WebView/WebViewClient from sending out a request for favicon.ico when I call WebView.loadUrl()? I can see the call being made while profiling requests via CharlesProxy.</p>
<p>I do not own the HTML content that I am displaying in the WebView. My research has turned up a lot of results on workarounds from the server side but these won't work for me.</p> | 1 |
Can I remove event listeners with a Chrome extension? | <p>In Chrome's dev tools, there's a lovely interface where you can see all the event listeners attached to a given DOM element, and remove any of them as you see fit. Here's a screenshot (arrow added for emphasis):</p>
<p><a href="//i.stack.imgur.com/DCkKG.png" rel="noreferrer"><img src="//i.stack.imgur.com/DCkKG.png" alt="Removing an event listener with Chrome dev tools"></a></p>
<p>I'd like to write a Chrome extension that automatically removes event listeners from any web page (I'm trying to write a Chrome extension to disable smooth scrolling on any website that tries to force it upon you -- I figure removing the 'wheel' listener from <code><body></code> is the most direct route to do this). Is there any JavaScript API available for accessing and modifying this list of event listeners from a Chrome extension, or is it limited to the dev tools GUI?</p>
<p>To be clear, I'm aware of <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener" rel="noreferrer">removeEventListener()</a>, but that method requires that you have a reference to the original listener object -- I have no such reference, so that method won't suit my purposes.</p> | 1 |
Collapse absolutePanel in shiny? | <p>Following the example of superZip (<a href="http://shiny.rstudio.com/gallery/superzip-example.html" rel="noreferrer">http://shiny.rstudio.com/gallery/superzip-example.html</a>), is it possible to create a collapse absoltePanel in shiny which is collapse into right, bottom corner, in case there are lots of controls and outputs. </p>
<p>Thanks for any suggestions.</p>
<p>This is a minimum example for absolutePanel:</p>
<pre><code>library(shiny)
ui <- shinyUI(bootstrapPage(
absolutePanel(
id = "controls", class = "panel panel-default", fixed = TRUE,
draggable = TRUE, top = 60, left = "auto", right = 20, bottom = "auto",
width = 330, height = "auto",
checkboxInput('input_draw_point', 'Draw point', FALSE ),
verbatimTextOutput('summary'))
))
server <- shinyServer(function(input, output, session) {
output$summary <- renderPrint(print(cars))
})
shinyApp(ui = ui, server = server)
</code></pre> | 1 |
WinSCP Disable ResumeSupport in PowerShell | <p>I am using WinSCP to write to connect a SQL Server to an SFTP server. I am trying to write a file to an SFTP server where I only have write access, not modify. I am having a problem because I get back</p>
<blockquote>
<p>Cannot create remote file '/xxx.filepart'.</p>
</blockquote>
<p>The documentation suggests this is because I do not have modify access to the target directory. I did this <em>WinSCP -> Preferences -> Endurance -> Disable</em><br>
I checked the <code>winscp.ini</code> file and <code>ResumeSupport</code> is <code>2</code> (I believe this means disabled). I ran <code>"echo $transferOptions.ResumeSupport"</code> and it says that it is in a default state.</p>
<p>I have checked this documentation:<br>
<a href="https://winscp.net/eng/docs/ui_pref_resume" rel="nofollow">https://winscp.net/eng/docs/ui_pref_resume</a><br>
<a href="https://winscp.net/eng/docs/library_transferoptions#resumesupport" rel="nofollow">https://winscp.net/eng/docs/library_transferoptions#resumesupport</a></p>
<p>However, I don't see a PowerShell example, just C#.</p>
<p>I have tried various permutations of <code>$transferOptions.ResumeSupport.State = Off</code>, <code>$transferOptions.ResumeSupport.Off</code>, and whatnot. One of these says that it's read-only.</p>
<p>I know <code>$transferOptions</code> is a variable here but it comes from the default script. The object determines transfer options <code>$transferOptions = New-Object WinSCP.TransferOptions</code></p>
<p>Thanks in advance for help </p>
<p>edit: The overall problem is I only have write access to the server, but not modify. I am getting a new error: "Cannot overwrite remote file '/xxx'.$$. It looks like the dollar signs are some sort of temp file that it's trying to create. Is there a way to disable whatever setting is causing this? </p> | 1 |
Postgresql postmaster takes very long time to start | <p>My situation in Postgres 9.1 is that
I had some running queries which take a lot of memory, then I restarted Postgres immediately. After that I used postmaster to start it again.</p>
<p>/usr/pgsql-9.1/bin/postmaster -p 5432 -D /var/lib/pgsql/9.1/data</p>
<p>However, it got stuck for a very long time without starting successfully.</p>
<p>From Postgres documentation, when we restart server immediately, it may prevent postmaster from freeing the system resources (e.g., shared memory and semaphores).
So what should I do now? or just wait for postmaster starting?</p> | 1 |
How to deploy and serve prediction using TensorFlow from API? | <p>From google tutorial we know how to train a model in TensorFlow. But what is the best way to save a trained model, then serve the prediction using a basic minimal python api in production server.</p>
<p>My question is basically for TensorFlow best practices to save the model and serve prediction on live server without compromising speed and memory issue. Since the API server will be running on the background for forever.</p>
<p>A small snippet of python code will be appreciated. </p> | 1 |
How can I prevent my Spring Boot Batch application from running when executing test? | <p>I have a Spring Boot Batch application that I'm writing integration tests against. When I execute a test, the entire batch application runs. How can I execute just the application code under test? </p>
<p>Here's my test code. When it executes, the entire batch job step runs (reader, processor, and writer). Then, the test runs.</p>
<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = BatchApplication.class))
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
StepScopeTestExecutionListener.class })
public class StepScopeTestExecutionListenerIntegrationTests {
@Autowired
private FlatFileItemReader<String> reader;
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
public StepExecution getStepExection() {
StepExecution execution = MetaDataInstanceFactory.createStepExecution();
return execution;
}
@Test
public void testGoodData() throws Exception {
//some test code on one met
File testFile = testFolder.newFile();
PrintWriter writer = new PrintWriter(testFile, "UTF-8");
writer.println("test");
writer.close();
reader.setResource(new FileSystemResource(testFile));
reader.open(getStepExection().getExecutionContext());
String test = reader.read();
reader.close();
assertThat("test", equalTo(test));
}
}
</code></pre> | 1 |
Cannot convert value of type 'UITableViewCell' to specified type | <p>I have just created a new custom cell in the file 'Celda', now I need to use the labels in my UITableView using JSON.</p>
<pre><code>override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : Celda = tableView.dequeueReusableCellWithIdentifier("jsonCell")!
var dict = arrRes[indexPath.row]
cell.nombre1.text = dict["nombre"] as? String
cell.nombre2.text = dict["calle"] as? String
cell.id.text = dict["id"] as? String
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrRes.count
}
</code></pre>
<p>But I am getting error in 'let' line. It says: <code>Cannot convert value of type 'UITableViewCell' to specified type 'Celda'</code>.</p> | 1 |
warning:Cannot use a scalar value as an array | <p>I have a very basic code.That involves sessions and array.</p>
<pre><code>$abc=array();
$abc['name']=$db_name; //When i echo this one.It does echo the name i.e. 'Tilak'
$_SESSION['userpasswordmatch']=true;
$_SESSION['userpasswordmatch']['name']=$abc['name'];
echo $_SESSION['userpasswordmatch']['name'];
</code></pre>
<p>Now when i try to run the code.It shows me a warning stating <em>cannot use a scalar value as an array</em> as well as the echo part in the above code doesn't show anything.</p>
<p><strong>Question :</strong></p>
<p>1)Why am i seeing this error and what is the way to resolve this?</p>
<p>2)How to echo the above session.</p>
<p><strong>Note :</strong></p>
<p>1)<em>$db_name</em> is the name of the username that i get from the database.It works fine and i get the correct value in <em>$db_name</em>.</p>
<p><strong>Update:</strong></p>
<p><em>Same thing happens even if i do this :</em></p>
<pre><code> $_SESSION['userpasswordmatch']=true;
$_SESSION['userpasswordmatch']['name']=$db_name;
echo $_SESSION['userpasswordmatch']['name'];
</code></pre> | 1 |
Conditions on Date | <p>I am trying to create a condition on a recurrence trigger. I cannot seem to find any documentation on doing so with a date.</p>
<p>Specifically, I want to have a continue based on the day of the week (e.g, not continue on Sunday). Does anyone know of a blog post or MSDN documentation where they talk about date based conditions?</p> | 1 |
VB.NET GetObject(,"Excel.Application") fails to get running Excel | <p>I have a single, visible, running instance of Excel 2013. I have already performed a Quick Repair <em>and</em> an Online Repair, and waited for the Repair to completely finish.</p>
<p>If I run this VBA from Word, I <em>can</em> get a reference to the running Excel Application:</p>
<pre><code>Sub WordMacro()
'This works
Dim o As Object
Set o = GetObject(, "Excel.Application")
End Sub
</code></pre>
<p>But if I run this from Visual Studio 2013 Professional under .NET 4.5, it fails:</p>
<pre><code>Option Strict Off
Module Module1
Sub Main()
Dim o As Object
'Cannot create ActiveX component.
o = GetObject(, "Excel.Application")
'But this does create a new, hidden instance
o = CreateObject("Excel.Application")
End Sub
End Module
</code></pre>
<p>Is there some security consideration that I'm missing, or do I just need to do a complete uninstall/reinstall of Office?</p> | 1 |
Ignore clicks in the Chrome Dev Tools pane | <p>I'm trying to look at and alter the style of some elements that display on click and hide when anywhere else on the page is clicked (it's a modal popup). The problem is that clicking on the developer tools pane triggers the "click anywhere else" action, so the elements I'm trying to look at are being hidden.</p>
<p>How can I ignore clicks in the Chrome developer tools pane so the click action doesn't fire?</p>
<p><em>(Tagging jQuery and Javascript because I'm not sure if it's a problem with Chrome or if I need to load the script a different way.)</em></p> | 1 |
Compress a HttpWebRequest using gzip | <p>I am developing a <code>.NET 4.0</code> Console Application to serve as a <code>SOAP Web Service</code> client which will send data (POST) through to a third-party. I have no control over the web service on the server-side. The third-party did provide <code>WSDL's</code> to use, and I was able to import them and use them with reasonable success. However, there is a requirement to compress the request message using <code>gzip</code>, and I could not for the life of me figure out how to do that using the proxy services.</p>
<p><a href="https://stackoverflow.com/questions/9787923/using-compression-with-c-sharp-webservice-client-in-visual-studio-2010?lq=1">This topic</a> here on SO, led me to believe that without having control over both the client and server code, the request is unable to be compressed. As a result of this finding, I wrote the code in my application to manually create the <code>SOAP XML</code> in a <code>XDocument</code> object; then, populated the values from the <code>WSDL</code> proxy class objects which I had previously coded my client application to use.</p>
<p>The first requirement for this client, is to send the message compressed via <code>gzip</code>. After some research, I have seen answers as simple as just adding the <code>HttpRequestHeader.AcceptEncoding, "gzip, deflate"</code> to the request header. Unfortunately, doing that that didn't appear to work.</p>
<p>Currently, the certificate which I am retrieving is not the real certificate. I am trying to make the code as sound as I can before deploying to a test environment to do the actual service testing.</p>
<ol>
<li>Is there a way to compress the request via the proxy call (<code>wsdl</code>)?</li>
<li>Is there something I am missing in order to properly compress the <code>HttpWebRequest</code>?</li>
<li>Might there be something else going wrong which would result in the error message to be returned?<br>
<em>I would expect a different message pertaining to authentication being invalid if the request itself was OK</em>.</li>
<li>Is there a way the compression can be done through the <code>app.config</code>?</li>
</ol>
<p>The next set of requirements I'm a little confused on how to handle/what to do. Under the assumption that what I have set the <code>ContentType</code> of the request to, how (and what) do I add in order to add the <code>content-transfer-encoding</code> piece to the request? If the <code>ContentType</code> is incorrect, how should I add this information as well?</p>
<blockquote>
<p>The content type for the SOAP Evenlope with MTOM encoded attachment must be "application/xop+xml" and the content-transfer-encoding must be 8-bit.</p>
</blockquote>
<p>I've gone through a few iterations of the code below, however, I believe the relevant snippets are the code at its simplest form. Please let me know if there is other information that would be helpful.</p>
<p><strong>Method to create the HttpWebRequest:</strong> </p>
<pre><code>private static HttpWebRequest CreateWebRequest(SoapAction action)
{
string url = GetUrlAddress(action);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
request.Headers.Add("SOAPAction", action.ToString());
request.ContentType = "application/xop+xml";
request.Accept = "text/xml";
request.Method = "POST";
request.ClientCertificates.Add(/* Retrieve X509Certificate Object*/);
return request;
}
</code></pre>
<p><strong>Code to Send Request:</strong></p>
<pre><code>using (Stream stream = request.GetRequestStream())
{
soapXml.Save(stream);
}
</code></pre>
<p><strong>Code to retrieve the Response:</strong><br>
<em>This is how I am retrieving the error message that is occurring</em></p>
<pre><code>try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response, Encoding.Default))
{
File.AppendAllText(filePath, response.Headers.ToString());
File.AppendAllText(filePath, reader.ReadToEnd());
}
}
}
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
</code></pre>
<p><strong>Error Message being Received:</strong></p>
<blockquote>
<p>The request message must be sent using HTTP compression (RFC 1952 - GZIP).</p>
</blockquote> | 1 |
React Native - Sending events from Native to JavaScript in AppDelegate (iOS) | <p>In my React native app, I am trying to send events from Native Code to JavaScript in the AppDelegate. To do this I call:</p>
<pre><code>[self.bridge.eventDispatcher sendAppEventWithName:@"EventReminder"
body:@{@"name": eventName}];
</code></pre>
<p>In my app delegate. Of course to do this I need to import:</p>
<h1>import "RCTBridge.h"</h1>
<h1>import "RCTEventDispatcher.h"</h1>
<p>and synthesize the bridge</p>
<pre><code>@synthesize bridge = _bridge;
</code></pre>
<p>But event after this, the bridge variable doesn't exist. To make this error go away I made my AppDelegate conform to the RCTBridgeModule protocol like so:</p>
<pre><code>AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeModule>
</code></pre>
<p>And then in my AppDelegate.m, I did:</p>
<pre><code>RCT_EXPORT_MODULE()
</code></pre>
<p>After all that my bridge is finally not erroring, but Everytime I use it in the AppDelegate, it is nil.</p>
<p>Where am I going wrong?</p>
<p>Thanks in advance.</p> | 1 |
How to branch my Visual Studio Online (TFS) Solution? | <p>I have a fairly complex solution in Visual Studio 2015. It's source controlled using Visual Studio Online with TFS as the source control mechanism.</p>
<p>The structure is as follows:</p>
<pre><code>DefaultCollection
Team Project Root
|
----Web Apps Folder
|
----Web Application 1
|
----WebApplication1.csproj
|
----Web Service 1
|
----Web Service 2
|
----Winforms Folder
|
----Winforms App 1
|
----Winforms App 2
|
----Common Files Folder
MySolution.sln
</code></pre>
<p>MySolution.sln is in the Team Project Root, and the solution contains all the various applications within it which are a mixture of web apps, web services and Windows applications.</p>
<p>The problem I have is that I am new to branching and I want to branch the entire solution, but I think that the way my SLN file is in the root will make this difficult?</p>
<p>What I need is to have Web Application 1 branched, and I understand I can branch Web Application 1. But in order to run it I would need to create a new solution file to contain it which would mess things up.</p>
<p>Is there a way I can Branch the entire solution from this scenario, or will I have to try to re-structure things somehow?</p> | 1 |
laravel 5.2 will freak out if table exists when running migrations | <p>I need a work around or a check to see if the table exists.</p>
<p>Situation:</p>
<p>I have a test site and a production site, on the test site I created and ran a task that over time created 25million records. these records were then exported from the test database and imported into the production so I don't have to re-run the task over again. </p>
<p>this allowed me to switch out some the logic to now say, do the same fetch but check to make sure the record doesn't already exist, vastly increeasing the speed of this whole task (the task spawns about 125 ish jobs that do 100 fetches split up into 18 concurrent connections) So this takes a while.</p>
<p>Because of this on production the migration will be like "uh this table exists ... sorry crash time"</p>
<p>So I want to say "if table exists ignore the migration, else run the migration for create"</p>
<p><strong>ideas?</strong></p> | 1 |
WPF DataGrid CheckBox Check/Uncheck with single click | <p>I need check and uncheck of CheckBox using spacebar key in a single click.I tried like below.</p>
<pre><code><my:DataGridTemplateColumn Header="Chk" MinWidth="40">
<my:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Path=SELECT,UpdateSourceTrigger=PropertyChanged}" Name="ChkSelect"
Click="ChkSelect_Click" KeyDown="ChkSelect_KeyDown"/>
</DataTemplate>
</my:DataGridTemplateColumn.CellTemplate>
</my:DataGridTemplateColumn>
</code></pre>
<p>With mouse I am able to check/uncheck in a single click.
But the same thing I am not able to do it with spacebar key.
The key down event is firing only when I press tab key twice.
How to achieve check/uncheck CheckBox in a single click using spacebar key?</p> | 1 |
Jayway is looking up net.minidev classes when Im using Gson | <p>Im using Gson for some Jayway code that Im writing:</p>
<pre><code>private static final Configuration JACKSON_CONFIGURATION = Configuration
.builder()
.mappingProvider(new GsonMappingProvider())
.jsonProvider(new GsonJsonProvider())
.build();
</code></pre>
<p>but when I run it (Trying to apply some criteria for selection of elements inside the JSON), this exception occurred:</p>
<pre><code>Exception in thread "main" java.lang.NoClassDefFoundError: net/minidev/json/writer/JsonReaderI
at com.jayway.jsonpath.internal.DefaultsImpl.<init>(DefaultsImpl.java:17)
at com.jayway.jsonpath.internal.DefaultsImpl.<clinit>(DefaultsImpl.java:15)
at com.jayway.jsonpath.Configuration.getEffectiveDefaults(Configuration.java:48)
at com.jayway.jsonpath.Configuration.access$000(Configuration.java:34)
at com.jayway.jsonpath.Configuration$ConfigurationBuilder.build(Configuration.java:229)
at com.jayway.jsonpath.internal.filter.ValueNode$PathNode.evaluate(ValueNode.java:778)
at com.jayway.jsonpath.internal.filter.RelationalExpressionNode.apply(RelationalExpressionNode.java:37)
at com.jayway.jsonpath.Criteria.apply(Criteria.java:57)
at com.jayway.jsonpath.internal.path.PredicatePathToken.accept(PredicatePathToken.java:75)
at com.jayway.jsonpath.internal.path.PredicatePathToken.evaluate(PredicatePathToken.java:59)
at com.jayway.jsonpath.internal.path.PathToken.handleObjectProperty(PathToken.java:81)
at com.jayway.jsonpath.internal.path.PropertyPathToken.evaluate(PropertyPathToken.java:77)
at com.jayway.jsonpath.internal.path.PathToken.handleArrayIndex(PathToken.java:133)
at com.jayway.jsonpath.internal.path.ArrayPathToken.evaluateIndexOperation(ArrayPathToken.java:63)
at com.jayway.jsonpath.internal.path.ArrayPathToken.evaluate(ArrayPathToken.java:52)
at com.jayway.jsonpath.internal.path.PathToken.handleObjectProperty(PathToken.java:81)
at com.jayway.jsonpath.internal.path.PropertyPathToken.evaluate(PropertyPathToken.java:77)
at com.jayway.jsonpath.internal.path.RootPathToken.evaluate(RootPathToken.java:62)
at com.jayway.jsonpath.internal.path.CompiledPath.evaluate(CompiledPath.java:53)
at com.jayway.jsonpath.internal.path.CompiledPath.evaluate(CompiledPath.java:61)
at com.jayway.jsonpath.JsonPath.read(JsonPath.java:187)
at com.jayway.jsonpath.internal.JsonContext.read(JsonContext.java:164)
at com.jayway.jsonpath.internal.JsonContext.read(JsonContext.java:151)
at com.wfx.wte.Test.fn(Test.java:44)
at com.wfx.wte.Test.main(Test.java:32)
Caused by: java.lang.ClassNotFoundException: net.minidev.json.writer.JsonReaderI
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 25 more
</code></pre>
<p>It seems to be looking up some net.minidev classes. Any clues?</p> | 1 |
Flickering during the transition between views on iOS (ionic framework) | <p>This is the video of the issue: <a href="https://youtu.be/9m1MlaiuZB0" rel="nofollow noreferrer">https://youtu.be/9m1MlaiuZB0</a></p>
<p>On the video you can see that during the transition between tabs there is a strange flickering. This issue occures only when the animation of the transition goes from right to left.</p>
<p>The tabs are custom and implemented as a button-bar in the subheader.</p>
<pre><code>$scope.data.tabs = [
{
title: "Accepted",
state: "events.accepted"
},
{
title: "Pending",
state: "events.pending"
},
{
title: "Declined",
state: "events.declined"
}
];
<ion-view>
.....
<ion-header-bar align-title="center" class="bar bar-subheader event-type-bar">
<div class="button-bar">
<a class="button button-light event-type-bar-button" ng-repeat="tab in data.tabs" tab-state ui-sref="{{tab.state}}">
{{tab.title}}
</a>
</div>
</ion-header-bar>
<ion-nav-view name="events-view"></ion-nav-view>
.....
</ion-view>
</code></pre>
<p>Click on the tab changes the state and loads the new view.</p>
<p>This is my UI-router config for these tabs:</p>
<pre><code> .state('events', {
url: '/events',
abstract: true,
templateUrl: 'views/events/events.html',
controller: 'EventsCtrl'
})
.state('events.accepted', {
url: '/accepted',
views:{
'events-view':{
templateUrl: 'views/events/accepted.html',
controller: 'AcceptedEventsCtrl',
}
}
})
.state('events.pending', {
url: '/pending',
views: {
'events-view': {
templateUrl: 'views/events/pending.html',
controller: 'PendingEventsCtrl',
}
}
})
.state('events.declined', {
url: '/declined',
views: {
'events-view': {
templateUrl: 'views/events/declined.html',
controller: 'DeclinedEventsCtrl',
}
}
})
</code></pre>
<p>I tried to change the direction of the transition with <a href="http://ionicframework.com/docs/api/directive/navDirection/" rel="nofollow noreferrer">nav-direction</a>, but it doesn't help.</p>
<p>As a workaround I disabled the animation during the transitions between nav-views (from <a href="https://stackoverflow.com/questions/29098079/how-to-disable-change-animation-between-views-in-ion-nav-view">there</a>), but it's not the way which I'm looking for.</p>
<p>My ionic configuration:</p>
<ul>
<li>Cordova CLI: 5.3.3 </li>
<li>Ionic Version: 1.1.0 </li>
<li>Ionic CLI Version: 1.7.1</li>
</ul>
<p>By the way, the issue reproduces on the iOS device (iPhone 6) and simulator both, and also in the Chrome Device mode too.</p>
<p>Thanks in advance.</p> | 1 |
How to read multi-level json | <p>So, I know how to read a "single-level" json array. However, I can't figure out how to index the value I want from a multi-level json array.</p>
<p>I have this JSON data:</p>
<pre><code>{
"items": [
{
"snippet": {
"title": "YouTube Developers Live: Embedded Web Player Customization"
}
}
]
}
</code></pre>
<p>I would like to access the value of title, however neither of these access the value, but instead return undefined:</p>
<p><code>console.log(data["items"][0].title);</code></p>
<p>or:</p>
<p><code>console.log(data["items"][0]["title"]);</code></p>
<p>But, this code returns the <code>snippet</code> object:</p>
<p><code>console.log(data["items"][0]);</code></p>
<p>The <code>data</code> variable refers to the json data.</p>
<p>How should I go about this?</p> | 1 |
Fluentd gives the error: Log file is not writable, when starting the server | <p>Here's my td-agent.conf file</p>
<pre><code><source>
@type http
port 8888
</source>
<match whatever.access>
@type file
path /var/log/what.txt
</match>
</code></pre>
<p>But when I try to start the server using</p>
<pre><code>sudo /etc/init.d/td-agent start
</code></pre>
<p>it gives the following error: </p>
<blockquote>
<p>'2016-02-01 10:45:49 +0530 [error]: fluent/supervisor.rb:359:rescue in >main_process: config error file="/etc/td-agent/td-agent.conf" error="out_file: ><code>/var/log/what.txt.20160201_0.log</code> is not writable"</p>
</blockquote>
<p>Can someone explain what's wrong?</p> | 1 |
sklearn.linear_model not found in TensorFlow Udacity course | <p>I'm following the instructions of the Deep Learning course by Google with TensorFlow. Unfortunately I'm stuck <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/1_notmnist.ipynb" rel="nofollow noreferrer" title="here">with this workbook</a> right now.
I work in the docker vm with all the assignment code loaded as described <a href="https://www.udacity.com/course/viewer#!/c-ud730/l-6452084188/m-6560586345" rel="nofollow noreferrer">here</a>.</p>
<p>When I do all the imports everything works except for following line:</p>
<pre><code>from sklearn.linear_model import LogisticRegression
</code></pre>
<p>it throws the following error:</p>
<pre><code>>>> from sklearn.linear_model import LogisticRegression
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named sklearn.linear_model
</code></pre>
<p><a href="https://stackoverflow.com/a/17348144/3695715">This SO answer</a> sounds promising, but I did not find the source directory of sklearn. </p>
<p>Any help greatly aprreciated.</p> | 1 |
Laravel 5.2 App\Http\Controllers\Auth\AuthController@register does not exist | <p>I'm confused, when I use <code>php artisan route:list</code> in <strong>laravel 5.2</strong> I get a bunch of URLs and methods which are executed by visiting the specific url. for example, when I visit laravel.app/register it shows registration form, I can find the controller but not the function(method) called ShowRegistrationForm.
<em>where can I find that <strong>ShowRegistrationForm</strong> ?</em> I just dont see how it works.</p>
<pre><code>| Domain | Method | URI | Name | Action | Middleware |
+--------+----------+-------------------------+------+-----------------------------------------------------------------+------------+
| | GET|HEAD | / | | Closure | |
| | GET|HEAD | articles | | App\Http\Controllers\ArticlesController@index | web |
| | GET|HEAD | articles/create | | App\Http\Controllers\ArticlesController@create | web |
| | POST | articles/store | | App\Http\Controllers\ArticlesController@store | web |
| | PATCH | articles/{id} | | App\Http\Controllers\ArticlesController@update | web |
| | GET|HEAD | articles/{id} | | App\Http\Controllers\ArticlesController@show | web |
| | GET|HEAD | articles/{id}/edit | | App\Http\Controllers\ArticlesController@edit | web |
| | GET|HEAD | home | | App\Http\Controllers\HomeController@index | web,auth |
| | GET|HEAD | login | | App\Http\Controllers\Auth\AuthController@showLoginForm | web,guest |
| | POST | login | | App\Http\Controllers\Auth\AuthController@login | web,guest |
| | GET|HEAD | logout | | App\Http\Controllers\Auth\AuthController@logout | web |
| | POST | password/email | | App\Http\Controllers\Auth\PasswordController@sendResetLinkEmail | web,guest |
| | POST | password/reset | | App\Http\Controllers\Auth\PasswordController@reset | web,guest |
| | GET|HEAD | password/reset/{token?} | | App\Http\Controllers\Auth\PasswordController@showResetForm | web,guest |
| | GET|HEAD | register | | App\Http\Controllers\Auth\AuthController@showRegistrationForm | web,guest |
| | POST | register | | App\Http\Controllers\Auth\AuthController@register | web,guest
</code></pre> | 1 |
Shopping cart save data to database php mysql | <p>I am currently working on saving a data to database using php mysql in shopping cart</p>
<p>cart.php</p>
<pre><code><?php
foreach($_SESSION['cart'] as $product_id => $quantity) {
$sql = sprintf("SELECT prod_name, prod_code, prod_desc, prod_category, prod_price FROM product WHERE prod_id = %d;",
$product_id);
$result = mysql_query($sql);
//Only display the row if there is a product (though there should always be as we have already checked)
if(mysql_num_rows($result) > 0) {
list($name, $code, $description, $category, $price) = mysql_fetch_row($result);
$line_cost = $price * $quantity; //work out the line cost
$total = $total + $line_cost; //add to the total cost
echo "<tr>";
echo "<td align=\"center\">$name</td>";
echo "<td align=\"center\">$code</td>";
echo "<td align=\"center\">$description</td>";
echo "<td align=\"center\">$category</td>";
echo "<td align=\"center\">$quantity</td>";
echo "<td align=\"center\"><a href=\"index.php?page=inso94&action=add&id=$product_id\" class=\"btn btn-info btn-sm btn-fill pull-right\">Add quantity</a></td>";
echo "<td align=\"center\"><a href=\"index.php?page=inso94&action=remove&id=$product_id\" class=\"btn btn-warning btn-sm btn-fill pull-right\">Reduce</a></td>";
echo "<td align=\"center\">$price</td>";
echo "<td align=\"center\">$line_cost</td>";
echo "</tr>";
}
}
echo "<tr>";
echo "<td colspan=\"0\" align=\"left\"> <a href=\"index.php?page=inso94&action=empty\" class=\"btn btn-danger btn-sm btn-fill pull-right\">Empty Cart</a></td>";
echo "<td colspan=\"7\" align=\"right\">Total</td>";
echo "<td align=\"right\"><b>$total</b></td>";
echo "</tr>";
echo "<tr>";
echo "<td align=\"left\" colspan=\"9\">Note: If quantity becomes <b>'0'</b> it will automatically remove.</td>";
echo "</tr>";
echo "</table>";
?>
*<?php
if (isset($_POST['submit'])){
$orderid=mysql_insert_id();
$max=count($_SESSION['cart']);
for($i=0;$i<$max;$i++){
$pid=$_SESSION['cart'][$i]['productid'];
$q=$_SESSION['cart'][$i]['quantity'];
$total;
mysql_query("insert into order_detail values ($orderid,$pid,$q,$total)");
}
}
?>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
<button type="submit" name="submit" class="btn btn-info btn-sm btn-fill pull-right" id="checkout">Buy Now</button>
</form>*
</code></pre>
<p>I want to save the data in to my database using a form .please help me, this is my last problem that i want to solve.</p> | 1 |
How to upload a json file with secret keys to Heroku | <p>I'm building a rails app that pulls data from Google Analytics using the Google Api Client Library for Ruby.</p>
<p>I'm using OAuth2 and can get everything working in development on a local machine. My issue is that the library uses a downloaded file, <code>client_secrets.json</code>, to store two secret keys.</p>
<p><strong>Problem:I'm using Heroku and need a way to get the file to their production servers.</strong> </p>
<p>I don't want to add this file to my github repo as the project is public. </p>
<p>If there is a way to temporarily add the file to git, push to Heroku, and remove from git that would be fine. My sense is that the keys will be in the commits and very hard to prevent from showing on github. </p>
<p><strong>Tried:</strong>
As far I can tell you cannot SCP a file to Heroku via a Bash console. I believe when doing this you get a new Dyno and anything you add would be only be temporary. I tried this but couldn't get SCP to work properly, so not 100% sure about this.</p>
<p><strong>Tried:</strong>
I looked at storing the JSON file in an Environment or Config Var, but couldn't get it to work. This seems like the best way to go if anyone has a thought. I often run into trouble when ruby converts JSON into a string or hash, so possibly I just need guidance here. </p>
<p><strong>Tried:</strong>
Additionally I've tried to figure out a way to just pull out the keys from the JSON file, put them into Config Vars, and add the JSON file to git. I can't figure out a way to put <code>ENV["KEY"]</code> in a JSON file though. </p>
<hr>
<p><strong>Example Code</strong>
The <a href="https://developers.google.com/api-client-library/ruby/auth/web-app" rel="noreferrer">Google library has a method</a> that loads the JSON file to create an authorization client. The client then fetches a token (or gives a authorization url).</p>
<pre><code>client_secrets = Google::APIClient::ClientSecrets.load('client_secrets.json')
auth_client = client_secrets.to_authorization
</code></pre>
<p>** note that the example on google page doesn't show a filename because it uses a default ENV Var thats been set to a path</p>
<p>I figure this would all be a lot easier if the <code>ClientSecrets.load()</code> method would just take JSON, a string or a hash which could go into a Config Var. </p>
<p>Unfortunately it always seems to want a file path. When I feed it JSON, a string or hash, it blows up. <a href="http://ar.zu.my/how-to-store-private-key-files-in-heroku/" rel="noreferrer">I've seen someone get around the issue with a p12 key here</a>, but I'm not sure how to replicate that in my situation. </p>
<p><strong>Haven't Tried:</strong>
My only other though (aside from moving to AWS) is to put the JSON file on AWS and have rails pull it when needed. I'm not sure if this can be done on the fly or if the file would need to be pulled down when the rails server boots up. Seems like too much work, but at this point I've spend a few hours on it so ready to attempt. </p>
<p>This is the specific controller I am working on:
<a href="https://github.com/dladowitz/slapafy/blob/master/app/controllers/welcome_controller.rb" rel="noreferrer">https://github.com/dladowitz/slapafy/blob/master/app/controllers/welcome_controller.rb</a></p> | 1 |
Pandas assign value of one column based on another | <p>Given the following data frame:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(
{'A':[10,20,30,40,50,60],
'B':[1,2,1,4,5,4]
})
df
A B
0 10 1
1 20 2
2 30 1
3 40 4
4 50 5
5 60 4
</code></pre>
<p>I would like a new column 'C' to have values be equal to those in 'A' where the corresponding values for 'B' are less than 3 else 0.
The desired result is as follows:</p>
<pre><code> A B C
0 10 1 10
1 20 2 20
2 30 1 30
3 40 4 0
4 50 5 0
5 60 4 0
</code></pre>
<p>Thanks in advance!</p> | 1 |
pass razor variable to angular function | <p>razor code <br/>
<code>@{string razorVar= "test";}</code></p>
<p>HTML<br/>
<code><div ng-class="{active:vm.testSelected(@razorVar)}"> ...</div></code></p>
<p>angular controller function <br/>
<code>vm.testSelected = function(jsVar) {
return jsVar== 'test';
}</code></p>
<p><code>jsVar</code> is always <code>undefined</code></p>
<p><strong>Question</strong><br/>
What is the correct way to pass this <code>razorVar</code> to my function? (I do not want to use an ng-init)</p> | 1 |
Allowing for multiple modals in Vue.js | <p>Following the demo on the official site (<a href="http://vuejs.org/examples/modal.html" rel="nofollow">http://vuejs.org/examples/modal.html</a>)</p>
<p>I'm trying to set this up so that I can define multiple modal windows on a page, like this </p>
<p><a href="http://jsfiddle.net/m2sv4at5/" rel="nofollow">http://jsfiddle.net/m2sv4at5/</a></p>
<p>But since <code>modals['foo']</code> and <code>modals['bar']</code> aren't defined, Vue is throwing warnings that it's getting invalid types being sent into the prop. As soon as I initialize the script with <code>false</code> for both, it works, but that requires me to hard-code those modal names into the script, which is what I don't want.</p>
<p>In jQuery I would do this by defining a data target and simply making sure that matches an element with the right ID and a class of <code>modal</code>, but I'm unsure how to do something similar in Vue.</p> | 1 |
Extract city and ZIP code from a string | <p>I have a JavaScript string of the format:</p>
<pre><code>"New York City, New York 10024, United States"
</code></pre>
<p>The String contains city, state, ZIP code, and country information. I'm trying to fetch only the city name and ZIP code from the string but currently only being able to fetch the city name from the string.</p>
<p><strong>JavaScript Code</strong>:</p>
<pre><code>var sampleLocation = "New York City, New York 10024, United States";
var resLocation = sampleLocation.split(",");
console.log(resLocation);
console.log(resLocation[0].replace( /,/g, "" ));
</code></pre>
<p><strong>Output</strong>:</p>
<pre><code>["New York City", " New York 10024", " United States"]
New York City
</code></pre>
<p>I can't figure out how to extract the city and ZIP code efficiently. Is there a way to select the last six characters of an array element?</p> | 1 |
Web Api ASP.NET Custom Authentication | <p>I have a Web Api that returns basic info about a company's info. The login information is validated with their DB (this is used for an Desktop App) but with AngularJS im only ask to the API for Username and Password. How i can implement an authentication system (like the default on Visual Studio) on this with their users and passwords? Is possible to use something like Token? Can you help me? Thanks a lot. </p>
<p><strong>[EDIT 1]</strong></p>
<p>By the way, this webapi uses an old foxpro DB to manage the users and password. So if i gone to use the authentication system, i don't know how to use de database context with this type of old DB.</p> | 1 |
Is there a way to reference the Java class for a Kotlin top-level function? | <p>I want to load a resource in a top level function using <code>Class.getResourceAsStream()</code>.</p>
<p>Is there any way to get a reference to the class that the top level function will be compiled into so that I can write, for example</p>
<pre><code>val myThing = readFromStream(MYCLASS.getResourceAsStream(...))
</code></pre> | 1 |
Difference between database level trigger and server level trigger in SQL Server | <p>Can anyone please tell me the difference between database level trigger and server level trigger in SQL Server ? </p>
<p>Thanks in advance.</p> | 1 |
I want to get the image data from a stream in Xamarin Forms using XLABS | <p>I am trying to get the raw image data from a stream and I am not sure where to go from here. I have a viewmodel and a page where I use the function where I select a picture from a gallery using XLABS.</p>
<p>My viewmodel:</p>
<pre><code>public ImageSource ImageSource
{
get { return _ImageSource; }
set { SetProperty (ref _ImageSource, value); }
}
private byte[] imageData;
public byte[] ImageData { get { return imageData; } }
private byte[] ReadStream(Stream input)
{
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
public async Task SelectPicture()
{
Setup ();
ImageSource = null;
try
{
var mediaFile = await _Mediapicker.SelectPhotoAsync(new CameraMediaStorageOptions
{
DefaultCamera = CameraDevice.Front,
MaxPixelDimension = 400
});
VideoInfo = mediaFile.Path;
ImageSource = ImageSource.FromStream(() => mediaFile.Source);
}
catch (System.Exception ex)
{
Status = ex.Message;
}
}
private static double ConvertBytesToMegabytes(long bytes)
{
double rtn_value = (bytes / 1024f) / 1024f;
return rtn_value;
}
</code></pre>
<p>The page where I use the code:</p>
<pre><code>MyViewModel photoGallery = null;
photoGallery = new MyViewModel ();
private async void btnPickPicture_Clicked (object sender, EventArgs e)
{
await photoGallery.SelectPicture ();
imgPicked.Source = photoGallery.ImageSource; //imgPicked is my image x:name from XAML.
}
</code></pre> | 1 |
Case Insensitive Compare with Core Data and Swift | <p>The following code doesn't work:</p>
<pre><code>let sortDescriptor = NSSortDescriptor(key: "name", ascending: true, selector:"caseInsensitiveCompare")
</code></pre>
<p>And gives the following error:
'NSInvalidArgumentException', reason: 'unsupported NSSortDescriptor selector: caseInsensitiveCompare'</p>
<p>Seemed to work fine in Objective-C. Any ideas on why this might be?</p>
<p>Edit: seems like this may not be possible with Core Data/SQLite. In that case, is the best option to get the array and sort it in code afterwards?</p> | 1 |
Kartik/Krajee Select2 not disabled | <p>Setting Select to to 'disabled' does not disable the element. The user can still click on the text of Select2 and the options box opens up. Here is a disabled control that was opened by clicking on the text and not the down-arrow button.</p>
<p><a href="https://i.stack.imgur.com/AYagr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AYagr.png" alt="Disabled Control:"></a></p>
<p>Here is my code:</p>
<pre><code><?= $form->field($model, 'billing_currency_id')->widget(Select2::className(), [
'data' => BillingCurrency::listIdCodes('','',true),
'disabled' => true,
'options' => ['disabled' => true,],
'pluginOptions'=>[
'allowClear'=>false,
'dropdownAutoWidth'=>true,
'disabled' => true,
], ]); ?>
</code></pre>
<p>Clicking on the down-arrow button keeps the control closed, but clicking on the text area of the control opens the options box.</p>
<p><strong>UPDATE</strong>
Found my own mistake - see answer below.</p> | 1 |
export array as Component prop using React | <p>I am wondering if there is a way to have an array of React elements in one file and then export that for import into another file with props? Something like...</p>
<pre><code>import MenuItem from 'material-ui/lib/menus/menu-item';
exports.menuItems = [
<MenuItem primaryText='Make glue' onTouchTap={this.props.makeGlue}/>, //<-- I am guessing props cannot be passed like this???
<MenuItem primaryText='Make more sticky glue'/>
]
</code></pre>
<p>... and then import menuItems into another file as a child of another component? I would like to keep various arrays of different menuIems in one file and import them into others as needed. Any thoughts or ideas? I untimately prefer to have server arrays of different menuItems exported from a single file if that's possible.</p>
<p>TIA!</p> | 1 |
How to test a resource with OAuth2 and Mock | <p>I am using Jhipster with Oauth2 implementation and mongodb as a database.
I am trying to test a resource with OAuth2. But I got always an error message "Access Denied" and status code 401. I am looking for an JUnit example with OAuth2. Thank you!</p>
<p>Manuel</p>
<pre><code> /**
* Test class for the InvoiceResource REST controller.
*
* @see InvoiceResource
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest
public class InvoiceResourceIntTest {
...
private MockMvc restInvoiceMockMvcWebApp;
@PostConstruct
public void setup() {
MockitoAnnotations.initMocks(this);
this.restInvoiceMockMvcWebApp = MockMvcBuilders.webAppContextSetup(context).alwaysDo(MockMvcResultHandlers.print())
.apply(SecurityMockMvcConfigurers.springSecurity()).build();
}
@Before
public void initTest() {
// Create currentuser
currentUser = new User();
currentUser.setActivated(CURRENTUSER_ACTIVATED);
currentUser.setFirstName(CURRENTUSER_FIRSTNAME);
currentUser.setLastName(CURRENTUSER_LASTNAME);
currentUser.setEmail(CURRENTUSER_EMAIL);
Set<Authority> authorities = new HashSet<>();
Authority authority = new Authority();
authority.setName(AuthoritiesConstants.ADMIN);
currentUser.setAuthorities(authorities);
currentUser.setPassword(passwordEncoder.encode(CURRENTUSER_PASSWORD));
userRepository.save(currentUser);
}
@Test
// @WithMockUser(username = CURRENTUSER_EMAIL, password = CURRENTUSER_PASSWORD, roles = { "ADMIN" })
public void getAllInvoices() throws Exception {
// Initialize the database
invoice.setDeletedAt(LocalDate.now());
invoiceRepository.save(invoice);
invoice.setId(null);
invoice.setDeletedAt(null);
invoiceRepository.save(invoice);
// Get all the invoices
restInvoiceMockMvcWebApp.perform(get("/api/invoicessort=id,desc")
.with(user(CURRENTUSER_EMAIL).password(CURRENTUSER_PASSWORD.roles("ADMIN")))
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(jsonPath("$", hasSize(1)))
}
</code></pre> | 1 |
PHPstorm FTP can't upload files | <p>Im trying to configure my PHPstorm with FTP so after a file is saved, it needs to be uploaded to the host. I can connect (i did the test) but i can't upload a file unless i change the file permission to 777 of my file. Any idea how this is possible? Here is the error:</p>
<pre><code>[31/01/16 17:11] Failed to transfer file '/Applications/XAMPP/xamppfiles/htdocs/yventure.nl/app/Http/Controllers/Website/HomeController.php': cant open output connection for file "ftp://mm.server/app/Http/Controllers/Website/HomeController.php". Reason: "550 app/Http/Controllers/Website/HomeController.php: Permission denied".
[31/01/16 17:11] Automatic upload completed in less than a minute: 1 item failed
</code></pre>
<p>EDIT: i've enabled passive mode already</p> | 1 |
https before address shows only files in private_html folder on host | <p>when i try my webpage address with https, page shows only files in the private_html folder not public_html.
but my website runs in the public_html. for example i use an index.html file (including forwarder script) and when you type <a href="https://alirezah.net" rel="nofollow">https://alirezah.net</a> it redirects to <a href="http://alirezah.net" rel="nofollow">http://alirezah.net</a>.
how can i fix it? I wanna use cloudflare ssl service but this happens.
I tried to edit htaccess but it doesn't help</p> | 1 |
Are there alternative UIs for Swagger files | <p>We are currently using <code>Postman</code> for building and testing our REST endpoints. There are some serious drawbacks in their product when it comes to sharing a collection. Basically you can't use source control for the document because it changes all the guids in json file when you import.</p>
<p>So we're looking at possibly switching to <code>Swagger</code>, the issue with Swagger is that <code>SwaggerUI</code> isn't very user friendly. We like that Postman gives you the ability to break up your collections into folders, and gives you a split screen where you can run a request and see the output.</p>
<p>Are there any third party tools which give a <code>Postman</code> style interface to <code>Swagger</code> files? i.e. easy to find a set of methods for a resource, and to make calls to it.</p> | 1 |
Web API 2 - Return Pdf, Show/Download Received Pdf File on Client (AngularJs) | <p>This is the code in my Web API 2 controller: </p>
<pre><code>//pdfBytes is a valid set of...pdfBytes, how it's generated is irrelevant
Byte[] pdfBytes = pdfConverter.GeneratePdf(myPdfString);
//using HttpResponseMessage instead of IHttpActionResult here because I read
//that the latter can cause problems in this scenario
var response = new HttpResponseMessage();
//Set reponse content to my PDF bytes
response.Content = new ByteArrayContent(pdfBytes);
//Specify content type as PDF - not sure if this is necessary
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
</code></pre>
<p>How do I trigger the browser to automatically download the PDF or open it in a new window once I have received the PDF on the client? (Note - I am not sure if byte array is the format I want to receive here).</p>
<pre><code>callToGetPdfFromDb()
.success(function (pdfFromWebApi) {
console.log('Got pdf...'');
//How do I show the received PDF to the user?
});
</code></pre>
<p>I am pretty new to working with any sort of file downloads/uploads, so I apologize if I am missing something very basic. I am perfectly happy with pointers in the right direction as a response. </p> | 1 |
Vue.js limit selected checkboxes to 5 | <p>I need to limit number of selected checkboxes to 5.
I tried using :disabled like here:</p>
<pre><code> <ul>
<li v-for="item in providers">
<input type="checkbox"
value="{{item.id}}"
id="{{item.id}}"
v-model="selected_providers"
:disabled="limit_reached"
>
</li>
</ul>
</code></pre>
<p>And then:</p>
<pre><code>new Vue({
el: '#app',
computed:{
limit_reached: function(){
if(this.selected_providers.length > 5){
return true;
}
return false;
}
}
})
</code></pre>
<p>This kind of works, but when it reaches 5, all of the check boxes are disabled and you can't uncheck the ones you don't want.</p>
<p>I also tried to splice the array with timeout of 1 ms, which works but feels hacky.
Can anyone recommend anything please?</p> | 1 |
RSpec: How to test instance variable | <p>How Can I test @comments, @seller_items instance variables in my <strong>UsersController:</strong></p>
<pre><code>def show
@comments = @user.comments.hash_tree
@comment = @user.comments.build(parent_id: params[:parent_id])
@seller_items = User.seller_list(current_user)
end
</code></pre>
<p>Part of RSpec <strong>test:</strong></p>
<pre><code> context "User logged in" do
let(:user) { create(:user) }
let(:user2) { create(:user) }
let(:comment) { create(:comment, user: user) }
before { sign_in(user) }
describe "GET #show" do
it "assigns @user" do
get :show, id: user
expect(assigns(:user)).to eq(user)
end
it "assigns new comment" do
get :show, id: user
expect(assigns(:comment)).to be_instance_of(Comment)
end
it "redirect_to :show view" do
get :show, id: user
expect(response).to render_template :show
end
end
end
</code></pre> | 1 |
Creating a testing infrastructure with Pytest , Selenium Grid and Docker | <p>Based on this <a href="http://www.conductor.com/nightlight/running-selenium-grid-using-docker-compose/" rel="nofollow">article</a>, I successfully created the scalable selenium grid .
Then I want to run my test suites [written in Python] using Pytest into that Grid.</p>
<p>I am new to Docker and trying to find the best way to migrate my testing procedures into the microservices architecture. Essentially I want to give the ability to the devs to setup a full testing infrastructure locally on their PCs.</p>
<p>So, I have 4 <em>Dockerfiles</em> and 1 <em>docker-compose.yml</em> .</p>
<p>The BASE dockerfile:</p>
<pre><code>FROM ubuntu
ENV SEL_VERSION 2.44.0
# Update repos for Java
RUN apt-get update -qqy \
&& apt-get -qqy --no-install-recommends install \
software-properties-common \
&& rm -rf /var/lib/apt/lists/*
RUN add-apt-repository -y ppa:webupd8team/java
RUN echo debconf shared/accepted-oracle-license-v1-1 select true | debconf-set-selections
RUN echo debconf shared/accepted-oracle-license-v1-1 seen true | debconf-set-selections
# Install Java7
RUN apt-get update -qqy \
&& apt-get -qqy --no-install-recommends install \
oracle-java7-installer \
&& rm -rf /var/lib/apt/lists/*
# Download Selenium Server
RUN wget http://selenium-release.storage.googleapis.com/${SEL_VERSION%.*}/selenium-server-standalone-${SEL_VERSION}.jar
</code></pre>
<p>The HUB dockerfile :</p>
<pre><code>FROM org/grid:base
EXPOSE 4444
# Add and set permissions to the script that will launch the hub
ADD register-hub.sh /var/register-hub.sh
RUN chmod 755 /var/register-hub.sh
# start a shell and run the script
#WORKDIR /
CMD ["/bin/bash", "/var/register-hub.sh"]
</code></pre>
<p>The NODE dockerfile :</p>
<pre><code>FROM org/grid:base
# set the FF version to use
ENV FIREFOX_MINOR 34.0.5
# Update and install what's needed
RUN apt-get update -qqy \
&& apt-get -qqy --no-install-recommends install \
firefox \
xvfb \
bzip2 \
&& rm -rf /var/lib/apt/lists/*
# setup FF
RUN [ -e /usr/bin/firefox ] && rm /usr/bin/firefox
ADD https://ftp.mozilla.org/pub/mozilla.org/firefox/releases/${FIREFOX_MINOR}/linux-x86_64/en-US/firefox-${FIREFOX_MINOR}.tar.bz2 /tmp/
RUN apt-get install -q -y libdbus-glib-1-2
RUN tar -xvjf /tmp/firefox-${FIREFOX_MINOR}.tar.bz2 -C /opt/
RUN chmod -R +x /opt/firefox/
RUN ln -s /opt/firefox/firefox /usr/bin/firefox
# add and set permissions for the bash script to register the node
ADD register-node.sh /var/register-node.sh
RUN chmod 755 /var/register-node.sh
# start a shell and run the script
CMD ["/bin/bash", "/var/register-node.sh"]
</code></pre>
<p>And the PYTEST dockerfile :</p>
<pre><code># Starting from base image
FROM ubuntu
# Set the Github personal token [to clone the QA code]
#todo------secret------
ENV GH_TOKEN some_token_some_token_some_token_
# Install Python & pip
RUN apt-get update
RUN apt-get upgrade -y
RUN apt-get install -y python python-pip python-dev && pip install --upgrade pip
# Install GIT
RUN apt-get update -y && apt-get install git -y
# [in the / folder] Create the folder and add the whole project from the repo to the container
RUN git clone https://$GH_TOKEN:[email protected]/org/org_QA.git /org_QA_folder
# Install dependencies via pip
WORKDIR /org_QA_folder
RUN pip install -r dependencies.txt
#
CMD /bin/bash
</code></pre>
<p>And the docker-compose file :</p>
<pre><code>hub:
image: org/grid:hub # image must already exist
ports:
- "4444:4444" # HOST:CONTAINER
external_links: # link to a container created outside of this YAML file
- pytest
volumes_from:
- pytest # must be created first
firefox:
image: org/grid:nodeff # image must already exist
links:
- hub
expose:
- "5555" # grid console open to public
</code></pre>
<p>So...I cannot understand how should I run something like "py.test /org_QA_folder/testcase.py" and run on the grid [essentially the node].</p>
<p>I first run the pytest container with
<code>docker run -dit -v /org_QA_folder --name pytest schoox/grid:py</code> and the other services with <code>docker-compose up -d</code> .</p>
<p>I tried multiple approaches:</p>
<ol>
<li><p>Not use a Pytest container but clone the code in the hub. But in this case , HUB container runs the hub of the grid [one CMD per container directive] . <strong>[EDIT: I chose the microservices architecture as Docker suggests]</strong></p></li>
<li><p>I leave the hub and node containers to run their specified services, and create a separate container [pytest] to send the tests from there. But the test wont run cause this container does not have xvfb.<strong>[EDIT: I just installed xvfb and worked]</strong> </p></li>
<li><p>I tried to use the pytest container as volume for the hub but remains the problem of running the tests from the hub container that already has a service running.<strong>[EDIT: For dev purposes I mount the code from the pytest container and use its console to test stuff on the other containers. After that I will use the pytest container to have the code separate]</strong></p></li>
</ol>
<p>Should I install all the packages ,that node container has, in the other containers? Ideally I want to use the pytest container console [to develop the infrastructure at least] to run the tests which will be sent to hub and run to many nodes.<strong>[EDIT: I didn't mingled with the hub and node, I just installed xvfb on pytest container]</strong></p>
<p>How would you suggest to do that? Am I missing something ? </p>
<p><strong>EDIT [steps towards solution]:</strong></p>
<p>I first start the pytest container [<code>docker run -dit -v /org/org_QA_folder --name pytest org/grid:py</code>] and then I run <code>docker-compose up -d</code> to launch the grid</p>
<p>In the compose file I use <code>external_links</code> and <code>volumes_from</code> for dev purposes. I wont work from inside any container when the setup is finished.</p>
<p>I changed the Pytest dockerfile and added this:</p>
<pre><code># Install xvfb [THAT WAS NEEDED!!!!!]
RUN apt-get install -y xvfb
</code></pre>
<p>I run one of my tests ,from inside the pytest container, to my already running Grid[on an EC2 instance] as a proof of concept and worked fine. It remains to send it to the dockerized grid. </p> | 1 |
How do I narrow down scope when running an ansible playbook? | <p>I have a playbook that takes a lot of time to execute, partly due to having a lot of nodes on which it has to run on (I am wasting time with ansible checking the status of all the nodes), and I need to make some changes somewhere in the middle of it.</p>
<p>What would be the best way in which I could narrow down the scope of the playbook? I've considered isolating the required change and/or just running the modified part on a single node?</p> | 1 |
TripleDESCryptoServiceProvider Specified key is not a valid size for this algorithm at 128 bytes? | <p>I'm trying to update my encrypt decrypt function from DES to TripleDES.
However, when I try to increase my key and iv byte array size from 8 to 128:</p>
<pre><code>byte[] key = new byte[128], iv = new byte[128];
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
</code></pre>
<p>Where 8 was used for DESCryptoServiceProvider and 128 is now used for TripleDESCryptoServiceProvider I always get the same error:</p>
<pre><code>Specified key is not a valid size for this algorithm.
</code></pre>
<p>Even though my byte arrays are complete filled in.</p>
<p>What am I doing wrong? Is there any requirement besides the length to allow my key and iv to be used to create an Encryptor?</p> | 1 |
Jquery Select 2 not showing selected value | <p>Select2 plugin is not showing selected option with templateFormat option
Anyone knows how fix it ?</p>
<p>markup:</p>
<pre><code><select id="plans" style="width: 75%">
<option value="1" name="text1" price="$1" saving="text" selected="selected"></option>
<option value="2" name="text2" price="$2" saving="text" selected="selected"></option>
</code></pre>
<p></p>
<p>js:</p>
<pre><code>$(document).ready(function() {
$('select#plans').select2({
minimumResultsForSearch: Infinity,
templateResult: formatState
});
});
function formatState(state) {
if (!state.id) return state.text;
var html = '<span class="name">' + state.element.attributes.name.value + "</span>"
html += '<span class="price">' + state.element.attributes.price.value + </span>"
html += '<span class="saving">' + state.element.attributes.saving.value + "</span>"
var $state = $(html);
return $state
}
</code></pre>
<p>here is a <a href="https://jsfiddle.net/ed0pL2sd/" rel="nofollow">fiddle</a> of the above code</p>
<p>Thank you</p> | 1 |
Has anyone successfully used Azure AD to authenticate users for a Node.js web application? | <p>I am attempting to use Azure Active Directory to authenticate users for my node.js web application, so far with no luck.</p>
<p>I am wondering if anyone has actually ever achieved it since the documentation is quite poor. There is typically example code, but not really any indication of what the required parameters are and what they should be.</p>
<p>I have tried passport-azure-ad (which I think is from Microsoft) and passport.azure-ad-oauth2 (which is from Auth0(?)). For passport-azure-ad, I have tried the BearerStrategy and also the OIDCStrategy with no luck.</p>
<p>For BearerStrategy I get some cryptic message about my client and resource identifying the same application, but since there is no documentation telling me what those should be, I'm at a loss.</p>
<p>For the OIDCStrategy, I'm a bit closer in that I get redirected to Microsoft for authentication, but on return I get the error "Error: ID Token not present in response". I'm guessing that my request isn't correct enough to give me a token back for whatever reason, but since there is no documentation...(you get the idea). </p>
<p>Anyway, if anyone has actually successfully achieved it and is able to share some pointers as to how it was achieved, that would be great.</p>
<p>Many thanks.</p> | 1 |
How to exclude certain files while creating war file using jar command? | <p>I am using command <code>jar cvf MyWarFile.war <list all files and dir to be part of war file with space in between></code> to create a war file in linux. I don't want to specify each and every file/dir in the command rather I just want to use * (to create war file out of files in current dir) . What should I do to exclude certain file/dir while trying add all the files (using *) in the directory to the war file that i am creating. </p>
<p>I am looking for something like </p>
<pre><code>jar cvf MyWarFile.war * <how to exclude certain file/dir>
</code></pre> | 1 |
Twitter share link mobile issue | <p>I'm creating a Twitter share link. It works fine on desktop but for mobile its behaving differently.</p>
<p>Here is the Twitter share link</p>
<pre class="lang-html prettyprint-override"><code><a href="https://twitter.com/home?status=this%20a%20is%20a%20test" target="_blank"><svg class="twitter social_icon--twitter" ><use xlink:href="#icon-twitter"></use></svg></a>
</code></pre>
<p>It's just opening up the site without pre-filling the content.</p>
<p>Any ideas of possible fix, workaround or explanation.</p> | 1 |
Using Select2 (multiple selections) with vue.js | <p>I'm new to vue and have followed their 'custom directive' at <a href="http://vuejs.org/examples/select2.html" rel="nofollow">http://vuejs.org/examples/select2.html</a>. </p>
<p>This works well when only selecting one item, but when you're selecting multiple items it only passes the first one. I need it to pass all values selected.</p>
<p>I have a jsfiddle set up displaying the code which is available here.
<a href="https://jsfiddle.net/f3kd6f14/1/" rel="nofollow"></a><a href="https://jsfiddle.net/f3kd6f14/1/" rel="nofollow">https://jsfiddle.net/f3kd6f14/1/</a></p>
<p>The directive is as below;</p>
<pre><code> Vue.directive('select', {
twoWay: true,
priority: 1000,
params: ['options'],
bind: function() {
var self = this
$(this.el)
.select2({
data: this.params.options
})
.on('change', function() {
self.set(this.value)
})
},
update: function(value) {
$(this.el).val(value).trigger('change')
},
unbind: function() {
$(this.el).off().select2('destroy')
}
</code></pre>
<p>Any help would be appreciated.</p> | 1 |
How do I remove commas from an array of strings | <p>I have a list of arrays as so:</p>
<pre><code>0: "1 Trenchard Road, , , , Saltford, Bristol, Avon"
1: "10 Trenchard Road, , , , Saltford, Bristol, Avon"
2: "11 Trenchard Road, , , , Saltford, Bristol, Avon"
3: "12 Trenchard Road, , , , Saltford, Bristol, Avon"
</code></pre>
<p>And I want to remove the commas in the middle:</p>
<pre><code> , , ,
</code></pre>
<p>I am using Lodash and looked at using <code>_.compact()</code> however this doesn't seem to be getting me anywhere.</p>
<p>Let me know your thoughts</p>
<p>Update </p>
<pre><code> var addressArray = getAddressData.data.Addresses;
scope.items = _.compact(addressArray);
console.log(scope.items);
</code></pre> | 1 |
Make a CollectionViewCell bounce on highlight in Swift | <p>For the past couple of hours I have tried to accomplish the following:</p>
<p>In a UICollectionview when I highlight (touch down) a cell I want it to bounce inward a few pixels (to a smaller size) and on release bounce back to the original size.</p>
<p>Here is what I have tried so far:</p>
<pre><code>override func collectionView(collectionView: UICollectionView,
didHighlightItemAtIndexPath indexPath: NSIndexPath) {
collectionView.collectionViewLayout.invalidateLayout()
let cell = collectionView.cellForItemAtIndexPath(indexPath)
UIView.transitionWithView(cell!, duration: 1, options: UIViewAnimationOptions.CurveEaseIn, animations: {
let center = cell?.center
let frame2 = CGRect(x: 0, y: 0, width: 50, height: 50)
cell?.frame = frame2
cell?.center = center!
}, completion: nil)
}
</code></pre>
<p>(I have found much of this code example from this question:
<a href="https://stackoverflow.com/questions/13780153/uicollectionview-animate-cell-size-change-on-selection">UICollectionView: Animate cell size change on selection</a> but this is applied on cell selection. Not highlight.
)</p>
<p>So in the didHighlightItemAtIndexPath I set the highlighted cell to a new size. The size is set correct but the following problems arise:
1: it does not animate,
2: it moves to position (0,0) and animate back to center position. It should not move position at all - just the size.</p>
<p>I have seen this effect in the Shazam app for reference. It can be seen when you shazam a song (or view a previously shazamed song) on the buttons below the song name. </p> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.