title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
React-Native full box around text-input
|
<p>The default component for TextInput creates a box that goes around the bottom and up the sides, how do I change it to make it go all the way around the text field?</p>
| 2 |
Is it possible to register custom helpers in Ghost?
|
<p>I am using Ghost as an npm module following <a href="https://github.com/TryGhost/Ghost/wiki/Using-Ghost-as-an-npm-module" rel="nofollow noreferrer">this guide</a>.</p>
<p>I would like to add some custom helpers that I can leverage inside of my themes. Is there a way to do this without changing code inside the Ghost module?</p>
<p>This is my current code:</p>
<pre><code>const ghost = require('ghost');
const path = require('path');
const hbs = require('express-hbs');
const config = path.join(__dirname, 'config.js');
const coreHelpers = {};
coreHelpers.sd_nls = require('./sd_nls');
// Register a handlebars helper for themes
function registerThemeHelper(name, fn) {
hbs.registerHelper(name, fn);
}
registerThemeHelper('sd_nls', coreHelpers.sd_nls);
ghost({ config: config })
.then(ghostServer => ghostServer.start());
</code></pre>
<p>I think one possible problem is that my <code>hbs</code> is a new handlebars instance, not the same one used by Ghost, therefore when Ghost runs it doesn't include any helpers I've registered. </p>
| 2 |
I want to change button background color dynamically in based on collection using Wpf?
|
<p>Student:</p>
<pre><code>public class Student
{
private int _studentNo;
public int StudentNo
{
get { return _studentNo; }
set { _studentNo = value; }
}
private Rank _state;
public Rank State
{
get { return _state; }
set { _state = value; }
}
}
</code></pre>
<p>Rank:</p>
<pre><code>public enum Rank
{
Pass,
Fail
}
</code></pre>
<p>RankBoard:</p>
<pre><code>public class RankBoard
{
private static ObservableCollection<Student> _studentList;
public static ObservableCollection<Student> StudentList
{
get { return _studentList; }
set { _studentList = value; }
}
public RankBoard()
{
LoadDetails();
}
private void LoadDetails()
{
StudentList = new ObservableCollection<Student>()
{
new Student()
{
StudentNo=1,
State=Rank.Pass
},
new Student()
{
StudentNo=2,
State=Rank.Fail
},
new Student()
{
StudentNo=3,
State=Rank.Pass
},
};
}
}
</code></pre>
<p>BackgroundChangedConvertor:</p>
<pre><code>public class BackgroundChange : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var b = value as Button;
if(b!=null)
{
foreach (var x in RankBoard.StudentList)
{
if ((System.Convert.ToInt32(b.Content)==x.StudentNo)&&((x.State.ToString()=="Pass")))
{
return new SolidColorBrush(Colors.Green);
}
else
{
return new SolidColorBrush(Colors.Red);
}
}
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
</code></pre>
<p>MainWindow.xaml</p>
<pre><code> <Window x:Class="ButtonColorChanged.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ButtonColorChanged"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:BackgroundChange x:Key="Color"/>
</Window.Resources>
<Grid>
<StackPanel VerticalAlignment="Center">
<Button x:Name="btn1" Content="1" Width="75" Height="25" Background="{Binding Converter={StaticResource Color}}"/>
<Button x:Name="btn2" Content="2" Width="75" Height="25" Margin="0 20 0 20" Background="{Binding Converter={StaticResource Color}}"/>
<Button x:Name="btn3" Content="3" Width="75" Height="25" Background="{Binding Converter={StaticResource Color}}"/>
</StackPanel>
</Grid>
</Window>
</code></pre>
<p>I tried to change button background color depends upon to State(Pass or Fail) in Collection. but i Run this progrom object value throw null value in BackgroundChange class. so Button background color doesn't affect.? How do i do it.? </p>
| 2 |
Ghost items in javafx ListView with custom ListCell
|
<p>I try to view a custom object in a ListView using a custom ListCell. As an example to demonstrate the problem I chose <code>java.util.File</code>. Also for demonstration purpose I disable the ListCell directly when rendered. The items are added by an external process simulated by the thread. Everything looks nice until I apply the CSS coloring the disabled ListCell. Now it seems that there are some ghost items which get disabled together with the ListCell they are created of.</p>
<p>How can I solve this?</p>
<blockquote>
<p>App.java</p>
</blockquote>
<pre><code>public class App extends Application
{
@Override
public void start( Stage primaryStage )
{
final ListView<File> listView = new ListView<>();
listView.setCellFactory( column -> {
return new ListCell<File>()
{
protected void updateItem( File item, boolean empty )
{
super.updateItem( item, empty );
if( item == null || empty )
{
setGraphic( null );
return;
}
setDisable( true );
setGraphic( new TextField( item.getName() ) );
}
};
});
new Thread( () -> {
for( int i=0 ; i<10 ; ++i )
{
try
{
Thread.sleep( 1000 );
}
catch( Exception e )
{
e.printStackTrace();
}
final int n = i;
Platform.runLater( () -> {
listView.getItems().add( new File( Character.toString( (char)( (int) 'a' + n ) ) ) );
});
}
}).start();
Scene scene = new Scene( listView );
scene.getStylesheets().add( "app.css" );
primaryStage.setScene( scene );
primaryStage.show();
}
@Override
public void stop() throws Exception
{
super.stop();
}
public static void main( String[] args ) throws Exception
{
launch( args );
}
}
</code></pre>
<blockquote>
<p>app.css</p>
</blockquote>
<pre><code>.list-cell:disabled {
-fx-background-color: #ddd;
}
</code></pre>
| 2 |
Search BindingList by property
|
<p>I have in my program a bindingList to which I want to add some elements. The elements are some instances of a class <strong>NameValue_Client</strong> which contains three properties. I want to search through the list using any property I want.</p>
<p>This is the class:</p>
<pre><code>Public Class NameValue_Client
Implements INotifyPropertyChanged
Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
Private _assigned_db_name As String, _assigned_tcp_name As String
Private _val_obj As Client
Private _key_obj As Integer
Public WriteOnly Property DB_Name As String
Set(ByVal value As String)
_assigned_db_name = value
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("DB_Name"))
End Set
End Property
Public Property Value As Client
Get
Return _val_obj
End Get
Set(ByVal value As Client)
_val_obj = value
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("Value"))
End Set
End Property
Public Property Key As Integer
Get
Return _key_obj
End Get
Set(ByVal value As Integer)
_key_obj = value
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("Key"))
End Set
End Property
Public ReadOnly Property Name_Identifier As String
Get
Return String.Format("{0} : {1}", _assigned_db_name, _assigned_tcp_name)
End Get
End Property
Sub New(ByVal Key As Integer, ByVal DB_Name As String)
_assigned_db_name = DB_Name
_key_obj = Key
End Sub
Private Sub changed(ByVal sender As Object, ByVal e As PropertyChangedEventArgs) Handles Me.PropertyChanged
If e.PropertyName = "Value" Then
If _val_obj IsNot Nothing Then
_assigned_tcp_name = _val_obj.Details.Computer_Name
End If
End If
End Sub
Public Overrides Function ToString() As String
If _val_obj IsNot Nothing Then
Return String.Format("Db_Name:{0} Tcp_Name:{1} {2}", _assigned_db_name, _assigned_tcp_name, _val_obj.ToString)
Else
Return String.Format("Db_Name:{0} Tcp_Name:{1} Nothing", _assigned_db_name, _assigned_tcp_name)
End If
End Function
End Class
</code></pre>
<p>I found this on <a href="https://msdn.microsoft.com/ro-ro/library/ms132695%28v=vs.100%29.aspx?f=255&MSPPError=-2147217396" rel="nofollow">MSDN</a> and it looks it's the solution but it only serches for one property and I don't want to put a select case . It has to be a better way. </p>
<p>This is the code I found:</p>
<pre><code>Public Class MyFontList
Inherits BindingList(Of Font)
Protected Overrides ReadOnly Property SupportsSearchingCore() As Boolean
Get
Return True
End Get
End Property
Protected Overrides Function FindCore(ByVal prop As PropertyDescriptor, _
ByVal key As Object) As Integer
' Ignore the prop value and search by family name.<--That's why
Dim i As Integer
While i < Count
If Items(i).FontFamily.Name.ToLower() = CStr(key).ToLower() Then
Return i
End If
i += 1
End While
Return -1
End Function
End Class
</code></pre>
<p>And I don't know how to implement this 'child' class (never worked with this type). </p>
<hr>
<p>This is my code(until now):</p>
<pre><code>Public Class NameValue_Client
Implements INotifyPropertyChanged
Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
Private _assigned_db_name As String, _assigned_tcp_name As String
Private _val_obj As Client
Private _key_obj As Integer
Public WriteOnly Property DB_Name As String
Set(ByVal value As String)
_assigned_db_name = value
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("DB_Name"))
End Set
End Property
Public Property Value As Client
Get
Return _val_obj
End Get
Set(ByVal value As Client)
_val_obj = value
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("Value"))
End Set
End Property
Public Property Key As Integer
Get
Return _key_obj
End Get
Set(ByVal value As Integer)
_key_obj = value
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("Key"))
End Set
End Property
Public ReadOnly Property Name_Identifier As String
Get
Return String.Format("{0} : {1}", _assigned_db_name, _assigned_tcp_name)
End Get
End Property
Sub New(ByVal Key As Integer, ByVal DB_Name As String)
_assigned_db_name = DB_Name
_key_obj = Key
End Sub
Private Sub changed(ByVal sender As Object, ByVal e As PropertyChangedEventArgs) Handles Me.PropertyChanged
If e.PropertyName = "Value" Then
If _val_obj IsNot Nothing Then
_assigned_tcp_name = _val_obj.Details.Computer_Name
End If
End If
End Sub
Public Overrides Function ToString() As String
If _val_obj IsNot Nothing Then
Return String.Format("Db_Name:{0} Tcp_Name:{1} {2}", _assigned_db_name, _assigned_tcp_name, _val_obj.ToString)
Else
Return String.Format("Db_Name:{0} Tcp_Name:{1} Nothing", _assigned_db_name, _assigned_tcp_name)
End If
End Function
End Class
Public Class Interface_NameValue
Inherits BindingList(Of NameValue_Client)
Protected Overrides ReadOnly Property SupportsSearchingCore() As Boolean
Get
Return True
End Get
End Property
Protected Overrides Function FindCore(ByVal prop As PropertyDescriptor, _
ByVal key As Object) As Integer
' Ignore the prop value and search by family name.
Dim i As Integer
While i < Count
''Old-fashion way
Select Case prop.Name
Case "Value"
Case "Key"
Case "Name_Identifier"
End Select
i += 1
End While
Return -1
End Function
End Class
</code></pre>
<p>And now what am I supposed to do with this new class? How can I implement this?</p>
| 2 |
Getting Error While Inserting JSON object into JSOUP
|
<p>I was trying to post some json objects into Saiku Server using JSOUP. Here is my code. </p>
<pre><code>Response document1 = Jsoup
.connect(
"http://localhost:8080/saiku/rest/saiku/admin/datasources/")
.header("Content-Type", "application/json")
.data(testJson.toJSONString())
.ignoreContentType(true)
.referrer("http://localhost:8080/")
.cookie("JSESSIONID", res.cookie("JSESSIONID"))
.userAgent(
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36")
.method(Method.POST).timeout(10000).execute();
</code></pre>
<p>and I am getting error like </p>
<pre><code> Errorjava.lang.IllegalArgumentException: Must supply an even number of key value pairs .
</code></pre>
<p>I searched in many sites but can't able to find the solution for that . Can someone clarify me . Thanks in Advance. i attached my code here, </p>
| 2 |
InputTransparent=true does not work in Xamarin Forms Android
|
<p>From <a href="https://developer.xamarin.com/api/property/Xamarin.Forms.VisualElement.InputTransparent/" rel="noreferrer">this</a> link.</p>
<blockquote>
<p>false if the element should receive input; true if element should not receive input and should, instead, pass inputs to the element below. Default is false.</p>
</blockquote>
<p>What I want is, the Entry field must not be allowed to receive input from user. </p>
<p><code>InputTransparent=true</code> works well in iOS but doesn't work in Android, it still allows the user to give input.</p>
<p>I tried <code>IsEnabled=false</code> but that changes the look of my Entry field and I don't want that.</p>
<p>Is this some kind of bug?</p>
| 2 |
Android vimeo video uploading
|
<p>How to upload video using vimeo SDK <code>com.vimeo.networking:vimeo-networking</code>?
In the documentation and <a href="https://github.com/vimeo/vimeo-networking-java/tree/v1.1.0/example" rel="nofollow">example</a> project there is no example how to upload video. Also methods <code>VimeoClient.getInstance().putContent</code> and <code>VimeoClient.getInstance().postContent</code> are not documented. I've implemented method:</p>
<pre><code> VimeoClient.getInstance().postContent(videoUri, CacheControl.FORCE_CACHE, null, new ModelCallback<Video>(Video.class) {
@Override
public void success(Video video) {
toast("Staff Picks Success! " + video);
}
@Override
public void failure(VimeoError error) {
toast("Staff Picks Failure :( " + error);
}
});
</code></pre>
<p>but I'm receiving error when try to upload video. Here is stack trace</p>
<blockquote>
<p>W/System.err: java.lang.IllegalArgumentException: url == null
W/System.err: at okhttp3.Request$Builder.url(Request.java:121)
W/System.err: at retrofit2.RequestBuilder.build(RequestBuilder.java:204)
W/System.err: at retrofit2.RequestFactory.create(RequestFactory.java:67)
W/System.err: at retrofit2.OkHttpCall.createRawCall(OkHttpCall.java:122)
W/System.err: at retrofit2.OkHttpCall.enqueue(OkHttpCall.java:58)
W/System.err: at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.enqueue(ExecutorCallAdapterFactory.java:57)
W/System.err: at com.vimeo.networking.VimeoClient.POST(VimeoClient.java:1167)
W/System.err: at com.vimeo.networking.VimeoClient.postContent(VimeoClient.java:1061)</p>
</blockquote>
| 2 |
Dragula - Drag elements from one container to different elements
|
<p>My question is related to dragula <a href="https://github.com/bevacqua/dragula" rel="nofollow">https://github.com/bevacqua/dragula</a></p>
<p>I am trying to drag elements from one container and drop them (copy not move) into different containers. So, in this way I have one container which contains elements to drag and I want to drop them into different containers but its not working properly and sometimes its not working at all. Please guide me what is wrong with my code.</p>
<p>HTML</p>
<pre><code> /*container which contains elements to drag */
<div class="row">
<div class="col-md-12">
<div class="activityIcons" style="text-align:center;">
<ul class="media-list media-list-container" id="media-list-target-left">
<li class="media" style="display:inline-block;" id="phone">
<div class="media-left media-middle dots" ><i class="icon-phone2 text-indigo-800 dragula-handle" style="font-size:22px;" data-popup="tooltip" title="Phone Call" data-container="body" data-trigger="hover" data-placement="bottom"></i></div>
</li>
<li class="media" style="display:inline-block;" id="history">
<div class="media-left media-middle dots"><i class="icon-history text-orange-600 dragula-handle" style="font-size:22px;" data-popup="tooltip" title="Review Order History" data-container="body" data-trigger="hover" data-placement="bottom"></i></div>
</li>
<li class="media" style="display:inline-block;" id="order">
<div class="media-left media-middle dots"><i class="text-blue-600 icon-cart-add2 dragula-handle" style="font-size:22px;" data-popup="tooltip" title="Place Product Order" data-container="body" data-trigger="hover" data-placement="bottom"></i></div>
</li>
</ul>
</div>
</div>
</div>
/* containers where elements will be dropped */
<div class="activity" id="1" style="margin-top: 5px; padding:5px; border: 1px solid #ccc;">
<div class="row activityDetail" id="1" style="padding:5px; margin:15px;">
<div class="col-md-12" style="border-bottom:1px solid #ddd;">
<span class="text-bold text-black actTime" style="cursor:pointer; margin-right:5px;">Time</span>
<span class="text-bold text-black regionCust" style="cursor:pointer; margin-right:5px;">Region & Customer</span>
<span class="media-list-container" id="activitiesBar1"><span class="dropMsg1">Drop Here</span></span>
<span class="pull-right stats">
<ul></ul>
</span>
</div>
</div>
<div class="row activityDetailTwo" id="2" style="padding:5px; margin:15px;">
<div class="col-md-12" style="border-bottom:1px solid #ddd;">
<span class="text-bold text-black actTimeTwo" id="2" style="cursor:pointer; margin-right:5px;">Time</span>
<span class="text-bold text-black regionCustTwo" id="2" style="cursor:pointer; margin-right:5px;">Region & Customer</span>
<span class="media-list-container" id="bar2"><span class="dropMsg2">Drop Here</span></span>
<span class="pull-right stats">
<ul></ul>
</span>
</div>
</div>
</code></pre>
<p>JQuery</p>
<pre><code>dragula([document.getElementById('media-list-target-left'), document.getElementById('activitiesBar1')], {
copy: true,
revertOnSpill: true,
mirrorContainer: document.querySelector('.media-list-container'),
move: function (el, container, handle) {
return handle.classList.contains('dragula-handle');
}
}).on('drop', function(el) {
var actionId = $(el).attr('id');
if($('#activitiesBar1').children('.dropMsg1').length > 0){ $('.dropMsg1').remove(); }
if(actionId == "phone"){ $('.callDuration').modal(); }
if(actionId == "history"){ $('.orderHistoryModal').modal(); }
if(actionId == "order"){ $('.catalog').modal(); }
if(actionId == "chat"){ $('.conversation').modal(); }
if(actionId == "reschedule"){ $('.schedule').modal(); }
if(actionId == "training"){ $('.training').modal(); }
if(actionId == "visit"){ $('.carExpenses').modal(); }
});
dragula([document.getElementById('media-list-target-left'), document.getElementById('bar2')], {
copy: true,
revertOnSpill: true,
mirrorContainer: document.querySelector('#bar2'),
move: function (el, container, handle) {
return handle.classList.contains('dragula-handle');
}
}).on('drop', function(el) {
var actionId = $(el).attr('id');
if($('#bar2').children('.dropMsg2').length > 0){ $('.dropMsg2').remove(); }
if(actionId == "phone"){ $('.callDuration').modal(); }
if(actionId == "history"){ $('.orderHistoryModal').modal(); }
if(actionId == "order"){ $('.catalog').modal(); }
if(actionId == "chat"){ $('.conversation').modal(); }
if(actionId == "reschedule"){ $('.schedule').modal(); }
if(actionId == "training"){ $('.training').modal(); }
if(actionId == "visit"){ $('.carExpenses').modal(); }
});
</code></pre>
<p>Your suggestions will be highly appreciated. </p>
<p>Thank you.</p>
| 2 |
include gturri android xml rpc library in android project
|
<p>i need to include this library but i ve got several problems.
<a href="https://github.com/gturri/aXMLRPC" rel="nofollow">project library on github</a></p>
<p>i tried to follow the instructions on the github project but they did not work for me. I have to include the library in android studio. </p>
<p>i tried to:
1) copy the whole code in my project but i had a lot of conflicts about package, and, once solved, i began to have problems about lacks of functions not defined
2) i tried to use mvn install command, but it did not work, something like 100 errors displayed
3) i tried to open that project with intelliJ and then i tried to export jar file, but intelliJ told that it s an android project </p>
<p>does anyone have any idea about the procedure to include this library?
Thanks a lot in advance </p>
| 2 |
NLTK Relation Extraction - custom corpus in relextract.extract_rels
|
<p>I learnt that there is a built-in function in NLTK which could extract relations from NER-tagged sentences according the following:</p>
<pre><code> import re
IN = re.compile(r'.*\bin\b(?!\b.+ing\b)')
for fileid in ieer.fileids():
for doc in ieer.parsed_docs(fileid):
for rel in relextract.extract_rels('ORG', 'LOC', doc, corpus='ieer', pattern = IN):
print(relextract.rtuple(rel))
</code></pre>
<p>It seems me very promising for general purpose, but I understood that <code>relextract.extract_rels</code> accepts only <code>'ieer'</code> or <code>'conll2002'</code> for the parameter <code>corpus</code>. But in this case, its usage is restricted only to these two corpora, isn't it? How could one utilize it for his own corpus (presuming, of course, that it is NER-tagged).</p>
| 2 |
What happends when a perform_async is called but sidekiq is not running?
|
<p>I was wondering what happends when a perform_async is called on a worker but sidekiq (<code>bundle exec sidekiq</code>) isn't running ?</p>
<p>In my app I have some observers that ask sidekiq to do a job when one of my models is trigger (ie create, update or destroy in some cases).</p>
<p>I also have a rake task that builds me a database from some data I have.. When this task is running, it creates several records that trigger my observers who then push jobs in sidekiq queue.</p>
<p>For testing purpose I ran this task without turning on sidekiq and it's working fine, my data is being pushed in mysql !</p>
<p>I know ask myself what is happening to the job my observer tells my worker to do ? Is it still done ? Is it done but not asynchronously ? Is it <em>not</em> done ? </p>
| 2 |
Write from Serial Port to SD card
|
<p>I am trying to write from the Serial Port to an SD Card in my Arduino Mega 2560, using a card module.</p>
<p>I want to be able to write in a txt file what I type in the serial com.</p>
<pre><code>#include <SPI.h>
#include <SD.h>
const int chipSelect = 4;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.print("This is a test and should be ignored");
if (!SD.begin(chipSelect)) {
Serial.println("\nCard failed, or not present");
// don't do anything more:
return;
}
else{
Serial.println("\ncard initialized.");
}
}
void loop() {
// put your main code here, to run repeatedly
File OpenFile = SD.open("test.txt", FILE_WRITE);
if(OpenFile and Serial.available());
{
OpenFile.println(Serial1.read());
OpenFile.close();
}
}
</code></pre>
<p>However a continous line of "-1" and "1", without the ", is written to the SD.</p>
<p>Yes, I am able to write to the SD card through other methods...</p>
<p>Cheers, PoP</p>
| 2 |
Dynamically Link Images - Power Point
|
<p>I have a slide presentation with the same image on 10 of the 20 slides. When I rebuild with the presentation for another user I have to change those 10 slides to update the image.</p>
<p>Is there a way to have one of the images be the master image and all other link back to the master so I can update just the one image ? </p>
<p>Cheers,
Fox</p>
| 2 |
How to parse a JArray into JObjects, get the first 4 letters of a string of the JObjects and save them back in a JArray
|
<p>I am using a postcode related API service, where you can get all other postcodes within a given distance of a given postcode. </p>
<p>The following is an example of the <code>Json</code> results</p>
<pre><code>{
"postcode":"******",
"lat":111111111,
"lng":11111111,
"distance":0.0
},
{
"postcode":"******",
"lat":2222222222,
"lng":2222222222222,
"distance":0.0343
}
</code></pre>
<p>I am using the following in my <code>API Controller</code></p>
<pre><code>public object GetPostcodesWithin(string postcode, double distance)
{
var trimPostcode = postcode.Trim();
var url = "some url" + trimPostcode + "&miles=" + distance + "&format=json";
dwml = webClient.DownloadString(url);
dynamic jsonData = JArray.Parse(dwml);
var response = jsonData;
dynamic secondps = jsonData[1];
string newps = secondps.postcode;
JObject rss = JObject.Parse(jsonData);
var postcodes = from p in rss["{ }"]
select (string)p["postcode"];
JArray finalPostcodes = new JArray();
// List<string> finalPostcodes = new List<string>();
foreach (var item in postcodes)
{
var firstletters = item.Substring(0, 4);
finalPostcodes.Add(firstletters);
}
return finalPostcodes;
//int length = response.Count;
//for (int i = 0; i < response.Count; i++)
//{
// var item = (JObject)response[i];
// // JObject o = JObject.Parse(response);
//}
//for (int i=0; i< dwml.Length; i++)
//{
// JToken t[i] = JToken.Parse("{}");
//}
//JObject rss = JObject.Parse(json);
//var postTitles =
//from p in rss["channel"]["item"]
//select(string)p["title"];
//foreach(var item in postTitles)
// {
// Console.WriteLine(item);
// }
// return Json(newps);
}
</code></pre>
<p>All the commented out sections are different things I have tried. Basically I get the dynamic <code>Json</code> data, but at this line <code>JObject rss = JObject.Parse(jsonData);</code> it fails. Goal is to get only the first 4 letters of the postcode attribute of each object in the <code>JArray</code>, save it in another <code>JArray</code> or <code>List</code> so I can use it for querying matching data from the database of the <code>MVC</code> web application.</p>
| 2 |
OneNote REST API - Downloading big attached file gives 502 Bad Gateway error
|
<p>I'm downloading (video) file attachments using the OneNote REST API with PHP and cURL. While all goes smoothly with files < 30.0 MB, anything larger produces a 502 Bad Gateway error and no data.</p>
<p>Whereas, in <a href="https://stackoverflow.com/questions/36733189/onenote-api-fails-to-get-any-notes-from-shared-notebook-for-sharing-user">a different situation</a> (shared notebook) with a 502 error the addition of "FavorDataRecency: true" to the API request solved the problem, in this situation it has no effect.</p>
<p>What's the way around (or through) this problem?</p>
<p>[<strong>EDIT</strong>]</p>
<p>It is a timeout problem (thanks Jim). My logs show that file downloads halt with the 502 error exactly at 120 seconds.</p>
<p>My PHP script is running on localhost under IIS 10 on Windows 10. I thought I was onto something when I found the connection timeout for IIS was 120 seconds. But I've upped it to 240 seconds and the timeout barrier is still there.</p>
<p>Other config changes I've made:</p>
<ul>
<li>Upped the FastCgi requestTimeout and activityTimeout in IIS 10.</li>
<li>Added a CURLOPT_TIMEOUT of 240 secs (as well as the CURLOPT_CONNECTTIMEOUT of 240 secs already set).</li>
</ul>
<p>Is there some other timeout setting I'm missing?</p>
<p>Any chance it could be a timeout on the OneNote servers?</p>
| 2 |
Centos Postfix mail not received in gmail
|
<p>Simple usecase but doesn't work.</p>
<p>I have a web application and want to configure a SMTP server to send emails from application.</p>
<p>Installed mailx as per link - <a href="http://tecadmin.net/bash-mail-command-not-found/" rel="nofollow">http://tecadmin.net/bash-mail-command-not-found/</a>
All good.</p>
<pre><code>Test Sending email as: echo "This is a test email body " | mail -s "This is a test email " [email protected]
</code></pre>
<p>Now I get the following in logs :</p>
<pre><code>root@/var/log $ tail -f /var/log/maillog
Jul 19 16:47:57 bridgeapps-dev01 postfix/postfix-script[23104]: stopping the Postfix mail system
Jul 19 16:47:57 bridgeapps-dev01 postfix/master[1466]: terminating on signal 15
Jul 19 16:47:57 bridgeapps-dev01 postfix/postfix-script[23184]: starting the Postfix mail system
Jul 19 16:47:57 bridgeapps-dev01 postfix/master[23186]: daemon started -- version 2.10.1, configuration /etc/postfix
Jul 19 16:48:12 bridgeapps-dev01 postfix/pickup[23187]: 4163841204: uid=0 from=<root>
Jul 19 16:48:12 bridgeapps-dev01 postfix/cleanup[23194]: 4163841204: message-id=<[email protected]>
Jul 19 16:48:12 bridgeapps-dev01 postfix/qmgr[23188]: 4163841204: from=<[email protected]>, size=582, nrcpt=1 (queue active)
Jul 19 16:48:12 bridgeapps-dev01 postfix/smtp[23196]: connect to ASPMX.L.GOOGLE.com[2a00:1450:400c:c09::1b]:25: Network is unreachable
Jul 19 16:48:12 bridgeapps-dev01 postfix/smtp[23196]: 4163841204: to=<[email protected]>, relay=ASPMX.L.GOOGLE.com[64.233.166.26]:25, delay=0.47, delays=0.02/0.01/0.24/0.2, dsn=2.0.0, status=sent (250 2.0.0 OK 1468943292 l4si11397516wmf.56 - gsmtp)
Jul 19 16:48:12 bridgeapps-dev01 postfix/qmgr[23188]: 4163841204: removed
</code></pre>
<p>All green, no errors, just as things seem to be too good to be true, I never receive this email in gmail.</p>
<p>What am I missing ?</p>
<p>Thank you,</p>
| 2 |
code "Request.Headers.Range" not working on asp.net core
|
<pre class="lang-c# prettyprint-override"><code>RangeHeaderValue rangeHeader = base.Request.Headers.Range;
</code></pre>
<p>above codes are working on asp.net web api, however it is not working on asp.net core. Is there an altnative in asp.net core for getting RangeHeaderValue?</p>
| 2 |
Using `Node*` as iterator for a list
|
<pre><code>#include <iostream>
#include <algorithm>
struct Node
{
int value_;
Node* next_;
Node(int value, Node* next = nullptr)
: value_(value)
, next_(next)
{}
};
Node* operator++(Node* node)
{
node = node->next_;
return node;
}
int operator*(Node* node)
{
return node->value_;
}
int main()
{
Node* first = new Node(10);
first->next_ = new Node(20);
first->next_->next_ = new Node(17);
Node* endIter = nullptr;
std::cout << std::accumulate(first, endIter, 0) << std::endl;
}
</code></pre>
<p>In this example I have tried to use <code>Node*</code> as iterator for list. I am getting compiler errors</p>
<pre><code> 1 main.cpp:15:28: error: Node* operator++(Node*) must have an argument of class or enumerated type
2 Node* operator++(Node* node)
3 ^
4 main.cpp:21:25: error: int operator*(Node*) must have an argument of class or enumerated type
5 int operator*(Node* node)
</code></pre>
<p>Looks like I can't overload <code>operator++</code> and <code>operator*</code> for pointers. </p>
<p>I have copied this overloads from the book <code>Stroustrup: The C++ Programming Language (4th Edition) pg 703</code>.</p>
<p>Can anyone explain what I have done wrong?</p>
| 2 |
Finding a name in a CSV file
|
<p>I have code that finds the input name in a CSV if it is present it says yes else no. But I entered a name present in the CSV yet it still says no.</p>
<p>Here is the code:</p>
<pre><code>import csv
f=open("student.csv","r")
reader=csv.reader(f)
for row in reader:
print
studentToFind = raw_input("Enter the name of sudent?")
if studentToFind in reader:
print('yes')
else:
print('no')
f.close()
</code></pre>
| 2 |
Find gaps between repeated numbers in an array
|
<p>I have an ArrayList with a list of numbers. Each number is always between 0 - 9. So the ArrayList contains numbers something as follows: </p>
<p>1 2 7 4 9 1 8 8 3 2 9 0 1 3 .... </p>
<p>I want to count the gaps before the number repeats again. For example the number 1 has a gap of 4 before repeating again. And then it goes on to have another gap of 6. I am looking to find out gaps up to 30. The list is long. I am looking to store and produce the following: </p>
<pre><code>Number 0 gap 1 : none
Number 0 gap 2: 5 times
Number 0 gap 3: 7 times
.....
Number 0 gap 30: none
Number 1 gap 1: 5 times
Number 1 gap 2: 3 times
......
Number 9 gap 30: 2 times
</code></pre>
<p>I really can't get my head around to how I could do this. I tried the following but it is clearly going nowhere. Looking for some direction and help please.</p>
<pre><code>//arr is the ArrayList
int gapCount = 0;
int[] gaps = new int[10];
for (int i = 0; i < arr.size(); i++) {
for (int j = 0; j < arr.size(); j++) {
if(arr.get(i) == arr.get(j)){
}
gapCount++;
}
}
</code></pre>
| 2 |
where to put "WSGIPassAuthorization On"?
|
<p>I tried two methods:</p>
<p>1, /etc/apache2/sites-enabled/myproject.conf</p>
<p>2, /etc/apache2/mods-enabled/wsgi.conf</p>
<p>Both works. <strong>I just wonder which place is best to put it?</strong></p>
| 2 |
Basic Table Manipulation: How to change and Insert images in HTML Table using JavaScript?
|
<p>I spent a bit of time trying to figure out how to alter and insert cell information in JavaScript, so am recapping what I learned for others. Also included in the scripts are three urls I used to figure out these answers in hopes they will lead other folks to solve other questions they may have.</p>
<p><a href="https://i.stack.imgur.com/4efdn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4efdn.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/CsWeS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CsWeS.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/hL44z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hL44z.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/3JIhN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3JIhN.png" alt="enter image description here"></a></p>
| 2 |
In Pandas, generate DateTime index from Multi-Index with years and weeks
|
<p>I have a DataFrame <code>df</code> with columns <code>saledate</code> (in DateTime, dytpe <code><M8[ns]</code>) and <code>price</code> (dytpe <code>int64</code>), such if I plot them like</p>
<pre><code>fig, ax = plt.subplots()
ax.plot_date(dfp['saledate'],dfp['price']/1000.0,'.')
ax.set_xlabel('Date of sale')
ax.set_ylabel('Price (1,000 euros)')
</code></pre>
<p>I get a scatter plot which looks like below.</p>
<p><a href="https://i.stack.imgur.com/HNf63.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HNf63.png" alt="enter image description here"></a></p>
<p>Since there are so many points that it is difficult to discern an average trend, I'd like to compute the average sale price per week, and plot that in the same plot. I've tried the following:</p>
<pre><code>dfp_week = dfp.groupby([dfp['saledate'].dt.year, dfp['saledate'].dt.week]).mean()
</code></pre>
<p>If I plot the resulting 'price' column like this</p>
<pre><code>plt.figure()
plt.plot(df_week['price'].values/1000.0)
plt.ylabel('Price (1,000 euros)')
</code></pre>
<p>I can more clearly discern an increasing trend (see below).</p>
<p><a href="https://i.stack.imgur.com/5l1EZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5l1EZ.png" alt="enter image description here"></a></p>
<p>The problem is that I no longer have a time axis to plot this DataSeries in the same plot as the previous figure. The time axis starts like this:</p>
<pre><code> longitude_4pp postal_code_4pp price rooms \
saledate saledate
2014 1 4.873140 1067.5 206250.0 2.5
6 4.954779 1102.0 129000.0 3.0
26 4.938828 1019.0 327500.0 3.0
40 4.896904 1073.0 249000.0 2.0
43 4.938828 1019.0 549000.0 5.0
</code></pre>
<p>How could I convert this Multi-Index with years and weeks back to a single DateTime index that I can plot my per-week-averaged data against?</p>
| 2 |
Using Angular 2 Observable to display continuous stream of data
|
<p>I'm using a Couchbase Server as my database for my Angular 2 Web application. The data exchange happens through WebAPI's which talks to my CouchBase server.
I'm not sure if this is the correct way to do it yet at the moment I'm querying(polling) for the WebAPI every 5 seconds in order to get updated list of data</p>
<pre class="lang-javscript prettyprint-override"><code>this.events = getRecentEvents(_siteUrl: String) {
return Observable.interval(5000)
.switchMap(() => this.http.get(_siteUrl).map((res: Response) => res.json()))
.do(data => console.log('server data:', data)) // debug
.catch(this.handleError);
}
</code></pre>
<p>I'm using the Observable object returned from this call to bind it to a list on the UI using async pipes</p>
<pre class="lang-html prettyprint-override"><code><li class="item" *ngFor="#eventitem of events | async; #i = index">
<h1>{{eventitem}} {{i}}</h1>
</li>
</code></pre>
<p>The question I have is, Is this the right way to do?
Am I not putting too much load on the server with repetitive WebAPI calls?
Can any one suggest a better alternative if this is not the way to handle continuous flow of data.</p>
| 2 |
How can I convert an Unmanaged solution into Managed solution?
|
<p>I have a solution file (.zip) which contains an unmanaged solution from our supplier. </p>
<p>I also have an access of the instance of the supplier's CRM instance, but that instance doesn't show up the solution in the list as it is unmanaged one, and hence I am unable to export it.</p>
<p>It seems the supplier created the solution on other system, and exported it as unmanaged, and then imported that solution to the system on which he has provide access to me.</p>
<p>I want to import the solution to my target system but as a Managed solution.</p>
<p>Is there any possibility of doing so?</p>
| 2 |
Understanding the Storm Architecture
|
<p>I have been trying to understand the storm architecture, but I am not sure if I got this right. I'll try to explain as exactly as possible what I believe to be the case. Please explain what - if - I got wrong and what is right.</p>
<h2>Preliminary thoughts: <em>workers</em></h2>
<p><a href="http://storm.apache.org/releases/2.0.0-SNAPSHOT/Understanding-the-parallelism-of-a-Storm-topology.html" rel="nofollow">http://storm.apache.org/releases/2.0.0-SNAPSHOT/Understanding-the-parallelism-of-a-Storm-topology.html</a> suggests that a Worker is a process as does <a href="http://storm.apache.org/releases/2.0.0-SNAPSHOT/Concepts.html" rel="nofollow">http://storm.apache.org/releases/2.0.0-SNAPSHOT/Concepts.html</a> with "worker processes. Each worker process is a physical JVM", however <a href="http://storm.apache.org/releases/1.0.1/Setting-up-a-Storm-cluster.html" rel="nofollow">http://storm.apache.org/releases/1.0.1/Setting-up-a-Storm-cluster.html</a> states that a worker is a node with "Nimbus and worker machines". The website <a href="http://www.michael-noll.com/tutorials/running-multi-node-storm-cluster/" rel="nofollow">http://www.michael-noll.com/tutorials/running-multi-node-storm-cluster/</a> mentions "master node" and "worker nodes". So what: Is the worker a process or a physical node (or is a node a process)? Thus I think that there are two things: <em>Worker Nodes</em> and <em>Worker Processes</em>.</p>
<h2>What I believe to be true</h2>
<h3>Entities in play</h3>
<ul>
<li><em>Master Node</em> = Management Server</li>
<li><em>Worker Node</em> = <em>Slave Node</em></li>
<li><em>Nimbus</em> JVM process, running on <em>Master Node</em></li>
<li><em>ZooKeeper</em> JVM processes, running on <em>ZooKeeper Nodes</em></li>
<li><em>Supervisor</em> JVM process, running on <em>Worker Nodes</em></li>
<li><em>Worker Process</em> (JVM), running on <em>Worker Nodes</em></li>
<li><em>Executor</em> thread, run by <em>Worker Process</em></li>
<li><em>Task</em> (instances of <em>Bolts</em> and <em>Spouts</em>), executed by <em>Executor</em></li>
</ul>
<h3>How things work</h3>
<p>The <em>Nimbus</em> is a JVM process, running on the physical <em>Master Node</em>, that receives my program (<em>Storm topology</em>) takes the <em>Bolts and Spouts</em> and generates <em>tasks</em> from them. If a <em>Bolt</em> is supposed to be parallelized three times, the <em>Nimbus</em> generates three <em>tasks</em> for it. The <em>Nimbus</em> asks the <em>ZooKeeper</em> JVM processes about configurations of the cluster, e.g. where to run those <em>tasks</em> and the <em>ZooKeeper</em> JVM processes tells the <em>Nimbus</em>. In order to do this the <em>ZooKeeper</em> communicates with the <em>Supervisors</em> (what they are comes later). The <em>Nimbus</em> distributes the tasks then to the <em>Workers Nodes</em>, which are physical nodes. <em>Worker Nodes</em> are managed by <em>Supervisors</em>, which are JVM processes - exactly one <em>Supervisor</em> for one <em>Worker Node</em>. <em>Supervisors</em> manage (start, stop, etc.) the <em>Worker Processes</em>, which are JVM processes that run on the <em>Worker Nodes</em>. Each <em>Worker Node</em> can have multiple <em>Worker Processes</em> running. <em>Worker Processes</em> are JVM processes. They run one or multiple threads called <em>Executors</em>. Each <em>Executor Thread</em> runs one or multiple <em>Tasks</em>, meaning one or multiple instances of a <em>Bolt</em> or <em>Spout</em>, <a href="http://storm.apache.org/releases/2.0.0-SNAPSHOT/Understanding-the-parallelism-of-a-Storm-topology.html" rel="nofollow">but those have to be of the same <em>Bolt</em></a>. </p>
<p>If this is all true, it begs the questions:</p>
<ul>
<li>What is the point of having multiple <em>Worker Processes</em> run on one <em>Worker Node</em> - after all a process can use multiple processor cores, right?</li>
<li>What is the point of having multiple <em>Tasks</em> run by one <em>Executor</em> thread if they have to be of the same <em>Bolt</em>/<em>Spout</em>? A thread is only run on one processor core, so the multiple <em>Bolt</em>/<em>Spout</em> have to run after each other and can not be parallelized. Running indefinitely in the Storm topology - what would be the point having two instances of the same <em>Bolt</em>/<em>Spout</em> in a <em>Exectuor</em> thread?</li>
</ul>
<hr>
<p><strong>Edit:</strong> Good additional resource: <a href="http://www.tutorialspoint.com/apache_storm/apache_storm_cluster_architecture.htm" rel="nofollow">http://www.tutorialspoint.com/apache_storm/apache_storm_cluster_architecture.htm</a></p>
| 2 |
OpenCl maximum work-items per compute unit
|
<p>I am writing an <code>OpenCL</code> code to find an optimum work-group size to have maximum occupancy on GPU. For this, I want a function that returns the maximum number of work-items per compute unit.</p>
<p>Basically, I am deriving this from a <code>CUDA</code> code and I want an equivalent of <code>maxThreadsPerMultiProcessor</code>.
In CUDA these were the values returned on device query:
Maximum number of threads per multiprocessor: 2048
Maximum number of threads per block: 1024</p>
<p>In OpenCL:
CL_DEVICE_MAX_WORK_GROUP_SIZE: 1024</p>
<p>In CUDA it doesn't asks for kernel info to return this value.
I need an equivalent function for OpenCL.
Thanks in advance.</p>
| 2 |
Fluent-ffmpeg and complex filter in Electron (node)
|
<p>I want to use fluent-ffmpeg module to call ffmpeg with complex filter from Electron but have no success. The error '[AVFilterGraph @ 0xb8.......] No such filter " Error initalizing complex filters . Invalid argument' is the same as in this question <a href="https://stackoverflow.com/questions/37828262/error-running-ffmpeg-command-in-android-splitting-command-in-array-not-workin">Error : Running FFmpeg command in Android ,splitting command in array not working</a> but the context is different.</p>
<p><strong>What is needed?</strong>
Run this ffmpeg command using fluent-ffmpeg:</p>
<blockquote>
<p>ffmpeg -i safework-background-0.mp4 -i image1.png -i image2.png -i
image3.png -filter_complex "[0:v][1:v]
overlay=1:1:enable='between(t,5,8.5)' [tmp]; [tmp][2:v]
overlay=1:1:enable='between(t,8.5,12)' [tmp]; [tmp][3:v]
overlay=1:1:enable='between(t,12,15)'" test-video-safework3.mp4</p>
</blockquote>
<p>It uses a complex filter to overlay three images on a video in sequence and exports a new video.</p>
<p><strong>What doesn't work?</strong>
Obviously fluent-ffmpeg chokes with required quotes for complex filter, that is my conclusion (and is the same as for the Android variant question above).</p>
<p><strong>What works without fluent-ffmpeg in Electron?</strong>
As you can guess I have to resort to calling ffmpeg directly. To help others, the following command, with input and output video filenames parametrized, translates to Electron as:</p>
<pre><code> var spawn = require('child_process').spawn
var fargs = ['-y', '-i', sourceDir.path() + '/' + inVideoName, '-i', tempDir.path() + '/' + 'image1.png',
'-i', tempDir.path() + '/' + 'image2.png', '-i', tempDir.path() + '/' + 'image3.png',
'-filter_complex', '[0:v][1:v]overlay=1:1:enable=\'between(t,5,8.5)\'[tmp];' +
'[tmp][2:v]overlay=1:1:enable=\'between(t,8.5,12)\'[tmp];[tmp][3:v]' +
'overlay=1:1:enable=\'between(t,12,15)\'', targetDir.path() + '/' + outVideoName]
var ffmpeg = spawn(ffmpegc, fargs, { cwd:jetpack.cwd(app.getPath('home')).path() })
// some code ommitted
ffmpeg.on('close', (code) => {
console.log(`child process exited with code ${code}`)
webContents.send('notify-user-reply', 'Video processing done.')
})
</code></pre>
<p>The above command already has removed spaces between various filters (in complex filter) for each image or it would also choke.</p>
<p>I would really love to use fluent-ffmpeg in Electron, not just for the convenience of calling ffmpeg more elegantly but also for some additional features like easy progress reporting. </p>
| 2 |
How to implement dompdf in cakephp 3?
|
<p>I just making website that can make html file into pdf using cakephp 3 as php framework.</p>
<p>this is my code in layout as default.ctp for pdf view that i want to convert</p>
<pre><code><?php
require_once(APP . 'Vendor' . DS . 'dompdf' . DS . 'dompdf_config.inc.php');
spl_autoload_register('DOMPDF_autoload');
$dompdf = new DOMPDF();
$dompdf->set_paper = 'A4';
$dompdf->load_html(utf8_decode($content_for_layout), Configure::read('App.encoding'));
$dompdf->render();
echo $dompdf->output();
</code></pre>
<p>when i try to run it, it some error like this</p>
<pre><code>Error: Class 'Configure' not found
File C:\xampp\htdocs\MyProject\src\Template\Layout\pdf\default.ctp
Line: 6
</code></pre>
<p>is my syntax for calling dompdf is not right? </p>
| 2 |
How to have Facebook Messenger Bot send a message on button click
|
<pre><code>"type": "postback",
"title": "What can Chatbots do",
"payload": "One day Chatbots will control the Internet of Things! You will be able to control your homes temperature with a text",
}, {
"type": "postback",
"title": "The Future",
"payload": "Chatbots are fun! One day your BFF might be a Chatbot",
}],
</code></pre>
<p>When for example, a user clicks 'The Future' the app sends a message to user in the form of </p>
<pre><code>Postback received: {"payload":"Chatbots are fun! One day your BFF might be a Chatbot"}
</code></pre>
<p>How can I change it so that It just sends that in message form? </p>
| 2 |
Spring boot- RabbitMQ consumer keep on printing "Retrieving delivery for Consumer"
|
<p>Hi I am using Spring boot 1.3.5 along with starter RabbitMQ. In this project i am having a RabbitMQ consumer which consumes messages from a particular queue.But while running the application it keeps on printing below message in the console.while browsing in google i read setting heartBeat will resolve the issue but no luck for me,</p>
<pre><code>14:08:14.892 [SimpleAsyncTaskExecutor-1] DEBUG o.s.a.r.l.BlockingQueueConsumer - Retrieving delivery for Consumer: tags=[{amq.ctag-rDkzcToXLMWqF4fFUIHS0A=notificationQueue}], channel=Cached Rabbit Channel: AMQChannel(amqp://[email protected]:5672/,3), conn: Proxy@47914ea3 Shared Rabbit Connection: SimpleConnection@1096fe75 [delegate=amqp://[email protected]:5672/], acknowledgeMode=AUTO local queue size=0
14:08:14.913 [SimpleAsyncTaskExecutor-3] DEBUG o.s.a.r.l.BlockingQueueConsumer - Retrieving delivery for Consumer: tags=[{amq.ctag-jxyjMKfw6heu77XVdYh3tw=notificationQueue}], channel=Cached Rabbit Channel: AMQChannel(amqp://[email protected]:5672/,2), conn: Proxy@47914ea3 Shared Rabbit Connection: SimpleConnection@1096fe75 [delegate=amqp://[email protected]:5672/], acknowledgeMode=AUTO local queue size=0
14:08:14.917 [SimpleAsyncTaskExecutor-2] DEBUG o.s.a.r.l.BlockingQueueConsumer - Retrieving delivery for Consumer: tags=[{amq.ctag-AcbX0R5eM-ukqWN0a_nrwA=notificationQueue}], channel=Cached Rabbit Channel: AMQChannel(amqp://[email protected]:5672/,1), conn: Proxy@47914ea3 Shared Rabbit Connection: SimpleConnection@1096fe75 [delegate=amqp://[email protected]:5672/], acknowledgeMode=AUTO local queue size=0
14:08:15.893 [SimpleAsyncTaskExecutor-1] DEBUG o.s.a.r.l.BlockingQueueConsumer - Retrieving delivery for Consumer: tags=[{amq.ctag-rDkzcToXLMWqF4fFUIHS0A=notificationQueue}], channel=Cached Rabbit Channel: AMQChannel(amqp://[email protected]:5672/,3), conn: Proxy@47914ea3 Shared Rabbit Connection: SimpleConnection@1096fe75 [delegate=amqp://[email protected]:5672/], acknowledgeMode=AUTO local queue size=0
</code></pre>
<p>It's ever ending.Kindly find the below consumer code:</p>
<p><strong>RabbitMqConfiguration.java</strong></p>
<pre><code>import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableRabbit
public class RabbitMqConfiguration{
@Autowired
private CachingConnectionFactory cachingConnectionFactory;
@Value("${concurrent.consumers}")
public int concurrent_consumers;
@Value("${max.concurrent.consumers}")
public int max_concurrent_consumers;
@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory() {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(cachingConnectionFactory);
factory.setConcurrentConsumers(concurrent_consumers);
factory.setMaxConcurrentConsumers(max_concurrent_consumers);
factory.setMessageConverter(jsonMessageConverter());
return factory;
}
@Bean
public MessageConverter jsonMessageConverter()
{
final Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter();
return converter;
}
}
</code></pre>
<p><strong>NotificationConsumer.java</strong></p>
<pre><code>@Component
public class NotificationConsumer {
private static final Logger logger = LoggerFactory.getLogger(NotificationConsumer.class);
@Value("${notification.queue}")
public String notificationQueue;
@RabbitListener(id="notification",containerFactory="rabbitListenerContainerFactory",queues = "#{notificationQueue}")
public void handleNotificationMessage(Transaction transaction)
{
System.out.println("Entered handleNotificationMessage::"+transaction.getId());
System.out.println("Exit handleNotificationMessage::"+transaction.getData());
logger.info("Entered handleNotificationMessage::", transaction.getId());
logger.info("Exit handleNotificationMessage::", transaction.getData());
}
@Bean
public Queue notificationQueue() {
return new Queue(notificationQueue, true, false, false);
}
}
</code></pre>
<p><strong>application.yml</strong></p>
<pre><code>spring:
rabbitmq:
addresses: 127.0.0.1:5672
adminAddresses: http://127.0.0.1:15672
username: guest
password: guest
requested-heartbeat: 60
spring.rabbit.exchange: notification-exchange
notification.queue: notificationQueue
concurrent.consumers: 3
max.concurrent.consumers: 10
</code></pre>
<p>Message will be produced by another application and this application will only consume the message.</p>
<p>Your help should be appreciated.</p>
<p>As per Gary flipped the logger level from DEBUG to INFO resolved my issue.</p>
<pre><code>logging:
level:
ROOT: INFO
</code></pre>
<p>Now i am getting following exception:</p>
<p><strong>15:21:24.925 [SimpleAsyncTaskExecutor-2] WARN o.s.a.r.l.ConditionalRejectingErrorHandler - Fatal message conversion error; message rejected;
it will be dropped or routed to a dead letter exchange, if so configured: (Body:'{"id":"5784eed4f5a64b4d8663e706","clientIdentifier":"313131313131",
"data":"Sample data by vad","currentAction":{"state":{"status":"PENDING","errorCode":"404"},"data":"Sample data"},
"hasError":false,"errorMessage":""}'MessageProperties [headers={__TypeId__=com.global.produce.model.Transaction},
timestamp=null, messageId=null, userId=null, appId=null, clusterId=null, type=null, correlationId=null, replyTo=null, contentType=application/json,
contentEncoding=UTF-8, contentLength=0, deliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=,
receivedRoutingKey=notificationQueue, deliveryTag=1, messageCount=0])</strong></p>
<p>Anyone have any idea about this error?</p>
| 2 |
Foundation 6 Mega Menu and Responsive Toggle Navigation with Drilldown Title Bar on Small
|
<p>I want to create a full-width dropdown mega menu that I can also combine with a top bar that has an drilldown menu in mobile screens. Any method I've tried on Foundation only works with Foundation 5, since they changed top bar in Foundation 6. </p>
<p>So far, (with the help from this thread: <a href="http://foundation.zurb.com/forum/posts/36800-f6-and-mega-menus" rel="nofollow">http://foundation.zurb.com/forum/posts/36800-f6-and-mega-menus</a>) I have been able to create the dropdown mega menu and on small screens, the title bar appears and toggles open. However, when I try to open an item with a drilldown submenu, it still treats it as though it is a dropdown item.</p>
<p>Also, I am noticing that full-width hover for the submenus are somehow pushing the screen to a lot of extra empty space horizontally. While I can get rid of the extra empty horizontal space by adding a max-width:100% to the dropdown-pane class, the second of my two mega submenus doesn't display full-width correctly when I hover over them. Although in the codepen, they show just fine.</p>
<p>This is the link to the codepen: <a href="http://codepen.io/jen188/pen/PzRkbg" rel="nofollow">http://codepen.io/jen188/pen/PzRkbg</a></p>
<p>This is the code for my header;</p>
<pre><code><header>
<div class="row columns expanded">
<a href="index.html"><img src="img/REPLogo.png" alt="Real Estate Promo" class="logo show-for-small-only" /></a>
<div class="title-bar" data-responsive-toggle="main-menu" data-hide-for="medium">
<button class="menu-icon" type="button" data-toggle></button>
<div class="title-bar-title">Menu</div>
</div>
<div class="top-bar" id="main-menu">
<div class="top-bar-left"><a href="index.html"><img src="img/REPLogo.png" alt="Real Estate Promo" class="logo hide-for-small-only" /></div>
<div class="top-bar-right">
<ul class="vertical medium-horizontal expanded dropdown menu" data-responsive-menu="drilldown medium-dropdown">
<li><a href="#">About Us</a></li>
<li><a href="#">Events Calendar</a></li>
<li class="has-submenu is-drilldown-submenu-parent">
<a href="#" class="dropdown" data-toggle="megamenu-resources">Resources
<div class="dropdown-pane" id="megamenu-resources" data-dropdown data-options="closeOnClick:true; hover: true; hoverPane: true">
<div class="row column expanded">
<div class="large-9 columns">
<div class="row column expanded">
<div class="large-4 columns">
<ul>
<li><a href="#"><h3>Foreclosure Laws</h3></a></li>
<li><a href="#"><img src="img/laws.png" alt="Click for More Info" /></a></li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam molestie ullamcorper nisl, sit amet tristique est dapibus nec.</li>
</ul>
</div>
<div class="large-4 columns">
<ul>
<li><a href="lenders.html"><h3>Hard Money Lenders</h3></a></li>
<li><a href="#"><img src="img/coin-stack.png" alt="Click for More Info" /></a></li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam molestie ullamcorper nisl, sit amet tristique est dapibus nec.</li>
</ul>
</div>
<div class="large-4 columns">
<ul>
<li><a href="glossary.html"><h3>Real Estate Glossary</h3></a></li>
<li><a href="#"><img src="http://placehold.it/500x250" alt="Click for More Info" /></a></li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam molestie ullamcorper nisl, sit amet tristique est dapibus nec.</li>
</ul>
</div>
</div>
</div>
<div class="large-3 columns">
<ul>
<li><a href="#"><h3>Find a REIA</h3></a></li>
<li><a href="#"><img src="img/map-icon.png" alt="Click for More Info"/></a></li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam molestie ullamcorper nisl, sit amet tristique est dapibus nec.</li>
</ul>
</div>
<!-- <div class="small-12 large-3 columns">
<ul>
<li><a href="#">Find a REIA</a></li>
<li><a href="#"><img src="http://placehold.it/500x250" alt="Click for More Info"/></a></li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam molestie ullamcorper nisl, sit amet tristique est dapibus nec.</li>
</ul>
</div> -->
<!-- <div class="small-12 large-3 columns">
</div>
<div class="small-12 large-3 columns">
<ul>
<li><a href="lenders.html">Hard Money Lenders</a></li>
<li><a href="#"><img src="http://placehold.it/500x250" alt="Click for More Info"/></a></li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam molestie ullamcorper nisl, sit amet tristique est dapibus nec.</li>
</ul>
</div>
<div class="small-12 large-3 columns">
<ul>
<li><a href="glossary.html">Real Estate Glossary</a></li>
<li><a href="#"><img src="http://placehold.it/500x250" alt="Click for More Info"/></a></li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam molestie ullamcorper nisl, sit amet tristique est dapibus nec.</li>
</ul>
</div> -->
</div>
</div>
</a>
</li>
<li class="has-submenu is-drilldown-submenu-parent">
<a href="#" class="dropdown" data-toggle="megamenu-property-listings">Property Listings
<div class="dropdown-pane" id="megamenu-property-listings" data-dropdown data-options="closeOnClick:true; hover: true; hoverPane: true">
<div class="row column expanded">
<div class="small-12 large-3 columns">
<ul>
<li><a href="#">All Properties</a></li>
<li><a href="#"><img src="http://placehold.it/1000x250" alt="Click for More Info" /></a></li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam molestie ullamcorper nisl, sit amet tristique est dapibus nec.</li>
</ul>
</div>
<div class="small-12 large-4 columns">
<ul>
<li><a href="#">Single Family Properties</a></li>
<li><a href="#"><img src="http://placehold.it/1000x250" alt="Click for More Info" /></a></li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam molestie ullamcorper nisl, sit amet tristique est dapibus nec.</li>
</ul>
</div>
<div class="small-12 large-4 columns">
<ul>
<li><a href="#">Multi Family Properties</a></li>
<li><a href="#"><img src="http://placehold.it/1000x250" alt="Click for More Info" /></a></li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam molestie ullamcorper nisl, sit amet tristique est dapibus nec.</li>
</ul>
</div>
</div>
</div>
</a>
</li>
<li class="has-submenu is-drilldown-submenu-parent">
<a href="#" class="dropdown" data-toggle="megamenu-websites">Get a Website
<div class="dropdown-pane" id="megamenu-websites" data-dropdown data-options="closeOnClick:true; hover: true; hoverPane: true">
<div class="row column expanded">
<div class="small-12 large-6 columns">
<ul>
<li><a href="#">Get Started</a></li>
<li><a href="#"><img src="http://placehold.it/1000x250" alt="Click for More Info" /></a></li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam molestie ullamcorper nisl, sit amet tristique est dapibus nec.</li>
</ul>
</div>
<div class="small-12 large-6 columns">
<ul>
<li><a href="#">Features</a></li>
<li><a href="#"><img src="http://placehold.it/1000x250" alt="Click for More Info" /></a></li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam molestie ullamcorper nisl, sit amet tristique est dapibus nec.</li>
</ul>
</div>
</div>
</div>
</a>
</li>
<li><a href="#">Reviews</a></li>
<li><a href="#">Sign In</a></li>
</ul>
</div>
</div>
</div>
</header>
</code></pre>
| 2 |
How do I make this pure CSS image comparison slider start at the middle?
|
<p>I have the following </p>
<p><a href="http://codepen.io/anon/pen/AXrEzK" rel="nofollow">http://codepen.io/anon/pen/AXrEzK</a></p>
<p>I want the slider to start in the middle instead of starting way at the left. I have tried to edit the width and make it 185px, but the problem with that is it ruins the slider, the slider starts at the middle but no longer slides to the left.</p>
<pre><code>.image-slider > div {
position: absolute;
top: 0; bottom: 0; left: 0;
width: 185px;
max-width: 100%;
overflow: hidden;
resize: horizontal;
}
</code></pre>
<p>Any help is appreciated, thank you in advance</p>
| 2 |
How are Arrows and Functions different in haskell?
|
<p>I learned and searched about Arrows for a while, and I'm a bit confused about necessity of Arrow class.
As I know, Arrow class is abstraction of function, and Arrow <code>A a b c</code> represents something takes input of type b and output of type c. Also, it provides several fundamental operations like <code>>>></code>, <code>arr</code>, and <code>first</code>.</p>
<p>However, I can't find any difference between standard function of type <code>b -> c</code> and Arrow of type <code>A a b c</code>. In my view, <code>first</code> and <code>>>></code> can be replaced by <code>\(b, c) -> (f b, c)</code>, and <code>(.)</code>. Also, since every computation inside arrow are represented by function, if we replace arrows by those function, I think there will be no difference.</p>
<p>In short, I think every node of computation graph of Arrows(something like in <a href="https://www.haskell.org/arrows/syntax.html" rel="noreferrer">https://www.haskell.org/arrows/syntax.html</a>) can be replaced by standard function of Haskell. If it is true, why do we use Arrow instead of functions?</p>
| 2 |
Angular 2, localhost/null error when trying to use http.get?
|
<p>I am using Angular 2 to make a webpage. When I load the page, I use OnInit to run the following method (with generic names substituted):</p>
<pre><code>getAllObjects(): Promise<object[]>{
return this.http.get(this.getAllObjectsUrl).toPromise().then(response => response.json().data).catch(this.handleError);
}
</code></pre>
<p>I've verified in my browser that the getAllObjects url does indeed return an array of <code>object</code> in JSON format. Here is the url if it is helpful:</p>
<pre><code>private getAllObjectsUrl : 'http://99.240.124.235:7060/REST/rest/companyService/getAllCompanies.json/';
</code></pre>
<p>However, this method triggers the handleError catch and the browser's debugging log shows <code>GET localhost:3000/null 404 NOT FOUND</code> (I am using an npm server to run it, hence the localhost).</p>
<p>I do not believe it is a CORS issue because I downloaded the Chrome CORS plugin and other API calls have worked. It is only this particular API url that is causing a problem, which I find strange as my other API calls work and they follow the exact same format (except a different url). </p>
<p>I thought maybe the <code>appComponent</code> wasn't allowed an OnInit, but I replaced <code>getAllObjects()</code> with a different working API call, and I didn't receive this error.</p>
<p>I am completely stuck and any help would be appreciated (could this error be because of the web API, not the front end?).</p>
| 2 |
Yii2 subquery GROUP BY in active record
|
<p>can I convert this query
"SELECT * FROM (SELECT * FROM blog_post ORDER BY data DESC) blog_post GROUP BY blog_id LIMIT 2" </p>
<p>into a Yii2 active record query?</p>
<p>Thx
Ms</p>
| 2 |
Sql query join average of one column where another column is between two columns values of another table
|
<p>I have two tables, one has two columns that have dates. The other has one column with dates and another with numeric data. I would like to join the average of the second table's numeric column values where its date column is in between the values of the two date columns in the first table. Something like the following:</p>
<p>Table1:</p>
<pre><code>Date1 Date2
6/28 2:00 6/30 4:00
7/1 4:00 7/4 7:00
...
</code></pre>
<p>Table2:</p>
<pre><code>Date3 Value
6/29 1:00 6.5
6/30 3:00 2.5
7/1 5:00 3.0
7/3 9:00 5.0
...
</code></pre>
<p>FinalTable:</p>
<pre><code>Date1 Date2 AvgValue
6/28 2:00 6/30 4:00 4.5
7/1 4:00 7/4 7:00 4.0
</code></pre>
| 2 |
aws cli fails s3 copy with parameter validation
|
<p>On Windows Server 2008 R2 (64), copying a file to s3 bucket:</p>
<blockquote>
<p>aws s3 cp somefile.bak s3://bucket/</p>
</blockquote>
<pre><code>*Parameter validation failed: Invalid type for parameter UploadId, value: None, type: <type 'NoneType'>, valid types: <type 'basestring'>*
</code></pre>
<p>Thanks for your help.</p>
| 2 |
Why member variables of a const object are not const
|
<p>Just asked a similar question which boils down to this one. </p>
<pre><code>#include <iostream>
using namespace std;
struct A {
A() : a{1} {};
int a;
};
template <typename Which>
struct WhichType;
int main() {
const A a;
const A& a_ref = a;
const A* a_ptr = &a;
WhichType<decltype(a.a)> which_obj; // template evaluates to int
WhichType<decltype(a_ref.a)> which_ref; // template evaluates to int
WhichType<decltype(a_ptr->a)> which_ptr; // template evaluates to int
return 0;
}
</code></pre>
<p>Why do the templates do not become <code>const int</code> instead of <code>int</code>?</p>
| 2 |
android AppCompatRadioButton get text if check
|
<p>I try to get text if AppCompatRadioButton is check by button click.<br>
this is layout :</p>
<pre><code><LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="status"
android:textColor="#f2ff00" />
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<android.support.v7.widget.AppCompatRadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radioButtonFull"
android:text="full"
android:textColor="#f2ff00"
app:buttonTint="#ffffff" />
<android.support.v7.widget.AppCompatRadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radioButtonEnd"
android:textColor="#f2ff00"
app:buttonTint="#28ff1c"/>
</RadioGroup>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonSearch"
android:textColor="#ffffff"/>
</LinearLayout>
</code></pre>
<p>this is my code :</p>
<pre><code>AppCompatRadioButton rb_full = (AppCompatRadioButton)view.findViewById(R.id.radioButtonFull);
rb_full.setText("This is full !");
AppCompatRadioButton rb_end = (AppCompatRadioButton)view.findViewById(R.id.radioButtonEnd);
rb_end.setText("This is end !");
String status;
if(rb_full.isChecked()){
status = "Full, please delete something";
}
if(rb_end.isChecked()){
status = "End, please select one of it";
}
bt_Search = (Button) view.findViewById(R.id.buttonSearch);
bt_Search.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Toast.makeText(getActivity().getApplicationContext(), status, Toast.LENGTH_SHORT).show();
}
});
</code></pre>
<p>I try get string status if AppCompatRadioButton is check by button click.<br>
but when click button, Toast show nothing.<br>
How to fix it ?</p>
| 2 |
Requiring only one of two dependencies in a requirements file
|
<p>Some Python packages require one of two packages as a dependency. For example, <code>Ghost.py</code> requires either <code>PySide</code> or <code>PyQt4</code>.</p>
<p>Is it possible to include such a dependency in a <code>requirements.txt</code> file? Is there any 'or' operator that works with these files?</p>
<p>If not, what can I do to add these requirements to the file so only one of them will be installed?</p>
| 2 |
Spark pivot one column but keep others intact
|
<p>Given the following dataframe, how do I pivot the max scores but aggregate the sum of plays?</p>
<pre><code>from pyspark import SparkContext
from pyspark.sql import HiveContext
from pyspark.sql import functions as F
from pyspark.sql import Window
df = sqlContext.createDataFrame([
("u1", "g1", 10, 0, 1),
("u1", "g3", 2, 2, 1),
("u1", "g3", 5, 3, 1),
("u1", "g4", 5, 4, 1),
("u2", "g2", 1, 1, 1),
], ["UserID", "GameID", "Score", "Time", "Plays"])
</code></pre>
<p><strong>Desired Output</strong></p>
<pre><code>+------+-------------+-------------+-----+
|UserID|MaxScoreGame1|MaxScoreGame2|Plays|
+------+-------------+-------------+-----+
| u1| 10| 5| 4|
| u2| 1| null| 1|
+------+-------------+-------------+-----+
</code></pre>
<p>I posted a solution below but I'm hoping to avoid using join.</p>
| 2 |
Swift Spritekit Background image
|
<p>I've recently started learning swift and sprite kit. i am currently trying to do the basics and was trying to fit a background image on to the screen. i have managed to get the background picture up and in the centre of the screen but it is not filling up the whole screen. all help would be appreciated.</p>
<pre><code> import SpriteKit
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
/* Setup your scene here */
let bgImage = SKSpriteNode(imageNamed: "background.png")
bgImage.position = CGPoint(x:self.size.width/2, y: self.size.height/2)
bgImage.anchorPoint = CGPointMake(0.5, 0.5)
bgImage.zPosition = -1
self.addChild(bgImage)
</code></pre>
| 2 |
Using mongoose but connect to Firebase
|
<p>I'm thinking about using mongoose for data modeling but the persistence layer I need to use Firebase. Is it possible to achieve that? For example override some moongose methods for data CRUD?</p>
| 2 |
How to insert value into a html table row by row from a popup modal using jQuery
|
<p>I have a textbox for user input and after submit the textbox does not show the result. The textbox only show the result if I click on the textbox again. It means every time I type, the textbox shows null. After I click again the submit button, it only shows again the result.</p>
<p>But what I want is when I finished filled up the information, the information will automatically appear when I click the "Next"button.</p>
<p>Here I provide my code in jsfiddle:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> $('.contactSelectDiv').off('click').click(function () {
$('#contactInfoModel').openModal();
})
$('#btnNextContactInfoModel').click(function () {
$("body").find('input[name="email"]').val($('#contacttype').val()+ " " + " " + $('#contact').val());
$('#contactInfoModel').closeModal();
})</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="striped">
<h5>Contact</h5>
<thead>
<tr>
<th> </th>
<th>Type</th>
<th>Contact Info</th>
</tr>
</thead>
<tbody>
<tr>
<td>1.</td>
<td>Email 1</td>
<td>
<div class="input-field col s12 m20 l20 contactSelectDiv">
<div class="input-wrapper">
</div>
<input id="email1" name="email" type="text" readonly>
</div>
</td>
</tr>
<tr>
<td>2.</td>
<td>Email 2</td>
<td><div class="input-field col s12 m20 l20 contactSelectDiv">
<div class="input-wrapper">
</div>
<input id="email2" name="email" type="text" readonly>
</div></td>
</tr>
<tr>
<td>3.</td>
<td>Email 3</td>
<td><div class="input-field col s12 m20 l20 contactSelectDiv">
<div class="input-wrapper">
</div>
<input id="email3" name="email" type="text" readonly>
</div></td>
</tr>
<tr>
<td>4.</td>
<td>Handphone 1</td>
<td><div class="input-field col s12 m20 l20 contactSelectDiv">
<div class="input-wrapper">
</div>
<input id="handphone1" name="handphone" type="text" readonly>
</div></td>
</tr>
<tr>
<td>5.</td>
<td>Handphone 2</td>
<td><div class="input-field col s12 m20 l20 contactSelectDiv">
<div class="input-wrapper">
</div>
<input id="handphone2" name="handphone" type="text" readonly>
</div></td>
</tr>
</tbody>
</table>
<div id="contactInfoModel" class="modal modal-fixed-footer" style="max-height:100%;height:80%;width:60%;margin-left:20%;">
<div class="modal-content">
<div class="bread-crumbs-header">
<div class="bread-crumbs-section">
<!--<i class="header-icon small mdi-image-hdr-weak"></i>-->
<div class="header truncate modal-header">
<span data-i18n="personal-particular-update.msg_lookup_contact_info"></span>
</div>
</div>
</div>
<div class="row">
<div class="input-field col s12 m3 l3">
<select id=contacttype>
<option value="" disabled selected>Please select</option>
<option value="1">Type 1</option>
<option value="2">Type 2</option>
<option value="3">Type 3</option>
</select>
<label data-i18n="personal-particular-update.msg_type"></label>
</div>
<div class="col s12 m3 l3">
<td>Contact Info</td>
<div id="Contact Info" >
<input id="contact" name="contacts" type="text">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button id="btnNextContactInfoModel" class="btn-large btn-form-2 btn-floating waves-effect waves-light blue darken-2 right" type="button">
<i class="mdi-navigation-check"></i>
<span>Next</span>
</button>
<button id="btnCloseContactInfoModel" class="btn-large btn-form-2 btn-floating waves-effect waves-light red darken-2 left" type="button">
<i class="mdi-navigation-close"></i>
<span >cancel</span>
</button>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>And I provide explanation of my problem in figure, too.</p>
<p><a href="http://i.stack.imgur.com/pFaNx.jpg" rel="nofollow">Problem Explanation in Figure</a> </p>
| 2 |
why is swift app in going in background when control center opens?
|
<p>In my swift app i am doing log out when activity will go to background,but it is going in background when control center opens.my code is like:</p>
<pre><code>class MyApp:UIViewController{
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(appMovedToBackground), name: UIApplicationWillResignActiveNotification, object: nil)
func appMovedToBackground() {
print("App moved to background!")
self.logout()
}
}
</code></pre>
<p>Is there any way where app will logout when activity runs in background but not when control center opens. </p>
| 2 |
Test offline browsing with Android Chrome
|
<p>I am trying to build an offline-data persistent web application with Service Workers. I managed to have it working on my laptop Chrome (51) and it loads the cached files and displays an offline message when I simulate being offline via the Chrome DevTools - Network tab.
I uploaded the application to github to make sure it is available with https (<a href="https://mguardos.github.io/index.html" rel="nofollow">https://mguardos.github.io/index.html</a>)</p>
<p>However, when I try to test it with my Android Chrome (Nexus 5 - Android 6.0.1 - Chrome 51), the application loads fine when online, but if I set the plane mode on and reload the page, the browsers is not checking the service worker but displaying the offline message directly</p>
<p>"You are offline.
Your devide is offline.
Try: ...
ERR_INTERNET_DISCONNECTED"</p>
<p>Is there any option that I have to enabled in my Android Chrome for Service workers to work?</p>
<p>Thanks for any tip</p>
<p>PS (edited): Same issue occurs with Opera 37 on Android 6.0.1. However, the Registration service happens properly for both Chrome and Opera in the background (validated via an alert upon the registration method is successfully completed)</p>
<p>PSS: The link above tries to be a very basic example of combining service workers with AppCache, to retrieve localStorage and IndexedDB data so any constructive critic would be very much appreciated on top of the original question</p>
| 2 |
React Immutable JS updateIn with list key in object
|
<p>I have an immutable state in React, where I have an map containing list elements. </p>
<p>My getIn function works correctly, e.g.:</p>
<pre><code>console.log(this.state.settings.getIn(["airlines"])[index].checked);
</code></pre>
<p>But I want to update this value with the reverse. </p>
<p>Reading the docs of immutable JS, it should be something like this, but due to my index key I can't get it to work, since my update val should be within the ().</p>
<p>What I currently have is something like this:</p>
<pre><code>this.state.settings.updateIn((["airlines"])[index].checked, val => !val);
</code></pre>
<p>Any help is appreciated!</p>
| 2 |
how to use 3d models in scenekit?
|
<p>So i am starting to learn scenekit and i have some models i want to try on the iphone simulator so i just changed </p>
<pre><code>let scene = SCNScene(named: "art.scassets/ship.scn")!
</code></pre>
<p>which works fine in the scenekit default file to</p>
<pre><code>let scene = SCNScene(named: "art.scassets/battleship.scn")!
</code></pre>
<p>which is a 3d model of a battleship but when i run it it gives me an error near a line of code:</p>
<pre><code>let ship = scene.rootNode.childNodeWithName("ship", recursively: true)!
</code></pre>
<p>The error says: Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP,subcode=0x0)
And: fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)</p>
<p>I'm sorry but it is very hard to explain, but if anyone understood what i said please tell me how to import 3d models to scenekit, i haven't found any tutorial that shows how to do that custom 3d models to scenekit</p>
| 2 |
Webpack can't parse fontello fonts
|
<p>I'm using a custom icon font, made with fontello.
When trying to use this in webpack, I get the following error:</p>
<pre><code>ERROR in ./src/assets/fonts/fontello/fontello.ttf?86736756
Module parse failed:
/Users/idamediafoundry/Documents/Work/Projects/ida-ida-default-
frontend-setup/ida-ida-default-frontend-setup-
static/src/assets/fonts/fontello/fontello.ttf?86736756 Unexpected
character '' (1:0)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected character '' (1:0)
</code></pre>
<p>And it does this for woff(2), ttf, svg... all of them.
I've used several solutions found on SOF, but none of them seem to work. </p>
<p>This is my webpack.config.js:</p>
<pre><code>module: {
loaders: [
{ test: /\.js$/, loader: 'babel', exclude: /node_modules/},
{ test: /\.css$/, loader: "style!css!" },
{ test: /\.scss$/, loader: "style!css!sass!" },
{ test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/font-woff'},
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream'},
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file'},
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml'},
]
}
</code></pre>
<p>Anyone got any ideas on this one?</p>
<p>Thanks!</p>
<p>Regards</p>
<p>Mario</p>
| 2 |
JQuery plugin not working when used multiple times in a page
|
<p>I am trying to write a JQuery plugin called grid2carousel which takes some content in a Bootstrap-style grid on desktop devices and becomes a carousel on smaller screens.</p>
<p>The plugin works fine if it is the only instance of it on a page but runs into some problems if there are more than one. I have created a Codepen here to demonstrate the issue:</p>
<p><a href="http://codepen.io/decodedcreative/pen/BzdBpb">http://codepen.io/decodedcreative/pen/BzdBpb</a></p>
<p>Try commenting out one of the components in the HTML section of the codepen, resizing the browser til it becomes a carousel, and then repeating this process again with it uncommented</p>
<p>The plugin works by running an internal function called SetupPlugin every time the browser width is below a breakpoint specified in a data attribute in the HTML. If the browser width exceeds this breakpoint a function called DestroyPlugin reverts the HTML back to its original state. Like so:</p>
<pre><code> checkDeviceState = function(){
if($(window).width()>breakpointValue){
destroyPlugin();
}else{
if(!$element.hasClass('loaded')){
setupPlugin();
}
}
},
</code></pre>
<p>Below is my plugin code in its entirety. Could someone give me a pointer as to what I'm doing wrong here?</p>
<pre><code>(function (window, $){
$.grid2Carousel = function (node, options){
var
options = $.extend({slidesSelector: '.g2c-slides', buttonsSelector: '.g2c-controls .arrow'}, {},options),
$element = $(node),
elementHeight = 0,
$slides = $element.find(options.slidesSelector).children(),
$buttons = $element.find(options.buttonsSelector),
noOfItems = $element.children().length + 1,
breakpoint = $element.data("bp"),
breakpointValue = 0;
switch(breakpoint){
case "sm":
breakpointValue = 767;
break;
case "md":
breakpointValue = 991;
break;
case "lg":
breakpointValue = 1199;
break;
}
setupPlugin = function(){
// Add loaded CSS class to parent element which adds styles to turn grid layout into carousel layout
$element.addClass("loaded");
// Get the height of the tallest child element
elementHeight = getTallestInCollection($slides)
// As the carousel slides are stacked on top of each other with absolute positioning, the carousel doesn't have a height. Set its height using JS to the height of the tallest item;
$element.height(elementHeight);
// Add active class to the first slide
$slides.first().addClass('active');
$buttons.on("click", changeSlide);
},
destroyPlugin = function(){
$element.removeClass("loaded");
$element.height("auto");
$buttons.off("click");
$slides.removeClass("active");
},
checkDeviceState = function(){
if($(window).width()>breakpointValue){
destroyPlugin();
}else{
if(!$element.hasClass('loaded')){
setupPlugin();
}
}
},
changeSlide = function(){
var $activeSlide = $slides.filter(".active"),
$nextActive = null,
prevSlideNo = $activeSlide.prev().index() + 1,
nextSlideNo = $activeSlide.next().index() + 1;
if($(this).hasClass('left')){
if(prevSlideNo !== 0){
$nextActive = $activeSlide.prev();
$nextActive.addClass('active');
$slides.filter(".active").not($nextActive).removeClass("active");
}else{
$nextActive = $slides.last();
$nextActive.addClass('active');
$slides.filter(".active").not($nextActive).removeClass("active");
}
}else if($(this).hasClass('right')){
if(nextSlideNo !== 0){
$nextActive = $activeSlide.next();
$nextActive.addClass('active');
$slides.filter(".active").not($nextActive).removeClass("active");
}else{
$nextActive = $slides.first();
$nextActive.addClass('active');
$slides.filter(".active").not($nextActive).removeClass("active");
}
}
},
getTallestInCollection = function(collection){
$(collection).each(function(){
if($(this).outerHeight() > elementHeight){
elementHeight = $(this).outerHeight();
}
});
return elementHeight;
};
setupPlugin();
checkDeviceState();
$(window).on("resize", checkDeviceState);
}
$.fn.grid2Carousel = function (options) {
this.each( function (index, node) {
$.grid2Carousel(node, options)
});
return this
}
})(window, jQuery);
</code></pre>
<p>Many thanks, </p>
<p>James</p>
| 2 |
Bootstrap grid putting images on top of each other
|
<p>I'm having issues getting the 3 images to appear next to each other. I'm using ng-repeat with angular to output the first 3 images, but they are on top of each other no matter how I mess with the grid's col-md size. Any suggestions on how to get the images next to each other.</p>
<p><a href="https://i.stack.imgur.com/ZQipK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZQipK.png" alt="enter image description here"></a></p>
<p>HTML</p>
<pre><code><!DOCTYPE html>
<html ng-app='formApp'>
<head>
<title>Bicycle App</title>
<link rel="stylesheet" href="bower_components/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
<link href="app.css" rel="stylesheet">
</head>
<body>
<div class="header">
<div class="container">
<div class='row'>
<div class='col-md-12'>
<i class="fa fa-bicycle" aria-hidden="true"><span>&nbsp;{{"Bike Shop"}}</span></i>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-offset-3 col-md-6">
<!-- end class not needed -->
<div class="chooseTitle">
Choose Your Bicycle
</div>
</div>
</div>
<div class="row">
<div class="col-md-3">
<!-- you missed md from offset, end class not needed -->
<div class="products" ng-controller="BikeController">
<div ng-repeat ="product in products | limitTo: -3">
{{product.manufacturer}}
<img class="img-responsive" ng-src="{{product.image}}" ></div>
</div><!--End controller-->
</div><!--end col-md-3-->
</div><!--end row-->
</div> <!--end container-->
<script src="bower_components/angular/angular.js"></script>
<script src="app.js"></script>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bikeimageslider.js"></script>
<script src="bower_components/angular-animate/angular-animate.js"></script>
</body>
</html>
</code></pre>
<p>app.js</p>
<pre><code>var app = angular.module('formApp', []);
app.controller('BikeController',['$scope', function($scope){
$scope.products = [
{
manufacturer: "Trek",
image: 'images/bike1.jpg'
},
{
manufacturer: "Mongoose",
image: 'images/bike2.jpg'
},
{
manufacturer: "Portlandia",
image: 'images/bike3.jpg'
},
{
manufacturer: "Giant",
image: 'images/bike4.jpg'
},
{
manufacturer: "Framed",
image: 'images/bike5.jpg'
},
{
manufacturer: "Windsor",
image: 'images/bike6.jpg'
}
];
/*
$scope.LeftArrowClick =function(selectedIndex){
if (products[selectedIndex] = products[-1]){
products[selectedIndex] = products[6];
}
};
$scope.increment =0;
$scope.RightArrowClick =function(selectedIndex){
$scope.selectedIndex++;
$scope.selectedObject = $scope.products[selectedIndex];
if ($scope.products === 7){
$scope.products = 0;
}
};
*/
}]);
</code></pre>
| 2 |
How to use the beforeEach in node-tap?
|
<p>Can someone provide an example on how to use the <code>beforeEach</code>? <a href="http://www.node-tap.org/api/" rel="nofollow">http://www.node-tap.org/api/</a>
Ideally, an example of the promise version, but a callback version example would also be nice. </p>
<p>Here is a test I created which works fine:</p>
<pre><code>'use strict';
const t = require('tap');
const tp = require('tapromise');
const app = require('../../../server/server');
const Team = app.models.Team;
t.test('crupdate', t => {
t = tp(t);
const existingId = '123';
const existingData = {externalId: existingId, botId: 'b123'};
const existingTeam = Team.create(existingData);
return existingTeam.then(() => {
stubCreate();
const newId = 'not 123'
const newData = {externalId: newId, whatever: 'value'};
const newResult = Team.crupdate({externalId: newId}, newData);
const existingResult = Team.crupdate({externalId: existingId}, existingData);
return Promise.all([
t.equal(newResult, newData, 'Creates new Team when the external ID is different'),
t.match(existingResult, existingTeam, 'Finds existing Team when the external ID exists')
]);
});
})
.then(() => {
process.exit();
})
.catch(t.threw);
function stubCreate() {
Team.create = data => Promise.resolve(data);
}
</code></pre>
<p>Before I do anything, I want to persist <code>existingTeam</code>. After it's saved, I want to stub <code>Team.create</code>. After these two things, I want to start actually testing. I think it would be cleaner if instead of using a <code>Promise.all</code> or perhaps duplicating the test code, I could use <code>beforeEach</code>.</p>
<p>How would I convert this to use <code>beforeEach</code>? Or what is an example of its usage?</p>
| 2 |
Customize Control center Swift and IOS 9+
|
<p>friends I am working on an ios app using Swift, I am suppose to add app icon in Control Center and also on any web page user should be able to select text or paragraph and save that text in the application. </p>
<p>I just need a hint or starting point, I am sort of new to IOS, have built 3-4 apps but never worked on Control Center and adding service which allow copy and save text and images from iphone browser.</p>
| 2 |
FreeRTOS suspend task from another function
|
<p>So I have a half duplex bus driver, where I send something and then always have to wait a lot of time to get a response. During this wait time I want the processor to do something valuable, so I'm thinking about using FreeRTOS and vTaskDelay() or something. </p>
<p>One way to do it would off be splitting the driver up in some send/receive part. After sending, it returns to the caller. The caller then suspends, and does the reception part after a certain period of time. </p>
<p>But, the level of abstraction would be finer if it continues to be one task from the user point of view, as today. Therefore I was thinking, is it possible for a function within a task to suspend the task itself? Like</p>
<pre><code> void someTask()
{
while(true){
someFunction(&someTask(), arg 1, arg 2,...);
otherStuff();
}
}
void someFunction(*someSortOfReferenceToWhateverTaskWhoCalled, arg1, arg2 ...)
{
if(something)
{
/*Use the pointer or whatever to suspend the task that called this function*/
}
}
</code></pre>
| 2 |
Selecting only rows where one date is less than another with Pandas Dataframe
|
<p>I have a pandas dataframe with this data:</p>
<pre><code>Id Converteddate Createddate
0015000000toohpAAA 2015-07-24 00:00:00 2014-07-08 19:36:13
0015000000tqEpKAAU 2015-03-17 00:00:00 2014-07-16 00:28:06
00138000015me01AAA 2015-10-22 00:00:00 2015-10-22 22:04:55
00138000015me56AAA 2015-10-22 00:00:00 2015-10-22 22:17:52
</code></pre>
<p>I'm trying to only keep rows where ConvertedDate <= CreatedDate + 3 days, so I converted both strings to datetime, then used timedelta to calculate the 3 days. I don't get any error codes, but my output dataframe is keeping records that don't meet my criteria of ConvertedDate <= CreatedDate + 3 days.</p>
<pre><code>netnewframe['CreatedDate'] = netnewframe.apply(lambda row: ToDateTimeObj(row['CreatedDate']), axis=1)
netnewframe['ConvertedDate'] = netnewframe.apply(lambda row: ToDateTimeObj(row['ConvertedDate']), axis=1)
netnewframe = netnewframe[(netnewframe.ConvertedDate <= (netnewframe.CreatedDate + timedelta(days=3)))]
</code></pre>
| 2 |
SAP UI5 oData2 Model use of read method on non-key field error
|
<p>I am trying to read data from Employee table using SAP UI5 and oData 2 Model. I am using Read method of oData model with primary key and it is working well but when I am trying to use with non key field then it is getting error with message </p>
<blockquote>
<p>No key property 'Employee_Name' exists</p>
</blockquote>
<p>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>oModel.read("/Employee_Service(Employee_ID=2)", {
success: function(oData, response) {
alert("Success!");
},
error: function(response) {
alert("Error");
}</code></pre>
</div>
</div>
</p>
<p>Here Employee_ID is primary key and this code is running well. </p>
<pre><code>oModel.read("/Employee_Service(Employee_Name='Bob')", {
success: function(oData, response) {
alert("Success!");
},
error: function(response) {
alert("Error");
}
</code></pre>
<p>This code is getting error as said earlier.</p>
<p>Can you please help me to solve the issue?</p>
| 2 |
Elevation/Shadow to a dialog for pre-21 or pre-lollipop
|
<p>There are posts related to elevation for views for pre-lollipop devices. I applied techniques that could be applied to the dialog but I still can not have elevation/shadow to my dialog. </p>
<p>I tried this in the style but it did not work.</p>
<pre><code><item name="android:background">@android:drawable/dialog_holo_light_frame</item>
</code></pre>
<p>ViewCompat.setElevation() and View.setOutLineProvider() methods are available from Lollipop. So can not use them. </p>
<p>I am not able to add the screeshots here for unknown reason. But the dialog is flat on KK and is elevated and look nice on Lollipop. </p>
<p>This is how I created dialog: </p>
<pre><code>AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(context, R.style.AlertDialogStyle));
Dialog dialog = builder.create();
</code></pre>
<p>And AlertDialogStyle is just this: </p>
<pre><code><style name="AlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
</style>
</code></pre>
<p>Can you help me with any clue on how can I add elevation to dialog on pre-lollipop or pre-21 devices ?</p>
| 2 |
Is every method of ServerEndpoint executed by different thread?
|
<p>I use GF 4 as JavaEE server. </p>
<p>This is how I understand servlet processing: There is a pool of threads and when request comes one thread from this pool is taken to process the request. After that the thread is put back to pool.</p>
<p>Based on the information above I suppose (I am not sure) that websockets (server end points) are processed this way: There is pool of threads, when</p>
<ul>
<li>Client creates new websocket a thread is taken from pool to create new instance of ServerEndpoint and to execute @OnOpen method. After that thread is put back to pool.</li>
<li>Client sends message over websocket to server. Thread is taken from pool to execute @OnMessage method. After that thread is put back to pool.</li>
<li>Client closes the websocket - thread is taken from pool to execute @OnClose method. After that thread is put back to pool.</li>
</ul>
<p>It all means that every method of ServerEndpoint can be executed by different threads. Is my understanding right?</p>
| 2 |
Align a view to the right (appcelerator alloy)
|
<p>I am trying to align the view to the right, I tried</p>
<p>right="0"
I tried getting the width on the controller and subtracting the view size and no succes</p>
<pre><code><View id="logoutAlignRightContainer" layout="horizontal" width="33%" heigh="40dp" right="0">
<View id="logoutAlignRight" left="" width="72dp" height="40dp" right="0">
<Label left="3" class="button" onClick="logoutEvent" width="Titanium.UI.SIZE">Log Out</Label>
</View>
</code></pre>
<p>I want to layout the $.logoutAlignRight to the right, but it stays at the left</p>
| 2 |
MariaDB Galera does not bootstrap the first node
|
<p>I have installed ubuntu 16.04 on a VMware VM. Then I added the repo from mariadb website and I installed the latest version of mariadb 10.1.</p>
<p>The installation works fine</p>
<p>I have then created a file </p>
<pre><code>sudo nano /etc/mysql/conf.d/cluster.cnf
</code></pre>
<p>with the following </p>
<pre><code>[mysqld]
# Cluster node configurations
wsrep_cluster_address="gcomm://20.0.1.51"
wsrep_node_address="20.0.1.51"
innodb_buffer_pool_size=800M
# Mandatory settings to enable Galera
wsrep_on=ON
wsrep_provider=/usr/lib/galera/libgalera_smm.so
binlog_format=ROW
default-storage-engine=InnoDB
innodb_autoinc_lock_mode=2
innodb_doublewrite=1
query_cache_size=0
bind-address=0.0.0.0
# Galera synchronisation configuration
wsrep_sst_method=rsync
</code></pre>
<p>I want only to bootstrap the first node and then add new nodes</p>
<p>So I run </p>
<pre><code>sudo service mysql bootstrap
</code></pre>
<p>But I get this error</p>
<pre><code>Jul 03 02:38:07 db1 mysqld[14779]: at gcomm/src/pc.cpp:connect():162
Jul 03 02:38:07 db1 mysqld[14779]: 2016-07-03 2:38:07 140418873596160 [ERROR] WSREP: gcs/src/gcs_core.cpp:gcs_core_open():208: Failed to open backend connection: -110 (Connection timed ou
Jul 03 02:38:07 db1 mysqld[14779]: 2016-07-03 2:38:07 140418873596160 [ERROR] WSREP: gcs/src/gcs.cpp:gcs_open():1379: Failed to open channel 'my_wsrep_cluster' at 'gcomm://20.0.1.51': -11
Jul 03 02:38:07 db1 mysqld[14779]: 2016-07-03 2:38:07 140418873596160 [ERROR] WSREP: gcs connect failed: Connection timed out
Jul 03 02:38:07 db1 mysqld[14779]: 2016-07-03 2:38:07 140418873596160 [ERROR] WSREP: wsrep::connect(gcomm://20.0.1.51) failed: 7
Jul 03 02:38:07 db1 mysqld[14779]: 2016-07-03 2:38:07 140418873596160 [ERROR] Aborting
Jul 03 02:38:08 db1 systemd[1]: mariadb.service: Main process exited, code=exited, status=1/FAILURE
Jul 03 02:38:08 db1 systemd[1]: Failed to start MariaDB database server.
Jul 03 02:38:08 db1 systemd[1]: mariadb.service: Unit entered failed state.
Jul 03 02:38:08 db1 systemd[1]: mariadb.service: Failed with result 'exit-code'.
</code></pre>
<p>What am I doing wrong??</p>
| 2 |
Enable AWS VPC Flow Logs with Ansible
|
<p>When creating an AWS VPC with Ansible, how to enable <a href="https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/flow-logs.html" rel="nofollow">VPC Flow Logs</a>?</p>
| 2 |
Highlight Table Row Based On Column Value Equal To Value In Another Table Column
|
<p>I have two tables, <code>tblPO</code> in sheet <code>Purchase Order</code> and <code>tblRiskItems</code> in sheet <code>Risky Items</code>. <code>tblPO</code> is used for the purchase order that has columns <code>Item #</code>, <code>Description</code>, <code>Unit Price</code> and <code>Line Total</code>. <code>tblRiskItems</code> contains a list of our items that are either fast movers, slow movers or obsolete, having columns <code>Item #</code>, <code>Description</code> and <code>Status</code> (this column showing whether an item is fast or slow moving or obsolete). Below are pictures of my tables:</p>
<h3>tblPO</h3>
<p><a href="https://i.stack.imgur.com/T60xo.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T60xo.jpg" alt="tblPO"></a></p>
<h3>tblRiskItems</h3>
<p><a href="https://i.stack.imgur.com/5Ygr9.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5Ygr9.jpg" alt="tblRiskItems"></a></p>
<p>What I need is to higlight the entire row in <code>tblPO</code> where it’s <code>Item #</code> matches <code>tblRiskItems</code>’ <code>Item #</code> so that the user knows ordering that item is a risk and needs to be followed up. It would also be great to format the row based on the value in column <code>Status</code> of <code>tblRiskItems</code>, for e.g. green if item is fast moving, yellow if item is slow moving and red if item is obsolete.</p>
<p>My efforts with Conditional Formatting has ended in a disaster. If anyone can suggest how I will be able to achieve this it would be greatly appreciated!</p>
| 2 |
How to use windows server 2012 with sql server standard on aws ec2 classic of t2 instance type?
|
<p>When I tried to launch a new instance of Amazon Machine Image windows server 2012 R2 with SQL server standard ,I was unable to use few of the instance types like t1.micro, t2.large, t2.medium .This instance type is not recommended for your selected Amazon Machine Image.
Few of the instance types are disabled,
Can anyone know the reason behind this ?How can I use t2 instance type for my current requirement to avoid high pricing?</p>
<p>Thanks in Advance</p>
| 2 |
Using RNN in R with factorial input variables
|
<p>In <a href="https://cran.r-project.org/package=rnn" rel="nofollow"><code>rnn</code></a> package in R, the example shows how to train a RNN with numeric input variables.</p>
<p>The example code is:</p>
<pre><code>library('rnn')
# create training numbers
set.seed(1)
X1 = sample(0:127, 7000, replace=TRUE)
X2 = sample(0:127, 7000, replace=TRUE)
# create training response numbers
Y <- X1 + X2
# convert to binary
X1 <- int2bin(X1, length=8)
X2 <- int2bin(X2, length=8)
Y <- int2bin(Y, length=8)
# create 3d array: dim 1: samples; dim 2: time; dim 3: variables
X <- array( c(X1,X2), dim=c(dim(X1),2) )
# train the model
model <- trainr(Y=Y,
X=X,
learningrate = 0.1,
hidden_dim = 10,
start_from_end = TRUE )
</code></pre>
<p>In the above example, <code>X1</code> and <code>X2</code> are numerical variables.</p>
<p>How can I train a RNN model in R if the input variables are factor?</p>
<p>Thanks a lot,</p>
| 2 |
getInboxThreads() for specific inbox folder. Google Apps Script gmail
|
<p>I am trying to retrieve email threads from only a specific folder which I named 'Approval_needed'. I have found a way to get all of my inbox threads like so from the <a href="https://developers.google.com/apps-script/reference/gmail/gmail-app#getInboxThreads()" rel="nofollow">Google Apps Script Reference page</a>:</p>
<pre><code>var threads = GmailApp.getInboxThreads();
for (var i = 0; i < threads.length; i++) {
Logger.log(threads[i].getFirstMessageSubject());
}
</code></pre>
<p>Is it possible to do something like <code>getInboxThreads for folder 'Approval_needed'</code>?<br />
I have searched around and have not found an answer for this. I have found other methods such as <code>getPriorityInboxThreads()</code> and <code>getStarredInboxThreads()</code>, but nothing like <code>getInboxThreads(string)</code>.</p>
| 2 |
Moq verify uses objects modified in Returns, rather than what was actually passed in
|
<p><strong>Background</strong></p>
<p>I have a class that uses NHibernate to persist objects to a database. When you call <code>MergeEntity</code> for an object that does not have an ID set, NHibernate populates that object with an ID when it is returned. In order to make sure I always use the same object as NHibernate is using, I pass that updated object back from my "<code>Save</code>" function.</p>
<p><strong>Problem</strong></p>
<p>I am trying to mock that same behavior using Moq, which is usually very intuitive and easy to use; however, I am having some trouble verifying that the calls to <code>Save()</code> are being made with the correct arguments. I would like to verify that the ID of the object being passed in is zero, then that it is set properly by the <code>Save</code> function. Unfortunately, when I modify the ID in the <code>Moq.Returns()</code> function, the <code>Moq.Verify</code> function uses the modified value rather than the value of the ID that was passed in.</p>
<p>To illustrate, here is a very basic class (I override the ToString() function so my test output will show me what ID was used when the mocked Save() is called):</p>
<pre><code>public class Class1
{
private readonly IPersistence _persistence;
/// <summary>Initializes a new instance of the <see cref="T:System.Object" /> class.</summary>
public Class1(IPersistence persistence)
{
_persistence = persistence;
}
public int Id { get; set; }
public void Save()
{
_persistence.Save(this);
}
public override string ToString()
{
return Id.ToString();
}
}
</code></pre>
<p>Here is the Interface (very straight forward):</p>
<pre><code>public interface IPersistence
{
Class1 Save(Class1 one);
}
</code></pre>
<p>And here is the test that I think should pass:</p>
<pre><code>[TestFixture]
public class Class1Tests
{
[Test]
public void Save_NewObjects_IdsUpdated()
{
var mock = new Mock<IPersistence>();
mock.Setup(x => x.Save(It.IsAny<Class1>()))
.Returns((Class1 c) =>
{
// If it is a new object, then update the ID
if (c.Id == 0) c.Id = 1;
return c;
});
// Verify that the IDs are updated for new objects when saved
var one = new Class1(mock.Object);
Assert.AreEqual(0, one.Id);
one.Save();
mock.Verify(x => x.Save(It.Is<Class1>(o => o.Id == 0)));
}
}
</code></pre>
<p>Unfortunately, it fails saying that it was never called with arguments that match that criteria. The only invocation to <code>Save</code> that was made on the mock is with an object that had an ID of 1. I have verified that the objects have an ID of 0 when they enter the Returns function. Is there no way for me to distinguish what was passed into the mock from what those objects are updated to be if I update the values in my <code>Returns()</code> function?</p>
| 2 |
How to get HTML from the browser in SWT after setting the URL
|
<p>I have tried using</p>
<pre><code>String html = browser.getText();
</code></pre>
<p>But I am getting this error </p>
<blockquote>
<p>Exception in thread "main" org.eclipse.swt.SWTException: Failed to change Variant type result = -2147352571
at org.eclipse.swt.ole.win32.OLE.error(Unknown Source)
at org.eclipse.swt.ole.win32.Variant.getAutomation(Unknown Source)
at org.eclipse.swt.browser.IE.getText(Unknown Source)
at org.eclipse.swt.browser.Browser.getText(Unknown Source)</p>
</blockquote>
<p>I have read this bug report: <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=433526" rel="nofollow">https://bugs.eclipse.org/bugs/show_bug.cgi?id=433526</a></p>
<p>Could anyone help me with other way to get HTML out of the browser?</p>
| 2 |
How can I do a POST redirect from the process_payment function in a woocommerce custom payment gateway?
|
<p>I wish to do a redirect from the process_payment in my custom payment gateway for Wordpress/Woocommerce. </p>
<p>To do a GET redirect you would do:</p>
<pre><code>function process_payment( $order_id ) {
//some code here
//CPN is a value entered by user from custom payment field
$cpn = $_POST['cpn'];
return array(
'result' => 'success',
'redirect' => 'https://www.sandbox.bankserver.com/cgi-bin/webscr?test_ipn=1&CPN='. $cpn
);
}
</code></pre>
<p>The values received from the user in custom payment fields are security sensitive so the bank does not want to receive them via GET. How can I do a POST? </p>
<p>I will POST to the bank URI...which will allow the user to enter CVV on the bank page and then redirect back to my Wordpress site.</p>
| 2 |
R Plotly: Smaller markers in bubble plot
|
<p>I'm making a bubble plot in Plotly (for R) and I keep getting overlapping markers. Is there a way to "scale down" all markers, so that their relative sizes are preserved but there is no overlap? I want to keep the dimensions of plot the same. Here's a test case:</p>
<pre><code>test <- data.frame(matrix(NA, ncol=3, nrow=14))
colnames(test) <- c("Group", "Numbers", "Days")
loop<- 1
for(i in 1:7){
test[i,] <- c(1, i, loop)
loop <- loop * 1.5
}
loop <- 1
for(i in 1:7){
test[i+7,] <- c(2, i, loop)
loop <- loop * 1.3
}
plot_ly(test, x=Group, y=Numbers, size=Days, mode="markers")
</code></pre>
<p><a href="https://i.stack.imgur.com/9d3IB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9d3IB.jpg" alt="booo overlapping markers"></a></p>
| 2 |
Spring MVC - setting properties to a @ModelAttribute object in controller
|
<p>I started to work with Spring, and I found a problem I can't sort out.
I have a User entity, with a 'roles' property, 'roles' is a Set Object, the estity is the following:</p>
<pre><code>private String id;
private String name;
private String surname;
private String email;
private String identificationNumber;
private String username;
private String password;
private String passwordConfirm;
private int sex;
private Timestamp birthDate;
private Set<Role> roles;
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
</code></pre>
<p>My 'Role' entity is the following:</p>
<pre><code>private String id;
private String name;
private Set<User> users;
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToMany(mappedBy = "roles")
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
</code></pre>
<p>In the jsp I have a combobox with the list of all 'Roles'</p>
<pre><code><spring:bind path="roles">
<div class="input-field is-empty cell2">
<form:select type="text" path="roles" class="validate ${status.error ? 'invalid' : ''}">
<form:option value="NONE" selected="selected" disabled="true">Roles</form:option>
<c:forEach items="${allRoles}" var="role">
<form:option value="${role.getId()}" >${role.getName() }</form:option>
</c:forEach>
</form:select>
<form:errors path="roles" class="alert alert-dismissible alert-danger"> </form:errors>
<span class="material-input"></span>
</div>
</spring:bind>
</code></pre>
<p>I select one or many 'roles' and submit the form to following controller, in this exist a @RequestParam with the list of ids of the selected 'roles'</p>
<pre><code>@RequestMapping(value="/user_edit/{id}", method=RequestMethod.POST)
public String edit_user(@ModelAttribute("userForm") User userForm, BindingResult bindingResult, @PathVariable String id, @RequestParam String role_ids) {
Set<Role> role_list = new HashSet<Role>();
for (String role_id : role_ids.split(",")) {
Role _role = roleService.getById(role_id);
Role role = new Role();
role.setName(_role.getName());
role.setId(role_id);
role_list.add(role);
}
userForm.setRoles(role_list);
userValidator.validate(userForm, bindingResult, false);
if (bindingResult.hasErrors()) {
return "edit_user";
}
userService.save(userForm);
return "redirect:/users";
}
</code></pre>
<p>In the line userValidator.validate(userForm, bindingResult, false); the program show the following error:</p>
<pre><code>Failed to convert property value of type [java.lang.String[]] to required type [java.util.Set] for property roles; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.gestcart.account.model.Role] for property roles[0]: no matching editors or conversion strategy found
</code></pre>
<p>Please, help to solve this problem</p>
| 2 |
angular 2 - cache http get result
|
<p>I have a LanguageService that provides a list of available languages.
This list needs to initialized by a backend request:</p>
<pre><code>getAvailableLanguages(): Observable<Language[]> {
...
return this.http.get(ApiResources.LANGUAGE, requestOptions)
.map(response => this.extractJson(response))
.catch(error => this.handleError(error));
}
</code></pre>
<p>I would like to avoid requesting the backend each time another service calls <code>languageService.getAvailableLangauges()</code>.</p>
<p>What would be a good way to cache the result of the necessary first request?</p>
| 2 |
angular 2 check if model change on component
|
<p>First, my code is working. This question is about if I am doing the proper thing and if I am using the power of angular 2. I come from angular 1 and still learning angular 2 core concepts. </p>
<p>Let's start: </p>
<p>Given an angular 2 app (RC.4) I have a calendar component which render a Calendar as view. Each calendar's day is "decorated" RED (busy) or GREEN (free) depending the result coming for an API rest call. If there is not data for a given day the day is not decorated at all.</p>
<p>So, I have the following Observable in calendar's @component. Once it is resolved, a property of the component "entries" is filled with the response. (The response is an array of day objects with a property "dayStatus" set to busy / green). </p>
<pre><code> ngOnInit() {
this.calendarService.getAll().subscribe(
response => {
this.entries = response.json();
}
);
}
</code></pre>
<p>The calendar template has a ngClass which resolves to decorateDay() handler:</p>
<pre><code><span class="day" *ngFor="let day of week.days"
[ngClass]="decorateDay(day)">
{{ day.number }}
</span>
</code></pre>
<p>Every "day", therefore, in a declarative way looks if it should be decorated green or red through the handler decorateDay(day).
It works as follows: "day" is passed as parameter and is used as key for retrieving the relevant object from the JSON array. From the object property a string green / red is passed to the view and decorated by CSS using ngClass. </p>
<pre><code> decorateDay(day) {
let dayFormatted = day.date.format("YYYY-MM-DD");
//when observable was resolved entries is not undefined.
if (typeof this.entries !== 'undefined') {
let data = this.entries[dayFormatted];
if (typeof data !== 'undefined') {
return data.dayStatus;
}
}
}
</code></pre>
<p><strong>And here comes my question:</strong> I don't know when "entries" will be defined so <strong>I check in the handler if undefined.</strong> Looks like when the entries is filled the component <em>Magically</em> recheck again the handler (through change detection). I am ok with that BUT, There is not a better way of checking when a property of the component has changed? Maybe decorating the property with @resolved or using a lifecycle hook..? I don't like the way I am doing it!</p>
<p>Hope some of you can give some pointers. Thanks in advance!</p>
<p>PS: The binding with the model property could be done on the template itself but I want to use a handler because it gives me more flexibility about how to decorate the given day in the future.</p>
| 2 |
Simple Text GUI (TUI) Using NCurses and C to Display System Info
|
<p>I am just beginning to toy around with combining ncurses and C to develop a very minimal TUI. The purpose of the TUI is to greet users with a basic login/welcome screen. The goal would be to display basic system information like the operating system, available memory, IP address, etc. Nothing beyond read-only. </p>
<p>What would be the best way to go about doing this? The part I'm struggling with is interfacing the shell commands like <code>df</code>, <code>ls</code>, <code>ifconfig</code>, etc with variables that I can then display or print in ncurses and C. I know something like this can be done, as well as calling the system command with a string, but this seems somewhat bulky:</p>
<pre><code>#include <ncurses.h>
#include <stdlib.h>
#include <stdio.h>
int main(void) {
FILE *pp;
initscr();
cbreak();
if ((pp = popen("df", "r")) != 0) {
char buffer[BUFSIZ];
while (fgets(buffer, sizeof(buffer), pp) != 0) {
addstr(buffer);
}
pclose(pp);
}
getch();
return EXIT_SUCCESS;
}
</code></pre>
<p>Are there any methods to execute a command in the command line from within a C program and then selectively access the output of that command for later display? Or is this information generally stored somewhere in a parseable file on the machine? I'm new to trying to pull system information/use the command line in a "TUI" sense and any help would be appreciated. Thanks so much in advance!</p>
| 2 |
Swift IOS: How to download image using NSURLSession and didReciveData?
|
<p>I'm a newbie in IOS development. Could you help me saying how to download image using NSURLSession and didReciveData method? I need a progress View with progress of uploading my image. I stuck after creating NSUrlSession. Please, help.</p>
<pre><code> class ViewController: UIViewController, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate {
@IBOutlet weak var progressLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var downloadButton: UIButton!
@IBAction func downloadImage(sender: UIButton) {
let urlString = "https://img-fotki.yandex.ru/get/6111/8955119.3/0_7e1f6_a73b98a0_orig"
let url = NSURL(string: urlString)
var configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
var session: NSURLSession = NSURLSession(configuration: self.configuration)
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
print("didReceiveData")
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
print("didReceiveRes")
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
let alert = UIAlertController(title: "Alert", message: error?.localizedDescription, preferredStyle: .Alert)
let alertAction = UIAlertAction(title: "Ok", style: .Default, handler: nil)
alert.addAction(alertAction)
presentViewController(alert, animated: true, completion: nil)
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
print("didReceiveSendData64")
var uploadProgress: Float = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
progressView.progress = uploadProgress
}
}
</code></pre>
| 2 |
Is there a master list / documentation for when clauses for vscode keybindings?
|
<p>Is there a master list / documentation for when clauses for vscode keybindings?</p>
<p>I can not find this documented anywhere. If I wanted to specify a different action. Say I wanted to have <code>Ctrl</code>+<code>B</code> start a build task when not in a task 'context' and terminate when I am in a task context.</p>
<p>I went through the file and wrote down every when I could find, but nothing looked like 'the thing'.</p>
<pre><code>// Place your key bindings in this file to overwrite the defaults
[{
"key": "cmd+b",
"command": "workbench.action.tasks.build",
"when": "editorTextFocus"
},{
"key": "ctrl+c",
"command": "workbench.action.tasks.terminate",
"when": "???"
}
]
</code></pre>
<ul>
<li>inDebugMode</li>
<li>inQuickOpen</li>
<li>editorTextFocus</li>
<li>suggestWidgetVisible</li>
<li>suggestionSupportsAcceptOnKey</li>
<li>editorLangId == 'xxx'</li>
<li>searchViewletVisible</li>
<li>renameInputVisible</li>
<li>accessibilityHelpWidgetVisible</li>
<li>quickFixWidgetVisible</li>
<li>parameterHintsVisible</li>
<li>referenceSearchVisible</li>
<li>!config.editor.stablePeek</li>
<li>markersNavigationVisible</li>
<li>editorFocus</li>
<li>inSnippetMode</li>
<li>breakpointWidgetVisible</li>
<li>findWidgetVisible</li>
<li>editorTabMovesFocus</li>
<li>editorHasSelection</li>
<li>editorHasMultipleSelections</li>
<li>inReferenceSearchEditor</li>
</ul>
<p>(Also after writing this I found <a href="https://stackoverflow.com/a/33124104/377252">this post where a similar list is posted, but there is no way to be sure that we have the entire list</a></p>
| 2 |
send push to chrome and encryption payload data in php
|
<p>I want send push to web(chrome) with php and I use <a href="https://github.com/Minishlink/web-push" rel="nofollow">https://github.com/Minishlink/web-push</a> lib for this work, but I don't know how to generate or give <code>$userPublicKey</code> and <code>$userAuthToken</code>.</p>
<p>code like this :</p>
<pre><code>use Minishlink\WebPush\WebPush;
$endpoint = 'https://android.googleapis.com/gcm/send/dwh8heIRnRI:APA91bH1nKZESimKK7Oh9ttQeoRovaS4drmCTQfkpvgtyQQKZZ1htwo4e-tKjMw_cS0ozINkXxXV8-jnYmK2__ZCZbrZUVrJxb931CahVUuat08DRqg4Z7yFpserazwCzCNBEcjb2jfb'; // Chrome
$apiKeys = array(
'GCM' => 'AIzacyDV2NtiuwLZGzDaC9bEeEeisS4BANjHw9s',
);
$webPush = new WebPush($apiKeys);
$webPush->sendNotification(
"https://android.googleapis.com/gcm/send/foV7YNoaKbk:APA91bETu6fPcDHsliBIaI3R0ejFqgIUwfMGFatia1563nTXVZTACaZw3tFaHW-z0Tu7YvZLJebxiYEapyzygO_5WvONVHHNDz7G9KPyPLxl-Il3h6QdgMVJhsmWs0ENVEcFt9HJKX0U",
"hey", // optional (defaults null)
"$userPublicKey",
"$userAuthToken"
true // optional (defaults false)
);
</code></pre>
| 2 |
Override Arrow Function in Child Class
|
<p>I use arrow functions in my classes instead of methods because they allow me to use the "this" keyword, and keep the "this" meaning the class itself, rather than the method. </p>
<p>I have an abstract class that defines an empty arrow function that is to be overridden by the child class. Correction, it was originally this:</p>
<pre><code>abstract _configureMultiselect(): void;
</code></pre>
<p>but trying to override that with an arrow function caused this:</p>
<pre><code>Class 'CategorySelect' defines instance member function '_configureMultiselect', but extended class 'SearchFilterCategorySelect' defines it as instance member property.
(property) Select.SearchFilterCategorySelect._configureMultiselect: () => void
</code></pre>
<p>So I changed it to an empty arrow function in the parent class:</p>
<pre><code>_configureMultiselect = () => {};
</code></pre>
<p>But when I try to override that, well, it just doesn't override it, so my <code>_configureMultiselect</code> in the child class is empty, when I obviously want it to have a function. Here is my code:</p>
<pre><code>interface ICategorySelect {
multiselectConfiguration: Object;
numberOfCategories: KnockoutObservable<number>;
allSelected: KnockoutObservable<boolean>;
selectedCategories: KnockoutObservableArray<Category>;
categories: KnockoutObservableArray<Category>;
}
abstract class CategorySelect implements ICategorySelect {
multiselectConfiguration: Object;
numberOfCategories: KnockoutObservable<number>;
allSelected: KnockoutObservable<boolean>;
selectedCategories: KnockoutObservableArray<Category>;
categories: KnockoutObservableArray<Category>;
constructor() {
this._configureMultiselect();
this._instantiateCategories();
this.numberOfCategories = ko.observable(7);
this.allSelected = ko.observable(false);
}
_configureMultiselect = () => {};
_instantiateCategories = () => {
this.categories = ko.observableArray([
new Category("Meat", 1),
new Category("Dairy", 2),
new Category("Confectionary", 3),
new Category("Dessert", 4),
new Category("Baking", 7),
new Category("Grocers", 6),
new Category("Restaurants", 5),
new Category("Condiments", 8),
new Category("beverages", 9),
]);
}
}
export class SearchFilterCategorySelect extends CategorySelect {
constructor() {
super();
}
_configureMultiselect = () => {
this.multiselectConfiguration = {
buttonWidth: '100%',
buttonContainer: '<div style="height: 64px;" />',
buttonClass: 'none',
nonSelectedText: "select categories",
nSelectedText: ' thingymajigs',
allSelectedText: "all of the things!!",
selectAllNumber: false,
includeSelectAllOption: true,
disableIfEmpty: true,
onSelectAll: () => {
this.allSelected(true);
},
onInitialized: () => {
},
onChange: (option, checked) => {
this.selectedCategories = ko.observableArray([]);
var self = this;
$('#category-select option:selected').each(function() {
self.selectedCategories.push(
<Category>($(this).text(), $(this).val())
)
});
console.log(this.selectedCategories());
if(this.selectedCategories().length < this.numberOfCategories()) {
this.allSelected(false);
}
}
};
}
}
</code></pre>
<p>How do I override <code>_configureMultiselect</code> in the child class successfully?</p>
| 2 |
Injected service is undefined right in the constructor
|
<p>For the note, I'm quite uninitiated to Angular (1 or 2 for that matter).</p>
<p>I'm trying to write a "super" layer of Http to avoid having to put the same headers everywhere.</p>
<pre><code>import {Http, ConnectionBackend, RequestOptions, Response, Headers} from '@angular/http';
import {Observable} from 'rxjs';
import {LoadingService} from "../../services/loading.service";
export class HttpLoading extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions,
private _ls: LoadingService )
{
super(backend, defaultOptions);
}
getPostPutHeader() {
var authHeader = new Headers();
authHeader.append("Authorization", "Bearer "+ localStorage.getItem('token') );
authHeader.append('Content-Type', 'application/json');
return authHeader;
}
post(url: string, data:any):Observable<Response> {
this._ls.isLoading = true; // Exception here: this._ls is undefined
return super.post(url, data, { headers: this.getPostPutHeader() })
.map(res => {
this._ls.isLoading = false;
return res;
});
}
}
</code></pre>
<p>And a service to tell when a request is executing; it's injected in the above class HttpLoading.</p>
<pre><code>import {Injectable} from '@angular/core';
@Injectable()
export class LoadingService {
isLoading: boolean = false;
}
</code></pre>
<p>I have a bunch of stuff in my bootstrap, including HttpLoading, LoadingService and ConnectionBackend (for this last one, I get an exception if it's not here).</p>
<pre><code>bootstrap(AppComponent, [
ConnectionBackend,
HttpLoading,
APP_ROUTER_PROVIDERS,
HTTP_PROVIDERS,
LoadingService,
disableDeprecatedForms(),
provideForms()
])
</code></pre>
<p>The problem is that the first time I call <code>HttpLoading</code>'s <code>post</code> method (in yet another service), I get an exception at <code>this._ls.isLoading</code>, because <code>this._ls</code> is undefined, and I can't figure why.</p>
<p>Please tell me if you need more information.</p>
<hr>
<p>Edit</p>
<p><code>LoadingService</code> is correctly injected in my <code>AppComponent</code> (main component).</p>
<pre><code>//imports
//@Component
export class AppComponent {
requesting:boolean = false;
constructor(public authService: AuthService, private router: Router, private _ls: LoadingService) {
}
navigate(route:string) {
this._ls.isLoading = true;
this.router.navigate([route])
.then(() => this._ls.isLoading = false);
}
}
</code></pre>
<hr>
<p>Potential solution</p>
<p>It seems that your public/private parameters must be placed first in the list. I'll let someone more skilled than me explain why, though...</p>
<pre><code>export class HttpLoading extends Http {
constructor(private _ls: LoadingService, backend: ConnectionBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
}
</code></pre>
| 2 |
Java : HttpSession timeout filter check returns valid session object
|
<p>My Web App is purely JS app with crossroads js for routing.
For Login I'm using j_security_check FORM Auth and /LogOut servlet to invalidate session.</p>
<p><strong>Issue 1</strong>
The real issue comes when the session is timed out, the login.html is rendered in part of the page with no css, with error 'Resource interpreted as Stylesheet but transferred with MIME type text/html'</p>
<p>When using filter </p>
<pre><code><filter>
<description>Session Timeout Filter</description>
<filter-name>SessionTimeoutFilter</filter-name>
<filter-class>filters.SessionTimeoutFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SessionTimeoutFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
....
<session-config>
<session-timeout>1</session-timeout>
</session-config>
</code></pre>
<p>and JAVA code</p>
<pre><code>public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = null;
HttpSession session = null;
try {
req = (HttpServletRequest) request;
session = req.getSession(false);
if (session != null && !session.isNew()){
LOGGER.log("Session is Valid");
chain.doFilter(request, response);
}else{
LOGGER.log("Session is Invalid");
req.getRequestDispatcher("/login.html?loggedOut=true").forward(request, response);
}
} catch (Throwable t) {
}
}
</code></pre>
<p><strong>Issue 2</strong>
When the filter runs after say inactive 2-3 mins, it prints "Session is Valid". Why is it so?</p>
| 2 |
Opscenter 6.0 Start up issue
|
<p>Yesterday, I tried to install opscenter and initiated import of existing DSE 5.0 cluster. It failed with certain errors which pointed out that installed version was not opscenter 6.0. root cause - opscenter installation was done from datastax community repo and not enterprise one. I corrected repo information to pointed to enterprose repo, removed existing opscenter 5.2.4, installed new opscenter 6.0 - All looks good. finally when i started the service - startup failed, opscenter fails to start and nothing comes in log files.</p>
<p>I did following to remove opscenter 5.x and to install opscenter 6.0</p>
<ol>
<li>Removed Old Version of ospcenter - Sudo yum remove opscenter</li>
<li>Modified repor to point to enterprise repo e.g sudo vi /etc/yum.repos.d/datastax.repo</li>
<li>Installed 6.0-1 version of opscenter . Sudo yum install opscenter</li>
<li>Started Opscenter - sudo service opscenterd start</li>
</ol>
<p>Opscenter process is not running . it starts and get killed after few seconds - i was able to verify it using top command.I went to check log files and can find only two log files startup.log & gc.log.0.current. nothing in log file opscenterd.log</p>
<pre><code>startup.log
-----------
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=128m; support was removed in 8.0
2016-07-06 15:00:22,763 [opscenterd] INFO: Loading OpsCenter...
2016-07-06 15:00:22,779 [opscenterd] INFO: Updating system path
2016-07-06 15:00:22,780 [opscenterd] INFO: Importing twisted logging
2016-07-06 15:00:25,710 [opscenterd] INFO: Finished importing twisted logging
2016-07-06 15:00:25,710 [opscenterd] INFO: Opscenterd starting up...
</code></pre>
<p>Python version on installation is 2.7.5</p>
<p>When I Start Opscenter in foreground mode - I can see some trace not sure if relevant</p>
<pre><code>sudo ./opscenter -f
--------------------
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=128m; support was removed in 8.0
2016-07-06 15:00:22,763 [opscenterd] INFO: Loading OpsCenter...
2016-07-06 15:00:22,779 [opscenterd] INFO: Updating system path
2016-07-06 15:00:22,780 [opscenterd] INFO: Importing twisted logging
2016-07-06 15:00:25,710 [opscenterd] INFO: Finished importing twisted logging
2016-07-06 15:00:25,710 [opscenterd] INFO: Opscenterd starting up...
Traceback (most recent call last):
File "./bin/twistd", line 63, in <module>
from twisted.scripts.twistd import run
File "/usr/share/opscenter/lib/py/twisted/scripts/twistd.py", line 13, in <module>
from twisted.application import app
File "/usr/share/opscenter/lib/py/twisted/application/app.py", line 17, in <module>
from twisted.application import service, reactors
File "/usr/share/opscenter/lib/py/twisted/application/service.py", line 24, in <module>
from twisted.internet import defer
File "/usr/share/opscenter/lib/py/twisted/internet/defer.py", line 29, in <module>
from twisted.python import lockfile, failure
File "/usr/share/opscenter/lib/py/twisted/python/lockfile.py", line 23, in <module>
from os import kill
ImportError: cannot import name kill
</code></pre>
<p>I tried to Verify if Kill is available in installed version of Python - Looks Ok</p>
<pre><code>$ python -c "import os; from os import kill;print kill"
<built-in function kill>
</code></pre>
<p>opscenter is not running and i cant really find anything in opscenter.log.</p>
<p>can this problem be there because i have removed older version and should have taken upgrade path ?</p>
<p>Edit - If i revert back opscenter 6.0 to 5.2.4 then it starts to work. Looks like i messed up something and need clean way to remove 5.2.4 first in order to get opscenter 6.0 work. Any help or direction is highly appreciated.</p>
| 2 |
difference between passenger and unicorn server
|
<p>I want to know when we should be passenger server and unicorn server and basic difference in both server.
which type of application is best suitable for passenger and unicorn server.</p>
| 2 |
How to call a constructor in a Junit Test in Java?
|
<p>Hello I am using Eclipse Luna and I tried to write a unittest with Junit. I want to give a value(null) to a method and it should throw an exception. The Method is a Constructor and the class has a main. What am i doing wrong. Usually I can call a Method like this Package.class.MethodName(Parameter Parameter) </p>
<p>Test class:</p>
<pre><code>public class WebUntisProviderTest {
public static URL url = null;
@Test(expected = IllegalArgumentException.class)
public void WebUntisProvider() {
final URL url = null;
WebUntisProvider prov = new WebUntisProvider(url);
assertNotNull("object was null" , prov.WebUntisProvider(url) );
fail( "url must not be null.");
}
}
</code></pre>
<p>The tested class:</p>
<pre><code>public class WebUntisProvider {
private URL url;
public static void main(String[] args) throws MalformedURLException {
URL test = new URL("HTTP://google.com");
System.out.println(test.getProtocol());
}
public WebUntisProvider(URL url) {
if (url == null)
throw new IllegalArgumentException("url must not be null.");
if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https"))
throw new IllegalArgumentException("url protocol must be http or https.");
this.url = url;
}
}
</code></pre>
| 2 |
node.js - express - typeerror: res.json is not a function
|
<p>I am trying to respond to an http request, and I'm getting the following error:</p>
<pre><code>TypeError: req.json is not a function
</code></pre>
<p>Here is where I call it:</p>
<pre><code>app.get('/', function (req, res) {
const channel_name = req.query.channel_name;
const user_name = req.query.user_name;
const text = req.query.text;
var input = text.split(" ");
if (input[0] == "move") { // Make move
game.move(user_name, channel_name, input[1], input[2], function(returnGame) {
req.json(game.getGameStatus(returnGame));
});
}
else {
var boardSize = 3;
if (input.length == 2)
boardSize = input[1];
var newGame = game.startGame(channel_name, user_name, input[0], boardSize);
res.json(game.getGameStatus(newGame));
}
});
app.listen(port);
</code></pre>
<p>game.move and game.startGame both return a JSON called Game. StartGame creates the JSON and returns it, but move loads the JSON from a database and uses a callback to return it.
I get the error when I call req.json from the callback, but it works fine for StartGame.</p>
<p>Any ideas? I've been stuck on this all day and can't seem to figure it out. Any help is appreciated, thanks.</p>
| 2 |
Spring boot exception handling for specific annotated methods
|
<p>Our spring boot controllers have methods called by ajax as well as the standard methods rendering CRUD templates. We'd like to be able to annotate all our ajax methods with a single annotation so that regardless of what type of exception is thrown, we can return a response the ui can handle. </p>
<p>I've been looking at the ControllerAdvice and ExceptionHandler annotations, but I don't think either can be used the way we intend. ControllerAdvice can only cover entire controllers, so any exception handling would also cover the non-ajax methods. Similarly, the ExceptionHandler annotation would handle exceptions from both types of methods.</p>
<p>The current idea is to split the two types of methods, ajax and CRUD, into separate controllers. Is there another way to do this?</p>
| 2 |
React unit tests with Enzyme don't re-bind context of helper functions
|
<p>This is an interesting issue that I came across while trying to refactor some of my React components using AirBnB's React testing library, <a href="https://github.com/airbnb/enzyme" rel="nofollow">Enzyme</a>.</p>
<p>I think the best way to explain my problem is through an example.</p>
<p>Here is a small React component that will display a message depending on the props it receives from its parent component:</p>
<p><strong>test.js:</strong></p>
<pre><code>import React from 'react';
function renderInnerSpan() {
const {foo} = this.props;
if (foo) {
return <span>Foo is truthy!</span>;
}
return <span>Foo is falsy!</span>;
}
export default class extends React.Component {
render() {
return (
<div>
{renderInnerSpan.call(this)}
</div>
);
}
}
</code></pre>
<p>And here is a test suite for this component with two passing tests:</p>
<p><strong>test.spec.js:</strong></p>
<pre><code>import Test from '../../src/test';
import React from 'react';
import {shallow} from 'enzyme';
import {expect} from 'chai';
describe('Test Suite', () => {
let renderedElement,
expectedProps;
function renderComponent() {
const componentElement = React.createElement(Test, expectedProps);
renderedElement = shallow(componentElement);
}
beforeEach(() => {
expectedProps = {
foo: true
};
renderComponent();
});
it('should display the correct message for truthy values', () => {
const span = renderedElement.props().children;
expect(span.props.children).to.equal('Foo is truthy!');
});
it('should display the correct message for falsy values', () => {
expectedProps.foo = false;
renderComponent();
const span = renderedElement.props().children;
expect(span.props.children).to.equal('Foo is falsy!');
});
});
</code></pre>
<p>This works fine, but the Test component's current implementation isn't as efficient as it could be. By using <code>.call(this)</code>, it is creating a new function every time the <code>render()</code> function is called. I could avoid this by binding the correct context of <code>this</code> in the component's constructor, like so:</p>
<pre><code>export default class extends React.Component {
constructor(props) {
super(props);
renderInnerSpan = renderInnerSpan.bind(this);
}
render() {
return (
<div>
{renderInnerSpan()}
</div>
);
}
}
</code></pre>
<p>After this change, the component still works as intended, but the tests start failing:</p>
<pre><code>AssertionError: expected 'Foo is truthy!' to equal 'Foo is falsy!'
Expected :Foo is falsy!
Actual :Foo is truthy!
</code></pre>
<p>I added a <code>console.log(props.foo)</code> in the constructor, which confirmed that the constructor was still being called when I expected it to, and the props it's receiving are correct. However, I added a <code>console.log(foo)</code> inside of <code>renderInnerSpan</code>, and it looks like the value is true all the time, even after re-rendering the component with its <code>foo</code> prop explicitly set to <code>false</code>.</p>
<p>It looks like <code>renderInnerSpan</code> is only be bound once, and Enzyme is re-using this for every single test. So, what gives? I'm re-creating my component in the test, which is calling its constructor with the values I expect - why is my bound <code>renderInnerSpan</code> function continuing to use old values?</p>
<p>Thanks in advance for the help.</p>
| 2 |
Spring Security BCrypt Password Encoder - Workload Factor
|
<p>I'm integrating Spring Security's Bcrypt Password Encoder into a new application, and while testing I noticed that the workload doesn't seem to have an effect when matching a password using two encoders with different work factors. Take the following example:</p>
<pre><code>public static void main(String[] args) {
PasswordEncoder strongEncoder = new BCryptPasswordEncoder(12);
PasswordEncoder weakEncoder = new BCryptPasswordEncoder(6);
String password = "SomePassword@@";
String strongEncodedPass = strongEncoder.encode(password);
String weakEncodedPass = weakEncoder.encode(password);
//Prints true
System.out.println(weakEncoder.matches(password, strongEncodedPass));
//Prints true
System.out.println(strongEncoder.matches(password, weakEncodedPass));
}
</code></pre>
<p>Shouldn't both print statements results in false since the encoders are using different work loads?</p>
<p>The above sample was tested using spring-security-core-4.1.0.RELEASE.jar in Java 8</p>
| 2 |
how to load my own data or online dataset in python for training CNN or autoencoder?
|
<p>I'm trouble in a simple problem during loading dataset in python. I want to define function called <code>loading_dataset()</code> to use it in training auto encoder
my code is</p>
<pre><code>import matplotlib
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from urllib import urlretrieve
import cPickle as pickle
import os
import gzip
rom urllib import urlretrieve
import cPickle as pickle
import os
import gzip
import matplotlib.cm as cm
import theano
import lasagne
from lasagne import layers
from lasagne.updates import nesterov_momentum
from nolearn.lasagne import NeuralNet
from nolearn.lasagne import visualize
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
#############################I tried to load data from open source
def load_dataset():
url = 'ftp://ftp nrg.wustl.edu/data/oasis_cross-sectional_disc2.tar.gz'
filename ='oasis_cross-sectional_disc2.tar.gz'
if not os.path.exists(filename):
print("Downloading MNIST dataset...")
urlretrieve(url, filename)
with gzip.open(filename, 'rb') as f:
data = pickle.load(f)
X_train, y_train = data[0]
X_val, y_val = data[1]
X_test, y_test = data[2]
X_train = X_train.reshape((-1, 1, 28, 28))
X_val = X_val.reshape((-1, 1, 28, 28))
X_test = X_test.reshape((-1, 1, 28, 28))
y_train = y_train.astype(np.uint8)
y_val = y_val.astype(np.uint8)
y_test = y_test.astype(np.uint8)
return X_train, y_train, X_val, y_val, X_test, y_test
X_train, y_train, X_val, y_val, X_test, y_test = load_dataset()
</code></pre>
<p>downloading MNIST dataset...</p>
<pre><code>Traceback (most recent call last):
File "<pyshell#46>", line 1, in <module>
X_train, y_train, X_val, y_val, X_test, y_test = load_dataset()
File "<pyshell#45>", line 6, in load_dataset
urlretrieve(url, filename)
File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 98, in urlretrieve
return opener.retrieve(url, filename, reporthook, data)
File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 245, in retrieve
fp = self.open(url, data)
File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 213, in open
return getattr(self, name)(url)
File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 526, in open_ftp
host = socket.gethostbyname(host)
IOError: [Errno socket error] [Errno 8] nodename nor servname provided, or not known
</code></pre>
<p>this error appeared</p>
<p>I also tried to load data from my desktop using this code
for path, dirs, files in os.walk(pat):
for filename in files:
fullpath = os.path.join(path, filename)
with open(fullpath, 'r') as f:
s=np.load(f)
data = f.read()
print data</p>
<p>but I failed to load data as values for X_train, y_train, X_val, y_val, X_test, y_test
I don't know if I should compress dataset in .pkl.gz or use different function for loading data
could you help me?</p>
| 2 |
Microsoft Access Send email to Client and get Email address from database
|
<p>Gday all,</p>
<p>I'm trying to send a Report from Microsoft Access to a Client.</p>
<p>So i have a client table with the client details including an email address etc..</p>
<p>And in my form i am using a button linked to a macro that creates the report and sends it via email using "EMailDatabaseObject"
However this way i cannot select the email address from the list in my clients section i have to type one in the macro builder or leave blank and get prompted for it.</p>
<p>Is there anyway that i could have a Select Query linked to the "to" section of EMailDatabaseObject?</p>
<p>Or is there another way i should be trying to do this?</p>
| 2 |
jekyll/liquid: given key access value from hash in template
|
<p>given the following code in a jekyll template</p>
<pre><code>{% assign resource = site.data.resources | where: "id", page.resource %}
</code></pre>
<p>that derives the following hash:</p>
<pre><code>{
"id"=>"resource-1234",
"title"=>"testing",
"description"=>"Quis autem vel eum iure reprehenderit qui"
}
</code></pre>
<p>How do I user liquid to output the value of the title key? I have tried the following:</p>
<pre><code>{{ resource }} # outputs the hash
{{ resource.title }} # nil
{{ resource["title"] }} # nil
</code></pre>
| 2 |
Create instance of a class and set variables
|
<p>in C# you can create a instance of a class and set the values of variables at the same time:</p>
<pre><code>public class Object
{
public virtual long Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int Version { get; set; }
public long ParentId { get; set; }
}
public class Start
{
Object object= new Object()
{
Id = 1,
Name = name,
ParentId = parentId,
Description = null,
Version= 2
};
}
</code></pre>
<p>Is this possible in Java aswell and how?</p>
| 2 |
Attach file from Google Drive to gmail api compose mail
|
<p>I have been trying to attach Google Drive Document to my php gmail api compose box.</p>
<p>So far I have managed to get file id on select file but can't find a proper way to how to attach that file.download url to mail box . is there any way to do so?</p>
<p>i also try download file using following code but showing error "<strong>Only binary file can be downloaded</strong>"</p>
<pre><code> var downloadUrl = 'https://www.googleapis.com/drive/v2/files/' + file.id + '?alt=media';
//var downloadUrl2 = file.downloadUrl1;
if (downloadUrl) {
//var accessToken = gapi.auth.getToken().access_token;
//debugger;
var xhr = new XMLHttpRequest();
xhr.open('GET',downloadUrl);
debugger;
xhr.setRequestHeader('Authorization', 'Bearer ' + AUTH_TOKEN);
xhr.onload = function() {
alert(xhr.responseText);
};
xhr.onerror = function() {
alert('Error');
};
xhr.send();
} else {
alert('No Url');
}
</code></pre>
| 2 |
Netty 4 : Write ByteBuf as a HTTP Chunk
|
<p>Netty 4.1.2.Final</p>
<p>Here is my pipeline:</p>
<pre><code>pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpObjectAggregator(65536));
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new HttpInboundHandler());
</code></pre>
<p>Here is <code>HttpInboundHandler</code> class:</p>
<pre><code>class HttpInboundHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg)
throws Exception {
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
if (HttpUtil.isKeepAlive(msg)) {
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
}
// Write the initial line and the header.
ctx.write(response);
if (msg.method() == HttpMethod.GET) {
ByteBuf buf = Unpooled.copiedBuffer("HelloWorld", CharsetUtil.UTF_8);
ByteBufInputStream contentStream = new ByteBufInputStream(buf);
// Write the content and flush it.
ctx.writeAndFlush(new HttpChunkedInput(new ChunkedStream(contentStream)));
//ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
//
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
</code></pre>
<p>Here is the HTTP request</p>
<pre><code>GET / HTTP/1.1
Host: 127.0.0.1:8888
Connection: keep-alive
Cache-Control: max-age=0
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en,zh-CN;q=0.8,zh;q=0.6
</code></pre>
<p>Here is the HTTP response</p>
<pre><code>HTTP/1.1 200 OK
transfer-encoding: chunked
connection: keep-alive
0
</code></pre>
<p>The "<code>HelloWorld</code>" does not appear in the response, but only a zero -length chunked is received. What is the problem?</p>
| 2 |
Audio player on bootstrap navbar
|
<p>I am trying to center elements on a bootstrap navbar. Everything works until I add an audio player.</p>
<p>Can anyone help me with how to center my navbar elements, and how to make sure it works on mobile?</p>
<p>Here is my code:</p>
<pre><code> <nav class="navbar navbar-inverse">
<div class="container-fluid top-nav">
<ul class="nav navbar-nav">
<li class="nav-item">
<a class="nav-link" href="https://www.facebook.com/999fmthezoo?ref=hl" target="_blank" onclick="ga('send', 'event', 'link', 'click', 'Facebook Social Clicks');">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-facebook fa-stack-1x fa-inverse"></i>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="https://twitter.com/wzooradio" target="_blank" onclick="ga('send', 'event', 'link', 'click', 'Twitter Social Clicks');">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-twitter fa-stack-1x fa-inverse"></i>
</a>
</li>
<li class="nav-item">
<ul class="nav navbar-nav">
<li class="nav-item">
<audio preload="auto" controls>
<source src="http://stream1.mtcstream.com:8500/wzoo">
</audio>
</li>
</ul>
</li>
<li class="nav-item">
<ul class="nav navbar-nav navbar-right cta-container">
<li class="nav-item">
<a class="phone" href="tel:336-672-3333">Call <u>336-672-3333</u></a>
</li>
</ul>
</li>
</ul>
</div>
</code></pre>
<p></p>
| 2 |
How to extract values from Eureka forms in swift to local variables?
|
<p>While I try to pass it to temporary variables it doesn't seem to happen.</p>
<p>Although there are no errors while building the app, once I try to enter a value for "rateOfPaddy", it fails, citing "fatal error: unexpectedly found nil while unwrapping an Optional value"</p>
<p>Please let me know if I'm doing anything wrong, either related to Swift or Eureka?</p>
<pre><code> form +++ Section()
<<< DateTimeRow() {
$0.tag = "RecordDateTag"
$0.title = "Date"
$0.value = NSDate()
}.cellSetup { cell, row in
cell.textLabel?.textColor = UIColor.blackColor()
}.onCellHighlight { _ in
if let dateInput = formInput["RecordDateTag"] as? String {
self.dateInputValue = dateInput
}
}.onCellUnHighlight { _ in
if let dateInput = formInput["RecordDateTag"] as? String {
self.dateInputValue = dateInput
}
}
</code></pre>
<p>I used .onChange callback to check and pass the information to local variables, which was of no use. .onCellHighlight and .onCellUnHighlight combination didn't do the trick either!!</p>
| 2 |
Kong in Docker : Configuring API endpoints without curl
|
<p>Is there a way to add API endpoints in Kong without using curl? I have Kong up and running in a docker container using docker-compose and I would like to be able to pass in a configuration file (or what-have-you) on container spin up that outlines the endpoints I would like setup. Is this possible? This is the closest I have found to a solution : <a href="http://blog.toast38coza.me/kong-up-and-running-part-2-defining-our-api-gateway-with-ansible/" rel="noreferrer">http://blog.toast38coza.me/kong-up-and-running-part-2-defining-our-api-gateway-with-ansible/</a></p>
| 2 |
Sonarqube incorrect report for duplicated code
|
<p>I am a newbie to SonarQube and trying to use the tool for measuring my product quality. </p>
<p>In some cases, I found that the duplicated lines is reported incorrectly by SonarQube . The number of lines of code is less than the duplicated lines. How can that be ? Either the count of lines of code is incorrect or the count of duplicated lines is incorrect.</p>
<p>Assuming it could be a problem with my code alone, I visited the demo page of Sonarqube <a href="https://sonarqube.com/component_measures/domain/Duplications?id=com.adobe%3Aas3corelib" rel="nofollow noreferrer">https://sonarqube.com/component_measures/domain/Duplications?id=com.adobe%3Aas3corelib</a></p>
<p>There as well , I found that one of the cases the lines of code is less than duplicated lines.</p>
<p>Where is the issue ? How do I address it ?</p>
<p><img src="https://i.stack.imgur.com/wzzKU.png" alt="Screenshot of the error from sonar demo "></p>
| 2 |
Rails: datetime_field does not display control buttons
|
<p>I have a form, where I use <code>date_field</code> helper and it works well, the control buttons are shown, but when I change it with a <code>datetime_field</code> the field is displayed but control buttons are no displayed.</p>
<p>My <code>date_field</code> which works fine:</p>
<pre><code>=f.date_field :publishing_date, placeholder: "yyyy-mm-dd", class: "form-control"
</code></pre>
<p>the <code>datetime_field</code> which does not shown controls:</p>
<pre><code>=f.datetime_field :publishing_date, class: "form-control"
</code></pre>
| 2 |
How to create mapping with json file in elasticsearch2.3?
|
<p>I'm using ES2.3</p>
<p>create new index mapping with below command works.</p>
<pre><code>curl -XPUT 'http://localhost:9200/megacorp' -d '
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1
},
"mappings": {
"employee": {
"properties": {
"first_name": {
"type": "string"
},
"last_name": {
"type": "string"
},
"age": {
"type": "integer"
},
"about": {
"type": "string"
},
"interests": {
"type": "string"
},
"join_time": {
"type": "date",
"format": "dateOptionalTime",
"index": "not_analyzed"
}
}
}
}
}
'
</code></pre>
<p>now i hope can use a json file to create same index. tmap.json file like below</p>
<pre><code> {
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1
},
"mappings": {
"employee": {
"properties": {
"first_name": {
"type": "string"
},
"last_name": {
"type": "string"
},
"age": {
"type": "integer"
},
"about": {
"type": "string"
},
"interests": {
"type": "string"
},
"join_time": {
"type": "date",
"format": "dateOptionalTime",
"index": "not_analyzed"
}
}
}
},
"aliases": [ "source" ]
}
</code></pre>
<p>then i usr curl to create it.</p>
<pre><code>curl -s -XPOST 'localhost:9200/megacorp' --data-binary @tmap.json
</code></pre>
<p>and </p>
<pre><code>curl -XPUT 'http://localhost:9200/megacorp' -d @tmap.json
</code></pre>
<p>both above commands not working, get error like below.</p>
<pre><code>{"error":{"root_cause":[{"type":"class_cast_exception","reason":"java.util.ArrayList cannot be cast to java.util.Map"}],"type":"class_cast_exception","reason":"java.util.ArrayList cannot be cast to java.util.Map"},"status":500}%
</code></pre>
<p>how to create index with curl and my json file? this is really confused me for long time.</p>
<p>can any body help me? thanks.</p>
| 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.