title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
Simple Xml - Element Declared Twice Error
|
<p>I have been trying to wrap a set of classes based on Simple XML (Java Serializer) around a RSS Feed. The sample feed is </p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
<channel>
<title>Coding Horror</title>
<link>http://www.codinghorror.com/blog/</link>
<description>programming and human factors - Jeff Atwood</description>
<language>en-us</language>
<lastBuildDate>Wed, 04 May 2011 20:34:18 -0700</lastBuildDate>
<pubDate>Wed, 04 May 2011 20:34:18 -0700</pubDate>
<generator>http://www.typepad.com/</generator>
<docs>http://blogs.law.harvard.edu/tech/rss</docs>
<image>
<title>Coding Horror</title>
<url>http://www.codinghorror.com/blog/images/coding-horror-official-logo-small.png</url>
<width>100</width>
<height>91</height>
<description>Logo image used with permission of the author. (c) 1993 Steven C. McConnell. All Rights Reserved.</description>
<link>http://www.codinghorror.com/blog/</link>
</image>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/codinghorror" />
</channel>
</rss>
</code></pre>
<p>The error that I am getting while running the code is </p>
<pre><code>org.simpleframework.xml.core.PersistenceException: Element 'link' declared twice at line 24
</code></pre>
<p>And the error is fair enough because the particular element name occurs twice in the xml but in different ways.</p>
<p>The first link element is here</p>
<pre><code><link>http://www.codinghorror.com/blog/</link>
</code></pre>
<p>Its directly under the Channel tag. And then the next link tag is again under Channel in the following format</p>
<p><code><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/codinghorror" /></code></p>
<p>In Channel.java class I cannot have two variables with the same name link. I tried changing a variable name to blogLink and tried giving name in the Element annotation and Eclipse gave me this error</p>
<pre><code> Change was
@Element("name=link")
Result is
The attribute value is undefined for the annotation Element
</code></pre>
<p>I know I am missing something here but I am not able to put my finger on it. I would appreciate any help on this.</p>
<p>UPDATE</p>
<p>Channel Class</p>
<pre><code>@Element(name="link")
@Namespace(reference="http://www.w3.org/2005/Atom",prefix="atom")
private atomlink atomlink;
public atomlink getAtomLink() {
return atomlink;
}
</code></pre>
<p>Link Class</p>
<pre><code> import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Root;
@Root(name="link")
@Namespace(reference="http://www.w3.org/2005/Atom",prefix="atom10")
public class atomlink {
@Attribute
private String rel;
public String getRel() {
return rel;
}
</code></pre>
<p>}</p>
<p>I have changed the class names and yet it still points to the same error.</p>
| 1 | 1,362 |
XML schema to java classes using XJC
|
<p>I am using an oficial XSD schema downloaded from here:</p>
<p><a href="http://docs.oasis-open.org/ubl/os-UBL-2.0.zip" rel="nofollow">http://docs.oasis-open.org/ubl/os-UBL-2.0.zip</a></p>
<p><em>(Path: xsd/maindoc/UBL-Order-2.0.xsd)</em></p>
<p>And when I use the following command for generating java classes with XJC, I always get an error in console which I don't know how to deal with.</p>
<p><strong>Command:</strong></p>
<pre><code>xjc -d C:\Users\Oscar\Desktop\results -p com.ubl.order C:\Users\Oscar\Desktop\os-UBL-2.0\xsd\maindoc\UBL-Order-2.0.xsd
</code></pre>
<p><strong>Error:</strong></p>
<pre><code>parsing a schema...
[WARNING] Simple type "UnitCodeContentType" was not mapped to Enum due to EnumMemberSizeCap limit. Facets count: 1.093, current limit: 256. You can use customization attribute "typesafeEnumMaxMembers" to extend the limit.
line 38 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/CodeList_UnitCode_UNECE_7_04.xsd
[WARNING] Simple type "BinaryObjectMimeCodeContentType" was not mapped to Enum due to EnumMemberSizeCap limit. Facets count: 616, current limit: 256. You can use customization attribute "typesafeEnumMaxMembers" to extend the limit.
line 38 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/CodeList_MIMEMediaTypeCode_IANA_7_04.xsd
[WARNING] Simple type "LanguageCodeContentType" was not mapped to Enum due to EnumMemberSizeCap limit. Facets count: 276, current limit: 256. You can use customization attribute "typesafeEnumMaxMembers" to extend the limit.
line 38 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/CodeList_LanguageCode_ISO_7_04.xsd
compiling a schema...
[ERROR] A class/interface with the same name "com.ubl.order.LocationType" is already in use. Use a class customization to resolve this conflict.
line 9890 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonAggregateComponents-2.0.xsd
[ERROR] (Relevant to above error) another "LocationType" is generated from here.
line 1543 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] A class/interface with the same name "com.ubl.order.TextType" is already in use. Use a class customization to resolve this conflict.
line 2598 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Relevant to above error) another "TextType" is generated from here.
line 1070 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UnqualifiedDataTypeSchemaModule-2.0.xsd
[ERROR] A class/interface with the same name "com.ubl.order.NameType" is already in use. Use a class customization to resolve this conflict.
line 1718 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Relevant to above error) another "NameType" is generated from here.
line 1105 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UnqualifiedDataTypeSchemaModule-2.0.xsd
[ERROR] A class/interface with the same name "com.ubl.order.AmountType" is already in use. Use a class customization to resolve this conflict.
line 613 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Relevant to above error) another "AmountType" is generated from here.
line 57 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UnqualifiedDataTypeSchemaModule-2.0.xsd
[ERROR] A class/interface with the same name "com.ubl.order.MeasureType" is already in use. Use a class customization to resolve this conflict.
line 1668 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Relevant to above error) another "MeasureType" is generated from here.
line 930 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UnqualifiedDataTypeSchemaModule-2.0.xsd
[ERROR] A class/interface with the same name "com.ubl.order.QuantityType" is already in use. Use a class customization to resolve this conflict.
line 2143 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Relevant to above error) another "QuantityType" is generated from here.
line 1035 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UnqualifiedDataTypeSchemaModule-2.0.xsd
[ERROR] A class/interface with the same name "com.ubl.order.ChannelCodeType" is already in use. Use a class customization to resolve this conflict.
line 763 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Relevant to above error) another "ChannelCodeType" is generated from here.
line 119 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] A class/interface with the same name "com.ubl.order.DocumentStatusCodeType" is already in use. Use a class customization to resolve this conflict.
line 1103 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Relevant to above error) another "DocumentStatusCodeType" is generated from here.
line 618 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] A class/interface with the same name "com.ubl.order.PackagingTypeCodeType" is already in use. Use a class customization to resolve this conflict.
line 1873 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Relevant to above error) another "PackagingTypeCodeType" is generated from here.
line 1113 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] A class/interface with the same name "com.ubl.order.TransportModeCodeType" is already in use. Use a class customization to resolve this conflict.
line 2753 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Relevant to above error) another "TransportModeCodeType" is generated from here.
line 1708 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] A class/interface with the same name "com.ubl.order.AllowanceChargeReasonCodeType" is already in use. Use a class customization to resolve this conflict.
line 603 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Relevant to above error) another "AllowanceChargeReasonCodeType" is generated from here.
line 19 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] A class/interface with the same name "com.ubl.order.TransportEquipmentTypeCodeType" is already in use. Use a class customization to resolve this conflict.
line 2728 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Relevant to above error) another "TransportEquipmentTypeCodeType" is generated from here.
line 1609 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] A class/interface with the same name "com.ubl.order.PaymentMeansCodeType" is already in use. Use a class customization to resolve this conflict.
line 1978 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Relevant to above error) another "PaymentMeansCodeType" is generated from here.
line 1212 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] A class/interface with the same name "com.ubl.order.CurrencyCodeType" is already in use. Use a class customization to resolve this conflict.
line 913 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Relevant to above error) another "CurrencyCodeType" is generated from here.
line 517 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] A class/interface with the same name "com.ubl.order.LongitudeDirectionCodeType" is already in use. Use a class customization to resolve this conflict.
line 1563 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Relevant to above error) another "LongitudeDirectionCodeType" is generated from here.
line 915 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] A class/interface with the same name "com.ubl.order.SubstitutionStatusCodeType" is already in use. Use a class customization to resolve this conflict.
line 2478 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Relevant to above error) another "SubstitutionStatusCodeType" is generated from here.
line 1411 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] A class/interface with the same name "com.ubl.order.LineStatusCodeType" is already in use. Use a class customization to resolve this conflict.
line 1528 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Relevant to above error) another "LineStatusCodeType" is generated from here.
line 816 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] A class/interface with the same name "com.ubl.order.LatitudeDirectionCodeType" is already in use. Use a class customization to resolve this conflict.
line 1468 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Relevant to above error) another "LatitudeDirectionCodeType" is generated from here.
line 717 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] Two declarations cause a collision in the ObjectFactory class.
line 9890 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonAggregateComponents-2.0.xsd
[ERROR] (Related to above error) This is the other declaration.
line 1543 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] Two declarations cause a collision in the ObjectFactory class.
line 2598 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Related to above error) This is the other declaration.
line 1070 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UnqualifiedDataTypeSchemaModule-2.0.xsd
[ERROR] Two declarations cause a collision in the ObjectFactory class.
line 1718 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Related to above error) This is the other declaration.
line 1105 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UnqualifiedDataTypeSchemaModule-2.0.xsd
[ERROR] Two declarations cause a collision in the ObjectFactory class.
line 613 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Related to above error) This is the other declaration.
line 57 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UnqualifiedDataTypeSchemaModule-2.0.xsd
[ERROR] Two declarations cause a collision in the ObjectFactory class.
line 1668 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Related to above error) This is the other declaration.
line 930 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UnqualifiedDataTypeSchemaModule-2.0.xsd
[ERROR] Two declarations cause a collision in the ObjectFactory class.
line 2143 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Related to above error) This is the other declaration.
line 1035 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UnqualifiedDataTypeSchemaModule-2.0.xsd
[ERROR] Two declarations cause a collision in the ObjectFactory class.
line 763 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Related to above error) This is the other declaration.
line 119 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] Two declarations cause a collision in the ObjectFactory class.
line 1103 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Related to above error) This is the other declaration.
line 618 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] Two declarations cause a collision in the ObjectFactory class.
line 1873 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Related to above error) This is the other declaration.
line 1113 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] Two declarations cause a collision in the ObjectFactory class.
line 2753 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Related to above error) This is the other declaration.
line 1708 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] Two declarations cause a collision in the ObjectFactory class.
line 603 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Related to above error) This is the other declaration.
line 19 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] Two declarations cause a collision in the ObjectFactory class.
line 2728 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Related to above error) This is the other declaration.
line 1609 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] Two declarations cause a collision in the ObjectFactory class.
line 1978 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Related to above error) This is the other declaration.
line 1212 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] Two declarations cause a collision in the ObjectFactory class.
line 913 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Related to above error) This is the other declaration.
line 517 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] Two declarations cause a collision in the ObjectFactory class.
line 1563 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Related to above error) This is the other declaration.
line 915 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] Two declarations cause a collision in the ObjectFactory class.
line 2478 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Related to above error) This is the other declaration.
line 1411 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] Two declarations cause a collision in the ObjectFactory class.
line 1528 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Related to above error) This is the other declaration.
line 816 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] Two declarations cause a collision in the ObjectFactory class.
line 1468 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
[ERROR] (Related to above error) This is the other declaration.
line 717 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-QualifiedDatatypes-2.0.xsd
[ERROR] Two declarations cause a collision in the ObjectFactory class.
line 166 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonAggregateComponents-2.0.xsd
[ERROR] (Related to above error) This is the other declaration.
line 230 of file:/C:/Users/Oscar/Desktop/os-UBL-2.0/xsd/common/UBL-CommonBasicComponents-2.0.xsd
Failed to produce code.
</code></pre>
<p>What I tried was to not use the oficial XSD and generate my own using trang.jar. The result was good, I got my generated java classes but when I create a XML document with JAXB (using those classes) the namespaces are not ok.</p>
<p>So, what I want is to use the oficial XSD but modified (maybe) to make it work.</p>
<p><strong>How can I solve this to get my generated classes?</strong> </p>
<p>Thanks in advance.</p>
| 1 | 5,870 |
Databinding the color of a RadialGradient brush in silverlight 3
|
<p>I am trying to databind the color of a RadialGradientBrush in silverlight 3 to a property, but just can't seem to get it to work.</p>
<p>For example, in a sample test app all I have is </p>
<pre><code><navigation:Page x:Class="SilverlightNavigator.HomePage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
x:Name="HomePageUC"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
Title="HomePage Page">
<Grid x:Name="LayoutRoot" Background="White">
<StackPanel>
<TextBlock
DataContext="{Binding ElementName=HomePageUC}"
Text="{Binding TestColorOne}" />
<Rectangle x:Name="testRectangle" Height="100" Width="100"
DataContext="{Binding ElementName=HomePageUC}" >
<Rectangle.Fill>
<RadialGradientBrush>
<GradientStop Color="{Binding TestColorOne}" Offset="0" />
<GradientStop Color="{Binding TestColorTwo}" Offset="1"/>
<!--
<GradientStop Color="#FFFF0000" />
<GradientStop Color="#FF00FF00" Offset="1"/>
-->
</RadialGradientBrush>
</Rectangle.Fill>
</Rectangle>
</StackPanel>
</code></pre>
<p>In the code behind, I have even made them dependency properties like this ..</p>
<pre><code> public static readonly DependencyProperty TestColorOneProperty =
DependencyProperty.RegisterAttached("TestColorOne", typeof(Color), typeof(HomePage), null);
public static readonly DependencyProperty TestColorTwoProperty =
DependencyProperty.RegisterAttached("TestColorTwo", typeof(Color), typeof(HomePage), null);
public Color TestColorOne
{
get { return (Color)GetValue(TestColorOneProperty); }
set { SetValue(TestColorOneProperty, value); }
}
public Color TestColorTwo
{
get { return (Color)GetValue(TestColorTwoProperty); }
set { SetValue(TestColorTwoProperty, value); }
}
</code></pre>
<p>But this still gives me the very unhelpful AG_E_PARSER_BAD_PROPERTY_VALUE exception. If I uncomment the two Xaml lines where the colors are hard coded, it works fine. I know the properties are fine because if I hard code the colors or comment out the rectangle, it displays the text fine. (Via the binding to the TextBlock) </p>
<p>I have also tried passing in the string "Red", "Blue" etc. instead of the color object. But the binding just doesn't seem to work.</p>
<p>Any advice?</p>
| 1 | 1,182 |
RecyclerView notifyItemInserted duplicates previous entry's data
|
<p>So for some reason whenever I add a new item to my ArrayList and notify the recyclerview that it's been added, it duplicates the previous entry's data. So the view gets created but with data from the last entry not the current data.</p>
<p>What's strange is that I save the items using ORM Sugar, and so when I retrieve them the correct data is displayed. Which shows that the data is getting added but the view is not showing it correctly.</p>
<p>I can only assume recyclerview is not calling the onBindViewHolder whenever I use the method notifyItemInserted, <strong>because the correct data is shown when I use notifyDataSetChange()</strong></p>
<p>Here's my method to add the new item</p>
<pre><code>@Override
public void AddCalorieToHistoryList(int calorieAmount, int currentCalorieAmount) {
// Get the date and the calorie amount from what the user entered.
Date date = new Date();
// Create the calorie history item and then save it (via ORM Sugar Library)
CalorieHistory calorieHistory = new CalorieHistory(date.toString(), calorieAmount);
calorieHistory.save();
// Notify the view of the new item that should be inserted.
historyView.InsertNewListItem(calorieHistory);
SubtractFromCurrentCalorieAmount(calorieAmount, currentCalorieAmount);
}
</code></pre>
<p>historyView's method</p>
<pre><code>@Override
public void InsertNewListItem(CalorieHistory calorieHistoryItem) {
// Add the new item
calorieHistories.add(calorieHistoryItem);
// Notify the insert so we get the animation from the default animator
historyListAdapter.notifyItemInserted(0);
}
</code></pre>
<p>Here's the recyclerview adapter</p>
<pre><code>public class HistoryListAdapter extends RecyclerView.Adapter<HistoryListAdapter.HistoryListViewHolder> {
List<CalorieHistory> calorieHistoryList;
public HistoryListAdapter(List<CalorieHistory> historyList) {
this.calorieHistoryList = historyList;
}
// I think this is run once, it generates the view holder from the layout that we are using for each list item.
// This way it won't have to grab it each time we make a new list item. It's all stored on our view holder.
@Override
public HistoryListViewHolder onCreateViewHolder(ViewGroup parent, int i) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.calorie_history_item, parent, false);
return new HistoryListViewHolder(itemView);
}
// This executes everytime we make a new list item, it binds the data to the view.
@Override
public void onBindViewHolder(HistoryListViewHolder holder, int position) {
// Get the current calorHistory object and set it's data to the views.
CalorieHistory calorieHistory = calorieHistoryList.get(position);
holder.tvDate.setText(calorieHistory.date);
holder.tvAmount.setText(String.valueOf(calorieHistory.numberOfCalories));
}
@Override
public int getItemCount() {
// Return the size of our array.
return calorieHistoryList.size();
}
public static class HistoryListViewHolder extends RecyclerView.ViewHolder {
public TextView tvDate;
public TextView tvAmount;
public HistoryListViewHolder(View v) {
super(v);
tvDate = (TextView) v.findViewById(R.id.calorie_date);
tvAmount = (TextView) v.findViewById(R.id.calorie_amount);
}
}
}
</code></pre>
| 1 | 1,193 |
Objective C Dynamic NSDictionary for UI Table View divided by Section Headers
|
<p>So this is based off of my question here</p>
<p><a href="https://stackoverflow.com/questions/14493725/objective-c-when-to-use-nsdictionary-instead-of-nsarray#comment20201177_14493725">objective c when to use NSDictionary instead of NSArray</a></p>
<p>Apologies for the noob questions. I just started learning objective c and I'm really confused. </p>
<pre><code>- (void)viewDidLoad
{
[super viewDidLoad];
headers = [NSArray arrayWithObjects:@"Header Section 1 (H1)", @"Header Section 2 (H2)", nil];
events = [NSArray arrayWithObjects:@"H1 Content 1", @"H1 Content 2", nil];
myInfo = [NSArray arrayWithObjects:@"H2 Content 1", @"H2 Content 2", @"H2 Content 3", nil];
menuDetails = [[NSMutableDictionary alloc] init];
for(NSString *event in events){
[menuDetails setValue:event forKey:@"Header Section 1 (H1)"];
}
for(NSString *info in myInfo){
[menuDetails setValue:info forKey:@"Header Section 1 (H2)"];
}
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return [[menuDetails allKeys] count];
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return [[[menuDetails allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]objectAtIndex:section];
}
</code></pre>
<ol>
<li><p>Wanted to limit this for the First Section but not on the 2nd section</p>
<pre><code>-(NSInteger)tableView:(UITableView *)tableview numberOfRowsInSection:(NSInteger)section {
return 5;
}
</code></pre></li>
<li><p>So I'm not really sure how to make this dynamic when I try to fill up the cells with this method. I'm not really sure how to make sure it selects the "Key" of the section the specific cell is at (blocked line) :</p></li>
</ol>
<hr>
<pre><code>-(UITableViewCell *)tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *) indexPath {
static NSString *CellIdentifier = @"OptionCellIdentifier";
MenuOptionTableCell *cell = (MenuOptionTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil){
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"OptionCellIdentifier" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
NSDictionary *menuItem = [[menuDetails valueForKey:[[[menuDetails allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.optionName.text = [menuItem objectForKey:@"Events"];
return cell;
}
</code></pre>
<p>EDIT: GAAAHHH, the formatting is killing me. It won't get inside the code markup</p>
<p>This is where Idk what to do:</p>
<blockquote>
<p>cell.optionName.text = [menuItem objectForKey:@"Events"];</p>
</blockquote>
<p>So what I wanted to happen is:</p>
<ul>
<li>Section Header 1
<ol>
<li>H1 Content 1</li>
<li>H1 Content 2</li>
</ol></li>
<li>Section Header 1
<ol>
<li>H2 Content 1</li>
<li>H2 Content 2</li>
<li>H1 Content 3</li>
</ol></li>
</ul>
| 1 | 1,136 |
How to solve "Cannot access androidx.activity.contextaware.ContextAware'"?
|
<p>I'm building a simple application using LiveData and viewmodels but iam getting the following warning messages in my activity surrodning my activity some of the warning</p>
<p><strong>Cannot access 'androidx.activity.contextaware.ContextAware' which is a supertype of 'com.example.movies.presentation.home.MoviesActivity'. Check your module classpath for missing or conflicting dependencies</strong></p>
<pre><code> dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$life_cycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$life_cycle_version"
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
kapt "androidx.lifecycle:lifecycle-compiler:$life_cycle_version"
// Hilt
implementation "com.google.dagger:hilt-android:$hilt_version"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$life_cycle_version"
kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
//moshi
implementation("com.squareup.moshi:moshi:$moshi_version")
kapt("com.squareup.moshi:moshi-kotlin-codegen:$moshi_version")
//retrofit
implementation "com.squareup.retrofit2:retrofit:$retrofit_version"
implementation "com.squareup.retrofit2:converter-moshi:$retrofit_version"
implementation("com.squareup.okhttp3:logging-interceptor:$okhttp_version")
//espresso testing
androidTestImplementation "androidx.test.espresso:espresso-core:$espresso_core"
androidTestImplementation "androidx.test:runner:$test_runner"
androidTestImplementation "androidx.test:rules:$test_runner"
// Hilt For instrumentation tests
androidTestImplementation "com.google.dagger:hilt-android-testing:$hilt_testing"
androidTestAnnotationProcessor "com.google.dagger:hilt-compiler:$hilt_testing"
//Hilt For local unit tests
testImplementation "com.google.dagger:hilt-android-testing:$hilt_testing"
testAnnotationProcessor "com.google.dagger:hilt-compiler:$hilt_testing"
//mockk for testing
testImplementation "io.mockk:mockk:$mockk_version"
//coroutine testing
testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutine_test_version"
testImplementation("org.junit.jupiter:junit-jupiter-api:$junit_5")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:$junit_5")
testImplementation "android.arch.core:core-testing:$arch_version"
</code></pre>
<p>my module build.gradle</p>
<pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.4.31"
ext.hilt_version = '2.31.2-alpha'
ext.junit = '1.7.1.1'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.1.3'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"
classpath "de.mannodermaus.gradle.plugins:android-junit5:$junit"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
ext {
life_cycle_version = "2.2.0"
espresso_core = "3.3.0"
test_runner = "1.3.0"
hilt_testing = "2.33-beta"
moshi_version = "1.10.0"
mockk_version = "1.11.0"
retrofit_version = "2.9.0"
okhttp_version = "4.9.0"
coroutine_test_version = "1.4.3"
junit_5 = "5.7.1"
arch_version = "2.2.0"
}
</code></pre>
<p><a href="https://i.stack.imgur.com/HzmPH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HzmPH.png" alt="enter image description here" /></a></p>
| 1 | 1,944 |
how to use multithreading with pika and rabbitmq to perform Requests and Responses RPC Messages
|
<p>I'm working on a Project with Rabbitmq, I'm using the RPC Pattern, basically I'm receiving or consuming Messages from a Queue, make some Processing and then send a Response back. Im using Pika, my goal is to use a Thread per Task so for every Task i ll make a Thread perticularly for that Task. I also read that the best Practice is to make only one Connection and under it many channels as i want to, but i get always this Error :<br />
'start_consuming may not be called from the scope of '
pika.exceptions.RecursionError: start_consuming may not be called from the scope of another BlockingConnection or BlockingChannel callback.</p>
<p>I made some Research and found out that Pika is not thread safe and we should use for every Thread an Independant Connection and a channel. but i dont want to do that since it is considered bad Practice. So I wanted to ask here if someone already achieved to make this work. I read also that it is Possible if i didn't use BlockingConnection to instantiate my Connection and also that there is a Function called add_callback_threadsafe which can make this Possible. but there is unfortunally no Examples for that and I read the Documentation but it's complex and without Examples it was hard for me to grasp what they want to describe.</p>
<p>my Try was to declare two Classes. Each class will represent a Task Executer which receive or consume a message from a queue and based on that made some Processing and deliver a Response back. my idea was to share a rabbitmq Connection between the two Tasks but every Task will get an independant Channel. in the Code above the rabbit Parameter passed to the function is a Class that holds some Variables like Connection and other Functions like EventSubscriber which when called it will assign a new Channel and start consuming messages from that Particular Exchanges and routingKey. Next i declare a Thread and give the subscribe or Consume function as a Target to that Thread. the other Task Class look also the same as this Class that's why i ll only upload this Code. in the main Class i make a Connection to rabbitmq and pass it as Parameter to the constructor of the Two Task Classes.</p>
<p>class On_Deregistration:</p>
<pre><code>def __init__(self, rabbit):
self.event(rabbit) # this will call event function and pass the connection shared between all Tasks. rabbit parameter hold a connection to rabbitmq
def event(self, rabbit):
self.Subscriber = rabbit.EventSubscriber(rabbit, 'testing.test', 'test', False, onDeregistrationFromHRS # this func is task listener)
def subscribeAsync(self):
self.Subscriber.subscribe() # here i call start_consuming
def start(self):
"""start Subscribtion in an Independant Thread """
thread = threading.Thread(target = self.subscribeAsync )
thread.start()
if thread.isAlive():
print("asynchronous subscription started")
</code></pre>
<hr />
<h1>MAin Class:</h1>
<p>class App:</p>
<pre><code>def __init__(self):
self.rabbitMq = RabbitMqCommunicationInterface(host='localhost', port=5672)
firstTask = On_Deregistration(self.rabbitMq)
secondTask = secondTask(self.rabbitMq)
</code></pre>
<p>app = App()</p>
<h1>error : 'start_consuming may not be called from the scope of '</h1>
<p>pika.exceptions.RecursionError: start_consuming may not be called from the scope of another BlockingConnection or BlockingChannel callback</p>
<p>I searched for the cause of this Error and obviously is pika not thread safe but there must be a Solution for this. maybe Not using a BlockingConnection ? maybe someone can give me an Example how to do that because i tried it and didnt work. Maybe I'm missing something about how to Implement multithreading with rabbitmq</p>
| 1 | 1,032 |
EditText field in AlertDialog not working
|
<p>I'm new to android, trying to build a simple app involving some simple data input and management. When I follow the guide <a href="http://www.mkyong.com/android/android-prompt-user-input-dialog-example/" rel="nofollow">here</a>, which ask for user input through an alert dialog. Everything works fine except that, after the AlertDialog appears, the <code>EditText</code> field does not have an input cursor displayed, and it won't display/update the text I typed. However, I can obtain the text string I typed in correctly after I pressed the 'OK' button in the alert dialog. Here is the xml file and code involving that dialog:</p>
<p>xml:</p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Type Your Message : "
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/grade_in"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</EditText>
</code></pre>
<p></p>
<p>code:</p>
<pre><code>Button grade_in = button;
grade_in.setTag(tag);
grade_in.setOnClickListener(new OnClickListener(){
public void onClick(View btn) {
LayoutInflater inflater = LayoutInflater.from(activity.getApplicationContext());
View prompt_grade_in = inflater.inflate(R.layout.grade_in, null);
final EditText input_field = (EditText)prompt_grade_in.findViewById(R.id.grade_in);
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(activity);
alertBuilder.setView(prompt_grade_in);
alertBuilder.setCancelable(true)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Log.v(null, input_field.getText().toString());
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setMessage("Grade for the course:");
AlertDialog alert = alertBuilder.create();
alert.show();
}
});
</code></pre>
<p>I tried adding a TextWatcher but it does not help. Is the version the source of this problem? Because I think I pretty much followed the guide except that I've made some minor changes. Thanks for helping!</p>
<p>p.s. the page containing the button invoke the input dialog is a fragment.</p>
<p><strong>UPDATE:</strong>
The fragment containing the button consists of an <code>ExpandableListView</code>, which is implemented according to this <a href="http://www.vogella.com/tutorials/AndroidListView/article.html#listfragments" rel="nofollow">guide</a> (part 15). And the above code implementing the alert dialog is in a custom adapter class, which create the group item in the list, inside the following function:</p>
<pre><code>public View getGroupView(int groupPosition, boolean isExpanded, View convertView, final ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.listrow_group, null);
}
CheckedTextView checkedTextView = (CheckedTextView) convertView.findViewById(R.id.textView1);
course courses = (course) getGroup(groupPosition);
((CheckedTextView) checkedTextView).setText(courses.code + " - " + courses.title);
((CheckedTextView) checkedTextView).setChecked(isExpanded);
String tag = courses.code + " - " + courses.title;
CheckBox checkbox = (CheckBox) convertView.findViewById(R.id.checkbox_course);
checkbox.setChecked(sharedPref.getBoolean(tag, false));
setBoxListener(checkbox, tag);
Button button = (Button) convertView.findViewById(R.id.grade_button);
setBtnListener(button, tag);
return convertView;
}
</code></pre>
| 1 | 1,861 |
Qemu fails to load when my initrd (cpio) is large ~80 mb
|
<p>I am new to qemu and am trying to learn kernel programming, I create an initrd which has busy box, but when I add a big tarbal ~80Mb in the cpio qemu fails to load.</p>
<p>I wanted to include golang in intrd, so that i could test the new kernel.</p>
<p>This is what is happening:</p>
<pre><code>mfrw@kp ~/os/busybox/test_build
% ls
bin linuxrc sbin usr
mfrw@kp ~/os/busybox/test_build
% !find
find . | cpio -o -H newc | gzip > rootfs_bb.gz
cpio: File ./rootfs_bb.gz grew, 1261568 new bytes not copied
7374 blocks
mfrw@kp ~/os/busybox/test_build
% ls -ltrh
total 2.6M
drwxr-xr-x 2 mfrw mfrw 4.0K Mar 18 01:56 bin
lrwxrwxrwx 1 mfrw mfrw 11 Mar 18 01:56 linuxrc -> bin/busybox
drwxr-xr-x 2 mfrw mfrw 4.0K Mar 18 01:56 sbin
drwxr-xr-x 4 mfrw mfrw 4.0K Mar 18 15:24 usr
-rw-r--r-- 1 mfrw mfrw 2.6M Mar 18 15:31 rootfs_bb.gz
mfrw@kp ~/os/busybox/test_build
%
</code></pre>
<p>Then I run it using qemu with a freshly made kernel with rootfs = 2.6 M</p>
<pre><code>mfrw@kp ~/os/linux_staging % qemu-system-x86_64 -nographic -no-reboot -kernel arch/x86/boot/bzImage -initrd ./../busybox/test_build/rootfs_bb.gz -append "panic=1 console=ttyS0 rdinit=/bin/sh"
[ 0.000000] Linux version 4.11.0-rc2+ (mfrw@kp) (gcc version 6.3.1 20170109 (GCC) ) #7 SMP Sat Mar 18 02:34:27 IST 2017
[ 0.000000] Command line: panic=1 console=ttyS0 rdinit=/bin/sh
[ 0.000000] x86/fpu: x87 FPU will use FXSAVE
[ 0.000000] e820: BIOS-provided physical RAM map:
[ 0.000000] BIOS-e820: [mem 0x0000000000000000-0x000000000009fbff] usable
...... the kernel boots fine
</code></pre>
<p>But When I include the tar.gz for golang in the rootfs, it shoots upto 80M and then fails to boot</p>
<pre><code>mfrw@kp ~/os/busybox/test_build
% cp ~/go/go1.6.linux-amd64.tar.gz usr
mfrw@kp ~/os/busybox/test_build
% !fin
find . | cpio -o -H newc | gzip > rootfs_bb.gz
170406 blocks
mfrw@kp ~/os/busybox/test_build
% ls -ltrh
total 82M
drwxr-xr-x 2 mfrw mfrw 4.0K Mar 18 01:56 bin
lrwxrwxrwx 1 mfrw mfrw 11 Mar 18 01:56 linuxrc -> bin/busybox
drwxr-xr-x 2 mfrw mfrw 4.0K Mar 18 01:56 sbin
drwxr-xr-x 4 mfrw mfrw 4.0K Mar 18 15:34 usr
-rw-r--r-- 1 mfrw mfrw 82M Mar 18 15:34 rootfs_bb.gz
mfrw@kp ~/os/busybox/test_build
%
</code></pre>
<p>I try to run it with the same command and it fails to run...</p>
<pre><code>mfrw@kp ~/os/linux_staging % qemu-system-x86_64 -nographic -no-reboot -kernel arch/x86/boot/bzImage -initrd ./../busybox/test_build/rootfs_bb.gz -append "panic=1 console=ttyS0 rdinit=/bin/sh"
.... no .. output
</code></pre>
<p>What am I doing wrong ? Any pointers please :)</p>
| 1 | 1,175 |
How to use AES Encryption and Decryption from Scala to Python
|
<p>I have a code in scala where I have my encryption and decryption code, It works fine and the code is:</p>
<pre><code>import java.util.Base64
import javax.crypto.Cipher
import javax.crypto.spec.{IvParameterSpec, SecretKeySpec}
class Encryption {
val key = "enIntVecTest2020"
val initVector = "encryptionIntVec"
def encrypt(text: String): String = {
val iv = new IvParameterSpec(initVector.getBytes("UTF-8"))
val skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES")
val cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv)
val encrypted = cipher.doFinal(text.getBytes())
return Base64.getEncoder().encodeToString(encrypted)
}
def decrypt(text:String) :String={
val iv = new IvParameterSpec(initVector.getBytes("UTF-8"))
val skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES")
val cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv)
val original = cipher.doFinal(Base64.getDecoder.decode(text))
new String(original)
}
}
val encryptobj = new Encryption()
val pwd = "#test@12345"
val result =encryptobj.encrypt(pwd)
</code></pre>
<p>pwd: String = #test@12345<br />
result: String = lHhq1OzMSYnj+0XxiNzKhQ==</p>
<pre><code>val pwd1 = encryptobj.decrypt(result)
println(pwd1)
</code></pre>
<p>pwd1: String = #test@12345<br />
#test@12345</p>
<p>I tried in Python to achieve the same but does not give the expected encryption result, here is my code(I took the help of other similar answers):</p>
<pre><code>from hashlib import sha256
import base64
from Crypto import Random
from Crypto.Cipher import AES
BS = 16
pad = lambda s: bytes(s + (BS - len(s) % BS) * chr(BS - len(s) % BS), 'utf-8')
unpad = lambda s : s[0:-ord(s[-1:])]
class AESCipher:
def __init__( self, key ):
self.key = bytes(key, 'utf-8')
def encrypt( self, raw ):
raw = pad(raw)
iv = "encryptionIntVec".encode('utf-8')
cipher = AES.new(self.key, AES.MODE_CBC, iv )
return base64.b64encode( iv + cipher.encrypt( raw ) )
def decrypt( self, enc ):
enc = base64.b64decode(enc)
iv = enc[:16]
cipher = AES.new(self.key, AES.MODE_CBC, iv )
return unpad(cipher.decrypt( enc[16:] )).decode('utf8')
cipher = AESCipher('enIntVecTest2020')
encrypted = cipher.encrypt('#test@12345')
decrypted = cipher.decrypt(encrypted)
print(encrypted)
</code></pre>
<p>b'ZW5jcnlwdGlvbkludFZlY5R4atTszEmJ4/tF8YjcyoU='</p>
<p>As you can see both the encryption is not right, I don't know where I am doing wrong. Please help in achieving the same encrypting result in python as showing in scala, I would be much thankful.</p>
| 1 | 1,152 |
Fetch Date from mysql db into dropdown box in PHP
|
<p>I am developing user edit form where users can edit their info. I wants only that date come in combo box which was user add in table as Date of Birth. In following code I successfully pull Month into Combo box which user added in table. </p>
<p>IN FOLLOWING LINE I RUN SELECT QUERY TO FETCH DATA FROM DB INCLUDING YEAR, MONTH AND DAY:</p>
<pre><code><?php
$cnic_selected=$_POST['all_cnic'];
if(isset($cnic_selected))
{
$query = mysql_query("SELECT refer_id, emp_name, emp_father, emp_cnic, YEAR(emp_dob) AS byear, MONTH(emp_dob) AS bmonth, DAY(emp_dob) AS bday FROM staff_users WHERE emp_cnic = '$cnic_selected'");
$count = mysql_num_rows($query);
while($row = mysql_fetch_object($query))
{
$ref = $row->refer_id;
$name = $row->emp_name;
$fname = $row->emp_father;
$cnic = $row->emp_cnic;
$byear = $row->byear;
$bmonth = $row->bmonth;
$bday = $row->bday;
}
?>
<html>
<head>
</head>
<body>
<table width="95%">
<form name="edituserform" action="" method="Post" onSubmit="return validateform(this);">
<tr><td width="125px"><b>Referral Code</b></td>
<td><?php echo $ref; ?></td></tr>
<tr><td><b>Full Name</b></td>
<td><input type="text" name="emp_name" id="emp_name" value="<?php echo $name; ?>" />
</td></tr>
<tr><td><b>Father's Name</b></td>
<td><input type="text" name="emp_father" id="emp_father" value="<?php echo $fname; ?>" />
</td></tr>
<tr><td><b>CNIC Number</b></td>
<td><?php echo $cnic; ?></td></tr>
<tr><td><b>Date of Birth</b></td>
<td>
/* Run Loop to generate 31 days of the month */
<select name="dt">
<option value='--'>--</option>
<?php
for ($d=1; $d<32; $d++)
{
"<option value='$d'>$d</option>";
}
?>
</select>
/* Here I manually type months list. Use "Selected" to fetch that month which user select in DB */
<select name="month">
<option value="--">--</option>
<option value='01' <?php echo ($bmonth == 1) ? 'selected="selected"': ''; ?>>
Jan</option>
<option value='02' <?php echo ($bmonth == 2) ? 'selected="selected"': ''; ?>>
Feb</option>
<option value='03' <?php echo ($bmonth == 3) ? 'selected="selected"': ''; ?>>
Mar</option>
<option value='04' <?php echo ($bmonth == 4) ? 'selected="selected"': ''; ?>>
Apr</option>
<option value='05' <?php echo ($bmonth == 5) ? 'selected="selected"': ''; ?>>
May</option>
<option value='06' <?php echo ($bmonth == 6) ? 'selected="selected"': ''; ?>>
Jun</option>
<option value='07' <?php echo ($bmonth == 7) ? 'selected="selected"': ''; ?>>
Jul</option>
<option value='08' <?php echo ($bmonth == 8) ? 'selected="selected"': ''; ?>>
Aug</option>
<option value='09' <?php echo ($bmonth == 9) ? 'selected="selected"': ''; ?>>
Sep</option>
<option value='10' <?php echo ($bmonth == 10) ? 'selected="selected"': ''; ?>>
Oct</option>
<option value='11' <?php echo ($bmonth == 11) ? 'selected="selected"': ''; ?>>
Nov</option>
<option value='12' <?php echo ($bmonth == 12) ? 'selected="selected"': ''; ?>>
Dec</option>
</select>
<select name="year">
<option value='--'>--</option>
<?php
for ($y=2000; $y>1950; $y--)
{
echo "<option value='$y'>$y</option>";
}
?>
</select>
</td></tr>
</table>
</body>
</html>
</code></pre>
<p>Now my question is Please tell how to pull Year and Day from table into combo box which user was added while I am using Loop to generate years and days!??</p>
<p>Regards,</p>
<p>MAT</p>
| 1 | 1,830 |
barnyard2 not talking to mysql
|
<p>I have snort installed with following config</p>
<pre><code>#/etc/snort/snort.conf
ipvar HOME_NET 172.16.0.0/22
ipvar EXTERNAL_NET !$HOME_NET
var RULE_PATH /etc/snort/rules
var SO_RULE_PATH /etc/snort/so_rules
var PREPROC_RULE_PATH /etc/snort/preproc_rules
# If you are using reputation preprocessor set these
var WHITE_LIST_PATH /etc/snort/rules
var BLACK_LIST_PATH /etc/snort/rules
output log_unified2: filename snort.u2, limit 128
</code></pre>
<p>I have a icmp rule set up as follows</p>
<pre><code>#/etc/snort/rules/icmp.rules
alert icmp any any -> any any (msg:"ICMP Packet"; sid:477; rev:3;)
</code></pre>
<p>I start snort using the following which starts fine and is logging as i see entries in <code>alerts</code> and <code>snort.u2.timestamp</code></p>
<pre><code>snort -q -u snort -g snort -c /etc/snort/snort.conf -i ens32 -D
</code></pre>
<p>My banyard2 config file</p>
<pre><code>#/etc/snort/barnyard2.conf
config reference_file: /etc/snort/reference.config
config classification_file: /etc/snort/classification.config
config gen_file: /etc/snort/gen-msg.map
config sid_file: /etc/snort/sid-msg.map
config logdir: /var/log/snort
config hostname: snort
config interface: ens32
config daemon
config waldo_file: /var/log/snort/barnyard2.waldo
input unified2
output database: log, mysql, user=root password=support dbname=snorby host=127.0.0.1
# if you want to have to forward alerts also to syslog, uncomment the following 2 lines.
#output alert_syslog_full: sensor_name snortIds1-eth1, local
#output log_syslog_full: sensor_name snortIds1-eth1, local, log_priority LOG_CRIT
</code></pre>
<p>I start using the following command</p>
<pre><code>barnyard2 -c /etc/snort/barnyard2.conf -d /var/log/snort -f snort.u2 -w /var/log/snort/barnyard2.waldo
</code></pre>
<p>In the logs i get the following problem and nothing gets written to mysql.</p>
<pre><code>Sep 1 17:15:22 snort snort[4374]:
Sep 1 17:15:22 snort snort[4374]: [ Port Based Pattern Matching Memory ]
Sep 1 17:15:22 snort snort[4374]: +- [ Aho-Corasick Summary ] -------------------------------------
Sep 1 17:15:22 snort snort[4374]: | Storage Format : Full-Q
Sep 1 17:15:22 snort snort[4374]: | Finite Automaton : DFA
Sep 1 17:15:22 snort snort[4374]: | Alphabet Size : 256 Chars
Sep 1 17:15:22 snort snort[4374]: | Sizeof State : Variable (1,2,4 bytes)
Sep 1 17:15:22 snort snort[4374]: | Instances : 169
Sep 1 17:15:22 snort snort[4374]: | 1 byte states : 159
Sep 1 17:15:22 snort snort[4374]: | 2 byte states : 10
Sep 1 17:15:22 snort snort[4374]: | 4 byte states : 0
Sep 1 17:15:22 snort snort[4374]: | Characters : 94550
Sep 1 17:15:22 snort snort[4374]: | States : 72655
Sep 1 17:15:22 snort snort[4374]: | Transitions : 7856776
Sep 1 17:15:22 snort snort[4374]: | State Density : 42.2%
Sep 1 17:15:22 snort snort[4374]: | Patterns : 5205
Sep 1 17:15:22 snort snort[4374]: | Match States : 5820
Sep 1 17:15:22 snort snort[4374]: | Memory (MB) : 37.50
Sep 1 17:15:22 snort snort[4374]: | Patterns : 0.58
Sep 1 17:15:22 snort snort[4374]: | Match Lists : 1.27
Sep 1 17:15:22 snort snort[4374]: | DFA
Sep 1 17:15:22 snort snort[4374]: | 1 byte states : 0.97
Sep 1 17:15:22 snort snort[4374]: | 2 byte states : 34.39
Sep 1 17:15:22 snort snort[4374]: | 4 byte states : 0.00
Sep 1 17:15:22 snort snort[4374]: +----------------------------------------------------------------
Sep 1 17:15:22 snort snort[4374]: [ Number of patterns truncated to 20 bytes: 319 ]
Sep 1 17:15:22 snort snort[4374]: pcap DAQ configured to passive.
Sep 1 17:15:22 snort snort[4374]: Acquiring network traffic from "ens32".
Sep 1 17:15:22 snort snort[4374]: Initializing daemon mode
Sep 1 17:15:22 snort snort[4375]: Daemon initialized, signaled parent pid: 4374
Sep 1 17:15:22 snort snort[4375]: Reload thread starting...
Sep 1 17:15:22 snort snort[4375]: Reload thread started, thread 0x7f1b35e85700 (4376)
Sep 1 17:15:22 snort snort[4375]: Decoding Ethernet
Sep 1 17:15:22 snort snort[4375]: Checking PID path...
Sep 1 17:15:22 snort snort[4375]: PID path stat checked out ok, PID path set to /var/run/
Sep 1 17:15:22 snort snort[4375]: Writing PID "4375" to file "/var/run//snort_ens32.pid"
Sep 1 17:15:22 snort kernel: device ens32 entered promiscuous mode
Sep 1 17:15:22 snort snort[4375]: Set gid to 40000
Sep 1 17:15:22 snort snort[4375]: Set uid to 40000
Sep 1 17:15:22 snort snort[4375]:
Sep 1 17:15:22 snort snort[4375]: --== Initialization Complete ==--
Sep 1 17:15:22 snort snort[4375]: Commencing packet processing (pid=4375)
Sep 1 17:15:39 snort barnyard2: +[ Signature Suppress list ]+
----------------------------
Sep 1 17:15:39 snort barnyard2: +[No entry in Signature Suppress List]+
Sep 1 17:15:39 snort barnyard2: ----------------------------
+[ Signature Suppress list ]+
Sep 1 17:15:47 snort barnyard2: Barnyard2 spooler: Event cache size set to [2048]
Sep 1 17:15:47 snort barnyard2: Log directory = /var/log/snort
Sep 1 17:15:47 snort barnyard2: INFO database: Defaulting Reconnect/Transaction Error limit to 10
Sep 1 17:15:47 snort barnyard2: INFO database: Defaulting Reconnect sleep time to 5 second
Sep 1 17:15:47 snort barnyard2: Initializing daemon mode
Sep 1 17:15:47 snort barnyard2: Daemon initialized, signaled parent pid: 4378
Sep 1 17:15:47 snort barnyard2: PID path stat checked out ok, PID path set to /var/run/
Sep 1 17:15:47 snort barnyard2: Writing PID "4379" to file "/var/run//barnyard2_ens32.pid"
Sep 1 17:15:47 snort barnyard2: Daemon parent exiting
Sep 1 17:16:14 snort avahi-daemon[579]: Invalid response packet from host 172.16.0.211.
Sep 1 17:17:15 snort barnyard2: [SignatureReferencePullDataStore()]: No Reference found in database ...
Sep 1 17:17:15 snort barnyard2: database: compiled support for (mysql)
Sep 1 17:17:15 snort barnyard2: database: configured to use mysql
Sep 1 17:17:15 snort barnyard2: database: schema version = 107
Sep 1 17:17:15 snort barnyard2: database: host = 127.0.0.1
Sep 1 17:17:15 snort barnyard2: database: user = root
Sep 1 17:17:15 snort barnyard2: database: database name = snorby
Sep 1 17:17:15 snort barnyard2: database: sensor name = snort:ens32
Sep 1 17:17:15 snort barnyard2: database: sensor id = 1
Sep 1 17:17:15 snort barnyard2: database: sensor cid = 12
Sep 1 17:17:15 snort barnyard2: database: data encoding = hex
Sep 1 17:17:15 snort barnyard2: database: detail level = full
Sep 1 17:17:15 snort barnyard2: database: ignore_bpf = no
Sep 1 17:17:15 snort barnyard2: database: using the "log" facility
Sep 1 17:17:15 snort barnyard2:
Sep 1 17:17:15 snort barnyard2: --== Initialization Complete ==--
Sep 1 17:17:15 snort barnyard2: Barnyard2 initialization completed successfully (pid=4379)
Sep 1 17:17:15 snort barnyard2: Using waldo file '/var/log/snort/barnyard2.waldo':
spool directory = /var/log/snort
spool filebase = snort.u2
time_stamp = 1409587851
record_idx = 475
Sep 1 17:17:15 snort barnyard2: Opened spool file '/var/log/snort/snort.u2.1409587851'
Sep 1 17:17:15 snort barnyard2: WARNING database [Database()]: Called with Event[0x0] Event Type [0] (P)acket [0x13f0d00], information has not been outputed.
Sep 1 17:17:15 snort barnyard2: WARNING database [Database()]: Called with Event[0x0] Event Type [0] (P)acket [0x13f0d00], information has not been outputed.
Sep 1 17:17:15 snort barnyard2: WARNING database [Database()]: Called with Event[0x0] Event Type [0] (P)acket [0x13f0d00], information has not been outputed.
Sep 1 17:17:15 snort barnyard2: WARNING database [Database()]: Called with Event[0x0] Event Type [0] (P)acket [0x13f0d00], information has not been outputed.
Sep 1 17:17:15 snort barnyard2: WARNING database [Database()]: Called with Event[0x0] Event Type [0] (P)acket [0x13f0d00], information has not been outputed.
Sep 1 17:17:15 snort barnyard2: WARNING database [Database()]: Called with Event[0x0] Event Type [0] (P)acket [0x13f0d00], information has not been outputed.
Sep 1 17:17:15 snort barnyard2: WARNING database [Database()]: Called with Event[0x0] Event Type [0] (P)acket [0x13f0d00], information has not been outputed.
Sep 1 17:17:15 snort barnyard2: WARNING database [Database()]: Called with Event[0x0] Event Type [0] (P)acket [0x13f0d00], information has not been outputed.
Sep 1 17:17:15 snort barnyard2: WARNING database [Database()]: Called with Event[0x0] Event Type [0] (P)acket [0x13f0d00], information has not been outputed.
Sep 1 17:17:15 snort barnyard2: Closing spool file '/var/log/snort/snort.u2.1409587851'. Read 484 records
Sep 1 17:17:15 snort barnyard2: Opened spool file '/var/log/snort/snort.u2.1409588122'
Sep 1 17:17:15 snort barnyard2: WARNING database [Database()]: Called with Event[0x0] Event Type [0] (P)acket [0x13f0d00], information has not been outputed.
Sep 1 17:17:15 snort barnyard2: WARNING database [Database()]: Called with Event[0x0] Event Type [0] (P)acket [0x13f0d00], information has not been outputed.
Sep 1 17:17:15 snort barnyard2: WARNING database [Database()]: Called with Event[0x0] Event Type [0] (P)acket [0x13f0d00], information has not been outputed.
</code></pre>
| 1 | 3,542 |
float un-ordered list items(ul) next to one another
|
<p>I wanna place two child un-ordered lists side by side.
They are having Class Names L and R</p>
<p>Heres the relevant part of the HTML markup.</p>
<pre><code><ul class="SearchResult">
<li class="Pagination">
<a id="lnkPageNumber_top_1" class="ACTIVE" onclick="ShowPage(this.id);" style="cursor: pointer;">1</a>
<a id="lnkPageNumber_top_2" onclick="ShowPage(this.id);" style="cursor: pointer;">2</a>
</li>
<li>
<ul class="L">
<li style="border: medium none ;">
</li>
<li class="Pagination">
<a id="lnkImagePageNumber_1" class="ACTIVE" onclick="ShowImage(this.id);" style="cursor: pointer;">1</a>
<a id="lnkImagePageNumber_2" onclick="ShowImage(this.id);" style="cursor: pointer;">2</a>
<a id="lnkImagePageNumber_3" onclick="ShowImage(this.id);" style="cursor: pointer;">3</a>
<a id="lnkImagePageNumber_4" onclick="ShowImage(this.id);" style="cursor: pointer;">4</a>
</li>
</ul>
<ul class="R">
<li class="T">Rose Villa</li>
<li>
<span>
<strong>Price</strong>
: Rs. 2,000,000
</span>
</li>
<li>
<strong>Features</strong>
:
<img height="16" width="16" src="bed.png" alt="Beds:" title="Bedrooms"/>
3
<img height="16" width="16" src="bath.png" alt="Baths:" title="Bathrooms"/>
3
</li>
</ul>
</li>
</ul>
</code></pre>
<p>The styleSheet applied is this</p>
<pre><code>ul.SearchResult { width:100%; list-style:none; }
ul.SearchResult li { margin:2px; height:200px; border:solid 1px #B5D335;clear:left; }
ul.SearchResult img { padding:0px; margin:0px; width:235px; height:156px; border:none }
ul.SearchResult li.Pagination { padding:5px; height:auto; }
ul.SearchResult li.Pagination a { color:#669900; font-weight:bold; }
ul.SearchResult li.Pagination a:hover { color:#FF9900; }
ul.SearchResult li.Pagination a.ACTIVE { color:#FF9900; border:solid 1px #B5D335; padding-left:3px; padding-right:3px; }
ul.SearchResult li ul {float:left; list-style:none; }
ul.SearchResult li ul.L { width:245px;} /* Set as Television set BG */
ul.SearchResult li ul.R { width:292px;}
ul.SearchResult li ul li { padding:3px; border:none; height:auto; border-bottom:dotted 1px #C9C9C9; }
ul.SearchResult li ul li.T { text-transform:uppercase; color:#44962A; font-weight:bold }
ul.SearchResult li ul li span { display:table-cell; min-width:125px; width:auto; }
ul.SearchResult li ul li a { color:#44962A; }
ul.SearchResult li ul li a:hover { color:#FF9900; }
</code></pre>
<p>But the side by side alignment is not working at all.
What could be wrong?
h?
P.S: and yeah, I saw <a href="https://stackoverflow.com/questions/93625/float-divs">floating divs in list items</a>
Its DIV mentioned there and ul here. Is "clear:left" applicable for bot?</p>
<p>It may be duplicate post for experts in CSS, but I am not. So please bear with it [:)]</p>
<p>Edit Note:- To explain the stuff in detail heres an image
<a href="http://www.yetanothercoder.com/img.jpg" rel="nofollow noreferrer">alt text http://www.yetanothercoder.com/img.jpg</a></p>
| 1 | 1,300 |
Issue with LibPng (incomplete type, forward references) on Snow Leopard
|
<p>I am using MAC OS Snow Leopard and have tried to compile my program, a1.cpp, but I seem to have trouble with the linking libpng. Is this my issue? If not, what is? And, how can I resolve it?
Thanks in advance </p>
<pre><code>ew-host-2:a1 gifford$ make
g++ -O3 -o a1 a1.cpp -I . -L/opt/local/lib -lpng
In file included from a1.cpp:2:0:
./SImageIO.h: In static member function 'static void SImageIO::read_png_file(const char*, SDoublePlane&, SDoublePlane&, SDoublePlane&)':
./SImageIO.h:97:23: error: invalid use of incomplete type 'png_info {aka struct png_info_def}'
In file included from ./SImageIO.h:21:0,
from a1.cpp:2:
/opt/local/include/png.h:566:16: error: forward declaration of 'png_info {aka struct png_info_def}'
In file included from a1.cpp:2:0:
./SImageIO.h:98:24: error: invalid use of incomplete type 'png_info {aka struct png_info_def}'
In file included from ./SImageIO.h:21:0,
from a1.cpp:2:
/opt/local/include/png.h:566:16: error: forward declaration of 'png_info {aka struct png_info_def}'
In file included from a1.cpp:2:0:
./SImageIO.h:99:28: error: invalid use of incomplete type 'png_info {aka struct png_info_def}'
In file included from ./SImageIO.h:21:0,
from a1.cpp:2:
/opt/local/include/png.h:566:16: error: forward declaration of 'png_info {aka struct png_info_def}'
In file included from a1.cpp:2:0:
./SImageIO.h:100:27: error: invalid use of incomplete type 'png_info {aka struct png_info_def}'
In file included from ./SImageIO.h:21:0,
from a1.cpp:2:
/opt/local/include/png.h:566:16: error: forward declaration of 'png_info {aka struct png_info_def}'
In file included from a1.cpp:2:0:
./SImageIO.h:113:43: error: invalid use of incomplete type 'png_info {aka struct png_info_def}'
In file included from ./SImageIO.h:21:0,
from a1.cpp:2:
/opt/local/include/png.h:566:16: error: forward declaration of 'png_info {aka struct png_info_def}'
In file included from ./SImage.h:4:0,
from a1.cpp:1:
./DTwoDimArray.h: In instantiation of '_DTwoDimArray<T>& _DTwoDimArray<T>::operator=(const _DTwoDimArray<T>&) [with T = double]':
./SImage.h:9:7: required from here
./DTwoDimArray.h:84:7: error: 'memcpy' was not declared in this scope, and no declarations were found by argument-dependent lookup at the point of instantiation [-fpermissive]
In file included from ./SImage.h:5:0,
from a1.cpp:1:
/usr/include/string.h:83:7: note: 'void* memcpy(void*, const void*, size_t)' declared here, later in the translation unit
</code></pre>
| 1 | 1,038 |
Uncaught TypeError: Cannot read property 'stopPropagation' of null? - ReactJS
|
<p>React Component</p>
<pre><code>export default class CommentBox extends React.Component {
constructor() {
super()
this.state ={
showComments: false,
comments: [
{ id: uuid.v4(), author: 'Clu', body: 'Just say no to love!', avatarUrl: 'images/default-avatar.png' },
{ id: uuid.v4(), author: 'Anne Droid', body: 'I wanna know what love is...', avatarUrl: 'images/default-avatar.png' }
]
}
}
render() {
const comments = this._getComments() || [];
let commentList;
if (this.state.showComments) {
commentList = <div className="comment-list">{comments}</div>
}
return(
<div className="comment-box">
<h3>COMMENTS</h3>
{this._getPopularMessage(comments.length)}
<h4 className="comment-count">{this._getCommentsTitle(comments.length)}</h4>
<button className="comment-toggle" onClick={this._toggleShowComments.bind(this)}>{this._toggleCommentButton()}</button>
<CommentForm addComment={this._addComment.bind(this)}/>
{commentList}
</div>
);
}
_addComment(author, body) {
const comment = {
id: uuid.v4(),
author: author,
body: body
}
this.setState({comments: this.state.comments.concat([comment])})
}
_getComments() {
return this.state.comments.map((comment) => {
return (<Comment
author={comment.author}
body={comment.body}
avatarUrl={comment.avatarUrl}
key={comment.id}
onDelete = {this._deleteComment.bind(this, null, comment.id)}/>)
});
}
</code></pre>
<p>The main issue...
If I leave out <code>event.stopPropagation</code>, when I run this and click the 'Delete Comment' link, everything works as expected. However, when I add it in, I get the error <code>Uncaught TypeError: Cannot read property 'stopPropagation' of null</code>. I assume the <code>onClick</code> event in the Comment component (see bottom code box), is not passing the event through. Is there any way to rectify this?</p>
<pre><code> _deleteComment(event, key) {
event.stopPropagation()
console.log(key)
this.setState (
{comments: this.state.comments.filter((singleComment) => singleComment.id !== key)
}
)
console.log(this.state.comments)
}
}
</code></pre>
<p>For reference, the Comment component:
I tried binding(this) to <code>onDelete</code> e.g. <code><a className="comment-actions-delete" href="#" onClick={this.props.onDelete.bind(this)}>Delete comment</a></code> but it didn't seem to work.</p>
<pre><code>export default class Comment extends React.Component {
constructor() {
super();
this.state = {
isAbusive: false
};
}
render() {
let commentBody;
if (!this.state.isAbusive) {
commentBody = this.props.body;
} else {
commentBody = <em>Content marked as abusive</em>;
}
return(
<div className="comment">
<p className="comment-header">{this.props.author}</p>
<p className="comment-body">
{commentBody}
</p>
<div className="comment-actions">
<VotingButtons />
<a className="comment-actions-delete" href="#" onClick={this.props.onDelete}>Delete comment</a>
<a className="comment-actions-abuse" href="#" onClick={this._toggleAbuse.bind(this)}>Report as abuse</a>
</div>
</div>
);
}
_toggleAbuse(event) {
event.preventDefault();
this.setState({isAbusive: !this.state.isAbusive})
}
}
</code></pre>
| 1 | 1,590 |
Is there any documentation for xmlseclibs?
|
<p>I have signed the XML but I don't know how to include KeyValue element in the signature. Having some documentation would save a lot of time.</p>
<p>The code below (if you are interested) is what I managed to do with xmlseclibs so far:</p>
<pre><code><?php
require('xmlseclibs.php');
</code></pre>
<p>XML string</p>
<pre><code>$getToken = '<getToken>
<item>
<Semilla>Random string</Semilla>
</item>
</getToken>';
</code></pre>
<p>Creating XML object (to sign)</p>
<pre><code>$getToken_DOMDocument = new DOMDocument();
$getToken_DOMDocument -> loadXml($getToken);
</code></pre>
<p>Creating the signature object with xmlseclibs</p>
<pre><code>$getToken_XMLSecurityDSig = new XMLSecurityDSig();
$getToken_XMLSecurityDSig -> setCanonicalMethod(XMLSecurityDSig::C14N);
</code></pre>
<p>Trying to turn off the ds: prefix which didn't work</p>
<pre><code>$options['prefix'] = '';
$options['prefix_ns'] = '';
$options['force_uri'] = TRUE;
$options['id_name'] = 'ID';
$getToken_XMLSecurityDSig -> addReference($getToken_DOMDocument, XMLSecurityDSig::SHA1, array('http://www.w3.org/2000/09/xmldsig#enveloped-signature', 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315'), $options);
</code></pre>
<p>Accessing the necessary key data</p>
<pre><code>$XMLSecurityKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type'=>'private'));
$XMLSecurityKey -> loadKey('../../DTE/certificado/firma/certificado.pem', TRUE);
/* if key has Passphrase, set it using $objKey -> passphrase = <passphrase> */
</code></pre>
<p>Signing the XML object</p>
<pre><code>$getToken_XMLSecurityDSig -> sign($XMLSecurityKey);
</code></pre>
<p>Adding the public key</p>
<pre><code>$getToken_XMLSecurityDSig -> add509Cert(file_get_contents('../../DTE/certificado/firma/certificado.pem'));
</code></pre>
<p>Appending the enveloped signature to the XML object </p>
<pre><code>$getToken_XMLSecurityDSig -> appendSignature($getToken_DOMDocument -> documentElement);
</code></pre>
<p>Saving the signed XML code toa file</p>
<pre><code>$getToken_DOMDocument -> save('sign-basic-test.xml');
?>
</code></pre>
<p>Additionaly would also like from this library:</p>
<ol>
<li>Know official and trustable repository to ensure the library is not corrupted.</li>
<li>Turning off the "ds:" prefix (because nor the example nor the documentation of the XML I am producing includes such prefix).</li>
<li>Linebreaks every X characters in the Base64 type values.</li>
<li>Full indentation (otherwise none at all).</li>
</ol>
<p>I got the library from <a href="https://code.google.com/p/xmlseclibs/" rel="nofollow">enter link description here</a></p>
<p>Thanks in advance.</p>
| 1 | 1,032 |
CheckBoxList AJAX async postback issue
|
<p>I have 2 CheckBoxList controls - chk1 and chk2. I need to use an async postback to clear the selections of a CheckBoxList if the other one is selected. The following will not clear chk1 if it had selections, and an item chk2 was checked: </p>
<pre><code><asp:ScriptManager ID="sm1" runat="server" ></asp:ScriptManager>
<asp:UpdatePanel ID="upd" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="chk1" />
<asp:AsyncPostBackTrigger ControlID="chk2" />
</Triggers>
<ContentTemplate>
<asp:Label ID="result" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
<div style="overflow: auto; height: 150px;">
<asp:CheckBoxList runat="server" ID="chk1" OnDataBound="assignClickBehaviours" AutoPostBack="true">
<asp:ListItem Value="1" Text="One"></asp:ListItem>
<asp:ListItem Value="2" Text="Two"></asp:ListItem>
<asp:ListItem Value="3" Text="Three"></asp:ListItem>
<asp:ListItem Value="100" Text="..."></asp:ListItem>
<asp:ListItem Value="150" Text="One hundred and Fifty"></asp:ListItem>
</asp:CheckBoxList>
</div>
<div style="overflow: auto;">
<asp:CheckBoxList runat="server" ID="chk2" AutoPostBack="true">
<asp:ListItem Value="1" Text="One"></asp:ListItem>
<asp:ListItem Value="2" Text="Two"></asp:ListItem>
<asp:ListItem Value="3" Text="Three"></asp:ListItem>
</asp:CheckBoxList>
</div>
</code></pre>
<p>code behind:</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
processChecks();
}
private void processChecks()
{
if(chk2.SelectedIndex>-1)
chk1.ClearSelection();
}
</code></pre>
<p>If the whole thing was put in the update panel, it would work... but because there can be 150 items in the checkbox, the scrolling on the overflow:auto would flick back to the top if an item at the bottom was selected. I need the scroll state to stay put (hence the need for async postback). Any ideas or alternatives?</p>
| 1 | 1,047 |
how to display information in jsp page from controller Spring MVC
|
<p>I need display data in jsp with controller, i have <code>List</code> with information for print in jsp.</p>
<p>When run this code i get error:</p>
<blockquote>
<p>HTTP Status 500 - Request processing failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [entities.Pupil]: No default constructor found; nested
exception is java.lang.NoSuchMethodException: entities.Pupil.()</p>
</blockquote>
<p><strong>Controller</strong></p>
<pre><code> @Controller
public class PupilController {
@RequestMapping(value = "/add", method = RequestMethod.POST)
public List add(@ModelAttribute Pupil pupil){
System.out.println(pupil.toString());
List<Pupil> pupilList = new ArrayList<Pupil>();
pupilList.add(new Pupil(1, "Name", "Last", 13));
pupilList.add(new Pupil(2, "Name", "Last", 55));
pupilList.add(new Pupil(3, "Name", "Last", 41));
return pupilList;
}
}
</code></pre>
<p><strong>index.jsp</strong></p>
<pre><code><body>
<h2>Hello World!</h2>
<a href="hello">click</a>
<form action="/add" method="post">
<p>1:</p><input type="text" name="one">
<p>2:</p><input type="text" name="two">
<p>3:</p><input type="text" name="three">
<p>4:</p><input type="text" name="four">
<input type="submit" value="button">
</form>
</body>
</code></pre>
<p><strong>add.jsp</strong></p>
<pre><code><body>
<h3>This is add.jsp</h3>
<table>
<thead>
<tr>
<td>ID</td>
<td>NAME</td>
<td>LAST</td>
<td>YEAR</td>
</tr>
</thead>
<tbody>
<c:forEach items="${pupilList}" var="tester">
<tr>
<td>${tester.id}</td>
<td>${tester.name}</td>
<td>${tester.last}</td>
<td>${tester.year}</td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</code></pre>
| 1 | 1,218 |
Firebase Cloud Functions async function
|
<p>I need some help with async function with firebase and node.js</p>
<p>I have this function in my index.js</p>
<pre><code>const funcBiglietti = require('./biglietti');
//Region biglietti
exports.getBiglietti = functions.https.onRequest((req, res) => {
let userid = req.url.replace('/','');
let utente = admin.database().ref("Utenti").child(userid).once("value");
var userInfo = {};
utente.then(snap =>{
if(snap === undefined)
return res.status(400).send('utente non trovato.');
else
return userInfo = JSON.stringify(snap);
}).catch(err => {
return res.status(500).send('errore:' + err);
})
let tickets = await funcBiglietti.getBiglietti(userInfo,userid,admin.database());
return res.status(200).send(tickets);
});
</code></pre>
<p>instead in biglietti.js i have this function:</p>
<pre><code>///Restituisce tutti i biglietti di un utente
exports.getBiglietti = async function(Utente,IDUtente,database){
console.log('userinfo' + Utente);
const biglietti = database.ref("Biglietti").child(IDUtente).once("value");
biglietti.then(snap =>{
console.log(JSON.stringify(snap));
return snap;
}).catch(err => {
return err;
})
}
</code></pre>
<p>I need the function in index.js to wait the result in biglietti.js but when I'm trying to use the async / await i keep getting:</p>
<pre><code> deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint
> functions@ lint /Users/Giulio_Serra/Documents/Server Firebase/Hangover/functions
> eslint .
/Users/Giulio_Serra/Documents/Server Firebase/Hangover/functions/biglietti.js
3:30 error Parsing error: Unexpected token function
/Users/Giulio_Serra/Documents/Server Firebase/Hangover/functions/locali.js
13:9 warning Avoid nesting promises promise/no-nesting
✖ 2 problems (1 error, 1 warning)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions@ lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions@ lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
</code></pre>
<p>I'm running node v 11.10</p>
<pre><code>node -v
v11.10.0
MBP-di-Giulio:~ Giulio_Serra$
</code></pre>
<p>and here is my package.json:</p>
<pre><code>{
"engines": {"node": "8"},
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase serve --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"dependencies": {
"async": "^2.6.2",
"firebase-admin": "~5.12.1",
"firebase-functions": "^2.2.0",
"request": "^2.88.0"
},
"devDependencies": {
"eslint": "^4.12.0",
"eslint-plugin-promise": "^3.6.0"
},
"private": true
}
</code></pre>
<p>What I'm missing to use async functions? I'm a little bit lost. </p>
<p><strong>EDIT</strong></p>
<p>resolved by changing code like this:</p>
<pre><code>//Region biglietti
exports.getBiglietti = functions.https.onRequest((req, res) => {
let userid = req.url.replace('/','');
let utente = admin.database().ref("Utenti").child(userid).once("value");
utente.then(snap =>{
if(snap === undefined)
return res.status(400).send('utente non trovato.');
else{
return funcBiglietti.getBiglietti(snap,userid,admin.database()).then(function(data){
return res.status(200).send(data);
}).catch(err => {
return res.status(500).send('errore:' + err);
})
}
}).catch(err => {
return res.status(500).send('errore:' + err);
})
});
</code></pre>
| 1 | 1,613 |
How to convert this PHP array of objects to json?
|
<p>I have an array of 10 objects that I am trying to convert to JSON. The array is being stored in a variable called <code>$invoices</code>. Below is the ouput of <code>var_dump($invoices)</code> shorted to only the first object.</p>
<p>I've tried the following:</p>
<pre><code>$invoices = json_encode($invoices, FALSE);
$invoices = json_encode($invoices, TRUE);
$invoices = json_encode($invoices, JSON_UNESCAPED_UNICODE);
</code></pre>
<p>However, the output is always:</p>
<pre><code>string(31) "[{},{},{},{},{},{},{},{},{},{}]"
</code></pre>
<p>How can this array be properly converted to JSON?</p>
<p>Note: I am running PHP 5.5.9</p>
<p>Update:</p>
<p>It turns out the problem is due the fact that json_encode won't work with "protected member variables." Is there a way to declare those variables as public if I don't have access to the class that created them?</p>
<pre><code>array(10) {
[0]=>
object(QuickBooks_IPP_Object_Invoice)#285 (1) {
["_data":protected]=>
array(22) {
["Id"]=>
array(1) {
[0]=>
string(6) "{-224}"
}
["SyncToken"]=>
array(1) {
[0]=>
string(1) "0"
}
["MetaData"]=>
array(1) {
[0]=>
object(QuickBooks_IPP_Object_MetaData)#282 (1) {
["_data":protected]=>
array(2) {
["CreateTime"]=>
array(1) {
[0]=>
string(25) "2014-12-07T09:48:47-08:00"
}
["LastUpdatedTime"]=>
array(1) {
[0]=>
string(25) "2014-12-07T09:48:47-08:00"
}
}
}
}
["CustomField"]=>
array(1) {
[0]=>
object(QuickBooks_IPP_Object_CustomField)#292 (1) {
["_data":protected]=>
array(3) {
["DefinitionId"]=>
array(1) {
[0]=>
string(4) "{-1}"
}
["Name"]=>
array(1) {
[0]=>
string(6) "Crew #"
}
["Type"]=>
array(1) {
[0]=>
string(10) "StringType"
}
}
}
}
["DocNumber"]=>
array(1) {
[0]=>
string(4) "1038"
}
["TxnDate"]=>
array(1) {
[0]=>
string(10) "2014-12-07"
}
["Line"]=>
array(2) {
[0]=>
object(QuickBooks_IPP_Object_Line)#263 (1) {
["_data":protected]=>
array(5) {
["Id"]=>
array(1) {
[0]=>
string(4) "{-1}"
}
["LineNum"]=>
array(1) {
[0]=>
string(1) "1"
}
["Amount"]=>
array(1) {
[0]=>
string(9) "155555.00"
}
["DetailType"]=>
array(1) {
[0]=>
string(19) "SalesItemLineDetail"
}
["SalesItemLineDetail"]=>
array(1) {
[0]=>
object(QuickBooks_IPP_Object_SalesItemLineDetail)#765 (1) {
["_data":protected]=>
array(2) {
["ItemRef"]=>
array(1) {
[0]=>
string(4) "{-3}"
}
["TaxCodeRef"]=>
array(1) {
[0]=>
string(6) "{-NON}"
}
}
}
}
}
}
[1]=>
object(QuickBooks_IPP_Object_Line)#748 (1) {
["_data":protected]=>
array(3) {
["Amount"]=>
array(1) {
[0]=>
string(9) "155555.00"
}
["DetailType"]=>
array(1) {
[0]=>
string(18) "SubTotalLineDetail"
}
["SubTotalLineDetail"]=>
array(1) {
[0]=>
string(0) ""
}
}
}
}
["TxnTaxDetail"]=>
array(1) {
[0]=>
object(QuickBooks_IPP_Object_TxnTaxDetail)#287 (1) {
["_data":protected]=>
array(1) {
["TotalTax"]=>
array(1) {
[0]=>
string(1) "0"
}
}
}
}
["CustomerRef"]=>
array(1) {
[0]=>
string(5) "{-11}"
}
["BillAddr"]=>
array(1) {
[0]=>
object(QuickBooks_IPP_Object_BillAddr)#284 (1) {
["_data":protected]=>
array(7) {
["Id"]=>
array(1) {
[0]=>
string(5) "{-11}"
}
["Line1"]=>
array(1) {
[0]=>
string(13) "1045 Main St."
}
["City"]=>
array(1) {
[0]=>
string(13) "Half Moon Bay"
}
["CountrySubDivisionCode"]=>
array(1) {
[0]=>
string(2) "CA"
}
["PostalCode"]=>
array(1) {
[0]=>
string(5) "94213"
}
["Lat"]=>
array(1) {
[0]=>
string(10) "37.4559621"
}
["Long"]=>
array(1) {
[0]=>
string(11) "-122.429939"
}
}
}
}
["ShipAddr"]=>
array(1) {
[0]=>
object(QuickBooks_IPP_Object_ShipAddr)#814 (1) {
["_data":protected]=>
array(7) {
["Id"]=>
array(1) {
[0]=>
string(5) "{-11}"
}
["Line1"]=>
array(1) {
[0]=>
string(13) "1045 Main St."
}
["City"]=>
array(1) {
[0]=>
string(13) "Half Moon Bay"
}
["CountrySubDivisionCode"]=>
array(1) {
[0]=>
string(2) "CA"
}
["PostalCode"]=>
array(1) {
[0]=>
string(5) "94213"
}
["Lat"]=>
array(1) {
[0]=>
string(10) "37.4559621"
}
["Long"]=>
array(1) {
[0]=>
string(11) "-122.429939"
}
}
}
}
["DueDate"]=>
array(1) {
[0]=>
string(10) "2015-01-06"
}
["TotalAmt"]=>
array(1) {
[0]=>
string(9) "155555.00"
}
["ApplyTaxAfterDiscount"]=>
array(1) {
[0]=>
string(5) "false"
}
["PrintStatus"]=>
array(1) {
[0]=>
string(11) "NeedToPrint"
}
["EmailStatus"]=>
array(1) {
[0]=>
string(6) "NotSet"
}
["Balance"]=>
array(1) {
[0]=>
string(9) "155555.00"
}
["Deposit"]=>
array(1) {
[0]=>
string(1) "0"
}
["AllowIPNPayment"]=>
array(1) {
[0]=>
string(5) "false"
}
["AllowOnlinePayment"]=>
array(1) {
[0]=>
string(5) "false"
}
["AllowOnlineCreditCardPayment"]=>
array(1) {
[0]=>
string(5) "false"
}
["AllowOnlineACHPayment"]=>
array(1) {
[0]=>
string(5) "false"
}
}
}
[1]=>
object(QuickBooks_IPP_Object_Invoice)#830 (1) {
["_data":protected]=>
array(22) {
...
...
</code></pre>
| 1 | 5,300 |
"A case label may only be used within a switch"
|
<p>I am new to coding, and need some help with something. I am sorting out cases from a GTA Mod Menu, and trying to add a new one from an SDK. When I try to add it, and add a case for it so it knows what to do, I get the error in the title. I am coding in C++. </p>
<pre><code> int activeLineIndexVeh = 0;
void process_veh_menu()
{
const float lineWidth = 230.0;
const int lineCount = 9;
std::string caption = "Vehicle Options";
static struct {
LPCSTR text;
bool *pState;
bool *pUpdated;
} lines[lineCount] = {
{ "Car Spawner", NULL, NULL },
{ "Random Paint", NULL, NULL },
{ "Fix", NULL, NULL },
{ "Custom Plate", NULL, NULL },
{ "Seat Belt", &featureVehSeatbelt, &featureVehSeatbeltUpdated },
{ "Wrap In Spawned", &featureVehWrapInSpawned, NULL },
{ "Invincible", &featureVehInvincible, &featureVehInvincibleUpdated },
{ "Strong Wheels", &featureVehInvincibleWheels, &featureVehInvincibleWheelsUpdated },
{ "Speed Boost", &featureVehSpeedBoost, NULL }
};
DWORD waitTime = 150;
while (true)
{
// timed menu draw, used for pause after active line switch
DWORD maxTickCount = GetTickCount() + waitTime;
do
{
// draw menu
draw_menu_line(caption, lineWidth, 7.9, 14.0, 4.0, 4.0, false, true);
for (int i = 0; i < lineCount; i++)
if (i != activeLineIndexVeh)
draw_menu_line(line_as_str(lines[i].text, lines[i].pState),
lineWidth, 4.0, 60.0 + i * 22.8, 4.0, 9.0, false, false);
draw_menu_line(line_as_str(lines[activeLineIndexVeh].text, lines[activeLineIndexVeh].pState),
lineWidth + 0.0, 2.0, 60.0 + activeLineIndexVeh * 22.9, 4.0, 7.0, true, false);
update_features();
WAIT(0);
} while (GetTickCount() < maxTickCount);
waitTime = 0;
// process buttons
bool bSelect, bBack, bUp, bDown;
get_button_state(&bSelect, &bBack, &bUp, &bDown, NULL, NULL);
if (bSelect)
{
menu_beep();
// common variables
BOOL bPlayerExists = ENTITY::DOES_ENTITY_EXIST(PLAYER::PLAYER_PED_ID());
Player player = PLAYER::PLAYER_ID();
Ped playerPed = PLAYER::PLAYER_PED_ID();
switch (activeLineIndexVeh)
{
case 0:
if (process_carspawn_menu()) return;
break;
case 1:
if (bPlayerExists)
{
if (PED::IS_PED_IN_ANY_VEHICLE(playerPed, 0))
{
Vehicle veh = PED::GET_VEHICLE_PED_IS_USING(playerPed);
VEHICLE::SET_VEHICLE_CUSTOM_PRIMARY_COLOUR(veh, rand() % 255, rand() % 255, rand() % 255);
if (VEHICLE::GET_IS_VEHICLE_PRIMARY_COLOUR_CUSTOM(veh))
VEHICLE::SET_VEHICLE_CUSTOM_SECONDARY_COLOUR(veh, rand() % 255, rand() % 255, rand() % 255);
}
else
{
set_status_text("player isn't in a vehicle");
}
}
break;
case 2:
if (bPlayerExists)
if (PED::IS_PED_IN_ANY_VEHICLE(playerPed, 0))
VEHICLE::SET_VEHICLE_FIXED(PED::GET_VEHICLE_PED_IS_USING(playerPed));
else
set_status_text("player isn't in a vehicle");
break;
// switchable features
default:
if (lines[activeLineIndexVeh].pState)
*lines[activeLineIndexVeh].pState = !(*lines[activeLineIndexVeh].pState);
if (lines[activeLineIndexVeh].pUpdated)
*lines[activeLineIndexVeh].pUpdated = true;
}
waitTime = 200;
}
else
if (bBack || trainer_switch_pressed())
{
menu_beep();
break;
}
else
if (bUp)
{
menu_beep();
if (activeLineIndexVeh == 0)
activeLineIndexVeh = lineCount;
activeLineIndexVeh--;
waitTime = 150;
}
else
if (bDown)
{
menu_beep();
activeLineIndexVeh++;
if (activeLineIndexVeh == lineCount)
activeLineIndexVeh = 0;
waitTime = 150;
}
case 3: // error starts here
Ped playerPed = PLAYER::PLAYER_PED_ID();
// No point in displaying the keyboard if they aren't in a vehicle
if (!PED::IS_PED_IN_ANY_VEHICLE(playerPed, false)) return;
// Invoke keyboard
GAMEPLAY::DISPLAY_ONSCREEN_KEYBOARD(true, "", "", VEHICLE::GET_VEHICLE_NUMBER_PLATE_TEXT(PED::GET_VEHICLE_PED_IS_IN(playerPed, false)), "", "", "", 9);
// Wait for the user to edit
while (GAMEPLAY::UPDATE_ONSCREEN_KEYBOARD() == 0) WAIT(0);
// Make sure they didn't exit without confirming their change, and that they're still in a vehicle
if (!GAMEPLAY::GET_ONSCREEN_KEYBOARD_RESULT() || !PED::IS_PED_IN_ANY_VEHICLE(playerPed, false)) return;
// Update the licenseplate
VEHICLE::SET_VEHICLE_NUMBER_PLATE_TEXT(PED::GET_VEHICLE_PED_IS_IN(playerPed, false), GAMEPLAY::GET_ONSCREEN_KEYBOARD_RESULT());
}
}
</code></pre>
| 1 | 3,127 |
jQuery Draggable, Droppable, ASP.NET MVC
|
<p>I've been looking through a lot of tutorials on jQuery draggable/droppable, and trying to apply it to ASP.NET MVC, but I am really confused. </p>
<p>Most of the samples I keep finding seem pretty difficult to understand at least where it pertains to where things are wired. I'm basically trying to have a targetable box (a 'roster') and a list of units ('attendees'). The goal is to be able to drag any of the units into the box, and they are added to the roster in the database.</p>
<p>Does anyone know of some simpler samples that might shed some light on how to use this part of jQuery with ASP.NET MVC?</p>
<p>For instance, I've been looking at <a href="http://philderksen.com/2009/06/18/drag-and-drop-categorized-item-list-with-jquery-and-aspnet-mvc-part-1/" rel="nofollow noreferrer">http://philderksen.com/2009/06/18/drag-and-drop-categorized-item-list-with-jquery-and-aspnet-mvc-part-1/</a> and it is pretty neat, but it just doesn't explain what I need. It doesn't make a lot of sense and most of the code is pretty strewn about, and I can't even trace where certain calls are being made to figure out how things are wired. (How is jQuery calling the Controller actions, for instance, to trigger when something is dropped? How do I get the ID of the item being dragged so I can add it to the target?)</p>
<hr>
<p>Here, I made some changes - I apologize for the confusion. It still isn't quite working how I'm trying to get it to. Is it possible to make it not fire events if things are re-arranged in their original list, but only when dropped onto another list?</p>
<pre><code><%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Draggable.Item>>" %>
<asp:Content ContentPlaceHolderID="TitleContent" runat="server">
Index
</asp:Content>
<asp:Content ContentPlaceHolderID="MainContent" runat="server">
<h2>
Index</h2>
<div style="float: left; width: 250px;">
<ul class="itemBox">
<% foreach (var item in Model)
{ %>
<% Html.RenderPartial("Item", item); %>
<% } %>
</ul>
</div>
<div style="float: left; width: 250px;">
<ul class="itemBox">
<p>
Drop here</p>
</ul>
</div>
</asp:Content>
<asp:Content ContentPlaceHolderID="ScriptContent" runat="server">
<style type="text/css">
#draggable {
width: 100px;
height: 100px;
padding: 0.5em;
float: left;
margin: 10px 10px 10px 0;
}
#droppable {
width: 150px;
height: 150px;
padding: 0.5em;
float: left;
margin: 10px;
}
</style>
<script type="text/javascript">
$(function() {
$(".itemList").sortable({
connectWith: ".itemList",
containment: "document",
cursor: "move",
opacity: 0.8,
placeholder: "itemRowPlaceholder",
update: function(event, ui) {
//Extract column num from current div id
var colNum = $(this).attr("id").replace(/col_/, "");
$.post("/Home/UpdateSortOrder", { columnNum: colNum, sectionIdQueryString: $(this).sortable("serialize") });
}
});
});
</script>
</asp:Content>
</code></pre>
<hr>
<p>Alright, I'm trying to follow Phil's instructions, this is what I have so far... I hope I am even on the right track. This is all very new to me. I'm trying and trying, but the 'update' stuff is never firing. . .</p>
<pre><code><%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Draggable.Item>>" %>
<asp:Content ContentPlaceHolderID="TitleContent" runat="server">
Index
</asp:Content>
<asp:Content ContentPlaceHolderID="MainContent" runat="server">
<h2>
Index</h2>
<div style="float: left; width: 250px;">
<ul id="sortable" class="itemBox">
<% foreach (var item in Model)
{ %>
<% Html.RenderPartial("Item", item); %>
<% } %>
</ul>
</div>
<div id="droppable" class="ui-widget-header">
<p>
Drop here</p>
</div>
</asp:Content>
<asp:Content ContentPlaceHolderID="ScriptContent" runat="server">
<style type="text/css">
.draggable {
width: 100px;
height: 100px;
padding: 0.5em;
float: left;
margin: 10px 10px 10px 0;
}
#droppable {
width: 150px;
height: 150px;
padding: 0.5em;
float: left;
margin: 10px;
}
</style>
<script type="text/javascript">
$(function() {
$("#sortable").sortable({
update: function(event, ui) {
//Extract column num from current div id
var colNum = $(this).attr("id").replace(/item_/, "");
$.post("UpdateSortOrder", { columnNum: colNum, sectionIdQueryString: $(this).sortable("serialize") });
}
});
$("#droppable").droppable({
drop: function(event, ui) {
$(this).find('p').html('Dropped!');
//Extract column num from current div id
var colNum = $(this).attr("id").replace(/item_/, "");
$.post("UpdateSortOrder", { columnNum: colNum, sectionIdQueryString: $(this).sortable("serialize") });
}
});
});
</script>
</asp:Content>
</code></pre>
<p><strong>And the Item.ascx</strong></p>
<pre><code><%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Draggable.Item>" %>
<li class="itemRow" id="item_<%= Model.ItemId %>">
<p>Drag me to my target</p>
</li>
</code></pre>
<p><strong>And the repository...</strong></p>
<pre><code>using System;
using System.Linq;
namespace Draggable
{
public partial class ItemRepository
{
DatabaseDataContext database = new DatabaseDataContext();
public IQueryable<Item> GetItems()
{
var items = from i in database.Items
select i;
return items;
}
}
}
</code></pre>
<p><strong>And the controller</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
namespace Draggable.Controllers
{
public class HomeController : Controller
{
//
// GET: /Index/
public ActionResult Index()
{
ItemRepository repository = new ItemRepository();
return View("Index", repository.GetItems());
}
public ActionResult Item()
{
return View();
}
}
}
</code></pre>
<hr>
<p>This method gets the styling a lot closer to how your sample is ...but it really doesn't work. It doesn't get the id of the element - but making the elements themselves sortable doesn't seem to work either....</p>
<pre><code><%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Draggable.Item>>" %>
<asp:Content ContentPlaceHolderID="TitleContent" runat="server">
Index
</asp:Content>
<asp:Content ContentPlaceHolderID="MainContent" runat="server">
<h2>
Index</h2>
<div class="itemBox">
<ul class="itemList">
<% foreach (var item in Model)
{ %>
<% Html.RenderPartial("Item", item); %>
<% } %>
</ul>
</div>
<div class="itemBox">
<ul class="itemList">
<p>
Drop here</p>
</ul>
</div>
</asp:Content>
<asp:Content ContentPlaceHolderID="ScriptContent" runat="server">
<script type="text/javascript">
$(function() {
$(".itemList").sortable({
connectWith: ".itemList",
containment: "document",
cursor: "move",
opacity: 0.8,
placeholder: "itemRowPlaceholder",
update: function(event, ui) {
//Extract column num from current div id
var colNum = $(this).attr("id").replace(/col_/, "");
alert(colNum);
$.post("/Home/UpdateSortOrder", { columnNum: colNum, sectionIdQueryString: $(this).sortable("serialize") });
}
});
});
</script>
</asp:Content>
</code></pre>
| 1 | 4,318 |
How to use api_gateway_base_path_mapping with terraform?
|
<p>I'm trying to setup a custom domain name for an api in api gateway on aws. I have setup the api fine using terraform. However when I try to setup the custom domain it fails with the following error.</p>
<p>Error applying plan:</p>
<p>1 error(s) occurred:</p>
<ul>
<li><p>module.BillingMetrics.aws_api_gateway_base_path_mapping.billing: 1 error(s) occurred:</p></li>
<li><p>aws_api_gateway_base_path_mapping.billing: Error creating Gateway base path mapping: Error creating Gateway base path mapping: BadRequestException: Invalid REST API identifier specified
status code: 400, request id: b14bbd4c-5823-11e7-a4ea-93525a34b321</p></li>
</ul>
<p>I can see in the terraform log that it does get the correct api_id. But I don't understand why it's saying the rest api identifier is invalid.</p>
<p>Below is an excerpt of my terraform file showing how I'm configuring the api_gateway_base_path_mapping.</p>
<pre><code>resource "aws_api_gateway_resource" "views_resource" {
provider = "aws.regional"
rest_api_id = "${aws_api_gateway_rest_api.billing_api.id}"
parent_id = "${aws_api_gateway_rest_api.billing_api.root_resource_id}"
path_part = "views"
}
resource "aws_api_gateway_method" "views-get" {
provider = "aws.regional"
rest_api_id = "${aws_api_gateway_rest_api.billing_api.id}"
resource_id = "${aws_api_gateway_resource.views_resource.id}"
http_method = "GET"
authorization = "NONE"
}
resource "aws_api_gateway_method_response" "views_200" {
provider = "aws.regional"
rest_api_id = "${aws_api_gateway_rest_api.billing_api.id}"
resource_id = "${aws_api_gateway_resource.views_resource.id}"
http_method = "${aws_api_gateway_method.views-get.http_method}"
status_code = "200"
}
resource "aws_api_gateway_integration" "views-integration" {
provider = "aws.regional"
rest_api_id = "${aws_api_gateway_rest_api.billing_api.id}"
resource_id = "${aws_api_gateway_resource.views_resource.id}"
http_method = "${aws_api_gateway_method.views-get.http_method}"
type = "AWS"
uri = "arn:aws:apigateway:${var.region}:lambda:path/2015-03-31/functions/arn:aws:lambda:${var.region}:${var.account_id}:function:${aws_lambda_function.get_views.function_name}/invocations"
credentials = "${var.metrics_role_arn}"
http_method = "${aws_api_gateway_method.views-get.http_method}"
integration_http_method = "POST"
}
resource "aws_api_gateway_integration_response" "Views_Get_IntegrationResponse" {
provider = "aws.regional"
rest_api_id = "${aws_api_gateway_rest_api.billing_api.id}"
resource_id = "${aws_api_gateway_resource.views_resource.id}"
http_method = "${aws_api_gateway_method.views-get.http_method}"
status_code = "${aws_api_gateway_method_response.views_200.status_code}"
}
/* Deploy api */
resource "aws_api_gateway_deployment" "metric_deploy" {
provider = "aws.regional"
depends_on = ["aws_api_gateway_integration.metrics-integration", "aws_api_gateway_integration.hours-integration"]
stage_name = "beta"
rest_api_id = "${aws_api_gateway_rest_api.billing_api.id}"
}
resource "aws_api_gateway_domain_name" "billing" {
domain_name = "billing.example.com"
certificate_arn = "arn:aws:acm:us-east-1:6--:certificate/5--"
}
resource "aws_api_gateway_base_path_mapping" "billing" {
api_id = "${aws_api_gateway_rest_api.billing_api.id}"
stage_name = "${aws_api_gateway_deployment.metric_deploy.stage_name}"
domain_name = "${aws_api_gateway_domain_name.billing.domain_name}"
}
resource "aws_route53_record" "billing" {
zone_id = "Z-------"
name = "${aws_api_gateway_domain_name.billing.domain_name}"
type = "A"
alias {
name = "${aws_api_gateway_domain_name.billing.cloudfront_domain_name}"
zone_id = "${aws_api_gateway_domain_name.billing.cloudfront_zone_id}"
evaluate_target_health = true
}
}
</code></pre>
<p>Are there any more elements that needed to be configured to have the base_path_mapping apply correctly? Any other hints what I might be doing wrong?</p>
<p>I should also mention I'm on terraform 0.9.7.</p>
| 1 | 1,666 |
Sequelize Transactions : ER_LOCK_WAIT_TIMEOUT
|
<p>i've problem with sequelize transactions with mysql(5.6.17),i've one insert statement and two updates which should all done or none,howerver in the end <code>transactions.create</code> seems rolling back but <code>driver.update</code> executes and doesn't rollback and third update which is <code>trip.update</code> statement without any changes or rollback,the console hangs and after a few seconds throw this error:</p>
<pre><code>Executing (42a68c8e-8347-45af-b9a2-7b0e7a89606b): START TRANSACTION;
Executing (42a68c8e-8347-45af-b9a2-7b0e7a89606b): SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
Executing (42a68c8e-8347-45af-b9a2-7b0e7a89606b): SET autocommit = 1;
Executing (42a68c8e-8347-45af-b9a2-7b0e7a89606b): INSERT INTO `transactions` (`id`,`tId`,`total_price`,`company_share`,`driver_share`,`at`) VALUES (DEFAULT,'13',1000,100,900,'2016-07-04 10:44:43');
Executing (default): UPDATE `driver` SET `balance`=`balance` - 100 WHERE `id` = '1'
Executing (default): UPDATE `trip` SET `paid`=1 WHERE `id` = '13'
Executing (42a68c8e-8347-45af-b9a2-7b0e7a89606b): ROLLBACK;
5---SequelizeDatabaseError: ER_LOCK_WAIT_TIMEOUT: Lock wait timeout exceeded; try restarting transaction
</code></pre>
<p>the transaction section is:</p>
<pre><code>var Sequelize = require('sequelize');
var config = {};
config.sequelize = new Sequelize('mydb', 'root', null, {
host: 'localhost',
port: 3306,
dialect: 'mysql',
logging: true,
pool: {
max: 100,
min: 0,
idle: 10000
},
define: {
timestamps: false
}
});
require('sequelize-isunique-validator')(Sequelize);
var driver = require('./../models/driver.js')(config.sequelize, Sequelize);
var transactions = require('./../models/transactions.js')(config.sequelize, Sequelize);
var trip = require('./../models/trip.js')(config.sequelize, Sequelize);
return config.sequelize.transaction({isolationLevel:Sequelize.Transaction.ISOLATION_LEVELS.READ_COMMITTED},function (t) {
return transactions.create({tId: tripId, total_price: totalPrice, company_share: companyShare, driver_share: driverShare}, {transaction: t})
.then(function (result) {
return driver.update({balance: config.sequelize.literal('`balance` - '+companyShare)}, {where: {id: dId}}, {transaction: t})
.then(function (result) {
return trip.update({paid: 1}, {where: {id: tripId}}, {transaction: t});
});
});
}).then(function (result) {
RequestQueue.hmset(ticket,"ticketState",value.Paid);
res.json({'status': 'success','change':(-company_share)});
}).catch(function (err) {
global.console.log('5---'+err);
res.json({'status': 'failed'});
});
</code></pre>
<p>I'm sure my models are correct because I used them somewhere else without any problem on crud and not putting them here in order to keeps the question clean and on topic but if it helps ask in comments,tnx!</p>
| 1 | 1,084 |
How to use mutually exclusive flags in your shell and add an optional argument flag ( stuck with getopts)
|
<p>I am using a standard getopts logic. But I want to how I can make the options I offer- mutually exclusive.
e.g. </p>
<pre><code>shell.sh -a SID
<accepted>
shell.sh -b SID
<accepted>
shell.sh -ab SID
Message- using ab together is the same as running shell.sh without any options supplying just SID . Help usage < ya da ya >
shell.sh
Please enter SID at the minimum. Usage < ya da ya >
shell.sh SID
<accepted>
</code></pre>
<p>I am trying to develop this logic using something like below </p>
<pre><code>while getopts ":a:b:" opt; do
case $opt in
a ) SID="$OPTARG";;
set var=1
b ) SID="$OPTARG";;
set var=2
\?) echo "Invalid option: -"$OPTARG"" >&2
exit 1;;
) echo "Option -"$OPTARG" requires an argument." >&2
exit 1;;
esac
done
If (( val == 1 )) then ; # option a is invoked SID supplied
<stuff>
elif (( val == 2 )) then ; # option b is invoked SID supplied
<stuff>
else # SID supplied but neither a or b is invoked
<stuff>
fi
</code></pre>
<p>How do enforce mutually exclusive flags. I a sure there are more acrobat ways to do it. I think I am missing something commonsense here - and trying to figure that out .
Thx </p>
<pre><code>$ more opt.ksh
die () {
echo "ERROR: $*. Aborting." >&2
return 1
}
var=
while getopts ":a:b:" opt; do
case $opt in
a ) SID="$OPTARG"
[ "$var" = 2 ] && die "Cannot specify option a after specifying option b"
[ "$OPTARG" = b ] && die "Do not specify b as a value for option a"
var=1
;;
b ) SID="$OPTARG"
[ "$var" = 1 ] && die "Cannot specify option b after specifying option a"
[ "$OPTARG" = a ] && die "Do not specify a as a value for option b"
var=2
;;
:) die "Must supply an argument to $OPTARG"
;;
\?) die "Invalid option: -$OPTARG. Abort"
;;
esac
done
shift $(($OPTIND - 1))
[ "$SID" ] || SID=$1
[ "$SID" ] || die "You must, at the minimum, supply SID"
</code></pre>
<p>I am using ksh </p>
<pre><code>$ ps -p $$
PID TTY TIME CMD
1261 pts/45 00:00:00 ksh
</code></pre>
<p>1st time I run it .</p>
<pre><code>$ . opt.ksh -a 123 -b 123 # c0
ERROR: Cannot specify option b after specifying option a. Aborting.
-bash: /home/d1ecom1/gin1: No such file or directory
$ . opt.ksh -ab 123 # c1 should reject "cant use a and b togather. try with a or b"
-nologin: .[25]: shift: 4: bad number
$ . opt.ksh -a -b # c2 same as c1's message
$ . opt.ksh -a -b 123 # c3 same as c1
$ . opt.ksh -a -b 123 # c5
$ . opt.ksh -ab 123 # c6
$ . opt.ksh -a 123 -b 123 # c7
</code></pre>
<p>All above cases C0:C7 should reject. Notice C0 and C7 are the same. Yet inspite of this C0 gives the expected error and C7 will not give any error ? strange </p>
<p>only ones to work should be </p>
<pre><code>. opt.ksh -a 123
. opt.ksh -b 123
. opt.ksh 123
</code></pre>
<p>@hvd :TYSM for your reply.
I would like to add an additonal flag -p that will give a "path override" option.
so maybe we have to extend getopt to take parameters like this </p>
<pre><code> die () {
echo "ERROR: $*. Aborting." >&2
exit 1
}
var=
opta=false
optb=false
while getopts ":ab:p" opt; do
case $opt in
a ) $optb && die "Cannot specify option a after specifying option b"
opta=true
;;
b ) $opta && die "Cannot specify option b after specifying option a"
optb=true
;;
p ) [ -d "$mypath" ] && die "path is invalid"
;;
\?) die "Invalid option: -$OPTARG. Abort"
;;
esac
done
shift $(($OPTIND - 1))
test $# -eq 0 && die "You must supply SID"
test $# -eq 1 || die "Too many command-line arguments"
# SID=$1
</code></pre>
<p>The above was the old approach. Now I have 2 Input parameters. One is the SID and the other is the path. Is it as simple as the above or do I need to add more checks to prevent other unwanted combinations. The question I guess I am trying to aim at is , what more provisions would need to be made to allow this -p parameter which is an optiona override parameter. - p can co-exist with any parameter above but then I guess one requirement is that it should be immediately following the -p flag
so this should not allow - because its not clear .</p>
<pre><code>shell.sh -b -p 123 /home/yadaya
</code></pre>
<p>Thanks again </p>
| 1 | 1,959 |
Spring application build failure
|
<p>I am not able to figure out what is wrong while running <strong>mvn spring-boot:run</strong> command. <strong>mvn clean install</strong> gives a build success but for <strong>mvn spring-boot:run</strong> i get a build failure.
This is my error log in my console when i run <strong>mvn spring-boot:run -X</strong>.</p>
<pre><code> [WARNING]
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:506)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoClassDefFoundError: org/springframework/core/env/EnvironmentCapable
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at com.example.DemoApplication.main(DemoApplication.java:10)
... 6 more
Caused by: java.lang.ClassNotFoundException: org.springframework.core.env.EnvironmentCapable
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 18 more
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 10.024 s
[INFO] Finished at: 2016-12-11T15:24:36+05:30
[INFO] Final Memory: 23M/223M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.4.2.RELEASE:run (default-cli) on project demo: An exception occurred while running. null: InvocationTargetException: org/springframework/core/env/EnvironmentCapable: org.springframework.core.env.EnvironmentCapable -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.4.2.RELEASE:run (default-cli) on project demo: An exception occurred while running. null
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:212)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.MojoExecutionException: An exception occurred while running. null
at org.springframework.boot.maven.AbstractRunMojo$IsolatedThreadGroup.rethrowUncaughtException(AbstractRunMojo.java:475)
at org.springframework.boot.maven.RunMojo.runWithMavenJvm(RunMojo.java:92)
at org.springframework.boot.maven.AbstractRunMojo.run(AbstractRunMojo.java:234)
at org.springframework.boot.maven.AbstractRunMojo.execute(AbstractRunMojo.java:170)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207)
... 20 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:506)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoClassDefFoundError: org/springframework/core/env/EnvironmentCapable
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at com.example.DemoApplication.main(DemoApplication.java:10)
... 6 more
Caused by: java.lang.ClassNotFoundException: org.springframework.core.env.EnvironmentCapable
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 18 more
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
</code></pre>
<p>This is my pom.xml . I have also removed pom.xml from the active maven profiles in eclipse ide, cause it was given as one of the solutions in this link <a href="https://stackoverflow.com/questions/28192761/spring-maven-clean-error-the-requested-profile-pom-xml-could-not-be-activate">Spring Maven clean error - The requested profile "pom.xml" could not be activated because it does not exist</a></p>
<pre><code> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Test</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
<relativePath />
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<start-class>com.example.DemoApplication</start-class>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- <plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
</plugin> -->
</plugins>
</pluginManagement>
</build>
</project>
</code></pre>
| 1 | 4,405 |
Having trouble installing OpenSSL Cocoapod
|
<p>I'm trying to install the OpenSSL Cocoapod in Xcode 9.4 and I get the following:</p>
<blockquote>
<p>[!] /bin/bash -c set -e VERSION="1.0.2h" SDKVERSION=<code>xcrun --sdk
iphoneos --show-sdk-version 2> /dev/null</code>
MIN_SDK_VERSION_FLAG="-miphoneos-version-min=7.0"</p>
<p>BASEPATH="${PWD}" CURRENTPATH="/tmp/openssl" ARCHS="i386 x86_64 armv7
armv7s arm64" DEVELOPER=<code>xcode-select -print-path</code></p>
<p>mkdir -p "${CURRENTPATH}" mkdir -p "${CURRENTPATH}/bin"</p>
<p>cp "file.tgz" "${CURRENTPATH}/file.tgz" cd "${CURRENTPATH}" tar -xzf
file.tgz cd "openssl-${VERSION}"</p>
<p>for ARCH in ${ARCHS} do CONFIGURE_FOR="iphoneos-cross"</p>
<p>if [ "${ARCH}" == "i386" ] || [ "${ARCH}" == "x86_64" ] ; then
PLATFORM="iPhoneSimulator"
if [ "${ARCH}" == "x86_64" ] ;
then
CONFIGURE_FOR="darwin64-x86_64-cc"
fi else
sed -ie "s!static volatile sig_atomic_t intr_signal;!static volatile intr_signal;!" "crypto/ui/ui_openssl.c"
PLATFORM="iPhoneOS" fi</p>
<p>export
CROSS_TOP="${DEVELOPER}/Platforms/${PLATFORM}.platform/Developer"<br>
export CROSS_SDK="${PLATFORM}${SDKVERSION}.sdk"</p>
<p>echo "Building openssl-${VERSION} for ${PLATFORM} ${SDKVERSION}
${ARCH}" echo "Please stand by..."</p>
<p>export CC="${DEVELOPER}/usr/bin/gcc -arch ${ARCH}
${MIN_SDK_VERSION_FLAG}" mkdir -p
"${CURRENTPATH}/bin/${PLATFORM}${SDKVERSION}-${ARCH}.sdk"<br>
LOG="${CURRENTPATH}/bin/${PLATFORM}${SDKVERSION}-${ARCH}.sdk/build-openssl-${VERSION}.log"</p>
<p>LIPO_LIBSSL="${LIPO_LIBSSL}
${CURRENTPATH}/bin/${PLATFORM}${SDKVERSION}-${ARCH}.sdk/lib/libssl.a"
LIPO_LIBCRYPTO="${LIPO_LIBCRYPTO}
${CURRENTPATH}/bin/${PLATFORM}${SDKVERSION}-${ARCH}.sdk/lib/libcrypto.a"</p>
<p>./Configure ${CONFIGURE_FOR}
--openssldir="${CURRENTPATH}/bin/${PLATFORM}${SDKVERSION}-${ARCH}.sdk" > "${LOG}" 2>&1 sed -ie "s!^CFLAG=!CFLAG=-isysroot ${CROSS_TOP}/SDKs/${CROSS_SDK} !" "Makefile"</p>
<p>make >> "${LOG}" 2>&1 make all install_sw >> "${LOG}" 2>&1 make
clean >> "${LOG}" 2>&1 done</p>
<p>echo "Build library..." rm -rf "${BASEPATH}/lib/" mkdir -p
"${BASEPATH}/lib/" lipo -create ${LIPO_LIBSSL} -output
"${BASEPATH}/lib/libssl.a" lipo -create ${LIPO_LIBCRYPTO} -output
"${BASEPATH}/lib/libcrypto.a"</p>
<p>echo "Copying headers..." rm -rf "${BASEPATH}/opensslIncludes/" mkdir
-p "${BASEPATH}/opensslIncludes/" cp -RL "${CURRENTPATH}/openssl-${VERSION}/include/openssl"
"${BASEPATH}/opensslIncludes/"</p>
<p>cd "${BASEPATH}" echo "Building done."</p>
<p>echo "Cleaning up..." rm -rf "${CURRENTPATH}" echo "Done."</p>
<p>cp: file.tgz: No such file or directory</p>
</blockquote>
<p>This is the command I'm using in the podfile:</p>
<pre><code>pod 'OpenSSL', '~> 1.0'
</code></pre>
<p>I've tried installing the Xcode Command Line Tools but this did not fix the problem.</p>
<p>Anyone have any idea what the problem is?</p>
| 1 | 1,387 |
Azure Key Vault: Secret not found error
|
<p>I've created the Key Vault and entered a secret. When I run my services locally using .NET, I am able to retrieve the secret via the key vault. Here's what I did:
1) Created an SSL certificate
2) Used that SSL certificate to create an AD application
3) Created a Service Principle for the above application
4) Gave full key vault access to this application
5) I put the VaultURI, ServicePrincipal.Application ID, and the cert thumbprint in the Web.config file
6) I also uploaded the *.pfx of that cert to my cloud service</p>
<p>When I run my service locally, I am able to retrieve the secret. I have even tried retrieving the secret via powershell and I have been successful. When I deploy my code to Azure, I am unable to retrieve the secret.</p>
<p>It says:</p>
<pre><code>Type : Microsoft.Azure.KeyVault.Models.KeyVaultErrorException, Microsoft.Azure.KeyVault, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 Message : Secret not found: QSAccounts7126 Source : Microsoft.Azure.KeyVault Help link :
</code></pre>
<p>I have spent 3 days looking at it and retesting every possible scenario and haven't figured out what is wrong. Can someone please help in identifying the issue or directing me in the right path for debugging?
I even tried publishing the cloud service in debug mode in Azure, and for some reason that did not work either. </p>
<p>Any help you can provide would be greatly appreciated.</p>
<pre><code>private async Task<string> getSecretConnection(string connectionName)
{
var kvName = ConfigurationManager.AppSettings["vaultName"];
var kvClientId = ConfigurationManager.AppSettings["clientId"];
var kvClientThumbprint = ConfigurationManager.AppSettings["clientThumbprint"];
using (keyVaultHelper = new AzureKeyVaultHelper(kvClientId, kvClientThumbprint, kvName))
{
var bundle = await keyVaultHelper.GetAzureKeyVaultSecretAsync(connectionName);
return bundle;
}
public async Task<string> GetAzureKeyVaultSecretAsync(string secretName)
{
var bundle = await this.KvClient.GetSecretAsync(KeyVaultUrl, secretName);
return bundle.Value;
}
</code></pre>
<p>This is the code that runs for authentication:</p>
<pre><code>private async Task<string> getAccessTokenFromSPNAsync(string authority, string resource, string scope)
{
//clientID and clientSecret are obtained by registering
//the application in Azure AD
var certificate = CertificateHelper.FindCertificateByThumbprint(this.ClientThumbprint);
var assertionCert = new ClientAssertionCertificate(this.ClientId, certificate); //needed for authentication
var clientCredential = new ClientCredential(this.ClientId, this.ClientThumbprint);
var authContext = new AuthenticationContext(authority, TokenCache.DefaultShared);
AuthenticationResult result = await authContext.AcquireTokenAsync(resource, assertionCert);
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the token from Azure AD using certificate");
}
return result.AccessToken;
}
</code></pre>
| 1 | 1,111 |
How can I run command line FFMPEG and accept multiple pipes (video and audio) without blocking on the first input?
|
<p>I'm trying to mux h264 and aac created with MediaCodec using FFMPEG, and also use FFMPEG's RTMP support to send to youtube. I've created two pipes, and am writing from java (android) through WriteableByteChannels. I can send to one pipe just fine (accepting null audio) like this:</p>
<pre><code>./ffmpeg -f lavfi -i aevalsrc=0 -i "files/camera-test.h264" -acodec aac -vcodec copy -bufsize 512k -f flv "rtmp://a.rtmp.youtube.com/live2/XXXX"
</code></pre>
<p>YouTube streaming works perfectly (but I have no audio). Using two pipes this is my command:</p>
<pre><code>./ffmpeg \
-i "files/camera-test.h264" \
-i "files/audio-test.aac" \
-vcodec copy \
-acodec copy \
-map 0:v:0 -map 1:a:0 \
-f flv "rtmp://a.rtmp.youtube.com/live2/XXXX""
</code></pre>
<p>The pipes are created with mkfifo , and opened from java like this:</p>
<pre><code>pipeWriterVideo = Channels.newChannel(new FileOutputStream(outputFileVideo.toString()));
</code></pre>
<p>The order of execution (for now in my test phase) is creation of the files, starting ffmpeg (through adb shell) and then starting recording which opens the channels. ffmpeg will immediately open the h264 stream and then wait, since it is reading from the pipe the first channel open (for video) will successfully run. When it comes to trying to open the audio the same way, it fails because ffmpeg has not actually started reading from the pipe. I can open a second terminal window and cat the audio file and my app spits out what i hope is encoded aac, but ffmpeg fails, usually just sitting there waiting. Here is the verbose output:</p>
<pre><code>ffmpeg version N-78385-g855d9d2 Copyright (c) 2000-2016 the FFmpeg
developers
built with gcc 4.8 (GCC)
configuration: --prefix=/home/dev/svn/android-ffmpeg-with-rtmp/src/ffmpeg/android/arm
--enable-shared --disable-static --disable-doc --disable-ffplay
--disable-ffprobe --disable-ffserver --disable-symver
--cross-prefix=/home/dev/dev/android-ndk-r10e/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin/arm-linux-androideabi-
--target-os=linux --arch=arm --enable-cross-compile
--enable-librtmp --enable-pic --enable-decoder=h264
--sysroot=/home/dev/dev/android-ndk-r10e/platforms/android-19/arch-arm
--extra-cflags='-Os -fpic -marm'
--extra-ldflags='-L/home/dev/svn/android-ffmpeg-with-rtmp/src/openssl-android/libs/armeabi '
--extra-ldexeflags=-pie --pkg-config=/usr/bin/pkg-config
libavutil 55. 17.100 / 55. 17.100
libavcodec 57. 24.102 / 57. 24.102
libavformat 57. 25.100 / 57. 25.100
libavdevice 57. 0.101 / 57. 0.101
libavfilter 6. 31.100 / 6. 31.100
libswscale 4. 0.100 / 4. 0.100
libswresample 2. 0.101 / 2. 0.101
matched as AVOption 'debug' with argument 'verbose'.
Trailing options were found on the commandline.
Finished splitting the commandline.
Parsing a group of options: global .
Applying option async (audio sync method) with argument 1.
Successfully parsed a group of options.
Parsing a group of options: input file files/camera-test.h264.
Successfully parsed a group of options.
Opening an input file: files/camera-test.h264.
[file @ 0xb503b100] Setting default whitelist 'file'
</code></pre>
<p>I think if I could just get ffmpeg to start listening to both pipes, the rest would work out!</p>
<p>Thanks for your time.</p>
<p>EDIT:
I've made progress by decoupling the audio pipe connection and encoding, but now as soon as the video stream has been passed it errors on audio. I started a separate thread to create the WriteableByteChannel for audio and it never gets passed the FileOutputStream creation.</p>
<pre><code>matched as AVOption 'debug' with argument 'verbose'.
Trailing options were found on the commandline.
Finished splitting the commandline.
Parsing a group of options: global .
Successfully parsed a group of options.
Parsing a group of options: input file files/camera-test.h264.
Successfully parsed a group of options.
Opening an input file: files/camera-test.h264.
[file @ 0xb503b100] Setting default whitelist 'file'
[h264 @ 0xb503c400] Format h264 probed with size=2048 and score=51
[h264 @ 0xb503c400] Before avformat_find_stream_info() pos: 0 bytes read:15719 seeks:0
[h264 @ 0xb5027400] Current profile doesn't provide more RBSP data in PPS, skipping
[h264 @ 0xb503c400] max_analyze_duration 5000000 reached at 5000000 microseconds st:0
[h264 @ 0xb503c400] After avformat_find_stream_info() pos: 545242 bytes read:546928 seeks:0 frames:127
Input #0, h264, from 'files/camera-test.h264':
Duration: N/A, bitrate: N/A
Stream #0:0, 127, 1/1200000: Video: h264 (Baseline), 1 reference frame, yuv420p(left), 854x480 (864x480), 1/50, 25 fps, 25 tbr, 1200k tbn, 50 tbc
Successfully opened the file.
Parsing a group of options: input file files/audio-test.aac.
Applying option vcodec (force video codec ('copy' to copy stream)) with argument copy.
Successfully parsed a group of options.
Opening an input file: files/audio-test.aac.
Unknown decoder 'copy'
[AVIOContext @ 0xb5054020] Statistics: 546928 bytes read, 0 seeks
</code></pre>
<p>Here is where I attempt to open the audio pipe.</p>
<pre><code>new Thread(){
public void run(){
Log.d("Audio", "pre thread");
FileOutputStream fs = null;
try {
fs = new FileOutputStream("/data/data/android.com.android.grafika/files/audio-test.aac");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Log.d("Audio", "made fileoutputstream"); //never hits here
mVideoEncoder.pipeWriterAudio = Channels.newChannel(fs);
Log.d("Audio", "made it past opening audio pipe");
}
}.start();
</code></pre>
<p>Thanks.</p>
| 1 | 2,027 |
XML to XSD from the foll. ER diagram
|
<p>Generate XML for this<a href="https://i.stack.imgur.com/AYOGL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AYOGL.png" alt="enter image description here"></a></p>
<p>My Xml:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<company>
<companyname>ABC company</companyname>
<address>xyz street, India.</address>
<department>
<dname>Marketing</dname>
<deptphoneno>9876543210</deptphoneno>
<deptfaxno>0442456879</deptfaxno>
<deptemail>marketing@abc.com</deptemail>
<employee>
<empid>101</empid>
<ename>Rishie</ename>
<emailid>rishie@abc.com</emailid>
<phoneno>9876543211</phoneno>
</employee>
<contractemployee>
<name>Ravi</name>
<phoneno>9874563214</phoneno>
</contractemployee>
</department>
</company>
</code></pre>
<p>and my XSD:</p>
<pre><code><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="company">
<xs:complexType>
<xs:sequence>
<xs:element name="companyname" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="department">
<xs:complexType>
<xs:sequence>
<xs:element name="dname" type="xs:string"/>
<xs:element name="deptphoneno" type="xs:integer"/>
<xs:element name="deptfaxno" type="xs:integer"/>
<xs:element name="deptemail" type="xs:string"/>
<xs:element name="employee">
<xs:complexType>
<xs:sequence>
<xs:element name="empid" type="xs:integer"/>
<xs:element name="ename" type="xs:string"/>
<xs:element name="emailid" type="xs:string"/>
<xs:element name="phoneno" type="xs:integer"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="contractemployee">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="phoneno" type="xs:integer"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
</code></pre>
<p>I know that at first glance everything looks correct...but i keep getting some errors! I hope someone could help me out with this!
Iam not sure whether its the xml or the xsd.</p>
<p>The Error:</p>
<pre><code>Exception: cvc-complex-type.2.4.a: Invalid content was found starting with eleme
nt 'employee'. One of '{contractemployee}' is expected.
</code></pre>
<p>Please help me out with the tag <code><xs:schema></code> in my XSD and <code><company></code> in xml.</p>
| 1 | 1,712 |
How to solve java.util.concurrent.RejectedExecutionException
|
<p>I have <code>java.util.concurrent.RejectedExecutionException</code> in this file. As I can see there is no more processes running after <code>onStop</code> called. Not sure where the error comes from. And I'm sure the executor isn't getting more tasks it can handle too.</p>
<p>Please help me to figure out where the error comes from.</p>
<pre><code>public static final String TAG = BroadcastService.class.getSimpleName();
private static final int TIMER_DELAY_SECONDS = 3;
private volatile JmDNS mService = null;
private WifiManager.MulticastLock mMulticastLock = null;
private ScheduledExecutorService mExecutorService = null;
private ScheduledFuture mPublisherFuture = null;
private ScheduledFuture mApiPublisherFuture = null;
private NetworkUtils mNetworkUtils = null;
private Runnable mDelayedKiller = null;
public static Intent getStartIntent(Context context) {
final Intent serviceIntent = new Intent(context, BroadcastService.class);
serviceIntent.setAction(BroadcastService.INTENT_ACTION_BROADCAST_START);
return serviceIntent;
}
public static Intent getStopIntent(Context context) {
final Intent serviceIntent = new Intent(context, BroadcastService.class);
serviceIntent.setAction(BroadcastService.INTENT_ACTION_BROADCAST_STOP);
return serviceIntent;
}
@Override
public void onCreate() {
super.onCreate();
mNetworkUtils = NetworkUtils.getInstance(getApplicationContext());
}
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
if (intent == null) {
return START_STICKY;
}
if (intent.getAction() != null) {
switch (intent.getAction()) {
case INTENT_ACTION_BROADCAST_START:
startBroadcast();
break;
case INTENT_ACTION_BROADCAST_STOP:
stopBroadcast();
break;
}
}
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(final Intent intent) {
return null;
}
/**
* Starts broadcast on a background thread
*/
public void startBroadcast() {
if (mDelayedKiller != null) {
NetworkThread.getCommonInstance().removeTask(mDelayedKiller);
mDelayedKiller = null;
}
if (mExecutorService == null || mExecutorService.isShutdown()) {
mExecutorService = Executors.newScheduledThreadPool(2);
}
if (mPublisherFuture != null) {
mPublisherFuture.cancel(true);
}
final BonjourPublisher bonjourPublisher = new BonjourPublisher();
mPublisherFuture = mExecutorService.schedule(bonjourPublisher, 2, TimeUnit.SECONDS);
if (mApiPublisherFuture != null) {
mApiPublisherFuture.cancel(true);
}
final ApiPublisher apiPublisher = new ApiPublisher();
mApiPublisherFuture = mExecutorService.scheduleWithFixedDelay(apiPublisher, 0, 30, TimeUnit.SECONDS);
//inform listeners
EventBus.getDefault().post(new EventServiceBroadcasting(true));
}
public synchronized void stopBroadcast() {
if (mPublisherFuture == null && mApiPublisherFuture == null) {
return;
}
if (mPublisherFuture != null) {
mPublisherFuture.cancel(true);
if (mMulticastLock != null) {
mMulticastLock.release();
mMulticastLock = null;
}
}
if (mApiPublisherFuture != null) {
mApiPublisherFuture.cancel(true);
}
mDelayedKiller = new Runnable() {
@Override
public void run() {
mExecutorService.shutdownNow();
killService();
stopSelf();
}
};
NetworkThread.getCommonInstance().postDelayed(mDelayedKiller, 1000 * 20); //kill the service after 20 seconds
//inform listeners
EventBus.getDefault().post(new EventServiceBroadcasting(false));
}
@Override
public void onDestroy() {
super.onDestroy();
killService();
}
private synchronized void killService() {
if (mService != null) {
try {
mService.unregisterAllServices();
mService.close();
mService = null;
} catch (IOException e) {
e.printStackTrace();
}
} else {
}
}
public static class DiscoverableAssistant {
private DiscoverableAssistant() {
}
public static boolean isDiscoverable(Context context) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getBoolean(PREF_DEVICE_DISCOVERABLE, true); //true by default
}
public static void setDiscoverable(Context context, boolean discoverable) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.edit().putBoolean(PREF_DEVICE_DISCOVERABLE, discoverable).apply();
}
}
private class BonjourPublisher implements Runnable {
@Override
public void run() {
final String serviceName = mNetworkUtils.getDeviceName(BroadcastService.this);
final String serviceType = getString(R.string.multi_dns_network_name);
final Map<String, String> properties = new HashMap<>();
properties.put(DeviceViewActivity.DEVICE_PROPERTY_DEVICE_TYPE, "Android");
properties.put(DeviceViewActivity.DEVICE_PROPERTY_FILE_SERVER_PORT,
String.valueOf(mNetworkUtils.getAssignedPort()));
if (DiscoverableAssistant.isDiscoverable(BroadcastService.this)) {
properties.put(DeviceViewActivity.DEVICE_PROPERTY_DISCOVERABLE, "true");
} else {
properties.put(DeviceViewActivity.DEVICE_PROPERTY_DISCOVERABLE, "false");
}
//acquire wifi multicast lock
if (mMulticastLock == null) {
final WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
mMulticastLock.setReferenceCounted(true);
mMulticastLock.acquire();
}
try {
if (mService == null) {
mService = JmDNS.create(mNetworkUtils.getMyInet4Address(),
NetworkUtils.getHostName(mNetworkUtils.getDeviceName(BroadcastService.this)));
}
final ServiceInfo info = ServiceInfo.create(serviceType, serviceName, mNetworkUtils.getAssignedPort(), 0, 0, true, properties);
while (mService != null) {
mService.registerService(info);
Thread.sleep(TIMER_DELAY_SECONDS * 1000);
mService.unregisterAllServices();
Thread.sleep(1000);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
} catch (Exception e) {
}
}
}
private class ApiPublisher implements Runnable {
private APo api = null;
private SimplifiedDeviceInfo mDeviceInfo = null;
public ApiPublisher() {
api = Utils.getRetrofitInstance(BroadcastService.this, null)
.create(api.class);
}
@Override
public void run() {
try {
if (mDeviceInfo == null) {
mDeviceInfo = new SimplifiedDeviceInfo(mNetworkUtils.getDeviceName(BroadcastService.this),
mNetworkUtils.getMyInet4Address().getHostAddress(), mNetworkUtils.getAssignedPort(),
NetworkUtils.getDeviceType(), BroadcastService.DiscoverableAssistant.isDiscoverable(BroadcastService.this));
}
Call<JsonElement> call = api.broadcastDevice(mDeviceInfo);
call.execute();
} catch (Exception e) {
}
}
}
</code></pre>
| 1 | 2,998 |
jQuery validation submitHandler not work in $.ajax post form data
|
<p>I have Send data using <code>$.ajax</code> and validation with jQuery validation plugin like this :</p>
<pre><code><div class="" id="ajax-form-msg1"></div>
<form id="myform" action="load.php">
<input type="input" name="name" id="name" value="" />
<input type="hidden" name="csrf_token" id="my_token" value="MkO89FgtRF^&5fg#547@d6fghBgf5" />
<button type="submit" name="submit" id="ajax-1">Send</button>
</form>
</code></pre>
<p>JS: </p>
<pre><code>jQuery(document).ready(function ($) {
$('#myform').validate({
rules: {
name: {
required: true,
rangelength: [4, 20],
},
},
submitHandler: function (form) {
$("#ajax-1").click(function (e) {
e.preventDefault(); // avoid submitting the form here
$("#ajax-form-msg1").html("<img src='http://www.drogbaster.it/loading/loading25.gif'>");
var formData = $("#myform").serialize();
var URL = $("#myform").attr("action");
$.ajax({
url: URL,
type: "POST",
data: formData,
crossDomain: true,
async: false
}).done(function (data, textStatus, jqXHR) {
if (data == "yes") {
$("#ajax-form-msg1").html(' < div class = "alert alert-success" > ' + data + ' < /div>');
$("#form-content").modal('show');
$(".contact-form").slideUp();
} else {
$("#ajax-form-msg1").html('' + data + '');
}
}).fail(function (jqXHR, textStatus, errorThrown) {
$("#ajax-form-msg1").html(' < div class = "alert alert-danger" >AJAX Request Failed < br / > textStatus = ' + textStatus + ', errorThrown = ' + errorThrown + ' < /code></pre > ');
});
});
}
});
});
</code></pre>
<p>In action my form validate using jQuery validation but after validation not submit and not send data.</p>
<p>how do fix this problem?!</p>
<p>DEMO <a href="http://jsfiddle.net/g7ssanvr/1/" rel="nofollow">HERE</a></p>
| 1 | 1,241 |
Bootstrap fluid grid overlap issues
|
<p>I have been playing with fluid grids for a while now using Twitter Bootstrap, but even in the latest version I am finding it impossible to create a fluid grid without getting overlapping elements. The correct bootstrap css file is included and all the mark up is correct, so I can only assume that this is to do with input fields, but I would have thought the creators of Bootstrap would take this into account?</p>
<p>You can view the code in a fiddle here: <a href="http://jsfiddle.net/pNRzV/1/" rel="nofollow">http://jsfiddle.net/pNRzV/1/</a>
Try re-sizing the content window and you will see the overlapping issues.</p>
<p>Any opinions/comments welcome, thanks for your time!</p>
<pre><code><div class="container-fluid">
<div class="row-fluid">
<div class="span2">
<div class="well well-small">
<ul class="nav nav-list" id="navigation">
<li><a href="/link" >link</a></li>
<li><a href="/link" >link</a></li>
<li><a href="/link" >link</a></li>
<li><a href="/link" >link</a></li>
<li><a href="/link" >link</a></li>
<li><a href="/link" >link</a></li>
</ul>
</div>
</div>
<div class="span10">
<div class="row-fluid">
<div class="span3">
<form method="POST">
<fieldset>
<legend>Some Random details</legend>
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type="submit" class="btn btn-primary" name="submit" value="Submit">
</fieldset>
</form>
</div>
<div class="span3">
<fieldset>
<legend>Some random long legend</legend>
<ul>
<li><a href="/">
<i class="icon-film"></i>berkeley napier 3</a>
<a href="/"><i class ="icon-trash"></i></a>
</li>
</ul>
<div class="btn-group">
<a class="btn btn-small btn-inverse" href="/">Preview Something</a>
<a class="btn btn-small btn-inverse" href="/">Preview Something else</a>
</div>
</fieldset>
</div>
<div class="span3">
<fieldset>
<legend>Options</legend>
<div class="btn-group-vertical">
<a class="btn btn-info" href="/">Some LongButton Text</a>
<a class="btn btn-info" href="/">Longer Long Button Text</a>
<a class="btn btn-info disabled" data-href="/">Button Text</a>
<a class="btn btn-info disabled" data-href="/">Button Text</a>
</div>
</fieldset>
</div>
<div class="span3 actions">
<fieldset>
<legend>Buttons</legend>
<div class="btn-group btn-group-vertical">
<a class="btn btn-primary" href="/"><i class="icon-list icon-white"></i>
Create Something
</a>
<a class="btn btn-primary" href="/"><i class="icon-circle-arrow-down icon-white"></i> Download Something</a>
<a class="btn btn-primary" href="/"><i class="icon-share icon-white"></i> Some Button</a>
</div>
</fieldset>
</div>
</div>
</div>
</div>
</code></pre>
<p></p>
| 1 | 2,477 |
jQuery tree traversal - Nested Unordered list elements to JSON
|
<p>Okay, Now I have an unordered list here:</p>
<pre><code><ul id="mycustomid">
<li><a href="url of Item A" title="sometitle">Item A</a>
<ul class="children">
<li><a href="url of Child1 of A" title="sometitle">Child1 of A</a>
<ul class="children">
<li><a href="url of Grandchild of A" title="sometitle">Grandchild of A</a>
<ul class="children">
<li><a href="url of Grand Grand child of A" title="sometitle">Grand Grand child of A</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="url of Item B" title="sometitle">Item B</a></li>
<li><a href="url of Item C" title="sometitle">Item C</a></li>
</ul>
</code></pre>
<p>Basically, I want to just convert this data into a JSON entity. I want to get this done in <strong>jQuery</strong> and I think I'm having a really tough time doing it. The above list is just an example and in reality, my list would ideally have more number of children and probably be 'n' levels deep (Meaning, it will have grandchildren of grandchildren of grandchildren...or more) I've lost countless hours of sleep on this and I don't think I'm going anywhere :(</p>
<p>I want to extract these things: The text inside the anchor, the url of the anchor and the title of the anchor and put them onto a JSON entity</p>
<p><strong>The JSON format for my list above is something like this:</strong></p>
<pre><code>{
name: "Item A",
url: "url of Item A",
title: "sometitle",
children: [{
name: "Child1 of A",
url: "url of Child1 of A",
title: "sometitle",
children: [{
name: "Grandchild of A",
url: "url of Grandchild of A",
title: "sometitle",
children: [{
name: "Grand Grand child of A",
url: "url of Grand Grand child of A",
title: "sometitle",
children: []
}]
}]
}]
},
{
name: "Item B",
url: "url of Item B",
title: "sometitle",
children: []
},
{
name: "Item C",
url: "url of Item C",
title: "sometitle",
children: []
}
</code></pre>
<p>Some useful references:</p>
<p><strong>Javascript solution:</strong>
<a href="https://stackoverflow.com/questions/3158265/traversing-unordered-lists-using-javascript-jquery">Traversing unordered lists using Javascript/Jquery</a></p>
<p>^ This one probably works, but the format of the JSON output I need is as shown above and not what this script outputs :(</p>
<p><strong>Other references:</strong></p>
<p><a href="https://stackoverflow.com/questions/2793688/how-do-i-put-unordered-list-items-into-an-array">How do I put unordered list items into an array</a></p>
<p><a href="https://jsfiddle.net/yS6ZJ/1/" rel="nofollow noreferrer">https://jsfiddle.net/yS6ZJ/1/</a></p>
<p><a href="https://jsfiddle.net/CLLts/" rel="nofollow noreferrer">https://jsfiddle.net/CLLts/</a></p>
<p><a href="https://jsfiddle.net/cWnwt/" rel="nofollow noreferrer">https://jsfiddle.net/cWnwt/</a></p>
<p>Someone please help :(<br />
Been breaking my head for many many sleepless nights..(P.s - It took me about 40+ mins to write this entire page along with the code)</p>
| 1 | 2,201 |
What does java.awt.FontFormatException: bad table, tag=1196445523 indicating?
|
<p>I have followed <a href="http://www.dynamicreports.org/documentation/fonts" rel="nofollow">this link</a> to add fonts to my jasper report project, but i get this exception when trying to build the report, what does this exception mean any way? i can't find any solution on how to solve it.
note that i am trying to add <code>Ubuntu-LI</code> font</p>
<pre><code>17:26:35-218 - - raysis.rohani.rg.report.builder.ReportBuilder.show(120) - error in showing the jasper report (called from ReportBuilder)
net.sf.jasperreports.engine.JRRuntimeException: java.awt.FontFormatException: bad table, tag=1196445523
at net.sf.jasperreports.engine.fonts.SimpleFontFace.<init>(SimpleFontFace.java:104)
at net.sf.jasperreports.engine.fonts.SimpleFontFace.<init>(SimpleFontFace.java:128)
at net.sf.jasperreports.engine.fonts.SimpleFontFace.getInstance(SimpleFontFace.java:67)
at net.sf.jasperreports.engine.fonts.SimpleFontFamily.setNormal(SimpleFontFamily.java:99)
at net.sf.jasperreports.engine.fonts.SimpleFontExtensionHelper.parseFontFamily(SimpleFontExtensionHelper.java:261)
at net.sf.jasperreports.engine.fonts.SimpleFontExtensionHelper.parseFontFamilies(SimpleFontExtensionHelper.java:232)
at net.sf.jasperreports.engine.fonts.SimpleFontExtensionHelper.loadFontFamilies(SimpleFontExtensionHelper.java:193)
at net.sf.jasperreports.engine.fonts.SimpleFontExtensionHelper.loadFontFamilies(SimpleFontExtensionHelper.java:162)
at net.sf.jasperreports.engine.fonts.FontExtensionsRegistry.getExtensions(FontExtensionsRegistry.java:56)
at net.sf.jasperreports.extensions.DefaultExtensionsRegistry.getExtensions(DefaultExtensionsRegistry.java:110)
at net.sf.jasperreports.engine.DefaultJasperReportsContext.getExtensions(DefaultJasperReportsContext.java:246)
at net.sf.jasperreports.engine.fonts.FontUtil.getFontInfo(FontUtil.java:185)
at net.sf.jasperreports.engine.fonts.FontUtil.getAwtFontFromBundles(FontUtil.java:245)
at net.sf.dynamicreports.design.transformation.StyleResolver.getFont(StyleResolver.java:96)
at net.sf.dynamicreports.design.transformation.StyleResolver.getFont(StyleResolver.java:71)
at net.sf.dynamicreports.design.transformation.StyleResolver.getFontHeight(StyleResolver.java:52)
at net.sf.dynamicreports.design.transformation.TemplateTransform.getTextFieldHeight(TemplateTransform.java:967)
at net.sf.dynamicreports.design.transformation.ComponentTransform.textField(ComponentTransform.java:332)
at net.sf.dynamicreports.design.transformation.ComponentTransform.component(ComponentTransform.java:152)
at net.sf.dynamicreports.design.transformation.ComponentTransform.list(ComponentTransform.java:285)
at net.sf.dynamicreports.design.transformation.BandTransform.band(BandTransform.java:184)
at net.sf.dynamicreports.design.transformation.BandTransform.transform(BandTransform.java:74)
at net.sf.dynamicreports.design.base.DRDesignReport.transform(DRDesignReport.java:135)
at net.sf.dynamicreports.design.base.DRDesignReport.<init>(DRDesignReport.java:107)
at net.sf.dynamicreports.design.base.DRDesignReport.<init>(DRDesignReport.java:99)
at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.toJasperReportDesign(JasperReportBuilder.java:261)
at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.getJasperParameters(JasperReportBuilder.java:288)
at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.toJasperPrint(JasperReportBuilder.java:299)
at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.show(JasperReportBuilder.java:328)
at raysis.rohani.rg.report.JasperBuilder.show(JasperBuilder.java:121)
at raysis.rohani.rg.report.builder.ReportBuilder.show(ReportBuilder.java:118)
at raysis.rohani.rg.report.test.ReportMaker.main(ReportMaker.java:46)
Caused by: java.awt.FontFormatException: bad table, tag=1196445523
at sun.font.TrueTypeFont.init(TrueTypeFont.java:547)
at sun.font.TrueTypeFont.<init>(TrueTypeFont.java:191)
at sun.font.SunFontManager.createFont2D(SunFontManager.java:2460)
at java.awt.Font.<init>(Font.java:614)
at java.awt.Font.createFont0(Font.java:968)
at java.awt.Font.createFont(Font.java:876)
at net.sf.jasperreports.engine.fonts.SimpleFontFace.<init>(SimpleFontFace.java:100)
... 31 more
</code></pre>
<p>any help will be highly apreciated</p>
| 1 | 1,553 |
How to add rows to a RadGridView in WinForms using c#
|
<p>I am trying to add a rows to a RadGridView when a use click a button on the form (ie. "Add".)</p>
<p>When the form load I add columns to the <code>RadGridView</code> and make all of them all ReadOnly except one .</p>
<p>When a user click the "Add" button, I want to add a row to this RadGridView. Basically, a user types a UPC code, then I read data from the database and add new row in a grid view with the item name, item price.</p>
<p>Here is what I did to create the columns</p>
<p>private void Register_Load(object sender, EventArgs e) {</p>
<pre><code> GridViewTextBoxColumn UPC = new GridViewTextBoxColumn();
UPC.Name = "UPC";
UPC.HeaderText = "UPC";
UPC.FieldName = "UPC";
UPC.MaxLength = 50;
UPC.TextAlignment = ContentAlignment.BottomRight;
radGridView1.MasterTemplate.Columns.Add(UPC);
radGridView1.Columns["UPC"].Width = 120;
radGridView1.Columns["UPC"].ReadOnly = true;
GridViewTextBoxColumn ItemName = new GridViewTextBoxColumn();
ItemName.Name = "Item Name";
ItemName.HeaderText = "Item Name";
ItemName.FieldName = "ItemName";
ItemName.MaxLength = 100;
ItemName.TextAlignment = ContentAlignment.BottomRight;
radGridView1.MasterTemplate.Columns.Add(ItemName);
radGridView1.Columns["Item Name"].Width = 210;
radGridView1.Columns["Item Name"].ReadOnly = true;
GridViewDecimalColumn QtyColumn = new GridViewDecimalColumn();
QtyColumn.Name = "Qty";
QtyColumn.HeaderText = "Quantity";
QtyColumn.FieldName = "Qty";
QtyColumn.DecimalPlaces = 1;
radGridView1.MasterTemplate.Columns.Add(QtyColumn);
radGridView1.Columns["Qty"].Width = 75;
GridViewMaskBoxColumn PriceColumn = new GridViewMaskBoxColumn();
PriceColumn.Name = "Unit Price";
PriceColumn.FieldName = "UnitPrice";
PriceColumn.HeaderText = "Unit Price";
PriceColumn.MaskType = MaskType.Numeric;
PriceColumn.Mask = "C";
PriceColumn.TextAlignment = ContentAlignment.BottomRight;
PriceColumn.FormatString = "{0:C}";
PriceColumn.DataType = typeof(decimal);
radGridView1.MasterTemplate.Columns.Add(PriceColumn);
radGridView1.Columns["Unit Price"].Width = 75;
radGridView1.Columns["Unit Price"].ReadOnly = true;
GridViewMaskBoxColumn TotalColumn = new GridViewMaskBoxColumn();
TotalColumn.Name = "Total Price";
TotalColumn.FieldName = "TotalPrice";
TotalColumn.HeaderText = "Total Price";
TotalColumn.MaskType = MaskType.Numeric;
TotalColumn.Mask = "C";
TotalColumn.TextAlignment = ContentAlignment.BottomRight;
TotalColumn.FormatString = "{0:C}";
TotalColumn.DataType = typeof(decimal);
radGridView1.MasterTemplate.Columns.Add(TotalColumn);
radGridView1.Columns["Total Price"].Width = 75;
radGridView1.Columns["Total Price"].ReadOnly = true;
}
</code></pre>
<p>To add the row Here is what I am doing "when a user click the 'Add' button)</p>
<pre><code>private void ButtonAdd_Click(object sender, EventArgs e) {
string UPC = InputUPC.Text.Trim();
if (UPC.Length < 3) {
return;
}
string sql = " SELECT p.productName, p.price "
+ " FROM products AS p "
+ " WHERE p.productUPC = @upc ";
var parms = new List<MySqlParameter>();
parms.Add(new MySqlParameter("@upc", UPC));
var db = new dbConnetion();
foreach (var i in db.getData(sql, parms, r =>
new ProductsTable() {
_productName = r["productName"].ToString(),
_price = Convert.ToDouble(r["price"])
}
)
) {
//radGridView1.Rows[0].Cells[0].Value = 4.3;
radGridView1.Rows[0].Cells["UPC"].Value = UPC;
radGridView1.Rows[0].Cells["Item Name"].Value = i._productName;
radGridView1.Rows[0].Cells["Qty"].Value = "1";
radGridView1.Rows[0].Cells["Unit Price"].Value = i._price;
radGridView1.Rows[0].Cells["Total Price"].Value = (Convert.ToDouble(i._price) * Convert.ToInt32(radGridView1.Rows[0].Cells["Qty"].Value)).ToString();
}
}
</code></pre>
<p>But the add row is giving me an error</p>
<pre><code>Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
</code></pre>
<p>How can I correctly add rows to the RadGridView when the "Add" button is clicked.</p>
| 1 | 2,223 |
Swiper pagination not working properly in desktop and mobile
|
<p>The pagination appears mixed up in the text and i would wish that it appears below the text as a stand alone item to be visibly seen. </p>
<p>Another thing is that when in mobile view the hamburger when open displays behind the slider and i want it to display in-front of the slider. </p>
<p>Html</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta name='viewport' content='width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1'>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" href="swiper.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
$('.menu-toggle').click(function(){
$('.site-nav').toggleClass('site-nav--open');
$(this).toggleClass('open');
})
})
</script>
</head>
<body>
<header>
<div class="container">
<div class="logo">
<ul>
<li><a href="#">SakaHapa</a></li>
</ul>
</div>
<nav class="site-nav">
<ul>
<li><a href="#"><i class="fa fa-home site-nav--icon"></i>HOME</a></li>
<li><a href="#"><i class="fa fa-question-circle-o site-nav--icon"></i>HOW IT WORKS</a></li>
<li><a href="#"><i class="fa fa-user-circle site-nav--icon"></i>PROFILE</a></li>
<li><a href="#"><i class="fa fa-cart-plus site-nav--icon"></i>PURCHASES</a></li>
<li><a href="#"><i class="fa fa-eye site-nav--icon"></i>POPULAR</a></li>
<li><a href="#"><i class="fa fa-envelope site-nav--icon"></i>CONTACT</a></li>
<li><a href="#"><i class="fa fa-power-off site-nav--icon"></i>Log Out</a></li>
</ul>
</nav>
<div class="menu-toggle">
<div class="hamburger"></div>
</div>
</div>
</header>
<div class="container">
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide">
<div class="slide-text">
<h2>Slide man</h2>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
when an unknown printer took a galley of type and scrambled it to make a type specimen
book. It has survived not only five centuries, but also the leap into electronic
typesetting, remaining essentially unchanged. It was popularised in the 1960s with the
release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>
</div>
<div class="swiper-slide">
<div class="slide-text">
<h2>Mafans</h2>
<p>It is a long established fact that a reader will be distracted by the readable
content of a page when looking at its layout. The point of using Lorem Ipsum is
that it has a more-or-less normal distribution of letters, as opposed to using
'Content here, content here', making it look like readable English. Many desktop
publishing packages and web page editors now use Lorem Ipsum as their default
model text, and a search for 'lorem ipsum' will uncover many web sites still in
their infancy. Various versions have evolved over the years, sometimes by accident,
sometimes on purpose.</p>
</div>
</div>
<div class="swiper-slide">Slide 3</div>
<div class="swiper-slide">Slide 4</div>
<div class="swiper-slide">Slide 5</div>
<div class="swiper-slide">Slide 6</div>
<div class="swiper-slide">Slide 7</div>
<div class="swiper-slide">Slide 8</div>
<div class="swiper-slide">Slide 9</div>
<div class="swiper-slide">Slide 10</div>
</div>
<!-- Add Pagination -->
<div class="swiper-pagination"></div>
</div>
<script type="text/javascript" src="swiper.min.js"></script>
<!-- Initialize Swiper -->
<script>
var swiper = new Swiper('.swiper-container', {
pagination: {
el: '.swiper-pagination',
clickable: true,
renderBullet: function (index, className) {
return '<span class="' + className + '">' + (index + 1) + '</span>';
},
},
});
</script>
</div>
</body>
</html>
</code></pre>
<p>CSS</p>
<pre><code>body{
background: #F0F8EA;
font-family: sans-serif;
}
.container{
width: 95%;
max-width: 1000px;
margin: 0 auto;
}
header{
background: #E54B4B;
color: #f8f4f4;
padding: 1em 0;
position: relative;
}
header::after{
content: '';
clear: both;
display: block;
}
.logo{
float: left;
font-size: 1.65em;
margin: 0;
font-weight: 700;
}
.logo ul{
margin: 0;
padding: 0;
list-style: none;
}
.logo a{
color: #f8f4f4;
text-decoration: none;
}
.logo a:hover,
.logo a:focus{
color: #464655;
}
.navbar-nav{
outline: none;
float: right;
}
.navbar-nav ul{
margin: 0;
padding: 0;
list-style: none;
}
.navbar-nav a{
color: #f8f4f4;
text-decoration: none;
font-size: 130%;
right: .75em;
}
.navbar-nav a:hover,
.navbar-nav a:focus{
color: #464655;
}
.site-nav{
position: absolute;
top: 100%;
right: 0%;
background: #464655;
clip-path: circle(0px at top right);
transition: clip-path ease-in-out 700ms;
/* display: none; */
}
.site-nav--open{
clip-path: circle(100%);
}
.site-nav ul{
margin: 0;
padding: 0;
list-style: none;
}
.site-nav li{
border-bottom: 1px solid #575766;
}
.site-nav li:last-child{
border-bottom: none;
}
.site-nav a{
color: #f8f4f4;
display: block;
padding: 1.5em 4.5em;
text-decoration: none;
}
.site-nav a:hover,
.site-nav a:focus{
background: #E4B363;
color: #464655;
}
.site-nav--icon{
display: inline-block;
font-size: 1.5em;
margin-right: 1em;
width: 0.7em;
text-align: right;
color: rgba(255,255,255,.4);
}
.menu-toggle{
padding: 1em;
position: absolute;
top: .75em;
right: .75em;
cursor: pointer;
}
.hamburger,
.hamburger::before,
.hamburger::after{
content: '';
display: block;
background: #f8f4f4;
height: 3px;
width: 1.95em;
border-radius: 3px;
transition: all ease-in-out 500ms;
}
.hamburger::before{
transform: translateY(-7px);
}
.hamburger::after{
transform: translateY(4px);
}
.open .hamburger{
transform: rotate(45deg);
}
.open .hamburger::before{
opacity: 0;
}
.open .hamburger::after{
transform: translateY(-3px) rotate(-90deg);
}
@media (min-width: 1077px){
.menu-toggle{
display: none;
}
.site-nav{
height: auto;
position: relative;
background: transparent;
float: right;
clip-path: initial;
}
.site-nav li{
display: inline-block;
border: none;
}
.site-nav a{
padding: 0;
margin-left: 1.2em;
font-size: 1.15em;
padding-top: 7px;
}
.site-nav a:hover,
.site-nav a:focus{
background: transparent;
}
.site-nav li .fa{
display: none;
}
}
.content-section{
background: #f8f4f4;
padding: 10px;
width: 500px;
margin: auto;
color: #131212;
margin-top: 5px;
margin-bottom: 5px;
border: 2px solid rgb(15, 15, 15);
font-weight: bold;
}
div.form-group{
margin-top: -24px;
}
.btn{
background: rgb(41, 159, 180);
}
h5{
color: #ffff;
}
h6{
color: #ffff;
}
.register{
background: #dbd7d7;
}
html, body{
position: relative;
height: 100%;
}
body{
background: #eee;
font-family: sans-serif;
font-size: 14px;
color:#000;
margin: 0;
padding: 0;
}
.swiper-container{
width: 100%;
height: 100%;
}
.swiper-slide{
text-align: center;
font-size: 18px;
background: #eee;
/* Center slide text vertically */
display: -webkit-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
position: relative;
}
.swiper-pagination-bullet{
width: 20px;
height: 20px;
text-align: center;
line-height: 30px;
font-size: 12px;
color:#000;
opacity: 1;
background: rgba(0,0,0,0.2);
font-weight: bold;
}
.swiper-pagination-bullet-active{
color: #000;
background: #007aff;
}
</code></pre>
<p>Kindly assist guys.</p>
| 1 | 5,595 |
html5 - how to do the brightness, contrast, saturation, hue up and down?
|
<p>How can i apply the brightness up and down instead of grey?
I have been trying but i was only able to get it into grey.</p>
<p>My goal was to make it brightness up and down.</p>
<p>Current code:</p>
<p><strong>HTML</strong></p>
<pre><code><h1>Effects Brightness</h1>
<table>
<tr>
<td style="vertical-align:text-top;">
<h2>BEFORE effect</h2>
<img id="cvs-src" src="/images/a.jpg" width=640 height=480/>
</td>
<td>
<h2>AFTER effect</h2>
<canvas width=1024 height=768></canvas>
</td>
</tr>
</table>
</code></pre>
<p><strong>JS</strong></p>
<pre><code>(function() {
window.onload = greyImages;
function greyImages() {
var img = document.getElementById("cvs-src");
var imageData;
var px;
var length;
var i = 0;
var grey;
var can = document.getElementsByTagName("canvas")[0].getContext('2d');
can.drawImage(img, 0, 0);
imageData = can.getImageData(0, 0, 1024, 768);
px = imageData.data;
length = px.length;
for ( ; i < length; i+= 4 ) {
grey = px[i] * .3 + px[i+1] * .59 + px[i+2] * .11;
px[i] = px[i+1] = px[i+2] = grey;
grey = px[i] * .3 + px[i+1] * .59 + px[i+2] * .11;
px[i] = px[i+1] = px[i+2] = grey;
grey = px[i] * .1 + px[i+1] * .1 + px[i+2] * .1;
px[i] = px[i+1] = px[i+2] = grey;
}
can.putImageData(imageData, 0, 0);
}
})();
</code></pre>
<p><strong>EDIT: copy and paste it</strong></p>
<pre><code><script>
function greyImages() {
var img = document.getElementById("cvs-src");
var imageData;
var px;
var length;
var i = 0;
var grey;
var can = document.getElementsByTagName("canvas")[0].getContext('2d');
can.drawImage(img, 0, 0);
imageData = can.getImageData(0, 0, 1024, 768);
px = imageData.data;
length = px.length;
for ( ; i < length; i+= 4 ) {
grey = px[i] * .3 + px[i+1] * .59 + px[i+2] * .11;
px[i] = grey;
}
can.putImageData(imageData, 0, 0);
}
</script>
<h1>Effects</h1>
<table>
<tr>
<td style="vertical-align:text-top;">
<h2>BEFORE effect</h2>
<button id="take" onclick="greyImages();" />
Download: http://people.opera.com/shwetankd/webm/sunflower.webm
<video id="cvs-src" autoplay="autoplay" src="/images/1.webm"
type="video/webm" width=640 height=480></video>
</td>
<td>
<h2>AFTER effect</h2>
<canvas width=1024 height=768></canvas>
</td>
</tr>
</table>
</code></pre>
| 1 | 1,430 |
How to build an array from a jSon object
|
<p>I am trying to build 2 arrays from JSON arrays.</p>
<pre><code>{
"2015-03-24": {
"bind": 0,
"info": "",
"notes": "",
"price": "150",
"promo": "",
"status": "available"
},
"2015-03-25": {
"bind": 0,
"info": "",
"notes": "",
"price": "150",
"promo": "",
"status": "available"
},
"2015-03-26": {
"bind": 0,
"info": "",
"notes": "",
"price": "150",
"promo": "",
"status": "available"
},
"2015-03-27": {
"bind": 0,
"info": "",
"notes": "",
"price": "100",
"promo": "",
"status": "available"
},
"2015-03-28": {
"bind": 0,
"info": "",
"notes": "",
"price": "100",
"promo": "",
"status": "available"
},
"2015-03-29": {
"bind": 0,
"info": "",
"notes": "",
"price": "100",
"promo": "",
"status": "available"
},
"2015-04-10": {
"bind": 0,
"info": "",
"notes": "",
"price": "",
"promo": "",
"status": "booked"
},
"2015-04-11": {
"bind": 0,
"info": "",
"notes": "",
"price": "",
"promo": "",
"status": "booked"
},
"2015-05-01": {
"bind": 0,
"info": "",
"notes": "",
"price": "",
"promo": "",
"status": "unavailable"
},
"2015-05-02": {
"bind": 0,
"info": "",
"notes": "",
"price": "",
"promo": "",
"status": "unavailable"
},
"2015-05-03": {
"bind": 0,
"info": "",
"notes": "",
"price": "",
"promo": "",
"status": "unavailable"
},
}
</code></pre>
<p>This is the jSon array, so I want to build 2 arrays.</p>
<p>1 array holding only keys (in this case the date) of those element where <code>status=='booked' nOR status=='unavailable'</code> and build it in jQuery array like this</p>
<pre><code>var array = ['2015-03-19', '2015-03-20', '2015-03-21', '2015-03-22', '2015-03-23', '2015-03-24', '2015-03-25', '2015-03-26', '2015-04-07', '2015-04-08', '2015-04-09', '2015-04-10'];
</code></pre>
<p>Another is building another array with the dates of those days where <code>status=='available' AND price > '100$'</code></p>
<p>var array2 = [ '2015-03-25', '2015-03-26', '2015-04-07', '2015-04-08'];</p>
<p>How can I achieve this on with jQuery?</p>
| 1 | 2,305 |
NullPointerException in AsyncTask OnPostExecute
|
<p>I am new to android.I am getting <code>data=null</code> when executing the onPostExecute which is correct.Now I just want to show a dialog that there is no data available.But I am getting the <code>NullPointerException</code>.</p>
<pre><code>public class GetPreviousChatNewThread extends AsyncTask<Void,Void,Void> {
ProgressDialog dialog;
ArrayList<HashMap<String,String>> data;
@Override
protected Void doInBackground(Void... void1) {
data=new ArrayList<HashMap<String,String>>();
data=HandleJSON.ParseJsonForUserAdminChats(sendHttpRequest(
"ReturnUserAdminChats",
"admin",
"You" ,
"a",
clientEmail,
UserAdminChatActivity.LastShowingChatDate));
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(!data.isEmpty()) // <-- error here
{
adapter.InsertValuesAtTop(data);
}
else
{
Toast.makeText(getApplicationContext(), "No more data", Toast.LENGTH_LONG).show();
}
if(dialog.isShowing())
dialog.dismiss();
}
@Override
protected void onPreExecute() {
dialog = ProgressDialog.show(UserAdminChatActivity.this, "", "Loading. Please wait...", true);
}
}
</code></pre>
<p>Here's my Logcat which shows the complete log of the process:</p>
<pre><code>07-23 12:22:55.976: I/finalAnswer(25159): ["a@hotmail.com","c@hotmail.com","b@hotmail.com"]
07-23 12:23:01.101: I/finalAnswer(25159): [{"username":"moji","chatText":"jingalala hu","chatDate":"4\\July\\2012"},{"username":"You","chatText":"bingalala hu","chatDate":"4\\July\\2012"},{"username":"moji","chatText":"jingalala hu","chatDate":"4\\July\\2012"}]
07-23 12:23:01.101: I/GoTo Json(25159): [{"username":"moji","chatText":"jingalala hu","chatDate":"4\\July\\2012"},{"username":"You","chatText":"bingalala hu","chatDate":"4\\July\\2012"},{"username":"moji","chatText":"jingalala hu","chatDate":"4\\July\\2012"}]
07-23 12:23:01.101: I/dateeeeeee(25159): 4\July\2012
07-23 12:23:01.101: I/dateeeeeee(25159): 4\July\2012
07-23 12:23:01.111: I/dateeeeeee(25159): 4\July\2012
07-23 12:23:01.161: I/finalAnswer(25159): new"[]"
07-23 12:23:02.603: I/finalAnswer(25159): []
07-23 12:23:02.603: I/GoTo Json(25159): []
07-23 12:23:02.613: D/AndroidRuntime(25159): Shutting down VM
07-23 12:23:02.613: W/dalvikvm(25159): threadid=1: thread exiting with uncaught exception (group=0x4001d578)
07-23 12:23:02.623: E/AndroidRuntime(25159): FATAL EXCEPTION: main
07-23 12:23:02.623: E/AndroidRuntime(25159): java.lang.NullPointerException
07-23 12:23:02.623: E/AndroidRuntime(25159): at com.app.ServerClient.UserAdminChatActivity$GetPreviousChatNewThread.onPostExecute(UserAdminChatActivity.java:197)
07-23 12:23:02.623: E/AndroidRuntime(25159): at com.app.ServerClient.UserAdminChatActivity$GetPreviousChatNewThread.onPostExecute(UserAdminChatActivity.java:1)
07-23 12:23:02.623: E/AndroidRuntime(25159): at android.os.AsyncTask.finish(AsyncTask.java:417)
07-23 12:23:02.623: E/AndroidRuntime(25159): at android.os.AsyncTask.access$300(AsyncTask.java:127)
07-23 12:23:02.623: E/AndroidRuntime(25159): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
07-23 12:23:02.623: E/AndroidRuntime(25159): at android.os.Handler.dispatchMessage(Handler.java:99)
07-23 12:23:02.623: E/AndroidRuntime(25159): at android.os.Looper.loop(Looper.java:138)
07-23 12:23:02.623: E/AndroidRuntime(25159): at android.app.ActivityThread.main(ActivityThread.java:3701)
07-23 12:23:02.623: E/AndroidRuntime(25159): at java.lang.reflect.Method.invokeNative(Native Method)
07-23 12:23:02.623: E/AndroidRuntime(25159): at java.lang.reflect.Method.invoke(Method.java:507)
07-23 12:23:02.623: E/AndroidRuntime(25159): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
07-23 12:23:02.623: E/AndroidRuntime(25159): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
07-23 12:23:02.623: E/AndroidRuntime(25159): at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p>Edit:</p>
<p>Heres the code for HandleJson:</p>
<pre><code>public class HandleJSON {
private static ArrayList<HashMap<String,String>> chat;
static final String Key_username="username_key";
static final String Key_email="email_key";
static final String Key_messageText="messageText_key";
static final String Key_messageDate="messageDate_key";
static final String Key_messageCounts="messageCount_key";
static boolean newObject;
public static ArrayList<HashMap<String,String>> ParseJsonForLatestChats(String jsonData)
{
try {
if(HandleJSON.newObject)
{
chat=new ArrayList<HashMap<String,String>>();
}
Log.i("jsonReturned",jsonData.toString());
JSONArray jsonarr=new JSONArray(jsonData);
for(int i=0;i<jsonarr.length();i++)
{
HashMap<String,String> hashMap=new HashMap<String,String>();
hashMap.put(HandleJSON.Key_username, jsonarr.getJSONObject(i).getString("username"));
hashMap.put(HandleJSON.Key_email, jsonarr.getJSONObject(i).getString("email"));
hashMap.put(HandleJSON.Key_messageCounts, jsonarr.getJSONObject(i).getString("count"));
chat.add(hashMap);
}
return chat;
}
catch(JSONException e)
{
Log.e("JsonDek", e.getMessage());
return null;
}
}
public static ArrayList<HashMap<String,String>> ParseJsonForUserAdminChats(String jsonData)
{
chat=new ArrayList<HashMap<String,String>>();
try {
JSONArray jsonarr=new JSONArray(jsonData);
Log.i("GoTo Json",jsonData);
UserAdminChatActivity.LastShowingChatDate=jsonarr.getJSONObject(0).getString("chatDate");
for(int i=jsonarr.length()-1;i>=0;i--)
{
HashMap<String,String> hashMap=new HashMap<String,String>();
hashMap.put(HandleJSON.Key_username, jsonarr.getJSONObject(i).getString("username"));
hashMap.put(HandleJSON.Key_messageText, jsonarr.getJSONObject(i).getString("chatText"));
hashMap.put(HandleJSON.Key_messageDate, jsonarr.getJSONObject(i).getString("chatDate"));
Log.i("dateeeeeee",jsonarr.getJSONObject(i).getString("chatDate"));
chat.add(hashMap);
}
return chat;
}
catch(JSONException e)
{
return null;
}
}
public static ArrayList<String> ReturnUsersEmail(String jsonData) throws JSONException
{
JSONArray jsonarr=new JSONArray(jsonData);
ArrayList<String> emails=new ArrayList<String>();
for(int i=0;i<jsonarr.length();i++)
{
emails.add(jsonarr.getString(i));
}
return emails;
}
}
</code></pre>
| 1 | 3,333 |
Dynamically load a <ul> and sort into columns of 5 rows
|
<p>Ok so I thought i would put this one out there. I have a list of 25 entries in my db which I would like to display on my page, in list form, in 5 columns with 5 rows. </p>
<p>I prepared a solution, albeit not such an elegant one.</p>
<pre><code><?php
$query = "SELECT * FROM city ORDER BY name ASC";
$result = mysql_query($query, $connection);
confirm_query($result);
echo "<ul class=\"floatleft\">";
$counter = 1;
while ($row = mysql_fetch_array($result)) {
if ($counter <= 5) {
echo "<li>{$row["name"]}</li>";
$counter = $counter + 1;
if ($counter == 6) {
echo "</ul>";
}
} elseif($counter > 5 && $counter <= 10) {
if ($counter == 6){
echo "<ul class=\"floatleft\">";
}
echo "<li>{$row["name"]}</li>";
$counter += 1;
if ($counter == 11) {
echo "</ul>";
}
} elseif($counter > 10 && $counter <= 15) {
if ($counter == 11){
echo "<ul class=\"floatleft\">";
}
echo "<li>{$row["name"]}</li>";
$counter += 1;
if ($counter == 16) {
echo "</ul>";
}
} elseif($counter > 15 && $counter <= 20) {
if($counter == 16){
echo "<ul class=\"floatleft\">";
}
echo "<li>{$row["name"]}</li>";
$counter += 1;
if ($counter == 21) {
echo "</ul>";
}
} elseif($counter > 20 && $counter <= 25) {
if($counter == 21){
echo "<ul class=\"floatleft\">";
}
echo "<li>{$row["name"]}</li>";
$counter += 1;
if ($counter == 26) {
echo "</ul>";
}
}
}
?>
</code></pre>
<p>This will Output the following</p>
<pre><code><ul class="floatleft">
<li>Belfast</li>
<li>Birmingham</li>
<li>Brighton</li>
<li>Bristol</li>
<li>Cambridge</li>
</ul>
<ul class="floatleft">
<li>Cardiff</li>
<li>Carlisle</li>
<li>Edinburgh</li>
<li>Glasgow</li>
<li>Hull</li>
</ul>
<ul class="floatleft">
<li>Lancaster</li>
<li>Leeds</li>
<li>Leicester</li>
<li>Liverpool</li>
<li>London</li>
</ul>
<ul class="floatleft">
<li>Manchester</li>
<li>Newcastle</li>
<li>Norwich</li>
<li>Nottingham</li>
<li>Oxford</li>
</ul>
<ul class="floatleft">
<li>Plymouth</li>
<li>Portsmouth</li>
<li>Southampton</li>
<li>Swansea</li>
<li>York</li>
</ul>
</code></pre>
<p>Does anybody know of a better way of doing this? I'm still new to php, and I kbnow there must be a better, neater way of doing this.</p>
| 1 | 3,113 |
Pandas: If statement with multiple conditions on pandas dataframe
|
<p>I am trying to compare rows within a group and if a condition is met within the rows, I want to either keep the complete group, keep the most recent row, or keep the first row. </p>
<p>The dataframe will only have 2 items per group. If the first row of the group has the LastFour digits of '2290' OR if it start with the letter 'M' AND if in the second row the LastFour column is equal to either 0087 OR 0117 AND if NUM != 6708 then I want to keep both rows. This is the first conditional. The second condition is if the rows are the same for each column except for the Date column then keep the row with the most recent date. Else, if neither of these conditions are met, keep the first row only and remove the second row.</p>
<p>Original df:</p>
<pre><code> KEY CLAIM LastFour NUM Date1 Date2 Code
166 0944 163 0087 30087 3/2/2012 3/5/2012 1
167 0944 164 0087 30087 3/3/2012 3/5/2012 1
225 1413 222 2290 123422 2/10/2012 2/11/2012 1
226 1413 223 0032 123123 2/10/2012 2/11/2012 1
315 1979 312 0025 70025 12/24/2011 1/6/2012 3
316 1979 313 0025 70025 12/24/2011 1/6/2012 3
320 1997 317 0007 140007 1/1/2012 1/4/2012 2
321 1997 318 0007 140007 1/1/2012 1/4/2012 2
</code></pre>
<p>Anticipated result:</p>
<pre><code> KEY CLAIM LastFour NUM Date1 Date2 Code Keep
166 0944 163 0087 30087 3/2/2012 3/5/2012 1 FALSE
167 0944 164 0087 30087 3/3/2012 3/5/2012 1 TRUE
225 1413 222 2290 123422 2/10/2012 2/11/2012 1 TRUE
226 1413 223 0032 123123 2/10/2012 2/11/2012 1 TRUE
315 1979 312 0025 70025 12/24/2011 1/6/2012 3 FALSE
316 1979 313 0025 70025 12/24/2011 1/6/2012 3 TRUE
320 1997 317 0007 140007 1/1/2012 1/4/2012 2 FALSE
321 1997 318 0007 140007 1/1/2012 1/4/2012 2 TRUE
</code></pre>
<p>My approach was to use an if statement but I'm having trouble.</p>
<pre><code>if ((df['KEY'] == df['KEY'].shift(-1)) & (df['LastFour'].isin(['2290'])) \
| (df['LastFour'].str.get(0).isin(['M']))) & \
((df['KEY'] == df['KEY'].shift(-1)) & (df['LastFour'].isin(['0087','0117'])) | (~df['NUM'].isin(['670899']))):
pass
if (df['KEY'] == df['KEY'].shift(-1)) & (df['LastFour'] == df['LastFour'].shift(-1)) & (df['NUM'] == df['NUM'].shift(-1)):
df.groupby('KEY').Date.transform('last')
else:
df.groupby('Key').iloc[0]
</code></pre>
<p>I appreciate any help.</p>
| 1 | 1,350 |
Do i need to install Nvidia's SDK(CUDA) for OpenCL to detect Nvidia GPU?
|
<p>I have a code written in C (using opencl specs) to list all the available devices. My PC has an AMD FirePro as well as Nvidia's Tesla graphics card installed. I first installed <a href="http://developer.amd.com/tools-and-sdks/opencl-zone/amd-accelerated-parallel-processing-app-sdk/#" rel="nofollow" title="MD-APP-SDK-v3.0-0.113.50-Beta-linux64.tar.bz2">AMD-APP-SDK-v3.0-0.113.50-Beta-linux64.tar.bz2</a> but it didn't seem to work so thereafter I installed OpenCL™ Runtime 15.1 for Intel® Core™ and Intel® Xeon® Processors for Red Hat* and SLES* Linux* OS (64-bit) & then <a href="https://software.intel.com/en-us/articles/opencl-drivers#sdk" rel="nofollow" title="OpenCL™ Code Builder">OpenCL™ Code Builder</a> .
But the following code lists only the CPU and does not detect the 2 graphics card.
</p>
<pre><code>int main() {
int i, j;
char* value;
size_t valueSize;
cl_uint platformCount;
cl_platform_id* platforms;
cl_uint deviceCount;
cl_device_id* devices;
cl_uint maxComputeUnits;
cl_device_type* dev_type;
// get all platforms
clGetPlatformIDs(2, NULL, &platformCount);
platforms = (cl_platform_id*) malloc(sizeof(cl_platform_id) * platformCount);
clGetPlatformIDs(platformCount, platforms, NULL);
for (i = 0; i < platformCount; i++) {
// get all devices
clGetDeviceIDs(platforms[i], CL_DEVICE_TYPE_ALL, 0, NULL, &deviceCount);
devices = (cl_device_id*) malloc(sizeof(cl_device_id) * deviceCount);
clGetDeviceIDs(platforms[i], CL_DEVICE_TYPE_ALL, deviceCount, devices, NULL);
clGetPlatformInfo(platforms[i], CL_PLATFORM_NAME, 0, NULL, &valueSize);
value = (char*) malloc(valueSize);
clGetPlatformInfo(platforms[i], CL_PLATFORM_NAME, valueSize, value, NULL);
printf("\n%d. Platform: %sn", j+1, value);
free(value);
// for each device print critical attributes
for (j = 0; j < deviceCount; j++) {
// print device name
clGetDeviceInfo(devices[j], CL_DEVICE_NAME, 0, NULL, &valueSize);
value = (char*) malloc(valueSize);
clGetDeviceInfo(devices[j], CL_DEVICE_NAME, valueSize, value, NULL);
printf("\n%d.%d Device: %sn", j+1,1, value);
free(value);
// print hardware device version
clGetDeviceInfo(devices[j], CL_DEVICE_TYPE, 0, NULL, &valueSize);
dev_type = (cl_device_type*) malloc(valueSize);
clGetDeviceInfo(devices[j], CL_DEVICE_TYPE, valueSize, dev_type, NULL);
if(*dev_type==CL_DEVICE_TYPE_CPU)
printf("\nIts a CPU.");
if(*dev_type==CL_DEVICE_TYPE_GPU)
printf("\nIts a GPU.");
if(*dev_type==CL_DEVICE_TYPE_ACCELERATOR)
printf("\nIts a ACCELERATOR.");
free(dev_type);
// print software driver version
clGetDeviceInfo(devices[j], CL_DRIVER_VERSION, 0, NULL, &valueSize);
value = (char*) malloc(valueSize);
clGetDeviceInfo(devices[j], CL_DRIVER_VERSION, valueSize, value, NULL);
printf(" \n%d.%d Software version: %sn", j+1, 2, value);
free(value);
// print parallel compute units
clGetDeviceInfo(devices[j], CL_DEVICE_MAX_COMPUTE_UNITS,
sizeof(maxComputeUnits), &maxComputeUnits, NULL);
printf(" \n%d.%d Parallel compute units: %dn\n", j+1, 4, maxComputeUnits);
}
free(devices);
}
free(platforms);
return 0;}
</code></pre>
<p>This is what it returns:</p>
<pre><code>gcc -lOpenCL 1.c -o 1 && ./1
1. Platform: AMD Accelerated Parallel Processingn
1.1 Device: Intel(R) Xeon(R) CPU X5660 @ 2.80GHzn
Its a CPU.
1.2 Software version: 1642.5 (sse2)n
1.4 Parallel compute units: 24n
</code></pre>
<p>Do I need to install any other driver or is there anything wrong with the code?</p>
| 1 | 1,535 |
How can I get this code for a GUI Countdown Timer to work properly?
|
<p>I'm trying to custom write a program for a GUI Countdown Timer (for a personal project), based on some other codes that I've found on this site. </p>
<p>The idea is that a user will be able to select the total time (variable <code>"remaining"</code>) in mins from a combo box, press <code>"Start"</code>, and the countdown will start.</p>
<p>However, in my current code (below), after selecting the total time from the combo box and pressing <code>"Start"</code>, the label will show the correct start time, but the countdown will not start. If I manually set <code>"remaining"</code> at the top of the code (line 23) to the total time, eg. <code>61000</code> and remove the line <code>"remaining = convertTime();"</code> under my <code>actionPerformed</code> interface, the countdown timer works perfectly fine.</p>
<p>I'm not sure what went wrong.</p>
<pre><code>import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.NumberFormat;
import javax.swing.*;
public class GUITimer extends JFrame implements ItemListener {
JLabel jltime;
JLabel jl;
JComboBox jcb;
JButton jbt;
JButton jbt2;
NumberFormat format;
public Timer timer;
public long initial;
public long ttime2;
public String ttime;
public long remaining;
GUITimer() {
jl=new JLabel("TOTAL TIME (minutes)");
jl.setHorizontalAlignment((int) CENTER_ALIGNMENT);
jltime=new JLabel("");
jltime.setHorizontalAlignment((int) CENTER_ALIGNMENT);
jltime.setForeground(Color.WHITE);
jltime.setBackground(Color.BLACK);
jltime.setOpaque(true);
jltime.setFont(new Font("Arial", Font.BOLD, 450));
jbt=new JButton("START");
jbt2=new JButton("RESET");
jcb=new JComboBox();
jcb.addItem("15");
jcb.addItem("14");
jcb.addItem("13");
jcb.addItem("12");
jcb.addItem("11");
jcb.addItem("10");
jcb.addItem("9");
jcb.addItem("8");
jcb.addItem("7");
jcb.addItem("6");
jcb.addItem("5");
jcb.addItem("4");
jcb.addItem("3");
jcb.addItem("2");
jcb.addItem("1");
JPanel jp1=new JPanel();
jp1.setLayout(new GridLayout(1,4,10,0));
jp1.add(jl);
jp1.add(jcb);
jp1.add(jbt);
jp1.add(jbt2);
getContentPane().add(jp1,BorderLayout.NORTH);
JPanel jp2=new JPanel();
jp2.setLayout(new GridLayout(1,2,10,10));
jp2.add(jltime);
getContentPane().add(jp2,BorderLayout.CENTER);
event e = new event();
jbt.addActionListener(e);
jbt2.addActionListener(e);
jcb.addItemListener(this);
}
public static void main(String[] args) {
GUITimer frame=new GUITimer();
frame.setSize(500,500);
frame.setTitle("LARC Moot Countdown Timer");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//this method will run when user presses the start button
void updateDisplay() {
Timeclass tc = new Timeclass();
timer = new Timer(1000, tc);
initial = System.currentTimeMillis();
timer.start();
}
//code for what happens when user presses the start or reset button
public class event implements ActionListener {
public void actionPerformed(ActionEvent e) {
String bname=e.getActionCommand();
if(bname.equals("START"))
{
updateDisplay();
}
else
{
jltime.setText("");
timer.stop();
remaining = convertTime();
}
}
}
//code that is invoked by swing timer for every second passed
public class Timeclass implements ActionListener {
public void actionPerformed(ActionEvent e) {
remaining = convertTime();
long current = System.currentTimeMillis();
long elapsed = current - initial;
remaining -= elapsed;
initial = current;
format = NumberFormat.getNumberInstance();
format.setMinimumIntegerDigits(2);
if (remaining < 0) remaining = (long)0;
int minutes = (int)(remaining/60000);
int seconds = (int)((remaining%60000)/1000);
jltime.setText(format.format(minutes) + ":" + format.format(seconds));
if (remaining == 0)
{
jltime.setText("Stop");
timer.stop();
}
}
}
//get the number of minutes chosen by the user and activate convertTime method
public void itemStateChanged(ItemEvent ie) {
ttime = (String)jcb.getSelectedItem();
convertTime();
}
//first need to convert no. of minutes from string to long.
//then need to convert that to milliseconds.
public long convertTime() {
ttime2 = Long.parseLong(ttime);
long converted = (ttime2*60000)+1000;
return converted;
}
}
</code></pre>
| 1 | 1,835 |
Output relational data in Yii2
|
<p>I trying to output related data in Yii2. My output code looks like this(like i do that in Yii 1):</p>
<pre><code>foreach ($model->comments as $key => $comment) {
echo $comment->title;
}
</code></pre>
<p>But i get the error <code>tying to get property on a non-object</code>, var_dump of <code>$model->comments</code> show the array, what look like:</p>
<pre><code> array (size=1)
0 =>
object(common\models\Comment)[74]
private '_attributes' (yii\db\BaseActiveRecord) =>
array (size=5)
'id' => int 1
'title' => string 'testComment' (length=11)
'body' => string 'body' (length=4)
'post_id' => int 1
'user_id' => int 1
private '_oldAttributes' (yii\db\BaseActiveRecord) =>
array (size=5)
'id' => int 1
'title' => string 'testComment' (length=11)
'body' => string 'body' (length=4)
'post_id' => int 1
'user_id' => int 1
private '_related' (yii\db\BaseActiveRecord) =>
array (size=0)
empty
</code></pre>
<p>var_dump of <code>$model->getComments()</code> return the ActiveQuery object:</p>
<pre><code>object(yii\db\ActiveQuery)[67]
public 'sql' => null
public 'on' => null
public 'joinWith' => null
public 'select' => null
public 'selectOption' => null
public 'distinct' => null
public 'from' => null
public 'groupBy' => null
public 'join' => null
public 'having' => null
public 'union' => null
public 'params' =>
array (size=0)
empty
private '_events' (yii\base\Component) =>
array (size=0)
empty
private '_behaviors' (yii\base\Component) =>
array (size=0)
empty
public 'where' => null
public 'limit' => null
public 'offset' => null
public 'orderBy' => null
public 'indexBy' => null
public 'modelClass' => string 'common\models\Comment' (length=21)
public 'with' => null
public 'asArray' => null
public 'multiple' => boolean true
public 'primaryModel' =>
object(common\models\Post)[65]
private '_attributes' (yii\db\BaseActiveRecord) =>
array (size=5)
'id' => int 1
'header' => string 'ds' (length=2)
'content' => string 'dsad' (length=4)
'created' => string '0000-00-00' (length=10)
'status' => int 1
private '_oldAttributes' (yii\db\BaseActiveRecord) =>
array (size=5)
'id' => int 1
'header' => string 'ds' (length=2)
'content' => string 'dsad' (length=4)
'created' => string '0000-00-00' (length=10)
'status' => int 1
private '_related' (yii\db\BaseActiveRecord) =>
array (size=0)
empty
private '_errors' (yii\base\Model) => null
private '_validators' (yii\base\Model) => null
private '_scenario' (yii\base\Model) => string 'default' (length=7)
private '_events' (yii\base\Component) =>
array (size=0)
empty
private '_behaviors' (yii\base\Component) =>
array (size=0)
empty
public 'link' =>
array (size=1)
'post_id' => string 'id' (length=2)
public 'via' => null
public 'inverseOf' => null
</code></pre>
<p>I see my data in both cases, but how i can recieve them from this constructs? (and what way $model->getComments() or $model->comments is wright?)</p>
| 1 | 1,649 |
React-Bootstrap - Pagination not showing
|
<p>I'm using the react-bootstrap to paginate the result. It is rendering the div #content, but it is not showing nothing more. It is showing only a empty div with width, height and background color as I configured on the CSS file. I would like to display the pagination showing one house per page. The result of data from JSON is catched successfully. How can I solve the pagination issue? Thanks! </p>
<pre><code>import React, { Component } from 'react'
import axios from 'axios'
import { Pagination } from 'react-bootstrap'
const URL_HOUSES = 'http://localhost:3001/houses';
class Casas extends Component {
constructor(props) {
super(props)
this.state = {
houses: []
}
this.handlePageChange = this.handlePageChange.bind(this)
}
getNumPages(currentPage) {
{ this.handlePageChange }
this.setState({
per_page: this.props.results ,
currentPage: currentPage + 1 ,
previousPage: currentPage - 1
});
}
handlePageChange(page, evt) {
const currentPage = this.state.currentPage || 1;
const numPages = this.getNumPages();
const pageLinks = [];
if (currentPage > 1) {
if (currentPage > 2) {
pageLinks.push(1);
pageLinks.push(' ');
}
pageLinks.push(currentPage - 1);
pageLinks.push(' ');
}
for (let i = 1; i <= numPages; i++) {
const page = i;
pageLinks.push(page);
}
if (currentPage < numPages) {
pageLinks.push(' ');
pageLinks.push(currentPage + 1);
if (currentPage < numPages - 1) {
pageLinks.push(' ');
pageLinks.push(numPages);
}
}
this.setState({ currentPage: currentPage + 1 } );
this.setState({ previousPage: currentPage - 1 } );
}
componentDidMount() {
axios.get(URL_HOUSES)
.then(res => {
this.setState({ houses: res.data })
})
}
render() {
const per_page = "1";
const paginationData = this.state.houses
let numPages = Math.ceil(paginationData.length / per_page);
if (paginationData.length % per_page > 0) {
numPages++;
}
return (
<div>
{this.state.houses.map(item =>
<div>
<h2>{item.name}</h2>
<p>{item.description}</p>
<ul>
{
item.photos.map(photo => <li>{photo}</li>)
}
</ul>
</div>
)}
<Pagination id="content" className="users-pagination pull-right"
bsSize="medium"
first last next prev boundaryLinks items={numPages}
activePage={ this.state.currentPage } onSelect={ this.handlePageChange
} />
</div>
)
}
}
export default Houses;
</code></pre>
| 1 | 1,126 |
Applying AutoNumeric.js to an entire class
|
<p>I would love if someone could help me with what i thought would be a simple application of AutoNumeric.js. I have the below code:</p>
<p>Fiddle link: <a href="https://jsfiddle.net/yu1s9nrv/8/" rel="nofollow noreferrer">https://jsfiddle.net/yu1s9nrv/8/</a> </p>
<pre><code><table id="shareInput" class="table_standard">
<tr>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Growth</th>
<th>Yield</th>
</tr>
<tr>
<td><input type="text" class="input_field_large" id="shareName" value=""></td>
<td><input type="text" class="input_field_medium_num" id="shareQty" value=""></td>
<td><input type="text" class="input_field_medium_dollar" id="sharePrice" value=""></td>
<td><input type="text" class="input_field_medium_pct" id="shareGrowth" value=""></td>
<td><input type="text" class="input_field_medium_pct" id="shareYield" value=""></td>
</tr>
<tr>
<td><input type="text" class="input_field_large" id="shareName" value=""></td>
<td><input type="text" class="input_field_medium_num" id="shareQty" value=""></td>
<td><input type="text" class="input_field_medium_dollar" id="sharePrice" value=""></td>
<td><input type="text" class="input_field_medium_pct" id="shareGrowth" value=""></td>
<td><input type="text" class="input_field_medium_pct" id="shareYield" value=""></td>
</tr>
</table>
<script>
window.onload = function() {
const anElement = new AutoNumeric('.input_field_medium_pct', 0, {
suffixText: "%"
});
};
</script>
</code></pre>
<p>The output I expect is for <em>all</em> the fields with the class input_field_medium_pct to have the desired AutoNumeric formatting, however it only formats the first field with that class. The documentation reads:</p>
<blockquote>
<p>// The AutoNumeric constructor class can also accept a string as a css
selector. Under the hood this use <code>QuerySelector</code> and limit itself to
only the first element it finds. anElement = new
AutoNumeric('.myCssClass > input'); anElement = new
AutoNumeric('.myCssClass > input', { options });</p>
</blockquote>
<p>Taken from: <a href="https://github.com/autoNumeric/autoNumeric#initialize-one-autonumeric-object" rel="nofollow noreferrer">https://github.com/autoNumeric/autoNumeric#initialize-one-autonumeric-object</a></p>
<p>I'm new to JS the and find the AutoNumeric documentation notes to be slightly confusing, has anyone run into this issue or able to shed some light on why this might be the case? Thanks in advance.</p>
| 1 | 1,152 |
Convert Microsoft Word equations to Latex
|
<p>I have a docx file containing a few equations in different pages. With Python and lxml, I was successful in extracting the content. I now need to convert the equations in Word to Latex. Some of the equations are shown as:</p>
<pre><code>- eq \\f (sinx,\\r(1 - sin 2 x))
</code></pre>
<p>Is there any Python library of any tool that I can use to convert the equation to Latex format?</p>
<p>Here is a snippet of the XML file which I obtained from docxfile/word/document.xml:</p>
<pre><code><w:p w:rsidR="00677018" w:rsidRPr="007D05E5" w:rsidRDefault="00677018" w:rsidP="00677018">
<w:pPr>
<w:pStyle w:val="w" />
<w:jc w:val="both" /></w:pPr>
<w:r w:rsidRPr="007D05E5">
<w:tab/>
<w:t>a.</w:t>
</w:r>
<w:r w:rsidRPr="007D05E5">
<w:tab/></w:r>
<w:r w:rsidR="00453EF1" w:rsidRPr="007D05E5">
<w:fldChar w:fldCharType="begin" /></w:r>
<w:r w:rsidRPr="007D05E5">
<w:instrText xml:space="preserve">eq \b\bc\[(\a\co2\hs4(7,-3,-1,2))</w:instrText>
</w:r>
<w:r w:rsidR="00453EF1" w:rsidRPr="007D05E5">
<w:fldChar w:fldCharType="end" /></w:r>
<w:r w:rsidRPr="007D05E5">
<w:tab/>
<w:t>b.</w:t>
</w:r>
<w:r w:rsidRPr="007D05E5">
<w:tab/></w:r>
<w:r w:rsidR="00453EF1" w:rsidRPr="007D05E5">
<w:fldChar w:fldCharType="begin" /></w:r>
<w:r w:rsidRPr="007D05E5">
<w:instrText xml:space="preserve">eq \f(5,8)</w:instrText>
</w:r>
<w:r w:rsidR="00453EF1" w:rsidRPr="007D05E5">
<w:fldChar w:fldCharType="end" /></w:r>
<w:r w:rsidR="00453EF1" w:rsidRPr="007D05E5">
<w:fldChar w:fldCharType="begin" /></w:r>
<w:r w:rsidRPr="007D05E5">
<w:instrText xml:space="preserve">eq \b\bc\[(\a\co2\hs4(7,-3,-1,2))</w:instrText>
</w:r>
<w:r w:rsidR="00453EF1" w:rsidRPr="007D05E5">
<w:fldChar w:fldCharType="end" /></w:r>
</w:p>
</code></pre>
| 1 | 1,626 |
Need a fixed navbar and landing page VH that incorporates navbar height
|
<p>I am working on my first portfolio and running into some trouble doing two things. </p>
<ol>
<li><p>Creating a fixed navbar. When I use position: fixed; it clears my float on the right "Contact Me", and everything collapses. I need this to stay spaced how it is in my example. Searched for quite some hours and I cannot find a fix as of yet, although I am a novice so I am sure that plays into this some as well.</p></li>
<li><p>For my landing page photo, I am trying to make a responsive design that allows it to resize to 100% of the available page size. I had implemented this with height: 100vh; however quickly noticed that it is taking the 100vh, and implementing this after my navbar, which leaves excess below. I tried to compensate by reducing the vh to account for the navbar, but of course I realized that this would not be a good fixed as it would only work for that viewport height, and not scale accordingly.
This leaves me either needing a fix to scale the content appropriately, or allow the photo to slide under the navbar, and occupy that space as well so that it is touching the top of the page.</p></li>
</ol>
<p>Relevant HTML:</p>
<pre><code> <header>
<div class="navbar">
<ul>
<li><a href="#home" class="active">Home</a></li>
<li><a href="#aboutme">About Me</a></li>
<li><a href="#mywork">My Work</a></li>
<li style="float:right"><a href="#contact">Contact Me</a></li>
</ul>
</div>
</header>
<main>
<section class="homeLanding">
<h1>Hi, I'm Michael.</h1>
<p>A Front-End Web Dev</p>
<a href="#aboutMe" class="myBtn">Start here to learn more about me,
<br>and how I can help you</a>
</section>
</code></pre>
<p>Relevant CSS:</p>
<pre><code>body {
margin: 0;
}
/** style navbar **/
.navbar ul {
background-color: #333;
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden
}
.navbar li {
float: left;
}
.navbar li a {
display: block;
text-align: center;
text-decoration: none;
color: white;
padding: 14px 16px;
}
.navbar li a:hover:not(.active) {
background-color: #111;
}
.active {
background-color: #4CAF50;
}
/** style landing page **/
.homeLanding {
height: 100vh;
width: 100%;
margin: auto;
background: url(/**Insert Image**/);
display: flex;
background-size: cover;
background-position: center;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
top: 0;
}
.myBtn {
color: white;
text-decoration: none;
border: solid 3px white;
border-radius: 6px;
padding: 7px 7px 0px 7px;
}
p, h1 {
color: white;
}
</code></pre>
<p>Background image: <a href="http://res.cloudinary.com/dtgbwo6mf/image/upload/v1502053498/bg_b0vucn.jpg" rel="nofollow noreferrer">http://res.cloudinary.com/dtgbwo6mf/image/upload/v1502053498/bg_b0vucn.jpg</a></p>
| 1 | 1,252 |
PyQT5 and Filtering a Table using multiple columns
|
<p>I am trying to make a <code>PyQt5</code> GUI to show a Pandas dataframe in the form of a table and provide column filtering options, similar to the Microsoft Excel filters. So far I managed to adopt a similar <a href="https://stackoverflow.com/questions/14068823/how-to-create-filters-for-qtableview-in-pyqt">SO answer</a>. Here is the picture of my table in the GUI:</p>
<p><a href="https://i.stack.imgur.com/hazQj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hazQj.png" alt="enter image description here"></a></p>
<p>As shown in the figure above, there are two ways to filter columns: the Regex Filter and clicking on each column. There is however a problem I need help to address: the currently applied filters (either regex filter or column click) disappear when I filter a second column. I want the second filter as <code>AND</code>, i.e. a filter that satisfies column 1 <code>AND</code> column 2.</p>
<p>Here is my code:</p>
<pre><code>#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
import pandas as pd
class PandasModel(QtCore.QAbstractTableModel):
def __init__(self, df=pd.DataFrame(), parent=None):
QtCore.QAbstractTableModel.__init__(self, parent=parent)
self._df = df.copy()
def toDataFrame(self):
return self._df.copy()
def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
if role != QtCore.Qt.DisplayRole:
return QtCore.QVariant()
if orientation == QtCore.Qt.Horizontal:
try:
return self._df.columns.tolist()[section]
except (IndexError, ):
return QtCore.QVariant()
elif orientation == QtCore.Qt.Vertical:
try:
# return self.df.index.tolist()
return self._df.index.tolist()[section]
except (IndexError, ):
return QtCore.QVariant()
def data(self, index, role=QtCore.Qt.DisplayRole):
if role != QtCore.Qt.DisplayRole:
return QtCore.QVariant()
if not index.isValid():
return QtCore.QVariant()
return QtCore.QVariant(str(self._df.iloc[index.row(), index.column()]))
def setData(self, index, value, role):
row = self._df.index[index.row()]
col = self._df.columns[index.column()]
if hasattr(value, 'toPyObject'):
# PyQt4 gets a QVariant
value = value.toPyObject()
else:
# PySide gets an unicode
dtype = self._df[col].dtype
if dtype != object:
value = None if value == '' else dtype.type(value)
self._df.set_value(row, col, value)
return True
def rowCount(self, parent=QtCore.QModelIndex()):
return len(self._df.index)
def columnCount(self, parent=QtCore.QModelIndex()):
return len(self._df.columns)
def sort(self, column, order):
colname = self._df.columns.tolist()[column]
self.layoutAboutToBeChanged.emit()
self._df.sort_values(colname, ascending= order == QtCore.Qt.AscendingOrder, inplace=True)
self._df.reset_index(inplace=True, drop=True)
self.layoutChanged.emit()
class myWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(myWindow, self).__init__(parent)
self.centralwidget = QtWidgets.QWidget(self)
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.view = QtWidgets.QTableView(self.centralwidget)
self.comboBox = QtWidgets.QComboBox(self.centralwidget)
self.label = QtWidgets.QLabel(self.centralwidget)
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.addWidget(self.lineEdit, 0, 1, 1, 1)
self.gridLayout.addWidget(self.view, 1, 0, 1, 3)
self.gridLayout.addWidget(self.comboBox, 0, 2, 1, 1)
self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
self.setCentralWidget(self.centralwidget)
self.label.setText("Regex Filter")
self.load_sites()
self.comboBox.addItems(["{0}".format(col) for col in self.model._df.columns])
self.lineEdit.textChanged.connect(self.on_lineEdit_textChanged)
self.comboBox.currentIndexChanged.connect(self.on_comboBox_currentIndexChanged)
self.horizontalHeader = self.view.horizontalHeader()
self.horizontalHeader.sectionClicked.connect(self.on_view_horizontalHeader_sectionClicked)
def load_sites(self):
df = pd.DataFrame({'site_codes': ['01', '02', '03', '04'],
'status': ['open', 'open', 'open', 'closed'],
'Location': ['east', 'north', 'south', 'east'],
'data_quality': ['poor', 'moderate', 'high', 'high']})
self.model = PandasModel(df)
self.proxy = QtCore.QSortFilterProxyModel(self)
self.proxy.setSourceModel(self.model)
self.view.setModel(self.proxy)
self.view.resizeColumnsToContents()
@QtCore.pyqtSlot(int)
def on_view_horizontalHeader_sectionClicked(self, logicalIndex):
self.logicalIndex = logicalIndex
self.menuValues = QtWidgets.QMenu(self)
self.signalMapper = QtCore.QSignalMapper(self)
self.comboBox.blockSignals(True)
self.comboBox.setCurrentIndex(self.logicalIndex)
self.comboBox.blockSignals(True)
valuesUnique = self.model._df.iloc[:, self.logicalIndex].unique()
actionAll = QtWidgets.QAction("All", self)
actionAll.triggered.connect(self.on_actionAll_triggered)
self.menuValues.addAction(actionAll)
self.menuValues.addSeparator()
for actionNumber, actionName in enumerate(sorted(list(set(valuesUnique)))):
action = QtWidgets.QAction(actionName, self)
self.signalMapper.setMapping(action, actionNumber)
action.triggered.connect(self.signalMapper.map)
self.menuValues.addAction(action)
self.signalMapper.mapped.connect(self.on_signalMapper_mapped)
headerPos = self.view.mapToGlobal(self.horizontalHeader.pos())
posY = headerPos.y() + self.horizontalHeader.height()
posX = headerPos.x() + self.horizontalHeader.sectionPosition(self.logicalIndex)
self.menuValues.exec_(QtCore.QPoint(posX, posY))
@QtCore.pyqtSlot()
def on_actionAll_triggered(self):
filterColumn = self.logicalIndex
filterString = QtCore.QRegExp( "",
QtCore.Qt.CaseInsensitive,
QtCore.QRegExp.RegExp
)
self.proxy.setFilterRegExp(filterString)
self.proxy.setFilterKeyColumn(filterColumn)
@QtCore.pyqtSlot(int)
def on_signalMapper_mapped(self, i):
stringAction = self.signalMapper.mapping(i).text()
filterColumn = self.logicalIndex
filterString = QtCore.QRegExp( stringAction,
QtCore.Qt.CaseSensitive,
QtCore.QRegExp.FixedString
)
self.proxy.setFilterRegExp(filterString)
self.proxy.setFilterKeyColumn(filterColumn)
@QtCore.pyqtSlot(str)
def on_lineEdit_textChanged(self, text):
search = QtCore.QRegExp( text,
QtCore.Qt.CaseInsensitive,
QtCore.QRegExp.RegExp
)
self.proxy.setFilterRegExp(search)
@QtCore.pyqtSlot(int)
def on_comboBox_currentIndexChanged(self, index):
self.proxy.setFilterKeyColumn(index)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
main = myWindow()
main.show()
main.resize(800, 600)
sys.exit(app.exec_())
</code></pre>
| 1 | 3,641 |
http.client.RemoteDisconnected: Remote end closed connection without response error using driver.quit() of Selenium Python
|
<p>I'm using:</p>
<ul>
<li>Python 3.8</li>
<li>Selenium 3.141.0</li>
<li>Windows 10 (behind a proxy)</li>
<li>Chrome:84.0.4147.105</li>
<li>Chromedriver:84.0.4147.30</li>
<li>Mac 10.15.6 (does not has a proxy)</li>
</ul>
<p>Here is my code:</p>
<pre><code>from selenium import webdriver
driver = webdriver.Chrome("D:/webdriver/chromedriver.exe")
driver.get("https://github.com")
driver.quit()
</code></pre>
<p>When executing <code>driver.quit()</code>, the exception raise:</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/taiping/Desktop/data_test/selenium_test.py", line 5, in <module>
driver.quit()
File "D:\python3.8\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 158, in quit
self.service.stop()
File "D:\python3.8\lib\site-packages\selenium\webdriver\common\service.py", line 151, in stop
self.send_remote_shutdown_command()
File "D:\python3.8\lib\site-packages\selenium\webdriver\common\service.py", line 127, in send_remote_shutdown_command
url_request.urlopen("%s/shutdown" % self.service_url)
File "D:\python3.8\lib\urllib\request.py", line 222, in urlopen
return opener.open(url, data, timeout)
File "D:\python3.8\lib\urllib\request.py", line 525, in open
response = self._open(req, data)
File "D:\python3.8\lib\urllib\request.py", line 542, in _open
result = self._call_chain(self.handle_open, protocol, protocol +
File "D:\python3.8\lib\urllib\request.py", line 502, in _call_chain
result = func(*args)
File "D:\python3.8\lib\urllib\request.py", line 1379, in http_open
return self.do_open(http.client.HTTPConnection, req)
File "D:\python3.8\lib\urllib\request.py", line 1354, in do_open
r = h.getresponse()
File "D:\python3.8\lib\http\client.py", line 1332, in getresponse
response.begin()
File "D:\python3.8\lib\http\client.py", line 303, in begin
version, status, reason = self._read_status()
File "D:\python3.8\lib\http\client.py", line 272, in _read_status
raise RemoteDisconnected("Remote end closed connection without"
http.client.RemoteDisconnected: Remote end closed connection without response
</code></pre>
<p>But this code has no error on my Macbook. What's the problem?</p>
<p>Updated: 2020-08-05</p>
<p>I open the debugger and found that every <code>HTTPConnection</code> object have been set the system wide http proxy. But I did not set any options explicitly in my code. And the <code>driver.quit</code> method will send http://localhost:59717/shutdown to chrome to perform quit. So I guess the shutdown url is actually sent to the proxy server, not the local browser.</p>
<p>And I try to use fiddler to check the request informations. There is another problem that I can not decode the https requests because of some certificates configs. So I change the argument of <code>driver.get()</code> to an internal web url of my company. The result is : If I close fiddler, <code>RemoteDisconnected</code> error raise again. And if I open fiddler, all works.</p>
<p>What happened? I know fiddler set the proxy to 127.0.0.1:8888, so I think there could be something wrong with the proxy settings. But I can not fix it. I guess the chrome use the system proxy so the github home page could open correctly, but when send shutdown url to chrome, the request object should not use the system proxy, but it does.</p>
<p>Am I right? And how to fix this problem?</p>
| 1 | 1,290 |
Unity Container Registration with Names are not working while without name works fine
|
<p>I know this sounds stupid. I'll provide some pieces of code and will try to explain as much.</p>
<h3>Implementation #1 - Without name</h3>
<pre><code> Container = new UnityContainer();
Container.RegisterType<IFirstInterface, FirstImplementation>();
Container.RegisterType<IDifferentAssemblyInterface, DifferentAssemblyImplementation>();
Container.RegisterType<ISameAssemblyInterface, SameAssemblyImplementation>();
</code></pre>
<h3>Implementation #2 - With name</h3>
<pre><code>const string configurationName = "simpleOption";
Container = new UnityContainer();
Container.RegisterType<IFirstInterface, FirstImplementation>(configurationName);
Container.RegisterType<IDifferentAssemblyInterface, DifferentAssemblyImplementation>(configurationName);
Container.RegisterType<ISameAssemblyInterface, SameAssemblyImplementation>(configurationName);
</code></pre>
<h3>Observations</h3>
<p>Implementation #1 works just fine. I used the immediate window and everything resolves.</p>
<p>With implementation #2 I used immediate window and everything from the same assembly resolves</p>
<p>Implementation #2 immediate window is not able to resolve exactly the IDifferentAssemblyInterface is not able to resolve</p>
<p>I opened up the Registrations constructor and all the dependencies are </p>
<h3>Questions</h3>
<ol>
<li>Am I using named registration correctly?</li>
<li>Is passing the name as simple as that? Just pass a string while registering and the same string during resolve should work.</li>
<li>How do I debug/resolve this?</li>
</ol>
<h3>Sample Code</h3>
<p>Program.cs</p>
<pre><code> static IUnityContainer Container;
static void Main(string[] args)
{
// Arrange
Container = new UnityContainer();
Container.AddExtension(new Diagnostic());
Container.RegisterType<IMessageReader, ConsoleMessageReader>("Local");
Container.RegisterType<IMessageWriter, ConsoleMessageWriter>("Local");
Container.RegisterType<Startup, Startup>("Local");
Startup startup = Container.Resolve<Startup>("Local");
// Act
startup.Run();
}
</code></pre>
<p>Startup.cs</p>
<pre><code> public class Startup
{
IMessageReader _reader;
IMessageWriter _writer;
public Startup(IMessageReader reader, IMessageWriter writer)
{
_reader = reader;
_writer = writer;
}
public void Run()
{
_writer.WriteMessage(_reader.ReadMessage());
}
}
</code></pre>
<p>Message ReaderWriter</p>
<pre><code>public interface IMessageReader
{
string ReadMessage();
}
public class ConsoleMessageReader : IMessageReader
{
public string ReadMessage()
{
return "Hello, DI";
}
}
public interface IMessageWriter
{
void WriteMessage(string message);
}
public class ConsoleMessageWriter : IMessageWriter
{
public void WriteMessage(string message)
{
Console.WriteLine("{0}", message);
}
}
</code></pre>
<h3>Error Message</h3>
<pre><code>Unhandled Exception: Unity.ResolutionFailedException: The current type, HelloDIApp.ConsoleClient.IMessageReader, is an interface and cannot be constructed. Are you missing a type mapping?
_____________________________________________________
Exception occurred while:
·resolving type: 'IMessageReader'
for parameter: 'reader'
on constructor: Startup(IMessageReader reader, IMessageWriter writer)
resolving type: 'Startup' registered with name: 'Local'
---> System.InvalidOperationException: The current type, HelloDIApp.ConsoleClient.IMessageReader, is an interface and cannot be constructed. Are you missing a type mapping? ---> Unity.Exceptions.InvalidRegistrationException: Exception of type 'Unity.Exceptions.InvalidRegistrationException' was thrown.
--- End of inner exception stack trace ---
at Unity.Processors.ConstructorDiagnostic.<>c.<GetResolver>b__11_0(BuilderContext& c)
at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c)
at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c)
at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c)
at Unity.UnityContainer.<>c__DisplayClass96_0.<OptimizingFactory>b__0(BuilderContext& c)
at Unity.Strategies.BuildPlanStrategy.PreBuildUp(BuilderContext& context)
at Unity.UnityContainer.ContextValidatingPlan(BuilderStrategy[] chain, BuilderContext& context)
at Unity.Builder.BuilderContext.Resolve(Type type, String name, InternalRegistration registration)
at Unity.Builder.BuilderContext.Resolve(Type type, String name)
at Unity.Builder.BuilderContext.Resolve(ParameterInfo parameter, Object value)
at Unity.Processors.ParametersProcessor`1.<>c__DisplayClass1_0.<CreateDiagnosticParameterResolvers>b__0(BuilderContext& context)
at Unity.Processors.ConstructorDiagnostic.<>c__DisplayClass12_0.<GetResolverDelegate>b__0(BuilderContext& c)
at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c)
at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c)
at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c)
at Unity.UnityContainer.<>c__DisplayClass96_0.<OptimizingFactory>b__0(BuilderContext& c)
at Unity.Strategies.BuildPlanStrategy.PreBuildUp(BuilderContext& context)
at Unity.UnityContainer.ExecuteValidatingPlan(BuilderContext& context)
--- End of inner exception stack trace ---
at Unity.UnityContainer.ExecuteValidatingPlan(BuilderContext& context)
at Unity.UnityContainer.Unity.IUnityContainer.Resolve(Type type, String name, ResolverOverride[] overrides)
at Unity.UnityContainerExtensions.Resolve[T](IUnityContainer container, String name, ResolverOverride[] overrides)
at HelloDIApp.ConsoleClient.Program.Main(String[] args) in C:\Code\HelloDI\HelloDIApp\HelloDIApp.ConsoleClient\Program.cs:line 18
</code></pre>
<h3>Working Code</h3>
<p>When I don't use names it works just fine.</p>
<pre><code>static void Main(string[] args)
{
// Arrange
Container = new UnityContainer();
Container.AddExtension(new Diagnostic());
Container.RegisterType<IMessageReader, ConsoleMessageReader>();
Container.RegisterType<IMessageWriter, ConsoleMessageWriter>();
Container.RegisterType<Startup, Startup>();
Startup startup = Container.Resolve<Startup>();
// Act
startup.Run();
}
</code></pre>
| 1 | 2,314 |
PayPal REST Api error: response 401 PPConnectionException
|
<p>I'm using the PHP PayPal REST API sandbox and getting errors when I do my <code>$payment->create( $apiContext );</code></p>
<p>My Error log reads as:</p>
<pre><code> PHP Fatal error: Uncaught exception 'PayPal\\Exception\\PPConnectionException' with message
'Got Http response code 401 when accessing https://api.paypal.com/v1/oauth2/token.
Retried 0 times.' in /usr/local/web/servers/domain/guts/paypal_api/vendor/paypal/sdk-core-php/lib/PayPal/Core/PPHttpConnection.php:99\nStack trace:\n
#0 /usr/local/web/servers/domain/guts/paypal_api/lib/PayPal/Auth/OAuthTokenCredential.php(96):
PayPal\\Core\\PPHttpConnection->execute('grant_type=clie...')\n
#1 /usr/local/web/servers/domain/guts/paypal_api/lib/PayPal/Auth/OAuthTokenCredential.php(76):
PayPal\\Auth\\OAuthTokenCredential->_generateAccessToken(Array)\n
#2 /usr/local/web/servers/domain/guts/paypal_api/lib/PayPal/Rest/RestHandler.php(56): PayPal\\Auth\\OAuthTokenCredential->getAccessToken(Array)\n
#3 /usr/local/web/servers/domain/guts/paypal_api/vendor/paypal/sdk-core-php/lib/PayPal/Transport/PPRestCall.php(41):
PayPal\\Rest\\RestHandler->handle(Object(PayPal\\Core\\PPHttpConfig), '{"intent":"sale...', Array)\n
#4 /usr/local/web/servers/domain/guts/paypal_api/lib/PayPal/A in
/usr/local/web/servers/domain/guts/paypal_api/vendor/paypal/sdk-core-php/lib/PayPal/Core/PPHttpConnection.php on line 99,
referer: http://domain.com/products/basket/verify/
</code></pre>
<p>my PayPal.log file shows:</p>
<pre><code>PayPal\Core\PPHttpConnection: Connecting to https://api.paypal.com/v1/oauth2/token
PayPal\Core\PPHttpConnection: Payload grant_type=client_credentials
PayPal\Core\PPHttpConnection: Adding header User-Agent: PayPalSDK/rest-sdk-php 0.6.0 (lang=PHP;v=5.3.3;bit=64;os=Linux_2.6.18-348.6.1.el5;machine=x86_64;openssl=0.9.8e-fips-rhel5;curl=7.15.5)
PayPal\Core\PPHttpConnection: Adding header Authorization: Basic QVpteVVCQ3VfdDhlb3QxcGx0UksyUG56Y3NhcXpOeXNIMlNDLXBDbTlUNGVGNDE3OFd1cFBFRmhkTVpnOkVGZ3g4UkNCZUppSkw3NW1JV1FDRFROTVVsanFOLW1fdlFuM3owMzZOZ3EwTUp3RVFwRkNlV0Z0dWhaag==
PayPal\Core\PPHttpConnection: Adding header Accept: */*
</code></pre>
<p>I've tried test cc numbers, cc numbers set up on paypal's sandbox site. I've tried using the credentials in the demo app provided in rest-api-skd-php-master (the demo works btw).</p>
<p>I can show you my code though it pretty precisely emulates the test case.</p>
<p>The only thing I can think of is that the processing files are buried below www access levels?</p>
<p>If you can clean any info from the error logs I'm all ears. If there's more info you need from me I can provide it.</p>
| 1 | 1,070 |
How to upload file using Cakephp 3.0?
|
<p>I am trying to create a file upload on cakephp, I haven't been able to find any decent tutorials for cakephp 3.0 that go in detail, and I don't understand how to install plugins. </p>
<p>I have this in my add section</p>
<pre><code>echo $this->Form->create('filename', array('action' => 'upload', 'type' => 'file'));
echo $this->Form->file('filename');
</code></pre>
<p>I haven't added anything in the controller yet</p>
<pre><code>/**
* Index method
*
* @return void
*/
public function index()
{
$this->paginate = [
'contain' => ['Courses']
];
$this->set('contents', $this->paginate($this->Contents));
$this->set('_serialize', ['contents']);
}
/**
* View method
*
* @param string|null $id Content id.
* @return void
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function view($id = null)
{
$content = $this->Contents->get($id, [
'contain' => ['Courses']
]);
$this->set('content', $content);
$this->set('_serialize', ['content']);
}
/**
* Add method
*
* @return void Redirects on successful add, renders view otherwise.
*/
public function add()
{
$content = $this->Contents->newEntity();
if ($this->request->is('post')) {
$content = $this->Contents->patchEntity($content, $this->request->data);
if ($this->Contents->save($content)) {
$this->Flash->success('The content has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The content could not be saved. Please, try again.');
}
}
$courses = $this->Contents->Courses->find('list', ['limit' => 200]);
$this->set(compact('content', 'courses'));
$this->set('_serialize', ['content']);
}
/**
* Edit method
*
* @param string|null $id Content id.
* @return void Redirects on successful edit, renders view otherwise.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function edit($id = null)
{
$content = $this->Contents->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$content = $this->Contents->patchEntity($content, $this->request->data);
if ($this->Contents->save($content)) {
$this->Flash->success('The content has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The content could not be saved. Please, try again.');
}
}
$courses = $this->Contents->Courses->find('list', ['limit' => 200]);
$this->set(compact('content', 'courses'));
$this->set('_serialize', ['content']);
}
/**
* Delete method
*
* @param string|null $id Content id.
* @return void Redirects to index.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$content = $this->Contents->get($id);
if ($this->Contents->delete($content)) {
$this->Flash->success('The content has been deleted.');
} else {
$this->Flash->error('The content could not be deleted. Please, try again.');
}
return $this->redirect(['action' => 'index']);
}
</code></pre>
<p>but after this no idea what to do.</p>
| 1 | 1,461 |
Authentication fails silently in Symfony2
|
<p>I'm having trouble getting authentication to work but it only appears to happen in very specific circumstances. Authentication is done via a third party API so I've written my own user provider class and inside that class is some code that syncs data between the API and Symfony, as part of that syncing process it determines which roles the user should have.
After doing this it sets up the relationships between the roles and user via a ManyToMany relationship.</p>
<p>The getRoles() method in my User object gets the role objects out of the database and turns it into an array of strings, the role names come from my database and all start with ROLE_.</p>
<p>If I login with an account that should have no extra roles it works fine, but if I login to an account that should have roles I just get sent back to the login screen with no error message.</p>
<p>I've checked the log and saw these entries:</p>
<pre><code>security.INFO: User "test105@example.com" has been authenticated successfully [] []
event.DEBUG: Notified event "security.interactive_login" to listener "Pogo\MyBundle\Listener\LoginListener::onSecurityInteractivelogin". [] []
event.DEBUG: Listener "Symfony\Component\Security\Http\Firewall::onKernelRequest" stopped propagation of the event "kernel.request". [] []
event.DEBUG: Listener "Symfony\Bundle\FrameworkBundle\EventListener\RouterListener" was not called for event "kernel.request". [] []
event.DEBUG: Listener "Symfony\Bundle\AsseticBundle\EventListener\RequestListener" was not called for event "kernel.request". [] []
event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\Security\Http\Firewall\ContextListener::onKernelResponse". [] []
security.DEBUG: Write SecurityContext in the session [] []
event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\ResponseListener::onKernelResponse". [] []
event.DEBUG: Notified event "kernel.response" to listener "Symfony\Bundle\SecurityBundle\EventListener\ResponseListener::onKernelResponse". [] []
event.DEBUG: Notified event "kernel.response" to listener "Symfony\Bridge\Monolog\Handler\FirePHPHandler::onKernelResponse". [] []
event.DEBUG: Notified event "kernel.response" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\CacheListener::onKernelResponse". [] []
event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelResponse". [] []
event.DEBUG: Notified event "kernel.response" to listener "Symfony\Bundle\WebProfilerBundle\EventListener\WebDebugToolbarListener::onKernelResponse". [] []
event.DEBUG: Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\RouterListener::onEarlyKernelRequest". [] []
event.DEBUG: Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\SessionListener::onKernelRequest". [] []
event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\Security\Http\Firewall::onKernelRequest". [] []
security.INFO: Populated SecurityContext with an anonymous Token [] []
event.DEBUG: Notified event "kernel.exception" to listener "Symfony\Component\Security\Http\Firewall\ExceptionListener::onKernelException". [] []
security.DEBUG: Access denied (user is not fully authenticated); redirecting to authentication entry point [] []
security.DEBUG: Calling Authentication entry point [] []
</code></pre>
<p>I don't understand how it can be authenticated at top, then as soon as it checks the firewall it finds itself with an anonymous token which is why it presumably sends me back to the login screen.</p>
<p>My firewall / access_control settings are:</p>
<pre><code>firewalls:
public:
pattern: /.*
anonymous: true
tessitura_login:
login_path: /account/login
check_path: /secure/login_check
logout:
path: /secure/logout
target: /
access_control:
- { path: ^/secure/.*, role: ROLE_USER }
- { path: ^/admin.*, role: ROLE_ADMIN }
- { path: ^/account/login/?, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: /.*, role: IS_AUTHENTICATED_ANONYMOUSLY }
</code></pre>
<p>Any help with this would be massively appreciated, I've spent a few hours on this now and am completely stumped.</p>
| 1 | 1,262 |
Accepting certificates in Java
|
<p>I'm having problems interacting with an HTTPS site via Java. My program uses one URL with an untrusted certificate each time the program runs. This program has to run on more than one system. Currently, I have the following:</p>
<pre><code>public class A{
HostnameVerifier hv = new HostnameVerifier(){
public boolean verify(String urlHostName, SSLSession session){
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new miTM();
trustAllCerts[0] = tm;
javax.net.ssl.SSLContext sc = null;
try {
sc = javax.net.ssl.SSLContext.getInstance("SSL");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try {
sc.init(null, trustAllCerts, null);
} catch (KeyManagementException e) {
e.printStackTrace();
}
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
class miTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager{
public java.security.cert.X509Certificate[] getAcceptedIssuers(){
return null;
}
public boolean isServerTrusted(java.security.cert.X509Certificate[] certs){
return true;
}
public boolean isClientTrusted(java.security.cert.X509Certificate[] certs){
return true;
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException{
return;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException{
return;
}
}
</code></pre>
<p>With this code, I can perform the following just fine:</p>
<pre><code>URL url = new URL(urlString);
URLConnection cnx = url.openConnection();
cnx.connect();
InputStream ins = cnx.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(ins));
String curline;
while( (curline = in.readLine()) != null ) {
System.out.println(curline);
}
</code></pre>
<p>However, I cannot do the following:</p>
<pre><code>httpClient = new HttpClient();
PostMethod postMethod = null;
int intResult = 0;
postMethod = new PostMethod(authURL);
Enumeration emParams = authParams.propertyNames();
while (emParams.hasMoreElements()) {
String paramName = (String) emParams.nextElement();
String paramValue = authParams.getProperty(paramName);
postMethod.addParameter(paramName, paramValue);
}
intResult = httpClient.executeMethod(postMethod);
postMethod.releaseConnection();
ins.close();
</code></pre>
<p>When executeMethod(postMethod) is executed, I get an SSLHandshakeException, CertPathBuilderException, and so on.</p>
<p>What can I do to remedy this? I'm thinking of either accepting the certificate or just bypassing all certificate validation (as the program runs internally within a private network).</p>
<p>Thanks</p>
| 1 | 1,064 |
External HTTP endpoint in Azure worker role possible?
|
<p>I am trying to host an external facing WCF service on Azure within a worker role. </p>
<p>I have a solution working very nice locally, but when I try to publish it to Azure it goes into an initializing/busy/stopped loop. </p>
<p>The information I've found around the internet says different things:</p>
<p><a href="http://www.theworkflowelement.com/2011/01/worker-role-service-hosting-faq.html" rel="nofollow">http://www.theworkflowelement.com/2011/01/worker-role-service-hosting-faq.html</a> (impossible)</p>
<p><a href="http://code.msdn.microsoft.com/WCF-Azure-Worker-Role-on-b394df49" rel="nofollow">http://code.msdn.microsoft.com/WCF-Azure-Worker-Role-on-b394df49</a> (possible with hack)</p>
<p>Other sources say it's possible, but I don't have the rep to post more than two links. </p>
<p>The last one hangs on busy when I try to publish it. </p>
<p>Anyone know how to do this, or if it really is impossible? It would be very nice to host it in a worker role, so I don't have to use the svc and web.config mess that a web role entails. </p>
<p>This is the code I am using:</p>
<pre><code> [ServiceContract(Namespace = "")]
public interface IMyService
{
[OperationContract]
[WebGet]
string Echo(string s);
}
public class MyService : IMyService
{
public string Echo(string s)
{
return "hey " + s;
}
}
public class TestPasswordValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
}
}
private static void StartService()
{
var endpoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["HttpsEndpoint"];
var uri = new Uri(endpoint.Protocol + "://" + endpoint.IPEndpoint + "/myservice");
var host = new ServiceHost(typeof(MyService), uri);
host.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
host.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new TestPasswordValidator();
var mexBehavior = new ServiceMetadataBehavior();
mexBehavior.HttpsGetEnabled = true;
mexBehavior.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
host.Description.Behaviors.Add(mexBehavior);
var soapBinding = new WSHttpBinding(SecurityMode.TransportWithMessageCredential);
soapBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
host.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpsBinding(), "mex");
host.AddServiceEndpoint(typeof(IMyService), soapBinding, "Soap");
var restBinding = new WebHttpBinding(WebHttpSecurityMode.Transport);
restBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
var restEndpoint = host.AddServiceEndpoint(typeof(IMyService), restBinding, "");
restEndpoint.Behaviors.Add(new WebHttpBehavior { HelpEnabled = true, DefaultOutgoingResponseFormat = WebMessageFormat.Json, AutomaticFormatSelectionEnabled = true, DefaultBodyStyle = WebMessageBodyStyle.WrappedRequest });
host.Open();
}
public override void Run()
{
StartService();
while (true)
{
Thread.Sleep(10000);
}
}
public override bool OnStart()
{
// Set the maximum number of concurrent connections
ServicePointManager.DefaultConnectionLimit = 12;
// For information on handling configuration changes
// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
return base.OnStart();
}
</code></pre>
| 1 | 1,365 |
Installation of npm fails with npm WARN deprecated
|
<p>Developing .Net 5 and Angular Primang 11 application on Windows 10 and facing difficulties with npm install. Tried many ways but not worked.
Like npm cache clean --force, uninstall and install cli and packages</p>
<p>Following is the CLI versions</p>
<pre><code> Package Version
------------------------------------------------------
@angular-devkit/architect 0.1100.5 (cli-only)
@angular-devkit/core 11.0.4
@angular-devkit/schematics 11.0.4
@schematics/angular 11.0.5 (cli-only)
@schematics/update 0.1100.5 (cli-only)
</code></pre>
<p>Following are the errors I am getting:-</p>
<pre><code> npm WARN deprecated node-uuid@1.4.8: Use uuid module instead
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated har-validator@5.1.5: this library is no longer supported
npm ERR! cb() never called!
npm ERR! This is an error with npm itself. Please report this error at:
npm ERR! <https://npm.community>
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\user_name\AppData\Roaming\npm-cache\_logs\2021-03-22T12_12_10_041Z-debug.log
</code></pre>
<p>Following is the Package.json</p>
<pre><code>{
"name": "hln",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"testci": "ng test --karma-config karma-ci.conf.js --code-coverage --watch=false",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "~10.2.0",
"@angular/cdk": "^11.0.3",
"@angular/common": "~10.2.0",
"@angular/compiler": "~10.2.0",
"@angular/core": "~10.2.0",
"@angular/forms": "~10.2.0",
"@angular/platform-browser": "~10.2.0",
"@angular/platform-browser-dynamic": "~10.2.0",
"@angular/router": "~10.2.0",
"@j2ba/primeng-styles": "^0.1.1",
"karma-tfs-reporter": "^1.0.2",
"ngx-extended-pdf-viewer": "^8.0.0-beta.3",
"oidc-client": "^1.10.1",
"primeflex": "^2.0.0",
"primeicons": "^4.1.0",
"primeng": "^11.2.0",
"rxjs": "~6.6.0",
"tslib": "^2.1.0",
"zone.js": "~0.10.2"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.1002.0",
"@angular/cli": "~10.2.0",
"@angular/compiler-cli": "~10.2.0",
"@types/jasmine": "~3.5.0",
"@types/jasminewd2": "~2.0.3",
"@types/node": "^12.19.13",
"codelyzer": "^6.0.0",
"jasmine-core": "~3.6.0",
"jasmine-spec-reporter": "~5.0.0",
"karma": "~5.0.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage-istanbul-reporter": "~3.0.2",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "^1.5.0",
"protractor": "~7.0.0",
"ts-node": "~8.3.0",
"tslint": "~6.1.0",
"typescript": "~4.0.2"
}
}
</code></pre>
<p>Please help.</p>
| 1 | 2,044 |
Dispatch multiple async actions with Redux Toolkit
|
<p>I'm building an app with Expo/React Native and using Redux via Redux Toolkit to handle the store/state of the app using slices.</p>
<p>I've been using this setup for a while without complications because my functions are simple (like user/auth, cart, category and products reducers).</p>
<p>But for this app I need to load multiple catalogs from a single endpoint. To achieve this I have created a "catalogs" slice with multiple reducers and a single action which performs the requests and dispatches the reducer depending on the name of the catalog.</p>
<pre><code>const initialState = {
catalogOne: [],
catalogTwo: [],
catalogThree: [],
catalogN: []
}
const catalogsSlice = createSlice({
name: "catalogs",
initialState,
reducers: {
catalogOneRequestSucceeded: (state,action) => {
state.catalogOne = action.payload
},
catalogTwoRequestSucceeded: (state,action) => {
state.catalogTwo = action.payload
},
// ... and so on a reducer for each catalog
}
});
</code></pre>
<p>And then I have the following action which is used to request the endpoint with the name of the catalog and dispatch the reducer:</p>
<pre><code>export const catalogRequest = (catalogName) => async (dispatch, getState) => {
const state = getState();
try {
const rsp = await axios.get(`https://catalogEndpointBase/${catalogName}`, {
headers: {
Authorization: `Bearer ${state.user.accessToken}`,
"Content-Type": "application/json",
},
});
switch (catalogName) {
case "catalogOne":
dispatch(catalogOneRequestSucceeded(rsp.data));
break;
case "catalogTwo":
dispatch(catalogTwoRequestSucceeded(rsp.data));
break;
case "catalogThree":
dispatch(catalogThreeRequestSucceeded(rsp.data));
break;
}
return rsp.data;
} catch (e) {
throw e;
}
};
</code></pre>
<p>So my question now is: how do I dispatch this action multiple times in an "async/await" way so the catalogs are loaded one after the other? and also: am I doing it the right way or is there a better approach to this kind of multiple requests?</p>
<p>I was thinking of something like this, but I don't really know how to accomplish that:</p>
<pre><code> useEffect(() => {
const loadCatalogsAsync = async() => {
try {
await dispatch(catalogRequest("catalogOne"));
await dispatch(catalogRequest("catalogTwo"));
await dispatch(catalogRequest("catalogThree"));
// ... and so on for all my catalogs
} catch ( e ) {
console.error(e);
}
}
loadCatalogsAsync();
}, []);
}
</code></pre>
<p>The goal is to find a best-practice for kind of behavior where the app is required to fetch multiple data when the app is loaded.</p>
<p>Thanks.</p>
| 1 | 1,068 |
RSA key pairs generating using bouncy castle. Making code runnable from java program
|
<p>I am using a Java code that I found that generates a public and a private key via the bouncy castle library. My problem is implementing it into code runnable by my android device. My code does not display the RSA keys like I programmed it to and through most of my troubleshooting I am still unable to make my code do as I ask, although I get no errors. My suspicion is the way I put all of my code into a <code>try</code>/<code>catch</code> block but I am not really sure.
Edit: Lower in code</p>
<p>This is the Java class that generates the RSA public and private key. (It works)</p>
<pre><code>public class ClassMain {
public static void main(String[]args) throws Exception {
String ST = "Ebenezersawesome";
byte[] plainText = "ST".getBytes("UTF8");
// Generating RSA Key
System.out.println("\nStart generating RSA key");
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(4096);
KeyPair key = keyGen.generateKeyPair();
System.out.println("Finish generating RSA key");
//
// Creates an RSA Cipher object (specifying the algorithm, mode, and
// padding).
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
//
// Print the provider information
System.out.println("\n" + cipher.getProvider().getInfo());
System.out.println("\nStart encryption");
//
// Initializes the Cipher object.
cipher.init(Cipher.ENCRYPT_MODE, key.getPublic());
//
// Encrypt the plaintext using the public key
byte[] cipherText = cipher.doFinal(plainText);
System.out.println("Finish encryption: ");
System.out.println(new String(cipherText, "UTF8"));
System.out.println("\nStart decryption");
//
// Initializes the Cipher object.
cipher.init(Cipher.DECRYPT_MODE, key.getPrivate());
//
// Decrypt the ciphertext using the private key
byte[] newPlainText = cipher.doFinal(cipherText);
System.out.println("Finish decryption: ");
System.out.println(new String(newPlainText, "UTF8"));
}
}
</code></pre>
<p>This is my attempt at trying to display the code in an android application.
Edit: The code works but for some reason my try/catch stops and does not generate code in tv3.</p>
<pre><code> TextView tv1;
TextView tv2;
TextView tv3;
Button convert;
String publicKeyFilename = null;
String privateKeyFilename = null;
String ST = "Ebenezersawesome";
@Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d("Ebz", "Made it to onCreate");
tv1 = (TextView) findViewById(R.id.tv1);
tv2 = (TextView) findViewById(R.id.tv2);
tv3 = (TextView) findViewById(R.id.tv3);
convert = (Button) findViewById(R.id.button1);
// tv2.setText(ST);
convert.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d("Ebz", "Made it to onCreate");
try {
byte[] plainText = "ST".getBytes("UTF8");
Log.d("Ebz", "made it to Try Block");
KeyPairGenerator keyGen = KeyPairGenerator
.getInstance("RSA");
keyGen.initialize(2048);
KeyPair key = keyGen.generateKeyPair();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
tv1.setText(cipher.getProvider().getInfo().toString());
Log.d("Ebz", "Made it passed tv1");
//tv1.setText(ST);
cipher.init(Cipher.ENCRYPT_MODE, key.getPublic());
byte[] cipherText = cipher.doFinal(plainText);
tv2.setText(new String(cipherText, "UTF8").toString());
Log.d("Ebz", "Made it passed tv2");
// tv2.setText(ST);
byte[] newPlainText = cipher.doFinal(cipherText);
//tv3.setText(new String(newPlainText, "UTF8").toString());
// tv3.setText(ST);
Log.d("Ebz", "Made it passed tv3");
} catch (Exception e) {
System.out.println("error");
}
}
});
}
</code></pre>
| 1 | 1,999 |
Using Stanford CoreNLP - Java heap space
|
<p>I am trying to use the coreference module of the Stanford CoreNLP pipeline, but I end up getting an OutOfMemory error in Java. I already increased the heap size (via Run->Run Configurations->VM Arguments in Eclipse) and set them to -Xmx3g -Xms1g. I even tried -Xmx12g -Xms4g, but that didn't help either. I'm using Eclipse Juno on OS X 10.8.5 with Java 1.6 on a 64-bit machine.
Does anyone have an idea what else I could try?</p>
<p>I'm using the example code from the website (<a href="http://nlp.stanford.edu/software/corenlp.shtml" rel="noreferrer">http://nlp.stanford.edu/software/corenlp.shtml</a>):</p>
<pre><code>Properties props = new Properties();
props.put("annotators", "tokenize, ssplit, pos, lemma, ner, parse, dcoref");
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
String text = "Stanford University is located in California. It is a great university";
Annotation document = new Annotation(text);
pipeline.annotate(document);
List<CoreMap> sentences = document.get(SentencesAnnotation.class);
for(CoreMap sentence: sentences) {
for (CoreLabel token: sentence.get(TokensAnnotation.class)) {
String word = token.get(TextAnnotation.class);
String pos = token.get(PartOfSpeechAnnotation.class);
String ne = token.get(NamedEntityTagAnnotation.class);
}
Tree tree = sentence.get(TreeAnnotation.class);
SemanticGraph dependencies = sentence.get(CollapsedCCProcessedDependenciesAnnotation.class);
}
Map<Integer, CorefChain> graph = document.get(CorefChainAnnotation.class);
</code></pre>
<p>And I get the error:</p>
<pre><code>Adding annotator tokenize
Adding annotator ssplit
Adding annotator pos
Reading POS tagger model from edu/stanford/nlp/models/pos-tagger/english-left3words/english-left3words-distsim.tagger ... done [0.9 sec].
Adding annotator lemma
Adding annotator ner
Loading classifier from edu/stanford/nlp/models/ner/english.all.3class.distsim.crf.ser.gz ... done [3.1 sec].
Initializing JollyDayHoliday for sutime
Reading TokensRegex rules from edu/stanford/nlp/models/sutime/defs.sutime.txt
Reading TokensRegex rules from edu/stanford/nlp/models/sutime/english.sutime.txt
Jan 9, 2014 10:39:37 AM edu.stanford.nlp.ling.tokensregex.CoreMapExpressionExtractor appendRules
INFO: Ignoring inactive rule: temporal-composite-8:ranges
Reading TokensRegex rules from edu/stanford/nlp/models/sutime/english.holidays.sutime.txt
Adding annotator dcoref
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.lang.String.substring(String.java:1939)
at java.lang.String.subSequence(String.java:1972)
at java.util.regex.Pattern.split(Pattern.java:1002)
at java.lang.String.split(String.java:2292)
at java.lang.String.split(String.java:2334)
at edu.stanford.nlp.dcoref.Dictionaries.loadGenderNumber(Dictionaries.java:382)
at edu.stanford.nlp.dcoref.Dictionaries.<init>(Dictionaries.java:553)
at edu.stanford.nlp.dcoref.Dictionaries.<init>(Dictionaries.java:463)
at edu.stanford.nlp.dcoref.SieveCoreferenceSystem.<init>(SieveCoreferenceSystem.java:282)
at edu.stanford.nlp.pipeline.DeterministicCorefAnnotator.<init>(DeterministicCorefAnnotator.java:52)
at edu.stanford.nlp.pipeline.StanfordCoreNLP$11.create(StanfordCoreNLP.java:775)
at edu.stanford.nlp.pipeline.AnnotatorPool.get(AnnotatorPool.java:81)
at edu.stanford.nlp.pipeline.StanfordCoreNLP.construct(StanfordCoreNLP.java:260)
at edu.stanford.nlp.pipeline.StanfordCoreNLP.<init>(StanfordCoreNLP.java:127)
at edu.stanford.nlp.pipeline.StanfordCoreNLP.<init>(StanfordCoreNLP.java:123)
at extraction.BaselineApproach.main(BaselineApproach.java:88)
</code></pre>
| 1 | 1,306 |
Find peak (regions) in 2D data
|
<p>I am looking to find <strong>peak regions</strong> in 2D data (if you will, grayscale images or 2D landscapes, created through a Hough transform). By <em>peak region</em> I mean a <strong>locally maximal peak</strong>, yet <strong><em>NOT a single point</em></strong> but a part of the surrounding <strong><em>contributing region</em></strong> that goes with it. I know, this is a vague definition, but maybe the word <em>mountain</em> or the images below will give you an intuition of what I mean. </p>
<p>The peaks marked in red (1-4) are what I want, the ones in pink (5-6) examples for the "grey zone", where it would be okay if those smaller peaks are not found but also okay if they are.</p>
<p><a href="https://i.stack.imgur.com/HdXT8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HdXT8.png" alt="an optimal result in 3D"></a></p>
<p>Images contain between 1-20 peaked regions, different in height. The 2D data for above surf plot is shown below with a possible result (orange corresponds to Peak 1, green corresponds to Peak 2 a/b, ...). Single images for tests can be found in the description links:</p>
<p><em>Image left</em>: <a href="https://i.stack.imgur.com/udIuy.png" rel="noreferrer">input image</a> - - - - <em>middle:</em> (okaish) <a href="https://i.stack.imgur.com/4GYrI.png" rel="noreferrer">result</a> - - - - <em>right</em>: result overlayed over image.</p>
<p><a href="https://i.stack.imgur.com/vdOqO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vdOqO.png" alt="input, result and overlayed result"></a></p>
<p>The result above was produced using simple thresholding (MATLAB code):</p>
<pre><code>% thresh_scale = 15; % parameter: how many thresholding steps
% thresh_perc = 6; % parameter: threshold at which we clip
thresh = multithresh(H,thresh_scale);
q_image = imquantize(H, thresh);
q_image(q_image <= thresh_perc) = 0; % regions under threshold are thrown away
q_image(q_image > thresh_perc) = 1; % ... while all others are preserved
q_image = imbinarize(q_image); % binarize for further processing
B = bwareaopen(q_image, nhood_minsize); % Filter really small regions
[L, L_num] = bwlabel(B); % <- result % Label connected components
</code></pre>
<p>Some values like these (15 and 6) often work fine if there are few similar peaks, but this isn't consistent if more peaks are present or they vary a lot. I mainly have two problems, that also can't be fixed by simply adjusting the parameters:</p>
<ul>
<li>higher peaks can mask lower (but clearly distinguishable) peaks. Since the threshold is relative to the highest peak, other peaks may fall below.</li>
<li>in some cases the valley between two peaks is above the threshold, merging several peaks into one (as can be observed with Peak 2 a/b). </li>
</ul>
<p>I also don't want a huge region for a high peak, so the <em>peak region</em> should probably be defined as some percentage of the mountain. I figured instead of a global thresholding, I'd rather have a method that finds peak regions relative to their immediate environment. I've looked into mean-shift and MSER segmentation, but those seem to be suited for segmenting real images, not kind of synthetic data. </p>
<p>Somehow I imagined filling a negative of the landscape with a certain amount of water would give me the regions I'm looking for: basins that fill and spread with how the surrounding regions are shaped. Like pouring water over below image and the resulting waterpools are the regions I'm looking for. </p>
<p><a href="https://i.stack.imgur.com/sgPqv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sgPqv.png" alt="negative image (complement), ready to pour water into it"></a></p>
<p>I thought that is what the floodfill or watershed algorithm do, but floodfill seems like something completely else and the watershed results are not at all what I had in mind, also when applying some preprocessing that I thought could help (clipped at 1/10):</p>
<p><a href="https://i.stack.imgur.com/d99c0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/d99c0.png" alt="watershed clipped with threshold 1/10"></a></p>
<p>Or when using the same clipping threshold as with above example (clipped at 6/15):</p>
<p><a href="https://i.stack.imgur.com/Qhfuv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Qhfuv.png" alt="watershed clipped with threshold 6/15"></a></p>
<p>Produced with this code (MATLAB):</p>
<pre><code>thresh = multithresh(H, 10); % set to either 10 || 15 for the examples
q_image = imquantize(H, thresh);
mask = false(size(q_image)); % create clipping mask...
mask(q_image > 1) = true; % ... to remove lowest 10% || lowest 6/15
% show with: figure, imshow(mask);
% OPTIONAL: Gaussian smoothing
H = imgaussfilt(H, 2); % apply before adding Inf values
% OPTIONAL: H-minima transform
H = imhmin(H, 10); % parameter is threshold for suppressing shallow minima
H = -H; % Complement the image
H(~mask) = Inf; % force "ground" pixels to Inf
L = watershed(D);
L(~mask) = 0; % clip "ground" from result
imshow(label2rgb(L,'lines',[.5 .5 .5])); % show result
</code></pre>
<hr>
<p><strong><em>My question now:</em></strong> <strong>Is there an algorithm that fills a landscape and gives me the resulting waterpools (for various amounts of water poured) to do what I've tried to achieve with above methods?</strong> Or any other suggestion is welcome. I'm implementing MATLAB (or if need be Python), but I can work with any code or pseude-code.</p>
<p>To distinguish this from <a href="https://stackoverflow.com/questions/9587173/algorithm-to-find-peaks-in-2d-array">this question</a>, my maxima are not separated by zero-values. What I want is similar, yet none of the suggestions there are helpful (hill-climbing/simulated annealing will give you only one point...).</p>
<p><a href="https://stackoverflow.com/questions/3684484/peak-detection-in-a-2d-array">This question</a> is also interesting, but it solves the problem with constraints (assume exactly 5 peaks of a certain size) that make the suggested approaches not useful for my case.</p>
| 1 | 2,060 |
CSS3 animate only on hover on and off
|
<p>I have an animation of a box, where it's width increases on hover:</p>
<p>JSFiddle: <a href="https://jsfiddle.net/hbpncv34/" rel="nofollow noreferrer">https://jsfiddle.net/hbpncv34/</a></p>
<p>HTML:</p>
<pre><code><div></div>
</code></pre>
<p>CSS:</p>
<pre><code>div {
background-color: red;
height: 10vh;
width: 10vw;
}
div:hover {
animation: change_width 0.7s forwards;
}
@keyframes change_width {
from {
width: 10vw;
}
to {
width: 15vw;
}
}
</code></pre>
<p><strong>Issue:</strong></p>
<p>I also want the box to smoothly move back when I hover off of it.</p>
<p>There are two ways I could do this:</p>
<h3>Method 1:</h3>
<p>JSFiddle: <a href="https://jsfiddle.net/hbpncv34/1/" rel="nofollow noreferrer">https://jsfiddle.net/hbpncv34/1/</a></p>
<p>HTML:</p>
<pre><code><div></div>
</code></pre>
<p>CSS:</p>
<pre><code>div {
background-color: red;
height: 10vh;
width: 10vw;
animation: change_width_back 0.7s forwards;
}
div:hover {
animation: change_width 0.7s forwards;
}
@keyframes change_width {
from {
width: 10vw;
}
to {
width: 15vw;
}
}
@keyframes change_width_back {
from {
width: 15vw;
}
to {
width: 10vw:
}
}
</code></pre>
<p><strong>Issue:</strong></p>
<p>The <code>change_width_back</code> animation also runs on page load.</p>
<p>Also, mousing on / off rapidly is not smooth like it is with <code>transition</code>, so:</p>
<h3>Method 2:</h3>
<p>JSFiddle: <a href="https://jsfiddle.net/hbpncv34/2/" rel="nofollow noreferrer">https://jsfiddle.net/hbpncv34/2/</a></p>
<p>HTML:</p>
<pre><code><div></div>
</code></pre>
<p>CSS:</p>
<pre><code>div {
background-color: red;
height: 10vh;
width: 10vw;
transition: width 0.7s;
}
div:hover {
width: 15vw;
}
</code></pre>
<p><strong>Issue:</strong></p>
<p>The animation also runs on zooming in and out.</p>
<p>I can fix this by using <code>px</code> or <code>%</code> instead of <code>vw</code> for my widths, but it's crucial in my actual issue that I keep it as viewport units.</p>
<p>So, is there any way to play an animation on hover on and off, and <strong>only</strong> hover on and off?</p>
<p>Since I don't know Javascript, please keep answers HTML / CSS only. If JS is <em>absolutely needed</em>, make it simple enough to just copy + paste with minimal editing.</p>
<p>Thanks for any help.</p>
| 1 | 1,080 |
sqlite foreach in select statement?
|
<p>I have got a problem with an SQLite select.</p>
<p>There are the tables "kategorie","lv","majetok","parcela".</p>
<p>Each person has information about what he owns in the table "majetok". The sample record:</p>
<pre><code>id idpodfk idlvfk podiel podield cislozlv datum1 datum2
1 31 1 1/10000 0,0001 789 16. 9. 2012 16. 9. 2012
</code></pre>
<p>idpodfk-fk of person id<br>
idlvfk-fk of land record id</p>
<p>There is also table LV (table of land records), sample record:</p>
<pre><code>idlv lvnazov katuzemie
1 1830 Plavecký Mikuláš
</code></pre>
<p>Also I use the table "parcela", I store in there information about parcels in the land record</p>
<pre><code>pnazov rozloha idlvfk idkategoriafk typ
5432 692312 1 1 C
</code></pre>
<p>And table kategorie</p>
<pre><code>idkategoria meno
1 Lesné pozemky
</code></pre>
<hr>
<p>What I need:
a foreach record in this select</p>
<pre><code>SELECT SUM(podield) AS sum1, idlvfk
FROM majetok a
WHERE idpodfk = 1
GROUP BY idlvfk
</code></pre>
<p>I need to select this</p>
<pre><code>SELECT SUM(par.rozloha)*sum1 AS m2, kat.meno --sum1 from statement above
FROM Parcela par
INNER JOIN kategorie kat ON par.IDkategoriaFK = kat.IDkategoria
WHERE par.IDLVFK = 1 --IDLVFK from statement above
GROUP BY kat.meno
</code></pre>
<p>The (second's) query output should look like this</p>
<pre><code>m2 kat.meno
123.23 Lesne pozemky --FOR FIRST IDLVFK
324.52 Ostatne pozemky --FOR FIRST IDLVFK
235 Pasienky --FOR FIRST IDLVFK
144.23 Lesne pozemky --FOR NEXT IDLVFK
543.52 Ostatne pozemky --FOR NEXT IDLVFK
756 Pasienky --FOR NEXT IDLVFK
.
.
.
</code></pre>
<p>And then I need to group by kat.meno so the final output should look like this:</p>
<pre><code>m2 kat.meno
267,46 Lesne pozemky
868,04 Ostatne pozemky
991 Pasienky
. --other kat.meno if there is
. --other kat.meno if there is
</code></pre>
<p>Is this possible in one query or do I need to process it on a front-end?</p>
<p>Tables and query background:</p>
<p>There are some parcels in land record (every parcel has its own category, eg forest parcel etc). Person owns a part of a land record (saved in table majetok, eg: 1/1000). That mean he owns 1/1000 from each parcel in that land record. I want to select the area (column "rozloha" in parcela table) that he owns for each category (SUM(par.rozloha)*sum1 AS m2). So we must count sum of all parcels in that category on that land record and multiply with part that owns that person. But he can own 1/1000 on one land record and 3/3456 on the second land record (another land record=another parcels) so we have to do for each land record and that summarize you can see in last code.</p>
| 1 | 1,187 |
dynamically create object tags in javascript
|
<p>I am wondering why the following code does not create two of my activex object. When the object tag is directly in the HTML it works fine, but for the life of me I can't dynamically create the object item. Is this a security issue or something? I am finding a difficult time finding documentation on this problem. </p>
<pre><code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="InkWebForm._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script language="javascript">
window.onload = function() {
var s = '<OBJECT id="inkImage" classid="InkControls.dll#InkControls.ResizableInk" VIEWASTEXT></OBJECT>';
document.getElementById("inkHolder").innerHTML = s;
};
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<!-- This one gets created -->
<OBJECT id="inkImage2" classid="InkControls.dll#InkControls.ResizableInk" VIEWASTEXT>
</OBJECT>
<!-- this one should get inserted but never gets created -->
<div id="inkHolder"></div>
</div>
</form>
</body>
</html>
</code></pre>
<p>Well when I explore the dom the object explorer does show the item but IE renders a little square box and not the activex control.</p>
<p>Here goes the second attempt based on casablanca's suggestion. I think there might be a security issue going on here as per your suggestion this should work but does not. Same problem.</p>
<pre><code> <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="InkWebForm._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<script language="javascript">
window.onload = function() {
var obj = document.createElement('object');
obj.setAttribute('id', 'inkImage');
obj.setAttribute('classid', 'InkControls.dll#InkControls.ResizableInk');
document.getElementById('inkHolder').appendChild(obj);
};
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<OBJECT id="inkImage2" classid="InkControls.dll#InkControls.ResizableInk">
</OBJECT>
<div id="inkHolder"></div>
</div>
</form>
</body>
</html>
</code></pre>
| 1 | 1,269 |
Rendering HTML table inside <div> using javascript function
|
<p>I'm trying to get my javascript function that creates a html table in my content div on my website. The problem is, that it is not displayed inside the div but under it. How can I put it inside?</p>
<pre><code><div id="tab-container" class='tab-container'>
<ul class='etabs'>
<li class='tab'><a href="#tabs1-start">Start</a></li>
<li class='tab'><a href="#tabs1-schicht">Schichtplan</a></li>
<li class='tab'><a href="#tabs1-rechnung">Rechnung</a></li>
<li class='tab'><a href="#tabs1-kontakt">Kontakt</a></li>
</ul>
<div class='panel-container'>
<div id="tabs1-start">
Test page 1
</div>
<div id="tabs1-schicht">
<script type"text/javascript">
tableCreate();
</script>
</div>
<div id="tabs1-rechnung">
Test page3
</div>
<div id="tabs1-kontakt">
Test page4
</div>
</div>
</div>
</code></pre>
<p>This is my basic website with the navigationbar. When I run it with xampp the js function tableCreate(); is displayed after the panel-container div closes.</p>
<p>Here is my js code:</p>
<pre><code>function tableCreate(){
//var schicht=["datum","schicht","schicht","schicht","dispo","schicht","schicht","schicht","schicht","schicht","schicht","dispo"];
var body=document.getElementsByTagName('body')[0];
var tbl=document.createElement('table');
tbl.style.width='100%';
tbl.setAttribute('border','1');
var tbdy=document.createElement('tbody');
for(var i=0;i<28;i++){
var tr=document.createElement('tr');
for(var j=0;j<12;j++){
if(i==27 && j==12){
break
} else {
var td=document.createElement('td');
td.appendChild(document.createTextNode('schicht'))
tr.appendChild(td)
}
}
tbdy.appendChild(tr);
}
tbl.appendChild(tbdy);
body.appendChild(tbl)
</code></pre>
<p>Thanks in advance.</p>
| 1 | 1,060 |
Upgrading React-Router and replacing hashHistory with browserHistory
|
<p>I have a bootstrap+react theme that was using react-router 1.x and hashHistory and I wanted to remove the hash so followed this <a href="https://stackoverflow.com/questions/25086832/how-to-stop-in-browser-with-react-router">advice</a>.
Initially I tried to do this while having the 1.x version and I was unable to do it so I've decided to upgrade react-router to 2.x.
After installing react-router 2.x the app worked because it was still using hashHistory but when I replaced it with browserHistory:</p>
<ul>
<li>it showed a grey screen</li>
<li>the HTML of the app had only the <code><noscript data-reactid=".0"></noscript></code> tag inside it</li>
<li>the React Developer Tools showed me that the router had a <code>null</code> inside it</li>
<li>I also checked the Network tab and all files were downloaded properly, and had the right content</li>
<li><p><strong>surprisingly the was nothing printed in the JavaScript Console, no error/no warnging</strong> (I'm really shocked about this, but I'm new React, I would like to know what to do in situations like this).
Here are my changes to <code>Router.jsx</code>:</p>
<pre><code> import React from 'react'
import {render} from 'react-dom'
-import {Router} from 'react-router'
+// import {Router} from 'react-router'
+import { Router, Route, Link, browserHistory } from 'react-router'
+// import { useRouterHistory } from 'react-router'
+// import { createHashHistory } from 'history'
+// import { createBrowserHistory } from 'history'`
import History from '../components/layout/navigation/classes/History.js';
import Routes from './Routes.jsx';
+// const appHistory = useRouterHistory(createHashHistory)({ queryKey: false })
+
var rootInstance = render((
- <Router history={History}>
+ <Router history={browserHistory}>
{Routes}
</Router>
), document.getElementById('smartadmin-root'));`
</code></pre></li>
</ul>
<p>The backend uses the <a href="http://www.phoenixframework.org/" rel="nofollow noreferrer">Phoenix Framework</a>.</p>
<p><strong>Later Edit</strong>:
Here you have the <code>hashHistory</code> version that works</p>
<p><a href="https://gitlab.com/blockbuster/react-router-2-with-hash-working-public/tree/master" rel="nofollow noreferrer">https://gitlab.com/blockbuster/react-router-2-with-hash-working/tree/master</a></p>
<p>And here is the <code>browserHistory</code> version that doesn't:</p>
<p><a href="https://gitlab.com/blockbuster/react-router-2-with-browserHistory-not-working-public/tree/master" rel="nofollow noreferrer">https://gitlab.com/blockbuster/react-router-2-with-browserHistory-not-working/tree/master</a></p>
<p>The react code for both can be found under the <code>src</code> directory.</p>
<p>To run the app you need to have <code>Elixir</code>, <code>Phoenix</code> and Postgresql installed, to get backend dependencies( run <code>$ mix deps.get</code>), get frontend dependecies( <code>npm install</code> and <code>bower install</code>), to change the database username and password in <code>config/dev.exs</code>, to create and migrate the database <code>mix ecto.create && mix ecto.migrate</code> and finally run <code>mix phoenix.server</code>.</p>
| 1 | 1,055 |
want to show print preview
|
<p>I want to show a print preview, so I chose to use <a href="https://github.com/etimbo/jquery-print-preview-plugin" rel="nofollow noreferrer">this plugin</a>.</p>
<p>I have added it to my code:</p>
<pre><code><%@ Page language="c#" AutoEventWireup="false" Inherits="System.Web.UI.Page" %>
<%@ Register TagPrefix="CP" TagName="TitleBar" Src="WebUserControl.ascx" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
<title>MyPage</title>
<link href="css/print-preview.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="css/print.css" type="text/css" media="print" />
<script type="text/javascript" src="jquery.tools.min.js"></script>
<script src="jquery.print-preview.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function () {
/*
* Initialise print preview plugin
*/
// Add link for print preview and intialise
$('#aside').prepend('<a class="print-preview">Print this page</a>');
$('a.print-preview').printPreview();
// Add keybinding (not recommended for production use)
$(document).bind('keydown', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 80 && !$('#print-modal').length) {
$.printPreview.loadPrintPreview();
return false;
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<CP:TitleBar Title="User Control Test" TextColor="green" Padding="10" runat="server" />
<div id="aside"></div>
</form>
</body>
</html>
</code></pre>
<p>In <code>UserControl</code> I did this:</p>
<pre><code><%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("p").text("The DOM is now loaded and can be manipulated.");
});
</script>
<p>Not loaded yet.</p>
<table>
<tr>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
</table>
</code></pre>
<p>Problem is, when I add the script in <code>UserControl</code>, the <code>Print-Preview-Plugin</code> is not working.</p>
<p>When I remove the script from the <code>UserControl</code> the <code>print-preview-plugin</code> works fine.</p>
<p>My question is, why is the plugin not working when I add script to the UserControl? How should I call the Print Preview Plugin file code?</p>
<pre><code>/*!
* jQuery Print Previw Plugin v1.0.1
*
* Copyright 2011, Tim Connell
* Licensed under the GPL Version 2 license
* http://www.gnu.org/licenses/gpl-2.0.html
*
* Date: Wed Jan 25 00:00:00 2012 -000
*/
(function($) {
// Initialization
$.fn.printPreview = function() {
this.each(function() {
$(this).bind('click', function(e) {
e.preventDefault();
if (!$('#print-modal').length) {
$.printPreview.loadPrintPreview();
}
});
});
return this;
};
// Private functions
var mask, size, print_modal, print_controls;
$.printPreview = {
loadPrintPreview: function() {
// Declare DOM objects
print_modal = $('<div id="print-modal"></div>');
print_controls = $('<div id="print-modal-controls">' +
'<a href="#" class="print" title="Print page">Print page</a>' +
'<a href="#" class="close" title="Close print preview">Close</a>').hide();
var print_frame = $('<iframe id="print-modal-content" scrolling="no" border="0" frameborder="0" name="print-frame" />');
// Raise print preview window from the dead, zooooooombies
print_modal
.hide()
.append(print_controls)
.append(print_frame)
.appendTo('body');
// The frame lives
for (var i=0; i < window.frames.length; i++) {
if (window.frames[i].name == "print-frame") {
var print_frame_ref = window.frames[i].document;
break;
}
}
print_frame_ref.open();
print_frame_ref.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' +
'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">' +
'<head><title>' + document.title + '</title></head>' +
'<body></body>' +
'</html>');
print_frame_ref.close();
// Grab contents and apply stylesheet
var $iframe_head = $('head link[media*=print], head link[media=all]').clone(),
$iframe_body = $('body > *:not(#print-modal):not(script)').clone();
$iframe_head.each(function() {
$(this).attr('media', 'all');
});
if (!$.browser.msie && !($.browser.version < 7) ) {
$('head', print_frame_ref).append($iframe_head);
$('body', print_frame_ref).append($iframe_body);
}
else {
$('body > *:not(#print-modal):not(script)').clone().each(function() {
$('body', print_frame_ref).append(this.outerHTML);
});
$('head link[media*=print], head link[media=all]').each(function() {
$('head', print_frame_ref).append($(this).clone().attr('media', 'all')[0].outerHTML);
});
}
// Disable all links
$('a', print_frame_ref).bind('click.printPreview', function(e) {
e.preventDefault();
});
// Introduce print styles
$('head').append('<style type="text/css">' +
'@media print {' +
'/* -- Print Preview --*/' +
'#print-modal-mask,' +
'#print-modal {' +
'display: none !important;' +
'}' +
'}' +
'</style>'
);
// Load mask
$.printPreview.loadMask();
// Disable scrolling
$('body').css({overflowY: 'hidden', height: '100%'});
$('img', print_frame_ref).load(function() {
print_frame.height($('body', print_frame.contents())[0].scrollHeight);
});
// Position modal
starting_position = $(window).height() + $(window).scrollTop();
var css = {
top: starting_position,
height: '100%',
overflowY: 'auto',
zIndex: 10000,
display: 'block'
}
print_modal
.css(css)
.animate({ top: $(window).scrollTop()}, 400, 'linear', function() {
print_controls.fadeIn('slow').focus();
});
print_frame.height($('body', print_frame.contents())[0].scrollHeight);
// Bind closure
$('a', print_controls).bind('click', function(e) {
e.preventDefault();
if ($(this).hasClass('print')) { window.print(); }
else { $.printPreview.distroyPrintPreview(); }
});
},
distroyPrintPreview: function() {
print_controls.fadeOut(100);
print_modal.animate({ top: $(window).scrollTop() - $(window).height(), opacity: 1}, 400, 'linear', function(){
print_modal.remove();
$('body').css({overflowY: 'auto', height: 'auto'});
});
mask.fadeOut('slow', function() {
mask.remove();
});
$(document).unbind("keydown.printPreview.mask");
mask.unbind("click.printPreview.mask");
$(window).unbind("resize.printPreview.mask");
},
/* -- Mask Functions --*/
loadMask: function() {
size = $.printPreview.sizeUpMask();
mask = $('<div id="print-modal-mask" />').appendTo($('body'));
mask.css({
position: 'absolute',
top: 0,
left: 0,
width: size[0],
height: size[1],
display: 'none',
opacity: 0,
zIndex: 9999,
backgroundColor: '#000'
});
mask.css({display: 'block'}).fadeTo('400', 0.75);
$(window).bind("resize..printPreview.mask", function() {
$.printPreview.updateMaskSize();
});
mask.bind("click.printPreview.mask", function(e) {
$.printPreview.distroyPrintPreview();
});
$(document).bind("keydown.printPreview.mask", function(e) {
if (e.keyCode == 27) { $.printPreview.distroyPrintPreview(); }
});
},
sizeUpMask: function() {
if ($.browser.msie) {
// if there are no scrollbars then use window.height
var d = $(document).height(), w = $(window).height();
return [
window.innerWidth || // ie7+
document.documentElement.clientWidth || // ie6
document.body.clientWidth, // ie6 quirks mode
d - w < 20 ? w : d
];
} else { return [$(document).width(), $(document).height()]; }
},
updateMaskSize: function() {
var size = $.printPreview.sizeUpMask();
mask.css({width: size[0], height: size[1]});
}
}
})(jQuery);
</code></pre>
| 1 | 5,549 |
Reduce the size of main.js Angular 11
|
<p>I encouter a problem with my app that has a main.js with a size of 8.34 MB by defalt (ng build).
I tested a lot ! of things to reduce it but i just don't arrive to..</p>
<p>I really need that the size be less than 2 mb.. ( and i think it's huge too..)
Thanks for help !
<a href="https://i.stack.imgur.com/Ja1c7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ja1c7.png" alt="enter image description here" /></a>
What i tried (size of main.js) :</p>
<pre><code>ng build = 8.34MB
ng build --prod = 7.71 MB
ng build --prod --aot --build-optimizer = 7.71 MB
ng build --prod --aot --build-optimizer && gzipper compress ./dist = ...
</code></pre>
<p>package.json</p>
<pre><code>{
"name": "app",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.conf.json --hmr",
"build": "ng build --prod --aot --build-optimizer && gzipper compress ./dist",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "11.1.2",
"@angular/cdk": "^11.1.2",
"@angular/common": "11.1.2",
"@angular/compiler": "11.1.2",
"@angular/core": "11.1.2",
"@angular/flex-layout": "^11.0.0-beta.33",
"@angular/forms": "11.1.2",
"@angular/material": "^11.1.2",
"@angular/material-moment-adapter": "^11.1.2",
"@angular/platform-browser": "11.1.2",
"@angular/platform-browser-dynamic": "11.1.2",
"@angular/router": "11.1.2",
"@ngx-translate/core": "^13.0.0",
"@ngx-translate/http-loader": "^6.0.0",
"@swimlane/ngx-charts": "^17.0.0",
"@swimlane/ngx-datatable": "^19.0.0",
"@types/d3-shape": "^2.0.0",
"ajv": "^7.0.4",
"angular-calendar": "^0.28.22",
"angular-feather": "^6.1.0",
"angular-ng-autocomplete": "^2.0.5",
"apexcharts": "^3.24.0",
"c3": "^0.7.20",
"chart.js": "^2.9.4",
"chartist": "^0.11.4",
"core-js": "^3.8.3",
"d3": "^6.5.0",
"date-fns": "^2.17.0",
"extend": "^3.0.2",
"gulp-cli": "^2.3.0",
"gzipper": "^4.4.0",
"handlebars": "^4.7.6",
"lodash": "^4.17.20",
"mat-table-exporter": "^9.1.0",
"moment": "^2.29.1",
"ng-apexcharts": "^1.5.7",
"ng-chartist": "4.1.0",
"ng-multiselect-dropdown": "^0.2.14",
"ng2-charts": "^2.4.2",
"ng2-completer": "^9.0.1",
"ng2-dragula": "^2.1.1",
"ng2-file-upload": "^1.4.0",
"ng2-search-filter": "^0.5.1",
"ngx-clipboard": "^14.0.1",
"ngx-cookie-service": "^11.0.2",
"ngx-custom-validators": "11.0.1",
"ngx-pagination": "^5.0.0",
"ngx-perfect-scrollbar": "^10.1.0",
"ngx-quill": "^13.1.0",
"quill": "^1.3.7",
"rxjs": "~6.6.3",
"rxjs-compat": "^6.6.3",
"sass": "^1.32.6",
"sweetalert2": "^10.14.0",
"tslib": "^2.1.0",
"zone.js": "~0.11.3"
},
"devDependencies": {
"@angular-devkit/build-angular": "0.1101.4",
"@angular/cli": "11.1.4",
"@angular/compiler-cli": "11.1.2",
"@types/chartist": "0.11.0",
"@types/jasmine": "~3.6.3",
"@types/jasminewd2": "~2.0.8",
"@types/node": "^14.14.25",
"codelyzer": "^6.0.1",
"jasmine-core": "~3.6.0",
"jasmine-spec-reporter": "~6.0.0",
"karma": "~6.1.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage-istanbul-reporter": "~3.0.3",
"karma-jasmine": "~4.0.1",
"karma-jasmine-html-reporter": "^1.5.4",
"protractor": "~7.0.0",
"ts-node": "~9.1.1",
"tslint": "~6.1.0",
"typescript": "^4.1.3"
}
}
</code></pre>
| 1 | 3,384 |
BroadcastReceiver for Incoming calls in android doesn't work
|
<p>I'm trying to develop android app for that can record phone calls. So, in the initial step, I've to see if BroadcastReceiver is getting fired or not.
I've added permissions, receiver tag in AndroidManifest file. I'm testing on OnePlus X. Activity is gets started but BroadcastReceiver doesn't get fired when I get call. What's going wrong here?</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name="com.example.myapp.MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".PhoneStateReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
</application>
</manifest>
</code></pre>
<p>PhoneStateReceiver.Java</p>
<pre><code>package com.example.myapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.widget.Toast;
public class PhoneStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try {
System.out.println("Receiver start");
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
Toast.makeText(context,"Incoming Call State",Toast.LENGTH_SHORT).show();
Toast.makeText(context,"Ringing State Number is -"+incomingNumber,Toast.LENGTH_SHORT).show();
}
if ((state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))){
Toast.makeText(context,"Call Received State",Toast.LENGTH_SHORT).show();
}
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
Toast.makeText(context,"Call Idle State",Toast.LENGTH_SHORT).show();
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
</code></pre>
| 1 | 1,165 |
How do I json_decode string with special chars (" \\ " )
|
<p>I have a problem with encoding and decoding json data. In js I send query with data type 'json', it looks like this:</p>
<pre><code>{\"front\":{\"0\":{\"type\":\"text\",\"width\":\"55px\",\"height\":\"27px\",\"top\":\"151px\",\"left\":\"86px\",\"zIndex\":\"1\",\"svg\":\"<svg width=\\\"54.9375\\\" height=\\\"27.09375\\\" viewBox=\\\"0 0 54.9375 27.09375\\\" xmlns=\\\"http://www.w3.org/2000/svg\\\" xmlns:xlink=\\\"http://www.w3.org/1999/xlink\\\"><g id=\\\"0.7882792934370437\\\"><text fill=\\\"#FF0000\\\" stroke=\\\"none\\\" stroke-width=\\\"0\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\" x=\\\"\\\" y=\\\"\\\" text-anchor=\\\"start\\\" font-size=\\\"24px\\\" font-family=\\\"arial\\\" data-textcurve=\\\"1\\\" data-itemzoom=\\\"1 1\\\" data-textspacing=\\\"0\\\"><textPath xmlns:xlink=\\\"http://www.w3.org/1999/xlink\\\" xlink:href=\\\"http://138.68.62.219/Buy-Hanes-T-shirt-PC61LS#textPath-item-0\\\"><tspan dy=\\\"0\\\">Hello</tspan></textPath></text></g><defs><path id=\\\"textPath-item-0\\\" d=\\\"M 0.125 22.117808976867764 A 3093.9720937064453 3093.9720937064453 0 0 1 54.124314613414626 22.117808976867764\\\"></path></defs></svg>\",\"rotate\":0,\"text\":\"Hello\",\"color\":\"#FF0000\",\"fontFamily\":\"arial\",\"align\":\"center\",\"outlineC\":\"none\",\"outlineW\":0}}
</code></pre>
<p>Then I save it to cell in <code>MySQL</code>, it looks like this: </p>
<pre><code>{\\&quot;front\\&quot;:{\\&quot;0\\&quot;:{\\&quot;type\\&quot;:\\&quot;text\\&quot;,\\&quot;width\\&quot;:\\&quot;55px\\&quot;,\\&quot;height\\&quot;:\\&quot;27px\\&quot;,\\&quot;top\\&quot;:\\&quot;151px\\&quot;,\\&quot;left\\&quot;:\\&quot;86px\\&quot;,\\&quot;zIndex\\&quot;:\\&quot;1\\&quot;,\\&quot;svg\\&quot;:\\&quot;&lt;svg width=\\\\\\&quot;54.9375\\\\\\&quot; height=\\\\\\&quot;27.09375\\\\\\&quot; viewBox=\\\\\\&quot;0 0 54.9375 27.09375\\\\\\&quot; xmlns=\\\\\\&quot;http:\/\/www.w3.org\/2000\/svg\\\\\\&quot; xmlns:xlink=\\\\\\&quot;http:\/\/www.w3.org\/1999\/xlink\\\\\\&quot;&gt;&lt;g id=\\\\\\&quot;0.7882792934370437\\\\\\&quot;&gt;&lt;text fill=\\\\\\&quot;#FF0000\\\\\\&quot; stroke=\\\\\\&quot;none\\\\\\&quot; stroke-width=\\\\\\&quot;0\\\\\\&quot; stroke-linecap=\\\\\\&quot;round\\\\\\&quot; stroke-linejoin=\\\\\\&quot;round\\\\\\&quot; x=\\\\\\&quot;\\\\\\&quot; y=\\\\\\&quot;\\\\\\&quot; text-anchor=\\\\\\&quot;start\\\\\\&quot; font-size=\\\\\\&quot;24px\\\\\\&quot; font-family=\\\\\\&quot;arial\\\\\\&quot; data-textcurve=\\\\\\&quot;1\\\\\\&quot; data-itemzoom=\\\\\\&quot;1 1\\\\\\&quot; data-textspacing=\\\\\\&quot;0\\\\\\&quot;&gt;&lt;textPath xmlns:xlink=\\\\\\&quot;http:\/\/www.w3.org\/1999\/xlink\\\\\\&quot; xlink:href=\\\\\\&quot;http:\/\/138.68.62.219\/Buy-Hanes-T-shirt-PC61LS#textPath-item-0\\\\\\&quot;&gt;&lt;tspan dy=\\\\\\&quot;0\\\\\\&quot;&gt;Hello&lt;\/tspan&gt;&lt;\/textPath&gt;&lt;\/text&gt;&lt;\/g&gt;&lt;defs&gt;&lt;path id=\\\\\\&quot;textPath-item-0\\\\\\&quot; d=\\\\\\&quot;M 0.125 22.117808976867764 A 3093.9720937064453 3093.9720937064453 0 0 1 54.124314613414626 22.117808976867764\\\\\\&quot;&gt;&lt;\/path&gt;&lt;\/defs&gt;&lt;\/svg&gt;\\&quot;,\\&quot;rotate\\&quot;:0,\\&quot;text\\&quot;:\\&quot;Hello\\&quot;,\\&quot;color\\&quot;:\\&quot;#FF0000\\&quot;,\\&quot;fontFamily\\&quot;:\\&quot;arial\\&quot;,\\&quot;align\\&quot;:\\&quot;center\\&quot;,\\&quot;outlineC\\&quot;:\\&quot;none\\&quot;,\\&quot;outlineW\\&quot;:0}}
</code></pre>
<p>When I read with php this data that's what I see ( <code>$tmp=$products[0]['design_file']; print_r($tmp);</code>) :</p>
<pre><code>"{\\"front\\":{\\"0\\":{\\"type\\":\\"text\\",\\"width\\":\\"55px\\",\\"height\\":\\"27px\\",\\"top\\":\\"151px\\",\\"left\\":\\"86px\\",\\"zIndex\\":\\"1\\",\\"svg\\":\\"<svg width=\\\\\\"54.9375\\\\\\" height=\\\\\\"27.09375\\\\\\" viewBox=\\\\\\"0 0 54.9375 27.09375\\\\\\" xmlns=\\\\\\"http:\/\/www.w3.org\/2000\/svg\\\\\\" xmlns:xlink=\\\\\\"http:\/\/www.w3.org\/1999\/xlink\\\\\\"><g id=\\\\\\"0.7882792934370437\\\\\\"><text fill=\\\\\\"#FF0000\\\\\\" stroke=\\\\\\"none\\\\\\" stroke-width=\\\\\\"0\\\\\\" stroke-linecap=\\\\\\"round\\\\\\" stroke-linejoin=\\\\\\"round\\\\\\" x=\\\\\\"\\\\\\" y=\\\\\\"\\\\\\" text-anchor=\\\\\\"start\\\\\\" font-size=\\\\\\"24px\\\\\\" font-family=\\\\\\"arial\\\\\\" data-textcurve=\\\\\\"1\\\\\\" data-itemzoom=\\\\\\"1 1\\\\\\" data-textspacing=\\\\\\"0\\\\\\"><textPath xmlns:xlink=\\\\\\"http:\/\/www.w3.org\/1999\/xlink\\\\\\" xlink:href=\\\\\\"http:\/\/138.68.62.219\/Buy-Hanes-T-shirt-PC61LS#textPath-item-0\\\\\\"><tspan dy=\\\\\\"0\\\\\\">Hello<\/tspan><\/textPath><\/text><\/g><defs><path id=\\\\\\"textPath-item-0\\\\\\" d=\\\\\\"M 0.125 22.117808976867764 A 3093.9720937064453 3093.9720937064453 0 0 1 54.124314613414626 22.117808976867764\\\\\\"><\/path><\/defs><\/svg>\\",\\"rotate\\":0,\\"text\\":\\"Hello\\",\\"color\\":\\"#FF0000\\",\\"fontFamily\\":\\"arial\\",\\"align\\":\\"center\\",\\"outlineC\\":\\"none\\",\\"outlineW\\":0}}
</code></pre>
<p>If I do this:</p>
<pre><code>$tmp=$products[0]['design_file'];
$info=json_decode($tmp);
print_r($info);
</code></pre>
<p>It gives me <strong>Null</strong>.
How can I get my array back from that mess?</p>
<p>Javascript sending:</p>
<pre><code>jQuery(document).triggerHandler( "before.addtocart.design", datas);
var finaldata=JSON.stringify(datas);
jQuery.ajax({
url: 'index.php?route=checkout/cart/add', //URL TO CONTROL FUNCTION add()
type: 'post',
data: 'product_id=' + product_id + '&quantity=' + q+"&option['options']="+finaldata,
</code></pre>
<p>Read in Php </p>
<pre><code>if (isset($this->request->post['option'])) {
$option = array_filter($this->request->post['option']);
</code></pre>
<p>Pass to view</p>
<pre><code>$data['products'][] = array(
'design_file'=>$product['design_file'],
...
$tmp=$products[0]['design_file'];
</code></pre>
| 1 | 3,089 |
undefined method `alias_method_chain' in active record 3.2.18 without rails migration
|
<p>This is my Rakefile</p>
<pre><code>require 'bundler'
Bundler.setup
require 'active_record'
require 'sqlite3'
require 'yaml'
require 'logger'
task :migrate => :environment do
ActiveRecord::Migrator.migrate('db/migrate', ENV["VERSION"] ? ENV["VERSION"].to_i : nil )
end
task :environment do
ActiveRecord::Base.establish_connection(YAML::load(File.open('config/database.yaml'))['development'])
ActiveRecord::Base.logger = Logger.new(STDOUT)
end
</code></pre>
<p>When I execute the task I got this error:</p>
<pre><code>rake aborted!
/usr/local/rvm/gems/ruby-2.0.0-p0@ta/gems/activerecord-2.3.18/lib/active_record/base.rb:2449: warning: already initialized constant Class::VALID_FIND_OPTIONS
/usr/local/rvm/gems/ruby-2.0.0-p0@ta/gems/activerecord-2.3.18/lib/active_record/base.rb:2449: warning: previous definition of VALID_FIND_OPTIONS was here
undefined method `alias_method_chain' for #<Class:0x00000001606340>
/usr/local/rvm/gems/ruby-2.0.0-p0@ta/gems/activerecord-2.3.18/lib/active_record/base.rb:2002:in `method_missing'
/usr/local/rvm/gems/ruby-2.0.0-p0@ta/gems/activerecord-2.3.18/lib/active_record/validations.rb:387:in `block in included'
/usr/local/rvm/gems/ruby-2.0.0-p0@ta/gems/activerecord-2.3.18/lib/active_record/validations.rb:386:in `class_eval'
/usr/local/rvm/gems/ruby-2.0.0-p0@ta/gems/activerecord-2.3.18/lib/active_record/validations.rb:386:in `included'
/usr/local/rvm/gems/ruby-2.0.0-p0@ta/gems/activerecord-2.3.18/lib/active_record/base.rb:3210:in `include'
/usr/local/rvm/gems/ruby-2.0.0-p0@ta/gems/activerecord-2.3.18/lib/active_record/base.rb:3210:in `block in <module:ActiveRecord>'
/usr/local/rvm/gems/ruby-2.0.0-p0@ta/gems/activerecord-2.3.18/lib/active_record/base.rb:3208:in `class_eval'
/usr/local/rvm/gems/ruby-2.0.0-p0@ta/gems/activerecord-2.3.18/lib/active_record/base.rb:3208:in `<module:ActiveRecord>'
/usr/local/rvm/gems/ruby-2.0.0-p0@ta/gems/activerecord-2.3.18/lib/active_record/base.rb:5:in `<top (required)>'
/home/marco/desenv/technical_analysis/Rakefile:14:in `block in <top (required)>'
/usr/local/rvm/gems/ruby-2.0.0-p0@ta/gems/rake-10.0.4/lib/rake/task.rb:246:in `call'
/usr/local/rvm/gems/ruby-2.0.0-p0@ta/gems/rake-10.0.4/lib/rake/task.rb:246:in `block in execute'
</code></pre>
<p>I had some debug and some test... <strong>Then i moved to 3.2.13</strong> version of active record, and all worked as expected. I didn't find any docs for 3.2.18 version...</p>
<p>I don't mind to use 3.2.13 version, but I got curious about that. </p>
| 1 | 1,130 |
Heroku on Rails - Invalid DATABASE_URL
|
<p>EDIT: The general advice is to use <strong>CEDAR</strong> stack.</p>
<p>Pretty new to RoR, Gems, Heroku and Git. Following tutorial: <a href="http://ruby.railstutorial.org/book/ruby-on-rails-tutorial" rel="nofollow noreferrer">http://ruby.railstutorial.org/book/ruby-on-rails-tutorial</a></p>
<p>Works smoothly on localhost, when deployed to Heroku got <strong>ConnectionNotEstablished error</strong>, that was solved here:
<a href="https://stackoverflow.com/questions/7542745/heroku-error-activerecordconnectionnotestablished">https://stackoverflow.com/questions/7542745/heroku-error-activerecordconnectionnotestablished</a> <em>(BTW: following same tutorial)</em> After changing production database to PostgreSQL <em>(gem 'pg')</em> it generates another error:</p>
<p><strong>Visting live site</strong></p>
<blockquote>
<p>An error occurred in the application and your page could not be
served. Please try again in a few moments.</p>
<p>If you are the application owner, check your logs for details.</p>
</blockquote>
<p>Tried this -
<a href="https://stackoverflow.com/questions/6335910/heroku-app-crashed-receiving-invalid-database-url-when-attempting-heroku-rake">Heroku app crashed, receiving "Invalid DATABASE URL" when attempting heroku rake db:migrate</a> -
<strong>heroku rake db:migrate</strong></p>
<pre><code>rake aborted!
Invalid DATABASE_URL
Tasks: TOP => db:migrate => db:load_config
(See full trace by running task with --trace)
</code></pre>
<p><strong>heroku console</strong></p>
<pre><code>Internal server error
</code></pre>
<p><strong>gemfile</strong></p>
<pre><code>source 'http://rubygems.org'
gem 'rails', '3.1.1'
group :development do
gem 'rspec-rails', '2.6.1'
gem 'annotate', '~> 2.4.1.beta'
gem 'sqlite3'
end
group :test do
gem 'rspec-rails', '2.6.1'
gem 'webrat', '0.7.1'
gem 'sqlite3'
end
group :production do
gem 'pg'
end
group :assets do
gem 'sass-rails', '~> 3.1.4'
gem 'coffee-rails', '~> 3.1.1'
gem 'uglifier', '>= 1.0.3'
end
</code></pre>
<p><strong>heroku logs</strong></p>
<pre><code>9:02+00:00 app[web.1]: from /usr/ruby1.9.2/lib/ruby/gems/1.9.1/gems/thin-1.2.6/lib/thin/runner.rb:143:in `run!'
9:02+00:00 app[web.1]: from /usr/ruby1.9.2/lib/ruby/gems/1.9.1/gems/thin-1.2.6/bin/thin:6:in `<top (required)>'
9:02+00:00 app[web.1]: from /usr/ruby1.9.2/lib/ruby/gems/1.9.1/gems/thin-1.2.6/lib/thin/runner.rb:177:in `run_command'
9:02+00:00 app[web.1]: from /home/heroku_rack/heroku.ru:18:in `block (2 levels) in <main>'
9:02+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/rack-1.3.6/lib/rack/builder.rb:51:in `initialize'
9:02+00:00 app[web.1]: from /usr/ruby1.9.2/bin/thin:19:in `<main>'
9:02+00:00 app[web.1]: from /usr/ruby1.9.2/bin/thin:19:in `load'
9:03+00:00 heroku[web.1]: State changed from starting to crashed
9:04+00:00 heroku[web.1]: Process exited
1:58+00:00 heroku[slugc]: Slug compilation started
3:09+00:00 heroku[api]: Deploy 3dea426 by mstefanow@gmail.com
3:09+00:00 heroku[api]: Release v7 created by mstefanow@gmail.com
3:09+00:00 heroku[web.1]: State changed from crashed to created
3:09+00:00 heroku[web.1]: State changed from created to starting
3:10+00:00 heroku[slugc]: Slug compilation finished
3:12+00:00 heroku[web.1]: Starting process with command `thin -p 44881 -e production -R /home/heroku_rack/heroku.ru start`
3:15+00:00 app[web.1]: (erb):9:in `rescue in <main>': Invalid DATABASE_URL (RuntimeError)
3:15+00:00 app[web.1]: from (erb):6:in `<main>'
3:15+00:00 app[web.1]: from /usr/ruby1.9.2/lib/ruby/1.9.1/erb.rb:753:in `eval'
3:15+00:00 app[web.1]: from /usr/ruby1.9.2/lib/ruby/1.9.1/erb.rb:753:in `result'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/railties-3.1.1/lib/rails/application/configuration.rb:106:in `database_configuration'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/lazy_load_hooks.rb:36:in `instance_eval'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activerecord-3.1.1/lib/active_record/railtie.rb:68:in `block (2 levels) in <class:Railtie>'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/lazy_load_hooks.rb:36:in `execute_hook'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/lazy_load_hooks.rb:43:in `block in run_load_hooks'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/lazy_load_hooks.rb:42:in `each'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/lazy_load_hooks.rb:42:in `run_load_hooks'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:2190:in `<top (required)>'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/dependencies.rb:240:in `require'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/dependencies.rb:240:in `block in require'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/dependencies.rb:225:in `load_dependency'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/dependencies.rb:240:in `require'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/dependencies.rb:489:in `load_missing_constant'
3:15+00:00 app[web.1]: from /app/app/models/user.rb:12:in `<top (required)>'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/dependencies.rb:179:in `each'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/dependencies.rb:179:in `const_missing'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/inflector/methods.rb:124:in `block in constantize'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/inflector/methods.rb:123:in `each'
3:15+00:00 a
from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/inflector/methods.rb:123:in `constantize'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/core_ext/string/inflections.rb:43:in `constantize'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/dependencies.rb:348:in `require_or_load'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/dependencies.rb:181:in `block in const_missing'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.1.1/lib/action_controller/metal/params_wrapper.rb:148:in `_default_wrap_model'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.1.1/lib/action_controller/metal/params_wrapper.rb:167:in `_set_wrapper_defaults'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.1.1/lib/action_controller/metal/params_wrapper.rb:128:in `inherited'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.1.1/lib/abstract_controller/railties/routes_helpers.rb:7:in `block (2 levels) in wi
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.1.1/lib/action_controller/railties/paths.rb:7:in `block (2 levels) in with'
3:15+00:00 app[web.1]: from /app/app/controllers/users_controller.rb:1:in `<top (required)>'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/dependencies.rb:240:in `block in require'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/dependencies.rb:225:in `load_dependency'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/dependencies.rb:240:in `require'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/dependencies.rb:240:in `require'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/dependencies.rb:348:in `require_or_load'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/dependencies.rb:302:in `depend_on'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.1.1/lib/active_support/dependencies.rb:214:in `require_dependency'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/railties-3.1.1/lib/rails/engine.rb:417:in `block (2 levels) in eager_load!'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/railties-3.1.1/lib/rails/engine.rb:416:in `each'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/railties-3.1.1/lib/rails/engine.rb:416:in `block in eager_load!'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/railties-3.1.1/lib/rails/engine.rb:414:in `each'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/railties-3.1.1/lib/rails/engine.rb:414:in `eager_load!'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/railties-3.1.1/lib/rails/application/finisher.rb:51:in `block in <module:Finisher>'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/railties-3.1.1/lib/rails/initializable.rb:30:in `instance_exec'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/railties-3.1.1/lib/rails/initializable.rb:30:in `run'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/railties-3.1.1/lib/rails/initializable.rb:55:in `block in run_initializers'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/railties-3.1.1/lib/rails/initializable.rb:54:in `each'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/railties-3.1.1/lib/rails/initializable.rb:54:in `run_initializers'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/railties-3.1.1/lib/rails/application.rb:96:in `initialize!'
3:15+00:00 app[web.1]: from /app/config/environment.rb:5:in `<top (required)>'
3:15+00:00 app[web.1]: from <internal:lib/rubygems/custom_require>:29:in `require'
3:15+00:00 app[web.1]: from <internal:lib/rubygems/custom_require>:29:in `require'
3:15+00:00 app[web.1]: from config.ru:3:in `block (3 levels) in <main>'
3:15+00:00 app[web.1]: from /home/heroku_rack/heroku.ru:23:in `eval'
3:15+00:00 app[web.1]: from /home/heroku_rack/heroku.ru:23:in `block (3 levels) in <main>'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/railties-3.1.1/lib/rails/railtie/configurable.rb:30:in `method_missing'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/rack-1.3.6/lib/rack/builder.rb:120:in `new'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/rack-1.3.6/lib/rack/builder.rb:120:in `map'
3:15+00:00 app[web.1]: from /home/heroku_rack/heroku.ru:18:in `block (2 levels) in <main>'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/rack-1.3.6/lib/rack/builder.rb:51:in `instance_eval'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/rack-1.3.6/lib/rack/builder.rb:51:in `initialize'
3:15+00:00 app[web.1]: from /home/heroku_rack/heroku.ru:11:in `new'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/rack-1.3.6/lib/rack/builder.rb:51:in `instance_eval'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/rack-1.3.6/lib/rack/builder.rb:51:in `initialize'
3:15+00:00 app[web.1]: from /home/heroku_rack/heroku.ru:11:in `block in <main>'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/rack-1.3.6/lib/rack/builder.rb:51:in `instance_eval'
3:15+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.9.1/gems/rack-1.3.6/lib/rack/builder.rb:51:in `initialize'
3:15+00:00 app[web.1]: from /home/heroku_rack/heroku.ru:1:in `new'
3:15+00:00 app[web.1]: from /home/heroku_rack/heroku.ru:1:in `<main>'
3:15+00:00 app[web.1]: from /usr/ruby1.9.2/lib/ruby/gems/1.9.1/gems/thin-1.2.6/lib/rack/adapter/loader.rb:36:in `eval'
3:15+00:00 app[web.1]: from /usr/ruby1.9.2/lib/ruby/gems/1.9.1/gems/thin-1.2.6/lib/rack/adapter/loader.rb:36:in `load'
3:15+00:00 app[web.1]: from /usr/ruby1.9.2/lib/ruby/gems/1.9.1/gems/thin-1.2.6/lib/thin/controllers/controller.rb:175:in `load_rackup_config'
3:15+00:00 app[web.1]: from /usr/ruby1.9.2/lib/ruby/gems/1.9.1/gems/thin-1.2.6/lib/thin/controllers/controller.rb:65:in `start'
3:15+00:00 app[web.1]: from /usr/ruby1.9.2/lib/ruby/gems/1.9.1/gems/thin-1.2.6/lib/thin/runner.rb:143:in `run!'
3:15+00:00 app[web.1]: from /usr/ruby1.9.2/lib/ruby/gems/1.9.1/gems/thin-1.2.6/bin/thin:6:in `<top (required)>'
3:15+00:00 app[web.1]: from /usr/ruby1.9.2/bin/thin:19:in `load'
3:15+00:00 app[web.1]: from /usr/ruby1.9.2/bin/thin:19:in `<main>'
3:15+00:00 app[web.1]: from /usr/ruby1.9.2/lib/ruby/gems/1.9.1/gems/thin-1.2.6/lib/thin/runner.rb:177:in `run_command'
3:16+00:00 heroku[web.1]: State changed from starting to crashed
3:17+00:00 heroku[web.1]: Process exited
5:55+00:00 heroku[router]: Error H10 (App crashed) -> GET high-wind-7473.heroku.com/pages/home dyno= queue= wait= service= status=503 bytes=
5:57+00:00 heroku[router]: Error H10 (App crashed) -> GET high-wind-7473.heroku.com/pages/home dyno= queue= wait= service= status=503 bytes=
</code></pre>
<h1>Kind of stuck, please help (point in right direction)</h1>
<p><strong>Of course</strong></p>
<pre><code>bundle install
git add .
git commit -m "another heroku fix"
git push
git push heroku
</code></pre>
| 1 | 6,533 |
pathlib: cannot import name 'Sequence' from 'collections'
|
<p>It has been a few days since I rebuilt my project but when I was testing some things this morning I wanted to update my Werkzeug package due to an issue I was having with its Multidict class, I rebuilt and started getting this error:</p>
<pre><code>#17 73.14 ERROR: Command errored out with exit status 1:
#17 73.14 command: /usr/local/bin/python -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-0qw1gt47/pathlib_cc19f11e095d4bbd895469d77780e6c9/setup.py'"'"'; __file__='"'"'/tmp/pip-install-0qw1gt47/pathlib_cc19f11e095d4bbd895469d77780e6c9/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-908_ate4
#17 73.14 cwd: /tmp/pip-install-0qw1gt47/pathlib_cc19f11e095d4bbd895469d77780e6c9/
#17 73.14 Complete output (13 lines):
#17 73.14 Traceback (most recent call last):
#17 73.14 File "<string>", line 1, in <module>
#17 73.14 File "/usr/local/lib/python3.10/site-packages/setuptools/__init__.py", line 16, in <module>
#17 73.14 import setuptools.version
#17 73.14 File "/usr/local/lib/python3.10/site-packages/setuptools/version.py", line 1, in <module>
#17 73.14 import pkg_resources
#17 73.14 File "/usr/local/lib/python3.10/site-packages/pkg_resources/__init__.py", line 23, in <module>
#17 73.14 import zipfile
#17 73.14 File "/usr/local/lib/python3.10/zipfile.py", line 19, in <module>
#17 73.14 import pathlib
#17 73.14 File "/tmp/pip-install-0qw1gt47/pathlib_cc19f11e095d4bbd895469d77780e6c9/pathlib.py", line 10, in <module>
#17 73.14 from collections import Sequence
#17 73.14 ImportError: cannot import name 'Sequence' from 'collections' (/usr/local/lib/python3.10/collections/__init__.py)
#17 73.14 ----------------------------------------
#17 73.14 WARNING: Discarding https://files.pythonhosted.org/packages/ac/aa/9b065a76b9af472437a0059f77e8f962fe350438b927cb80184c32f075eb/pathlib-1.0.1.tar.gz#sha256=6940718dfc3eff4258203ad5021090933e5c04707d5ca8cc9e73c94a7894ea9f (from https://pypi.org/simple/pathlib/). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
#17 73.14 ERROR: Could not find a version that satisfies the requirement pathlib==1.0.1 (from versions: 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.97, 1.0, 1.0.1)
#17 73.14 ERROR: No matching distribution found for pathlib==1.0.1
</code></pre>
<p>I attempted to install the dependencies requirements.txt on my local machine and it ran without any issues, but when the docker image is built it errors</p>
<p>Docker file:</p>
<pre><code>FROM python:3
WORKDIR /usr/src/app
COPY . .
RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 5010
RUN chmod u+x ./entrypoint.sh
</code></pre>
<p>requirements.txt:</p>
<pre><code>alembic==1.7.3
aniso8601==8.0.0
appdirs==1.4.4
artifactory==0.1.17
attrs==20.3.0
bcrypt==3.2.0
beautifulsoup4==4.9.3
bidict==0.21.3
blinker==1.4
boto3==1.18.50
botocore==1.21.50
bs4==0.0.1
cachelib==0.3.0
certifi==2020.12.5
cffi==1.14.5
chardet==3.0.4
click==8.0.1
cryptography==3.4.6
distlib==0.3.2
dnspython==1.16.0
dominate==2.6.0
email-validator==1.1.3
et-xmlfile==1.1.0
eventlet==0.30.2
filelock==3.0.12
Flask==2.0.1
Flask-Bootstrap==3.3.7.1
Flask-Login==0.5.0
Flask-Mail==0.9.1
flask-marshmallow==0.14.0
Flask-Migrate==3.1.0
Flask-RESTful==0.3.8
Flask-Session==0.4.0
Flask-SocketIO==5.1.1
Flask-SQLAlchemy==2.5.1
Flask-User==1.0.2.2
Flask-WTF==0.15.1
greenlet==1.1.0
gunicorn==20.1.0
idna==2.10
iniconfig==1.1.1
is-safe-url==1.0
itsdangerous==2.0.1
Jinja2==3.0.1
jmespath==0.10.0
Mako==1.1.5
MarkupSafe==2.0.1
marshmallow==3.12.2
marshmallow-sqlalchemy==0.26.1
numpy==1.21.0
openpyxl==3.0.7
packaging==20.9
pandas==1.2.5
paramiko==2.7.2
passlib==1.7.4
pexpect==4.8.0
pluggy==0.13.1
psycopg2-binary==2.9.1
ptyprocess==0.7.0
py==1.10.0
pycparser==2.20
PyNaCl==1.4.0
pyparsing==2.4.7
pytest==6.2.3
python-dateutil==2.8.1
python-dotenv==0.19.0
python-engineio==4.2.1
python-socketio==5.4.0
pytz==2021.1
requests==2.24.0
s3transfer==0.5.0
scp==0.13.3
shippo==2.0.2
simplejson==3.17.2
six==1.15.0
soupsieve==2.2
SQLAlchemy==1.4.15
SQLAlchemy-Utils==0.37.8
toml==0.10.2
urllib3==1.25.11
virtualenv==20.4.7
visitor==0.1.3
Werkzeug==2.0.2
WTForms==2.3.3
XlsxWriter==1.4.3
</code></pre>
<p>I also tried just taking pathlib out of the requirements file so that the other dependencies could install it on their own, which attempted multiple versions of pathlib, but it still errored:</p>
<pre><code>#9 86.72 ERROR: Could not find a version that satisfies the requirement pathlib (from artifactory) (from versions: 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.97, 1.0, 1.0.1)
#9 86.72 ERROR: No matching distribution found for pathlib
</code></pre>
<p>Any help would be greatly appreciated.</p>
| 1 | 2,473 |
Angular Material 6 - mat-table Data from service
|
<p>I want integrate Data from a service in an angular material table. </p>
<hr>
<p>All the examples I could see refer to hard data in the ts file but do not refer to a service.</p>
<p>My service allows to recover all of my patients, functional with bootstrap but when I want to integrate it with the angular material, I can not do it</p>
<p>Anyone know the solution ?</p>
<hr>
<p>Component.ts</p>
<pre><code>import { Component, OnDestroy, OnInit, ViewChild} from '@angular/core';
import { PatientsService } from '../services/patients.service';
import { Patient } from '../models/patient.model';
import { Subscription } from 'rxjs/Subscription';
import { Observable } from 'rxjs/observable';
import { Router } from '@angular/router';
import { MatPaginator, MatTableDataSource } from '@angular/material';
import { DataSource } from '@angular/cdk/collections';
@Component({
selector: 'app-patient-list',
templateUrl: './patient-list.component.html',
styleUrls: ['./patient-list.component.scss']
})
export class PatientListComponent implements OnInit {
displayedColumns = ['prenom', 'nom', 'sexe', 'daten'];
dataSource = new MatTableDataSource<Patient>();
patients: Patient[];
patientsSubscription: Subscription;
constructor(private patientsService: PatientsService, private router: Router)
{}
ngOnInit() {
this.patientsService.getPatients().subscribe(
data => {
this.dataSource.data = data;
}
);
this.patientsService.emitPatients();
}
onNewPatient() {
this.router.navigate(['/patients', 'new']);
}
onDeletePatient(patient: Patient) {
this.patientsService.removePatient(patient);
}
onViewPatient(id: number) {
this.router.navigate(['/patients', 'view', id]);
}
ngOnDestroy() {
this.patientsSubscription.unsubscribe();
}
}
export interface Element {
prenom: string;
nom : string;
sexe: string;
daten: new Date ();
}
</code></pre>
<hr>
<p>Component.ts</p>
<pre><code> <div >
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container matColumnDef="prenom">
<th mat-header-cell *matHeaderCellDef> Prénom </th>
<td mat-cell *matCellDef="let element"> {{element.prenom}} </td>
</ng-container>
<ng-container matColumnDef="nom">
<th mat-header-cell *matHeaderCellDef> Nom de naissance </th>
<td mat-cell *matCellDef="let element"> {{element.nom}}</td>
</ng-container>
<ng-container matColumnDef="daten">
<th mat-header-cell *matHeaderCellDef> Date de naissance </th>
<td mat-cell *matCellDef="let element"> {{element.daten}} </td>
</ng-container>
<ng-container matColumnDef="sexe">
<th mat-header-cell *matHeaderCellDef> Sexe </th>
<td mat-cell *matCellDef="let element"> {{element.sexe}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
</code></pre>
<p>Model</p>
<pre><code> export class Patient
{
photo: string;
constructor(public nom: string, public prenom: string, public sexe:
string, public daten = new Date ()) {}
}
</code></pre>
<p>Service</p>
<pre><code> import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Patient } from '../models/patient.model';
import * as firebase from 'firebase';
import DataSnapshot = firebase.database.DataSnapshot;
import {Observable} from "rxjs";
@Injectable()
export class PatientsService {
patients: Patient[] = [];
patientsSubject = new Subject<Patient[]>();
emitPatients() {
this.patientsSubject.next(this.patients);
}
savePatients() {
firebase.database().ref('/patients').set(this.patients);
}
getPatients() {
firebase.database().ref('/patients')
.on('value', (data: DataSnapshot) => {
this.patients = data.val() ? data.val() : [];
this.emitPatients();
}
);
}
getSinglePatient(id: number) {
enter code herereturn new Promise(
(resolve, reject) => {
firebase.database().ref('/patients/' + id).once('value').then(
(data: DataSnapshot) => {
resolve(data.val());
}, (error) => {
reject(error);
}
);
}
);
}
</code></pre>
<p>I don't see other post for this problem. </p>
| 1 | 1,872 |
How to compare one value in an arraylist of objects to output largest value?
|
<p>I need to create a method getLargestObject() that finds the object in the array list with the largest area that returns its position and outputs the contents of the object. The current loop I am using doesn't work and I'm not sure how to compare the values of the areas in an arraylist so I can get the largest one.</p>
<pre><code>package csu.cole;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Driver {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File(
"C:/Users/Charles/Desktop/GeometricObjectsData.txt"));
ArrayList<GeometricObject> list = new ArrayList<GeometricObject>();
while (input.hasNextLine()) {
String line = input.nextLine();
String[] tokens = line.split(", ");
if (tokens[0].equals("CIRCLE")) {
Circle c = new Circle();
if (tokens.length == 4) {
float radius = Float.parseFloat(tokens[1]);
c.setRadius(radius);
String color = String.valueOf(tokens[2]);
c.setColor(color);
Boolean filled = Boolean.valueOf(tokens[3]);
c.setFilled(filled);
c.getArea();
list.add(c);
System.out.println(c.toString());
} else if (tokens.length == 3) {
float radius = Float.parseFloat(tokens[1]);
c.setRadius(radius);
String color = String.valueOf(tokens[2]);
c.setColor(color);
Boolean filled = false;
c.setFilled(filled);
c.getArea();
list.add(c);
System.out.println(c.toString());
} else if (tokens.length == 1) {
String color = "white";
c.setColor(color);
Boolean filled = false;
c.setFilled(filled);
c.getArea();
list.add(c);
System.out.println(c.toString());
}
} else if (tokens[0].equals("RECTANGLE")) {
Rectangle r = new Rectangle();
if (tokens.length == 5) {
float height = Integer.parseInt(tokens[1]);
r.setHeight(height);
float width = Integer.parseInt(tokens[2]);
r.setWidth(width);
String color = String.valueOf(tokens[3]);
r.setColor(color);
Boolean filled = Boolean.valueOf(tokens[4]);
r.setFilled(filled);
r.getArea();
list.add(r);
System.out.println(r.toString());
} else if (tokens.length == 1) {
String color = "white";
r.setColor(color);
Boolean filled = false;
r.setFilled(filled);
r.getArea();
list.add(r);
System.out.println(r.toString());
}
}
}
}
public int getLargestObject() {
int max = Integer.MIN_VALUE;
for (int = 0; i < list.size(); i++){
if (list.get(i) > max){
max = list.get(i);
}
}
return max;
}
}
</code></pre>
| 1 | 2,048 |
Vuetify - bottom align text field
|
<p>I'm trying to align the bottom of my <code>search</code> text field with the bottom of my floating action button. <a href="https://codepen.io/Trimakas/pen/rRqOdj?editors=1010" rel="nofollow noreferrer">I've created a code pen which you can see here:</a></p>
<p>I've tried everything I know including: setting a negative margin, and vertical-align to both <code>baseline</code> and <code>bottom</code> to no effect. You can see my code in the codepen, but I've attached it below as well:</p>
<pre><code><template id="app">
<v-container>
<v-layout row wrap align-center class="text-xs-center">
<v-flex xs12 align-center>
<v-flex>
<h1 class="display-1 sans_pro_medium fix-title-height pb-3">Failed Order Report</h1>
</v-flex>
<v-layout row>
<v-flex xs12>
<side_drawer v-show="side_drawer_show"></side_drawer>
</v-flex>
</v-layout>
<!--<v-flex xs12>-->
<!--<v-spacer></v-spacer>-->
<v-layout row>
<v-flex xs1>
<v-btn fab large color="purple darken-4" align-left>
<v-icon x-large color="white">refresh</v-icon>
</v-btn>
</v-flex>
<v-flex xs4 offset-xs7>
<v-text-field
align-right
v-model="search"
append-icon="search"
label="Search"
single-line
hide-details
>
</v-text-field>
</v-flex>
</v-layout>
<!--</v-flex>-->
<v-data-table
:headers="headers"
:items="desserts"
:search="search"
class="elevation-11"
>
<template v-slot:no-data>
<v-alert :value="true" type="success">
Your orders are looking great! No orders have failed.
</v-alert>
</template>
<template slot="items" slot-scope="props">
<td>{{ props.item.name }}</td>
<td class="text-xs-center">{{ props.item.calories }}</td>
<td class="text-xs-center">{{ props.item.fat }}</td>
<!--<td class="text-xs-right">{{ props.item.carbs }}</td>-->
<!--<td class="text-xs-right">{{ props.item.protein }}</td>-->
<!--<td class="text-xs-right">{{ props.item.iron }}</td>-->
</template>
</v-data-table>
</v-flex>
</v-layout>
</v-container>
</template>
<script>
/*global localStorage*/
// import side_drawer from '../components/side_drawer.vue';
// import {dataShare} from '../packs/application.js';
import axios from 'axios';
export default {
components: {
side_drawer
},
data () {
return {
search: '',
side_drawer_show: true,
headers: [
{
text: 'Shopify Store URL',
align: 'center',
sortable: true,
value: 'url'
},
{ text: 'Shopify Order Number', value: 'shopify_order_number', align: 'center', sortable: true},
{ text: 'Amazon Order Id', value: 'amazon_order_id', align: 'center', sortable: true },
{ text: 'Shopify Order Status', value: 'shopify_order_status', align: 'center', sortable: true },
{ text: 'Amazon Order Status', value: 'amazon_order_status', align: 'center', sortable: true },
{ text: 'Action Needed', value: 'action' , sortable: true}
],
desserts: [
{
name: 'Frozen Yogurt',
calories: 159,
fat: 6.0,
carbs: 24,
protein: 4.0,
iron: '1%'
},
{
name: 'Ice cream sandwich',
calories: 237,
fat: 9.0,
carbs: 37,
protein: 4.3,
iron: '1%'
},
{
name: 'Eclair',
calories: 262,
fat: 16.0,
carbs: 23,
protein: 6.0,
iron: '7%'
},
{
name: 'Cupcake',
calories: 305,
fat: 3.7,
carbs: 67,
protein: 4.3,
iron: '8%'
}
]
}
}
}
</script>
<style>
.nudge_up {
padding-bottom: 10px !important;
}
</style>
</code></pre>
| 1 | 2,693 |
Can not open session for facebook
|
<p>I had make FBLogin demo using <a href="https://developers.facebook.com/docs/getting-started/facebook-sdk-for-android/3.0/" rel="nofollow">this tutotial</a></p>
<p>Code is here //MainActivity.java</p>
<pre><code>public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// start Facebook Login
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
@Override
public void call(Session session, SessionState state,
Exception exception) {
Log.v("log_tag", "Token=" + session.getAccessToken());
Log.v("log_tag", "Token=" + session.isOpened());
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
// callback after Graph API response with user
// object
@Override
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
TextView welcome = (TextView) findViewById(R.id.welcome);
welcome.setText("Hello "
+ user.getName() + "!");
}
}
});
}
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);
}
}
</code></pre>
<p>//AndroidManifest.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.fbdemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.fbdemo.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.facebook.LoginActivity" />
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/app_id" />
</application>
</manifest>
</code></pre>
<p>output in <code>log_cat</code> is like this</p>
<pre><code>02-14 19:08:25.251: V/log_tag(1558): Token=
02-14 19:08:25.251: V/log_tag(1558): Token=false
02-14 19:08:38.834: V/log_tag(1558): Token=
02-14 19:08:38.834: V/log_tag(1558): Token=false
</code></pre>
<p>please tell me where is the problem?</p>
| 1 | 1,612 |
Gradle: Call ant from a custom task
|
<p>I am new to gradle and trying to migrate our currently Maven based automated JAX-WS client building project, as gradle seems to provide an easier way for us to configure the builds for new projects.</p>
<p>I followed this tutorial <a href="http://jaxenter.com/tutorial-gradle-soap-features-revealed-42757-2.html" rel="nofollow">here</a> and was able to generate the client classes for a WSDL endpoint. What I want to achieve now is to put the Task definition in a new DefaultTask class to keep the build.gradle file cleaner, so I created the following file, put it in a new Groovy project and made it available to my build:</p>
<pre><code>class WsimportTask extends DefaultTask {
def List<String> wsdlUrls
@OutputDirectory
File destDir
@TaskAction
def wsimport() {
wsdlUrls.each() {
println "run wsimport for "+ it
ant {
sourceSets.main.output.classesDir.mkdirs()
destDir.mkdirs()
taskdef(name:'wsimport',
classname:'com.sun.tools.ws.ant.WsImport',
classpath:configurations.jaxws.asPath)
wsimport(keep:true,
destdir: sourceSets.main.output.classesDir,
sourcedestdir: destDir,
wsdl: it)
}
}
}
}
</code></pre>
<p>As I want to come up with one single project that contains a subproject for each web service client that we have, I altered the build.gradle file of the main project and added:</p>
<p><strong>main build.gradle</strong></p>
<pre><code>subprojects {
configurations {
wsimport
}
dependencies {
wsimport group: 'com.mycompany.gradle', name: 'tasks', version: '0.0.2-SNAPSHOT'
}
task wsimport(type: com.mycompany.gradle.WsimportTask) {
destDir = file("${buildDir}/generated")
}
compileJava.dependsOn(wsimport)
}
</code></pre>
<p>The subprojects itself should then only need to contain the following configuration:</p>
<p><strong>subproject build.gradle</strong></p>
<pre><code>buildscript {
wsimport {
wsdlUrls = [
"http://...endpoint1.wsdl",
"http://...endpoint2.wsdl"
]
}
}
</code></pre>
<p>On running gradle clean build on the main project, I get the following messages and Exception: </p>
<pre><code>:clean UP-TO-DATE
:Subproject:clean
:Subproject:wsimport
run wsimportfor http://endpoint1.wsdl
:Subproject:wsimport
* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':Subproject:wsimport'.
....
FAILED Caused by: org.gradle.api.internal.MissingMethodException: Could not find method ant() for arguments [com.mycompany.gradle.WsimportTask$_wsimport_closure1_closure2@16caac05] on task ':Subproject:wsimport'.
</code></pre>
<p>So gradle understands my configuration, applies the WSDL endpoint and calls my custom task. Then ant {} is evaluated to a local method call the method ant(), which doesn't exist. This makes perfect sense to me, but how can I achieve my goal of calling the actual ant wsimport task from within this custom gradle task?</p>
<hr>
<p><strong>Solution</strong> Thanks Peter for your answer. I think i do start to understand how the Task is getting wired into my build script. I paste the complete Task for future strugglers, as I don't think the whole process of creating such a task (especially the first time) is somewhat inscrutable:</p>
<pre><code>class WsimportTask extends DefaultTask {
def List<String> wsdlUrls
@OutputDirectory
File outDir
@TaskAction
def wsimport() {
wsdlUrls.each() {
def temp = it
println "run wsimport for "+ temp
project.sourceSets.main.output.classesDir.mkdirs()
outDir.mkdirs()
def classpath = project.configurations.jaxws.asPath
def destDir = project.sourceSets.main.output.classesDir
project.ant {
taskdef(name:'wsimport',
classname:'com.sun.tools.ws.ant.WsImport',
classpath:classpath)
wsimport(keep:true,
destdir: destDir,
sourcedestdir: outDir,
wsdl: temp)
}
}
}
}
</code></pre>
<p>Also notable is the fact that the task must not be defined within the buildscipt block of the build.gradle file, like Peter pointed out</p>
| 1 | 1,796 |
sendto: Network unreachable
|
<p>I have two machines I'm testing my code on, one works fine, the other I'm having some problems and I don't know why it is.</p>
<p>I'm using an object (C++) for the networking part of my project. On the server side, I do this: (error checking removed for clarity)</p>
<pre><code> res = getaddrinfo(NULL, port, &hints, &server)) < 0
for(p=server; p!=NULL; p=p->ai_next){
fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if(fd<0){
continue;
}
if(bind(fd, p->ai_addr, p->ai_addrlen)<0){
close(fd);
continue;
}
break;
}
</code></pre>
<p>This all works. I then make an object with this constructor</p>
<pre><code>net::net(int fd, struct sockaddr *other, socklen_t *other_len){
int counter;
this->fd = fd;
if(other != NULL){
this->other.sa_family = other->sa_family;
for(counter=0;counter<13;counter++)
this->other.sa_data[counter]=other->sa_data[counter];
}
else
cerr << "Networking error" << endl;
this->other_len = *other_len;
}
void net::gsend(string s){
if(sendto(this->fd, s.c_str(), s.size()+1, 0, &(this->other), this->other_len)<0){
cerr << "Error Sending, " << s << endl;
cerr << strerror(errno) << endl;
}
return;
}
string net::grecv(){
stringstream ss;
string s;
char buf[BUFSIZE];
buf[BUFSIZE-1] = '\0';
if(recvfrom(this->fd, buf, BUFSIZE-1, 0, &(this->other), &(this->other_len))<0){
cerr << "Error Recieving\n";
cerr << strerror(errno) << endl;
}
// convert to c++ string and if there are multiple trailing ';' remove them
ss << buf;
s=ss.str();
while(s.find(";;", s.size()-2) != string::npos)
s.erase(s.size()-1,1);
return s;
}
</code></pre>
<p>So my problem is, is that on one machine, everything works fine. On another, everything works fine until I call my server's gsend() function. In which I get a "Error: Network Unreachable." I call gercv() first before calling gsend() too. Can anyone help me? I would really appreciate it.</p>
<p>SOLUTION</p>
<p>It turns out that the server didn't like the way I set up the initial sockaddr structure. I was doing this:</p>
<pre><code> struct addrinfo hints;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE;
hints.ai_protocol = IPPROTO_UDP;
</code></pre>
<p>When it should have been like this</p>
<pre><code> struct addrinfo hints;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
</code></pre>
<p>Can anyone explain this?</p>
| 1 | 1,643 |
is there difference between dependencies and dependencies in plugin tags?
|
<p>I have a question.</p>
<p>In pom.xml, dependency is included in two places.
one place can be in <code><project></code> tag and the other place can be in <code><plugin></code> tag.</p>
<p>I think the dependencies in tags is just related with the plugin?
is it correct?</p>
<p>thanks in advance :)</p>
<pre><code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>clustered-queue</artifactId>
<packaging>jar</packaging>
<name>HornetQ JMS Clustered Queue Example</name>
<dependencies>
<dependency>
<groupId>org.hornetq.examples.jms</groupId>
<artifactId>hornetq-jms-examples-common</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.jms</groupId>
<artifactId>jboss-jms-api_1.1_spec</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.hornetq</groupId>
<artifactId>hornetq-maven-plugin</artifactId>
<executions>
<execution>
<id>start1</id>
<goals>
<goal>start</goal>
</goals>
<configuration>
<jndiPort>1199</jndiPort>
<jndiRmiPort>1198</jndiRmiPort>
<hornetqConfigurationDir>${basedir}/target/classes/hornetq/server1</hornetqConfigurationDir>
<fork>true</fork>
<systemProperties>
<property>
<name>udp-address</name>
<value>${udp-address}</value>
</property>
</systemProperties>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.hornetq</groupId>
<artifactId>hornetq-core-client</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.hornetq</groupId>
<artifactId>hornetq-server</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<configuration>
<waitOnStart>false</waitOnStart>
</configuration>
</plugin>
</plugins>
</build>
</project>
</code></pre>
| 1 | 1,900 |
Javascript function from external file not working
|
<p>I'm new to programming and currently learning javascript. I'm trying to test what I've learned so far using a payroll calculator, but my code is not working. I created a function that will be called when the user clicks a button; if I add the function inside the same HTML file, it works fine. When the function is in my external javascript file, the function doesn't work. I clicked on <em>View Page Source</em> to confirm the external javascript file was loaded and it was.</p>
<p><strong>HTML CODE</strong></p>
<pre><code><!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Payroll Calculator</title>
<meta name="viewport" contect="width=devide-width, user- scalable=no,initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/styles.css">
<link rel="stylesheet" href="css/myStyle.css">
</head>
<body>
<header>
<div class="container">
<div class="col-xs-12">
<h1>Payroll Calculator</h1>
</div>
</div>
</header>
<div class="container">
<section class="main row">
<article class="col-xs-12 col-sm-6 col-md-6">
<h3>Employee</h3>
<div class="input-group">
<span class="input-group-addon" id="firstName">First Name</span>
<input type="text" class="form-control" placeholder="First Name" aria-describedby="basic-addon1">
</div>
<br>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">Last Name</span>
<input type="text" class="form-control" placeholder="Last Name" aria-describedby="basic-addon1">
</div>
<br>
<div class="input-group">
<span class="input-group-addon" id="rate-type">Rate Type&nbsp</span>
&nbsp<input type="radio" name="optradio">Hourly
<input type="radio" name="optradio">Salary
</div>
<br>
<div class="input-group">
<span class="input-group-addon">Rate Amount</span>
<input type="text" class="form-control" aria-label="Amount (to the nearest dollar)">
<span class="input-group-addon">.00</span>
</div>
<br>
<label id="EnterHours" onclick="enterHours()">Enter Hours</label>
<br>
<p id="hours"></p>
<br>
<label id="EnterEarnings">Enter Earnings</label>
<br>
<p id="earnings"></p>
<br>
<button type="button" class="btn btn-default" onclick="enterHours()">Calculate</button>
<button type="button" class="btn btn-default">Cancel</button>
</article>
<aside class="col-xs-12 col-sm-6 col-md-6">
<h3 class="sidebar">Results</h3>
</aside>
</section>
</div>
<footer>
<div class="container" >
<h3>Andres Quintero</h3>
<p id="demo"></p>
</div>
</footer>
<script src="js/app2.js"></script>
</body>
</code></pre>
<p></p>
<p><strong>Javascript Code</strong></p>
<pre><code>$(document).ready(function(){
function enterHours(){
document.getElementById("hours").innerHTML = "This is a test";
}
}
</code></pre>
| 1 | 2,183 |
ASP.NET MVC Form - What is the proper way to return to a view with the previous form values?
|
<p>I had an assignment to implement a WCF Service and call it from a client of any type. I already have some experience with console, winform, WPF apps, so I wanted to use this as a chance to learn ASP.NET MVC. </p>
<p>I know that I'm not properly implementing the "M" part of it yet, but I'm wondering what the correct way of processing data on a form in order to update show a result would be instead of what I have (working) so far:</p>
<p>View:</p>
<pre><code>@using (Html.BeginForm("UseSimpleMathClient", "Home"))
{
<div style="width:450px">
<table style="width:100%">
<tr><td><h4>@Html.Label("First number", new { @for = "num1" })</h4></td> <td> @Html.TextBox("num1", ViewData["num1"])</td></tr>
<tr><td><h4>@Html.Label("Second number", new { @for = "num2" })</h4></td> <td> @Html.TextBox("num2", ViewData["num2"])</td></tr>
<tr>
<td colspan="2">
<h2 style="text-align:center">
<input type="submit" name="operation" value="+" />
<input type="submit" name="operation" value="-" />
<input type="submit" name="operation" value="*" />
<input type="submit" name="operation" value="÷" />
</h2>
</td>
</tr>
<tr>
<td colspan="2"><b>@Html.Label("Result")</b> &nbsp; @Html.TextBox("result", ViewData["result"], new {disabled = "disabled", style="min-width:80%;text-align:center" })</td>
</tr>
</table>
</div>
}
</code></pre>
<p>Controller:</p>
<pre><code> public ActionResult USeSimpleMathClient(char operation)
{
float num1, num2;
float? result = null;
if (!float.TryParse(Request.Form[0], out num1) || !float.TryParse(Request.Form[1], out num2))
{
ViewData["result"] = "Please enter valid numbers before selecting an operation.";
}
else
{
switch (operation)
{
case '+':
result = mathClient.Add(num1, num2);
break;
case '-':
result = mathClient.Subtract(num1, num2);
break;
case '*':
result = mathClient.Multiply(num1, num2);
break;
case '÷':
if (num2 != 0)
result = mathClient.Divide(num1, num2);
break;
default:
break;
}
ViewData["result"] = result != null ? String.Format("{0} {1} {2} = {3}", num1, operation, num2, result) : "You can't divide by zero!";
}
ViewData["num1"] = Request.Form[0];
ViewData["num2"] = Request.Form[1];
return View("Index");
}
</code></pre>
| 1 | 1,679 |
e2e testing in angularjs for page navigation
|
<p>I am writing e2e tests for my web app and stuck at the very beginning. I would appreciate any help to kick start my testing experience.</p>
<p>I am completely new to angularjs. So please bear with me.</p>
<p>I want to write a test that will check if we are on the landing page of the app. I am using jasmine and karma. </p>
<p>here is my config file
// Karma configuration</p>
<pre><code> module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '../',
// frameworks to use
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'source/assets/vendor/angular/angular.js',
'test/lib/angular-mocks.js',
'test/scripts/**/*.js',
'test/unit/**/*.js',
'test/e2e/**/*.js'
],
// list of files to exclude
exclude: [
],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// Start the browser, currently available:
browsers: ['Chrome'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
</code></pre>
<p>my mainscenario.js file.</p>
<pre><code> describe('appName', function() {
beforeEach(function() {
browser().navigateTo('../../source/views/home/landing.html');
});
it('should automatically redirect to landing page when location hash/fragment is empty', function() {
expect(browser().location().url()).toBe("/landing");
});
</code></pre>
<p>Well i cant post the screen shot of the error as it needs 10 reputation. But here is a description.</p>
<pre><code> AngularJS: Scenario Test Runner1 Errors0 Failures0 Passed
describe: appName
165ms should automatically redirect to landing page when location hash/fragment is empty
118ms browser navigate to '../../source/views/home/landing.html'
8ms $location.url()
http://localhost:8000/test/e2e/mainscenario.js:9:16
TypeError: Object [object Object] has no method 'injector'
at Object.<anonymous> (http://localhost:8000/test/lib/angular-scenario.js:27230:30)
...........blah blah
</code></pre>
<p>Thanks in advance.</p>
| 1 | 1,187 |
Why can't python find my file?
|
<p>So someone wrote a joke trapifier script (as in, 'Trap music') and I can't get it to work.</p>
<pre><code>usage: trapifier.py [-h] [--samples [SAMPLES]] inputfile outputfile
</code></pre>
<p>Yet, despite the folder looking like this</p>
<pre><code>ls -l
total 14288
-rwxrwxrwx 1 ________ ________ 7295612 Mar 2 2008 Chicago.mp3
-rwxr-xr-x@ 1 ________ ________ 1074 Apr 12 17:00 LICENSE
-rwxr-xr-x@ 1 ________ ________ 2871 Apr 12 17:00 README.md
-rwxr-xr-x@ 1 ________ ________ 6 Apr 12 17:00 requirements.txt
drwxr-xr-x@ 48 ________ ________ 1632 Apr 12 17:00 samples
-rwxr-xr-x 1 ________ ________ 2923 Apr 12 17:00 trapifier.py
</code></pre>
<p>This command always results in a [Errno 2] No such file or directory</p>
<pre><code>./trapifier.py Chicago.mp3 Chiraq.mp3
</code></pre>
<p>or</p>
<pre><code>python trapifier.py Chicago.mp3 Chiraq.mp3
</code></pre>
<p>or even</p>
<pre><code>./trapifier.py /full/path/to/Chicago.mp3 Chiraq.mp3
</code></pre>
<p>What gives? I feel like there is a rookie mistake somewhere.</p>
<p>The full error message by request:</p>
<pre><code> Traceback (most recent call last):
File "./trapifier.py", line 89, in <module>
overlay(parse())
File "./trapifier.py", line 32, in parse
base_track = pydub.AudioSegment.from_mp3(inputfile)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pydub/audio_segment.py", line 297, in from_mp3
return cls.from_file(file, 'mp3')
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pydub/audio_segment.py", line 284, in from_file
subprocess.call(convertion_command, stderr=open(os.devnull))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1249, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
</code></pre>
<p>Source of the script is hosted at <a href="https://github.com/japesinator/trapifier.py" rel="nofollow">https://github.com/japesinator/trapifier.py</a></p>
<p>I have all the required libraries (argparse, pydub, os, random).</p>
<p>First Useful Edit: It appears that pydub.AudioSegment failing to load is the culprit. However, things get stranger. In a python terminal I can do</p>
<pre><code>from pydub import AudioSegment
</code></pre>
<p>but I get a no such module error when I do</p>
<p>import pydub.AudioSegment</p>
| 1 | 1,053 |
Error when trying to run Polymer Starter Kit
|
<p>I'm trying to run the <a href="https://github.com/PolymerElements/polymer-starter-kit#getting-started" rel="nofollow">Polymer starter kit</a> but when I try to run 'gulp serve' (without the quotation) it opens the page on the browser, but it's not showing anything. </p>
<p>When I inspect the JS console, I'm getting the following errors:</p>
<p><a href="http://localhost:3000/bower_components/webcomponentsjs/webcomponents-lite.js" rel="nofollow">http://localhost:3000/bower_components/webcomponentsjs/webcomponents-lite.js</a> Failed to load resource: the server responded with a status of 404 (Not Found)
<a href="http://localhost:3000/bower_components/iron-flex-layout/classes/iron-flex-layout.html" rel="nofollow">http://localhost:3000/bower_components/iron-flex-layout/classes/iron-flex-layout.html</a> Failed to load resource: the server responded with a status of 404 (Not Found)
<a href="http://localhost:3000/bower_components/iron-icons/iron-icons.html" rel="nofollow">http://localhost:3000/bower_components/iron-icons/iron-icons.html</a> Failed to load resource: the server responded with a status of 404 (Not Found)
<a href="http://localhost:3000/bower_components/iron-pages/iron-pages.html" rel="nofollow">http://localhost:3000/bower_components/iron-pages/iron-pages.html</a> Failed to load resource: the server responded with a status of 404 (Not Found)
<a href="http://localhost:3000/bower_components/iron-selector/iron-selector.html" rel="nofollow">http://localhost:3000/bower_components/iron-selector/iron-selector.html</a> Failed to load resource: the server responded with a status of 404 (Not Found)
<a href="http://localhost:3000/bower_components/paper-drawer-panel/paper-drawer-panel.html" rel="nofollow">http://localhost:3000/bower_components/paper-drawer-panel/paper-drawer-panel.html</a> Failed to load resource: the server responded with a status of 404 (Not Found)
<a href="http://localhost:3000/bower_components/paper-header-panel/paper-header-panel.html" rel="nofollow">http://localhost:3000/bower_components/paper-header-panel/paper-header-panel.html</a> Failed to load resource: the server responded with a status of 404 (Not Found)
<a href="http://localhost:3000/bower_components/paper-icon-button/paper-icon-button.html" rel="nofollow">http://localhost:3000/bower_components/paper-icon-button/paper-icon-button.html</a> Failed to load resource: the server responded with a status of 404 (Not Found)
<a href="http://localhost:3000/bower_components/paper-item/paper-item.html" rel="nofollow">http://localhost:3000/bower_components/paper-item/paper-item.html</a> Failed to load resource: the server responded with a status of 404 (Not Found)
<a href="http://localhost:3000/bower_components/paper-material/paper-material.html" rel="nofollow">http://localhost:3000/bower_components/paper-material/paper-material.html</a> Failed to load resource: the server responded with a status of 404 (Not Found)
<a href="http://localhost:3000/bower_components/paper-menu/paper-menu.html" rel="nofollow">http://localhost:3000/bower_components/paper-menu/paper-menu.html</a> Failed to load resource: the server responded with a status of 404 (Not Found)
<a href="http://localhost:3000/bower_components/paper-styles/paper-styles-classes.html" rel="nofollow">http://localhost:3000/bower_components/paper-styles/paper-styles-classes.html</a> Failed to load resource: the server responded with a status of 404 (Not Found)
<a href="http://localhost:3000/bower_components/paper-toast/paper-toast.html" rel="nofollow">http://localhost:3000/bower_components/paper-toast/paper-toast.html</a> Failed to load resource: the server responded with a status of 404 (Not Found)
<a href="http://localhost:3000/bower_components/paper-toolbar/paper-toolbar.html" rel="nofollow">http://localhost:3000/bower_components/paper-toolbar/paper-toolbar.html</a> Failed to load resource: the server responded with a status of 404 (Not Found)
<a href="http://localhost:3000/bower_components/platinum-sw/platinum-sw-cache.html" rel="nofollow">http://localhost:3000/bower_components/platinum-sw/platinum-sw-cache.html</a> Failed to load resource: the server responded with a status of 404 (Not Found)
<a href="http://localhost:3000/bower_components/platinum-sw/platinum-sw-register.html" rel="nofollow">http://localhost:3000/bower_components/platinum-sw/platinum-sw-register.html</a> Failed to load resource: the server responded with a status of 404 (Not Found)
my-greeting.html:32 Uncaught ReferenceError: Polymer is not defined
my-list.html:27 Uncaught ReferenceError: Polymer is not defined
<a href="http://localhost:3000/bower_components/page/page.js" rel="nofollow">http://localhost:3000/bower_components/page/page.js</a> Failed to load resource: the server responded with a status of 404 (Not Found)</p>
<p>Any help would be appreciated. Thank you</p>
| 1 | 1,500 |
Detecting and Removing Vertical and Horizontal Lines in OpenCV
|
<p>I'm trying to remove the square boxes(vertical and horizontal lines) from a filled out form using opencv (Python). I am trying to detect the vertical and horizontal lines through morphological operations of OpenCV. <a href="https://i.stack.imgur.com/SkY8h.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SkY8h.jpg" alt="The original image"></a></p>
<p>After detecting the Vertical and Horizontal lines. <a href="https://i.stack.imgur.com/yFlF4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yFlF4.jpg" alt="Horizontal lines"></a></p>
<p>Vertical Lines <a href="https://i.stack.imgur.com/JynnN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JynnN.jpg" alt="result of vertical lines "></a></p>
<p>After the horizontal and vertical lines are detected , i am simply adding them and subtracting it from processed image.
<code>res = verticle_lines_img + horizontal_lines_img</code>
<code>exp = img_bin - res</code></p>
<p>The final results is not so smoothed as expected.
<a href="https://i.stack.imgur.com/wAteF.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wAteF.jpg" alt="Final image after removing H and V lines "></a></p>
<p>The full code for this is </p>
<pre><code># Read the image
img_for_box_extraction_path='aligned_filled.jpg'
img = cv2.imread(img_for_box_extraction_path, 0)
# Thresholding the image
(thresh, img_bin) = cv2.threshold(img, 128, 255,cv2.THRESH_BINARY|
cv2.THRESH_OTSU)
# Invert the image
img_bin = ~img_bin
cv2.imwrite("Image_bin.jpg",img_bin)
bw = cv2.adaptiveThreshold(img_bin, 255, cv2.ADAPTIVE_THRESH_MEAN_C, \
cv2.THRESH_BINARY, 15, -2)
horizontal = np.copy(bw)
vertical = np.copy(bw)
# Defining a kernel length for horizontal and vertical
cols = horizontal.shape[1]
horizontal_size = int(cols)
horizontalStructure = cv2.getStructuringElement(cv2.MORPH_RECT,
(horizontal_size, 1))
# Apply morphology operations
horizontal = cv2.erode(horizontal, horizontalStructure)
horizontal = cv2.dilate(horizontal, horizontalStructure)
rows = vertical.shape[0]
verticalsize = int(rows)
# Create structure element for extracting vertical lines through morphology
operations
verticalStructure = cv2.getStructuringElement(cv2.MORPH_RECT, (1,
verticalsize))
# Apply morphology operations
vertical = cv2.erode(vertical, verticalStructure)
vertical = cv2.dilate(vertical, verticalStructure)
#kernel_length = np.array(img).shape[1]//80
#kernel_length = 7
# A verticle kernel of (1 X kernel_length =6), which will detect all the
verticle lines from the image.
verticle_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 6))
# A horizontal kernel of (kernel_length=7 X 1), which will help to detect
all the horizontal line from the image.
hori_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 1))
# A kernel of (3 X 3) ones.
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
# Morphological operation to detect vertical lines from an image
img_temp1 = cv2.erode(img_bin, verticle_kernel, iterations=3)
verticle_lines_img = cv2.dilate(img_temp1, verticle_kernel, iterations=2)
cv2.imwrite("verticle_lines.jpg",verticle_lines_img)
# Morphological operation to detect horizontal lines from an image
img_temp2 = cv2.erode(img_bin, hori_kernel, iterations=3)
horizontal_lines_img = cv2.dilate(img_temp2, hori_kernel, iterations=2)
cv2.imwrite("horizontal_lines.jpg",verticle_lines_img)
res = verticle_lines_img + horizontal_lines_img
#fin = cv2.bitwise_and(img_bin, img_bin, mask = cv2.bitwise_not(res))
exp = img_bin - res
exp = ~exp
cv2.imwrite("final.jpg",exp)
</code></pre>
<p>What could be a novel way to detect and remove the square boxes?</p>
| 1 | 1,361 |
Using Hazelcast on Android gives random errors
|
<p>I'm trying to use Hazelcast on Android. I can include the dependency and the predefined "Hello World" will show up nicely without error. As soon as I put this code into my Activity (i.e. starting to use Hazelcast) it gives me an error:</p>
<p>Code:</p>
<pre><code>protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Config cfg = new Config();
HazelcastInstance instance = Hazelcast.newHazelcastInstance(cfg);
}
</code></pre>
<p>Stacktrace</p>
<pre><code>I/art: Rejecting re-init on previously-failed class java.lang.Class<android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper>: java.lang.NoClassDefFoundError: Failed resolution of: Landroid/view/View$OnUnhandledKeyEventListener;
at void android.support.v4.view.ViewCompat.setBackground(android.view.View, android.graphics.drawable.Drawable) (ViewCompat.java:2340)
at void android.support.v7.widget.ActionBarContainer.<init>(android.content.Context, android.util.AttributeSet) (ActionBarContainer.java:62)
at java.lang.Object java.lang.reflect.Constructor.newInstance0!(java.lang.Object[]) (Constructor.java:-2)
at java.lang.Object java.lang.reflect.Constructor.newInstance(java.lang.Object[]) (Constructor.java:430)
at android.view.View android.view.LayoutInflater.createView(java.lang.String, java.lang.String, android.util.AttributeSet) (LayoutInflater.java:652)
at android.view.View android.view.LayoutInflater.createViewFromTag(android.view.View, java.lang.String, android.content.Context, android.util.AttributeSet, boolean) (LayoutInflater.java:794)
at android.view.View android.view.LayoutInflater.createViewFromTag(android.view.View, java.lang.String, android.content.Context, android.util.AttributeSet) (LayoutInflater.java:734)
at void android.view.LayoutInflater.rInflate(org.xmlpull.v1.XmlPullParser, android.view.View, android.content.Context, android.util.AttributeSet, boolean) (LayoutInflater.java:865)
at void android.view.LayoutInflater.rInflateChildren(org.xmlpull.v1.XmlPullParser, android.view.View, android.util.AttributeSet, boolean) (LayoutInflater.java:828)
at android.view.View android.view.LayoutInflater.inflate(org.xmlpull.v1.XmlPullParser, android.view.ViewGroup, boolean) (LayoutInflater.java:525)
at android.view.View android.view.LayoutInflater.inflate(int, android.view.ViewGroup, boolean) (LayoutInflater.java:427)
I/art: at android.view.View android.view.LayoutInflater.inflate(int, android.view.ViewGroup) (LayoutInflater.java:378)
at android.view.ViewGroup android.support.v7.app.AppCompatDelegateImpl.createSubDecor() (AppCompatDelegateImpl.java:605)
at void android.support.v7.app.AppCompatDelegateImpl.ensureSubDecor() (AppCompatDelegateImpl.java:516)
at void android.support.v7.app.AppCompatDelegateImpl.setContentView(int) (AppCompatDelegateImpl.java:464)
at void android.support.v7.app.AppCompatActivity.setContentView(int) (AppCompatActivity.java:140)
at void nl.quintor.justanotherboardgame.MainActivity.onCreate(android.os.Bundle) (MainActivity.java:15)
at void android.app.Activity.performCreate(android.os.Bundle) (Activity.java:6955)
at void android.app.Instrumentation.callActivityOnCreate(android.app.Activity, android.os.Bundle) (Instrumentation.java:1126)
at android.app.Activity android.app.ActivityThread.performLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent) (ActivityThread.java:2927)
at void android.app.ActivityThread.handleLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent, java.lang.String) (ActivityThread.java:3045)
at void android.app.ActivityThread.-wrap14(android.app.ActivityThread, android.app.ActivityThread$ActivityClientRecord, android.content.Intent, java.lang.String) (ActivityThread.java:-1)
at void android.app.ActivityThread$H.handleMessage(android.os.Message) (ActivityThread.java:1642)
at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:102)
at void android.os.Looper.loop() (Looper.java:154)
at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:6776)
at java.lang.Object java.lang.reflect.Method.invoke!(java.lang.Object, java.lang.Object[]) (Method.java:-2)
at void com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run() (ZygoteInit.java:1496)
at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:1386)
Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.View$OnUnhandledKeyEventListener" on path: DexPathList[[zip file "/data/app/nl.quintor.justanotherboardgame-2/base.apk", zip file "/data/app/nl.quintor.justanotherboardgame-2/split_lib_dependencies_apk.apk", zip file "/data/app/nl.quintor.justanotherboardgame-2/split_lib_slice_0_apk.apk", zip file "/data/app/nl.quintor.justanotherboardgame-2/split_lib_slice_1_apk.apk", zip file "/data/app/nl.quintor.justanotherboardgame-2/split_lib_slice_2_apk.apk", zip file "/data/app/nl.quintor.justanotherboardgame-2/split_lib_slice_3_apk.apk", zip file "/data/app/nl.quintor.justanotherboardgame-2/split_lib_slice_4_apk.apk", zip file "/data/app/nl.quintor.justanotherboardgame-2/split_lib_slice_5_apk.apk", zip file "/data/app/nl.quintor.justanotherboardgame-2/split_lib_slice_6_apk.apk", zip file "/data/app/nl.quintor.justanotherboardgame-2/split_lib_slice_7_apk.apk", zip file "/data/app/nl.quintor.justanotherboardgame-2/split_lib_slice_8_apk.apk",
at java.lang.Class dalvik.system.BaseDexClassLoader.findClass(java.lang.String) (BaseDexClassLoader.java:56)
at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String, boolean) (ClassLoader.java:380)
at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String) (ClassLoader.java:312)
at void android.support.v4.view.ViewCompat.setBackground(android.view.View, android.graphics.drawable.Drawable) (ViewCompat.java:2340)
at void android.support.v7.widget.ActionBarContainer.<init>(android.content.Context, android.util.AttributeSet) (ActionBarContainer.java:62)
at java.lang.Object java.lang.reflect.Constructor.newInstance0!(java.lang.Object[]) (Constructor.java:-2)
at java.lang.Object java.lang.reflect.Constructor.newInstance(java.lang.Object[]) (Constructor.java:430)
at android.view.View android.view.LayoutInflater.createView(java.lang.String, java.lang.String, android.util.AttributeSet) (LayoutInflater.java:652)
at android.view.View android.view.LayoutInflater.createViewFromTag(android.view.View, java.lang.String, android.content.Context, android.util.AttributeSet, boolean) (LayoutInflater.java:794)
at android.view.View android.view.LayoutInflater.createViewFromTag(android.view.View, java.lang.String, android.content.Context, android.util.AttributeSet) (LayoutInflater.java:734)
at void android.view.LayoutInflater.rInflate(org.xmlpull.v1.XmlPullParser, android.view.View, android.content.Context, android.util.AttributeSet, boolean) (LayoutInflater.java:865)
at void android.view.LayoutInflater.rInflateChildren(org.xmlpull.v1.XmlPullParser, android.view.View, android.util.AttributeSet, boolean) (LayoutInflater.java:828)
at android.view.View android.view.LayoutInflater.inflate(org.xmlpull.v1.XmlPullParser, android.view.ViewGroup, boolean) (LayoutInflater.java:525)
at android.view.View android.view.LayoutInflater.inflate(int, android.view.ViewGroup, boolean) (LayoutInflater.java:427)
at android.view.View android.view.LayoutInflater.inflate(int, android.view.ViewGroup) (LayoutInflater.java:378)
at android.view.ViewGroup android.support.v7.app.AppCompatDelegateImpl.createSubDecor() (AppCompatDelegateImpl.java:605)
at void android.support.v7.app.AppCompatDelegateImpl.ensureSubDecor() (AppCompatDelegateImpl.java:516)
at void android.support.v7.app.AppCompatDelegateImpl.setContentView(int) (AppCompatDelegateImpl.java:464)
at void android.support.v7.app.AppCompatActivity.setContentView(int) (AppCompatActivity.java:140)
at void nl.quintor.justanotherboardgame.MainActivity.onCreate(android.os.Bundle) (MainActivity.java:15)
at void android.app.Activity.performCreate(android.os.Bundle) (Activity.java:6955)
at void android.app.Instrumentation.callActivityOnCreate(android.app.Activity, android.os.Bundle) (Instrumentation.java:1126)
at android.app.Activity android.app.ActivityThread.performLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent) (ActivityThread.java:2927)
at void android.app.ActivityThread.handleLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent, java.lang.String) (ActivityThread.java:3045)
at void android.app.ActivityThread.-wrap14(android.app.ActivityThread, android.app.ActivityThread$ActivityClientRecord, android.content.Intent, java.lang.String) (ActivityThread.java:-1)
at void android.app.ActivityThread$H.handleMessage(android.os.Message) (ActivityThread.java:1642)
at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:102)
at void android.os.Looper.loop() (Looper.java:154)
at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:6776)
at java.lang.Object java.lang.reflect.Method.invoke!(java.lang.Object, java.lang.Object[]) (Method.java:-2)
at void com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run() (ZygoteInit.java:1496)
at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:1386)
</code></pre>
<p>It can't seem to find some classes which are always working and are part of the Android Library. When I try to find the code I can find it. When I remove the instance creation of Hazelcast there is no problem either..</p>
<p>Anybody has an idea what this problem might be?</p>
<p>Thanks in advance!</p>
| 1 | 3,841 |
Adding a module in WildFly 8.2.0 Final release
|
<p>I am new in JBoss and I try to add a jdbc driver for derby as a module in WidlFly 8.2.0.</p>
<p>What I did: </p>
<ul>
<li>I added the org/apache/derby/main folder in the JBOSS_HOME/modules/system/layers/base directory</li>
<li>In this new folder, I added derbyclient.jar (from jdk 1.8.0_40, it contains the driver) and a new <code>module.xml</code> file.</li>
</ul>
<p>The <code>module.xml</code> file is as follows: </p>
<pre><code> <?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.0" name="org.apache.derby">
<resources>
<resource-root path="derbyclient.jar"/>
</resources>
<dependencies>
<module name="javax.api"/>
</dependencies>
</module>
</code></pre>
<p>Then, I updated the <code>standalone.xml</code> file as follows:</p>
<ul>
<li>addition of this tag (in <code><extensions></code>): <code><extension module="org.apache.derby"/></code></li>
</ul>
<p>Declaration of my datasource and of the driver: </p>
<pre><code><datasource jndi-name="java:/DerbyDS" pool-name="DerbyDS" enabled="true" use-ccm="false">
<connection-url>jdbc:derby:MyDB;create=true</connection-url>
<driver>org.apache.derby</driver>
<security>
<user-name>demo</user-name>
<password>demo</password>
</security>
<validation>
<validate-on-match>false</validate-on-match>
<background-validation>false</background-validation>
</validation>
<statement>
<share-prepared-statements>false</share-prepared-statements>
</statement>
</datasource>
<drivers>
<driver name="org.apache.derby" module="org.apache.derby">
<xa-datasource-class>org.apache.derby.jdbc.ClientXADataSource</xa-datasource-class>
</driver>
<driver name="h2" module="com.h2database.h2">
<xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
</driver>
</drivers>
</code></pre>
<p>I am getting the following error when I start <code>WildFly</code>:</p>
<pre><code>`16:19:49,856 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) JBAS014613: Operation ("add") failed - address: ([
("subsystem" => "datasources"),
("data-source" => "DerbyDS")
]) - failure description: {"JBAS014771: Services with missing/unavailable dependencies" => [
"jboss.data-source.java:/DerbyDS is missing [jboss.jdbc-driver.org_apache_derby]",
"jboss.driver-demander.java:/DerbyDS is missing [jboss.jdbc-driver.org_apache_derby]"
]}
16:19:49,866 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) JBAS014613: Operation ("add") failed - address: ([
("subsystem" => "datasources"),
("data-source" => "DerbyDS")
]) - failure description: {
"JBAS014771: Services with missing/unavailable dependencies" => [
"jboss.data-source.java:/DerbyDS is missing [jboss.jdbc-driver.org_apache_derby]",
"jboss.driver-demander.java:/DerbyDS is missing [jboss.jdbc-driver.org_apache_derby]"
],
"JBAS014879: One or more services were unable to start due to one or more indirect dependencies not being available." => {
"Services that were unable to start:" => [
"jboss.data-source.reference-factory.DerbyDS",
"jboss.naming.context.java.DerbyDS"
],
"Services that may be the cause:" => ["jboss.jdbc-driver.org_apache_derby"]
}
}
16:19:49,897 INFO [org.jboss.as.server] (ServerService Thread Pool -- 28) JBAS018559: Deployed "MyApp.ear" (runtime-name : "MyApp.ear")
16:19:49,897 INFO [org.jboss.as.server] (ServerService Thread Pool -- 28) JBAS018559: Deployed "MyApp2.ear" (runtime-name : "MyApp2.ear")
16:19:49,907 INFO [org.jboss.as.controller] (Controller Boot Thread) JBAS014774: Service status report
JBAS014775: New missing/unsatisfied dependencies:
service jboss.jdbc-driver.org_apache_derby (missing) dependents: [service jboss.driver-demander.java:/DerbyDS, service jboss.data-source.java:/DerbyDS]`
</code></pre>
<p>Do you know what I did wrong? </p>
<p>Thanks in advance</p>
| 1 | 1,845 |
Page accessible only if logged in
|
<p>Hello Stackoverflowers</p>
<p>Im new to PHP and im trying to make a members area for my testpage. I have made a successful register and login page, but now when I changed the code so if I log in correctly it redirects my to a page, and if I log in with wrong information it send me to a different page. However the members area is accessible if you type the location in the address-bar. Now, here's what I need help with, When someone tries to access that location without being logged in it should say "Access denied" but when you log in, it should redirect you to the members area and all it content is shown.</p>
<p>Here is my code:</p>
<p>login.php</p>
<pre><code><?php
session_start();
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'Data';
mysql_connect($host, $user, $pass);
mysql_select_db($db);
if(isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM Project WHERE username='$username' AND password='$password' LIMIT 1";
$res = mysql_query($sql);
if (mysql_num_rows($res) == 1){
header("Location: loggedin.php");
exit();
} else {
echo 'Anv&auml;ndarnamn eller l&ouml;senord st&auml;mmer ej med informationen i databasen, var sn&auml;ll f&ouml;rs&ouml;k igen <br>';
echo '<a href="login.php">G&aring; tillbaka</a> Eller <a href="signup.php">Registrera dig</a>';
exit();
}
}
?>
<html>
<head>
<meta charset="UTF-8">
<title>Logga in</title>
<script src="js/prefixfree.min.js"></script>
</head>
<body>
<div class="body"></div>
<div class="grad"></div>
<div class="wrapper">
<div class="header">
<div>bababa<span>bababa</span></div>
</div>
<br>
<div class="login">
<form method="post" action="login.php">
<input type="text" placeholder="Anv&auml;ndarnamn" name="username" required><br>
<input type="password" placeholder="L&ouml;senord" name="password" required><br>
<input type="submit" value="Logga in">
</form>
</div>
</div>
<script src='http://codepen.io/assets/libs/fullpage/jquery.js'></script>
</body>
</html>
</code></pre>
<p>signup.php</p>
<pre><code><!DOCTYPE HTML>
<html lang="sv">
<head>
<link href='http://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript" >
$(".name").focus(function(){
$(".name-help").slideDown(500);
}).blur(function(){
$(".name-help").slideUp(500);
});
$(".email").focus(function(){
$(".email-help").slideDown(500);
}).blur(function(){
$(".email-help").slideUp(500);
});
</script>
</head>
<div class="wrapper">
<h1>Registrera er h&auml;r</h1>
<p>Detta &auml;r ett test-formul&auml;r f&ouml;r Webbutvecklingsprojektet. Skriv ditt namn h&auml;r
under och om allt funkar r&auml;tt skall systemet lagra ditt namn i en MySQL databas.</p>
<form class="form" name="form" method="post" action="add.php">
<input type="text" id="username" name="username" placeholder="Anv&auml;ndarnamn" required>
<input type="password" id="password" name="password" placeholder="L&ouml;senord" required>
<input type="email" id="email" name="email" placeholder="E-mail" required>
<input type="submit" class="submit" value="Registrera dig">
</form>
<h3>
Allm&auml;nt & regler:
</h3>
<ul>
<li>Maximalt 2GB Lagring</li>
<li>Du m&aring;ste skriva f&ouml;r- och efternamn</li>
<li>Databasen lagrar bara upp till 60 anv&auml;ndare</li>
</ul>
</div>
<p class="optimize">
</p>
</html>
</code></pre>
<p>And last: loggedin.php</p>
<pre><code> <?php
session_start();
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'Data';
mysql_connect($host, $user, $pass);
mysql_select_db($db);
if(!isset($_SESSION['username'])) {
die("Please login");
} else {
echo 'Du &auml;r inloggad';
}
?>
</code></pre>
<p>FTR: I tried the if isset but even when I logged in correctly the same message shows up: Please log in, how should I fix this?</p>
<p>Im a newbie at this so help me a bit extra</p>
<p>Thank you!</p>
| 1 | 2,155 |
Execution failed for task ':app:artifactoryPublish'
|
<p>I followed this guide on how to set up a private maven repo:
(<a href="https://inthecheesefactory.com/blog/how-to-setup-private-maven-repository/en" rel="nofollow noreferrer">https://inthecheesefactory.com/blog/how-to-setup-private-maven-repository/en</a>).</p>
<p>But when I run the following command:</p>
<pre><code>gradlew.bat assembleRelease artifactoryPublish
</code></pre>
<p>I get this output:</p>
<pre><code>* What went wrong:
Execution failed for task ':app:artifactoryPublish'.
> File 'C:\Android\Artifact\app\build\outputs\aar\artifact-release.aar' does not exist,
and need to be published from publication aar
</code></pre>
<p>Running it with the --stacktrace flag</p>
<pre><code>* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:artifactoryPublish'.
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:84)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:55)
at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:46)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:51)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:236)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:228)
at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:61)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:228)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:215)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:77)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:58)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:32)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:113)
at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:196)
at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:193)
at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:193)
at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:44)
at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:29)
at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
at org.gradle.util.Swapper.swap(Swapper.java:38)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
Caused by: org.gradle.api.GradleException: File 'C:\Android\Artifact\app\build\outputs\aar\artifact-release.aar' does not exist, and need to be published from publication aar
at org.jfrog.gradle.plugin.artifactory.task.helper.TaskHelperPublications.createBuilder(TaskHelperPublications.java:253)
at org.jfrog.gradle.plugin.artifactory.task.helper.TaskHelperPublications.getArtifactDeployDetails(TaskHelperPublications.java:225)
at org.jfrog.gradle.plugin.artifactory.task.helper.TaskHelperPublications.collectDescriptorsAndArtifactsForUpload(TaskHelperPublications.java:147)
at org.jfrog.gradle.plugin.artifactory.task.ArtifactoryTask.collectDescriptorsAndArtifactsForUpload(ArtifactoryTask.java:70)
at org.jfrog.gradle.plugin.artifactory.task.BuildInfoBaseTask.prepareAndDeploy(BuildInfoBaseTask.java:367)
at org.jfrog.gradle.plugin.artifactory.task.BuildInfoBaseTask.collectProjectBuildInfo(BuildInfoBaseTask.java:129)
at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.doExecute(DefaultTaskClassInfoStore.java:141)
at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:123)
at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:632)
at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:615)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:95)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:76)
... 70 mor
</code></pre>
<p>The build.gradle file:</p>
<pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
classpath "org.jfrog.buildinfo:build-info-extractor-gradle:4.0.1"
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
</code></pre>
<p>and the app.gradle file:</p>
<pre><code>apply plugin: 'com.android.application'
apply plugin: 'com.jfrog.artifactory'
apply plugin: 'maven-publish'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "no.omega.artifact"
minSdkVersion 21
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
}
def libraryGroupId = 'no.omega'
def libraryArtifactId = 'artifact'
def libraryVersion = '1.0.0'
publishing {
publications {
aar(MavenPublication) {
groupId libraryGroupId
version libraryVersion
artifactId libraryArtifactId
artifact("$buildDir/outputs/aar/${artifactId}-release.aar")
}
}
}
artifactory {
contextUrl = 'http://*********:8081/artifactory'
publish {
repository {
repoKey = 'libs-release-local'
username = artifactory_username
password = artifactory_password
}
defaults {
publications('aar')
publishArtifacts = true
properties = ['qa.level': 'basic', 'q.os': 'android', 'dev.team': 'core']
publishPom = true
}
}
}
</code></pre>
<p>The project is just a Hello World generated by Android Studio. I am on a Windows 10 machine running Android Studio 2.3.</p>
<p>What am I doing wrong?</p>
| 1 | 4,994 |
Why not getting Android Firebase FCM registration token?
|
<p>I'm trying to send a push notification to my app from my app server but i'm not getting the FCM registration token through <code>FirebaseInstanceIdService</code>. Here i'm using Genymotion personal edition emulator.is that problem with my emulators API?</p>
<p>here is FirebaseInstanceIdService</p>
<pre><code>public class FcmInstanceIdService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
String recent_token = FirebaseInstanceId.getInstance().getToken();
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(getString(R.string.FCM_PREF), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(getString(R.string.FCM_TOKEN),recent_token);
editor.commit();
}
</code></pre>
<p>}
here is MainActivity</p>
<pre><code>public class MainActivity extends AppCompatActivity {
String url = "http://myurl.fcm_insert.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt = (Button) findViewById(R.id.button2);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(getString(R.string.FCM_PREF), Context.MODE_PRIVATE);
final String token = sharedPreferences.getString(getString(R.string.FCM_TOKEN),"");
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this,"Success",Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Response",error.toString());
Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_SHORT).show();
}
})
{
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("token",token);
return params;
}
} ;
Singletone.getSingletone(MainActivity.this).addToRequest(stringRequest);
}
});
}
}
</code></pre>
<p>it's only sending the default value to the server.</p>
| 1 | 1,081 |
Refresh v-model
|
<p>I'm developing question paper application.
<img src="https://i.stack.imgur.com/wPpKx.png" alt="enter image description here"></p>
<p>Once I type a question and hit the "+" button, the question goes to the question paper array and counter increased by one.
The problem is after I hit the "+" button, then also the question which I have entered previously is still in the fields of the UI. <strong>Because of I use v-model to bind the data fields.</strong></p>
<p>What I want is a method to clear those previous question data in UI.
This is something similar to reset button function.</p>
<pre class="lang-html prettyprint-override"><code><template>
<div>
<div class="container" v-if="counter<=5">
<h2>Question {{counter}}</h2><hr>
<textarea rows="7" cols="75" v-model="question"></textarea><br><br>
1. Answer <input type="text" v-model="answer1"> <input type="radio" name="q1answer" value="1" v-model="correctAnswer"><br><br>
2. Answer <input type="text" v-model="answer2"> <input type="radio" name="q1answer" value="2" v-model="correctAnswer"><br><br>
3. Answer <input type="text" v-model="answer3"> <input type="radio" name="q1answer" value="3" v-model="correctAnswer"><br><br>
4. Answer <input type="text" v-model="answer4"> <input type="radio" name="q1answer" value="4" v-model="correctAnswer"><br>
<hr>
Knowledge Area <select v-model="knowledgeArea">
<option value="Maths">Mathematics</option>
<option value="Language">Language Skills</option>
<option value="gk">General Knowledge</option>
<option value="other">Other</option>
</select><br><br>
<button type="button" class="btn" @click="pushToArray" >
<span class="glyphicon glyphicon-plus"></span></button>
</div>
<div v-if="counter>5">
<button type="button" class="btn btn-primary" @click="onSubmit">Save Question Paper</button>
</div>
</div>
</template>
</code></pre>
<pre class="lang-js prettyprint-override"><code><script>
import axios from 'axios';
var questionPaper = [];
export default {
data () {
return {
question:'',
answer1:'',
answer2:'',
answer3:'',
answer4:'',
correctAnswer:'',
knowledgeArea:'',
counter:1,
show:true
}
},
methods: {
onSubmit () {
},
pushToArray(){
const formData = {
question: this.question,
correctAnswer: this.correctAnswer,
answer1: this.answer1,
answer2: this.answer2,
answer3: this.answer3,
answer4: this.answer4,
knowledgeArea:this.knowledgeArea
}
this.counter++;
questionPaper.push(formData);
}
}
}
</script>
</code></pre>
| 1 | 1,349 |
Pandas - Add mean, max, min as columns in dataframe
|
<p>I have a <code>df =</code></p>
<pre><code> statistics s_values
year
1999 cigarette use 100
1999 cellphone use 310
1999 internet use 101
1999 alcohol use 100
1999 soda use 215
2000 cigarette use 315
2000 cellphone use 317
2000 internet use 325
2000 alcohol use 108
2000 soda use 200
2001 cigarette use 122
2001 cellphone use 311
2001 internet use 112
2001 alcohol use 144
2001 soda use 689
</code></pre>
<p>I calculated the max, min and mean based on the <code>year</code> <code>index</code> and <code>statistics</code> <code>column</code>.</p>
<p>I want to insert the mean, max and min as columns in the data frame where the output result looks like this</p>
<p>my desired output:</p>
<pre><code> statistics s_values mean min max
year
1999 alcohol use 100.0 104.0 100.0 108.0
1999 cellphone use 310.0 313.5 310.0 317.0
1999 cigarette use 100.0 207.5 100.0 315.0
1999 internet use 101.0 213.0 101.0 325.0
1999 soda use 215.0 207.5 200.0 215.0
2000 alcohol use 108.0 104.0 100.0 108.0
2000 cellphone use 317.0 313.5 310.0 317.0
2000 cigarette use 315.0 207.5 100.0 315.0
2000 internet use 325.0 213.0 101.0 325.0
2000 soda use 200.0 207.5 200.0 215.0
2001 alcohol use 144.0 104.0 100.0 108.0
2001 cellphone use 311.0 313.5 310.0 317.0
2001 cigarette use 122.0 207.5 100.0 315.0
2001 internet use 112.0 213.0 101.0 325.0
2001 soda use 689.0 207.5 200.0 215.0
</code></pre>
<p>I tried to do the following but values in the columns are all <code>NaN</code></p>
<pre><code>gen_mean = df.groupby('statistics').mean()
gen_min = df.groupby('statistics').min()
gen_max = df.groupby('statistics').max()
df.insert(2, 'Gen Avg', gen_mean)
df.insert(3, 'Gen Max', gen_max)
df.insert(4, 'Gen Min', gen_min)
</code></pre>
<p>Thank you</p>
| 1 | 1,046 |
How to fix in Unity "A failure occurred while executing com.android.build.gradle.internal.tasks.workers$actionfacade"
|
<p>I am working with adMob mediation in Unity. I have integrated inMobi and Unity ads network. After integrating them I am getting the following error "A failure occurred while executing com.android.build.gradle.internal.tasks.workers$actionfacade". Without integrating inMobi and Unity ads the build is successful. I just don't understand what is the problem</p>
<p>I looked up to a similar question in Unity forum <a href="https://forum.unity.com/threads/a-failure-occurred-while-executing-com-android-build-gradle-internal-tasks-workers-actionfacade.958112/" rel="nofollow noreferrer">https://forum.unity.com/threads/a-failure-occurred-while-executing-com-android-build-gradle-internal-tasks-workers-actionfacade.958112/</a> and tried solving by correctly entering the password,restarting Unity, creating seperate build file folder,etc but unfortunately nothing is working.</p>
<p>I saw similar question in stackOverflow, but they were for flutter,Cordova,etc and not Unity<a href="https://i.stack.imgur.com/HOrVX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HOrVX.png" alt="ScreenShot of the error" /></a></p>
<p>Some of the content of the Editor Log file near the error:</p>
<pre><code>Note: C:\Users\cheth\FlutteringBirds1\Temp\gradleOut\unityLibrary\src\main\java\com\unity3d\player\UnityPlayerActivity.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
D8: Cannot fit requested classes in a single dex file (# methods: 70023 > 65536)
com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:
The number of method references in a .dex file cannot exceed 64K.
Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html
at com.android.builder.dexing.D8DexArchiveMerger.getExceptionToRethrow(D8DexArchiveMerger.java:132)
at com.android.builder.dexing.D8DexArchiveMerger.mergeDexArchives(D8DexArchiveMerger.java:119)
at com.android.build.gradle.internal.transforms.DexMergerTransformCallable.call(DexMergerTransformCallable.java:102)
at com.android.build.gradle.internal.tasks.DexMergingTaskRunnable.run(DexMergingTask.kt:445)
at com.android.build.gradle.internal.tasks.Workers$ActionFacade.run(Workers.kt:348)
at org.gradle.workers.internal.AdapterWorkAction.execute(AdapterWorkAction.java:50)
at org.gradle.workers.internal.DefaultWorkerServer.execute(DefaultWorkerServer.java:47)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1$1.create(NoIsolationWorkerFactory.java:65)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1$1.create(NoIsolationWorkerFactory.java:61)
at org.gradle.internal.classloader.ClassLoaderUtils.executeInClassloader(ClassLoaderUtils.java:98)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1.execute(NoIsolationWorkerFactory.java:61)
at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:44)
at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:41)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
at org.gradle.workers.internal.AbstractWorker.executeWrappedInBuildOperation(AbstractWorker.java:41)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1.execute(NoIsolationWorkerFactory.java:56)
at org.gradle.workers.internal.DefaultWorkerExecutor$3.call(DefaultWorkerExecutor.java:215)
at org.gradle.workers.internal.DefaultWorkerExecutor$3.call(DefaultWorkerExecutor.java:210)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runExecution(DefaultConditionalExecutionQueue.java:215)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runBatch(DefaultConditionalExecutionQueue.java:164)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.run(DefaultConditionalExecutionQueue.java:131)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
at java.lang.Thread.run(Thread.java:748)
Caused by: com.android.tools.r8.CompilationFailedException: Compilation failed to complete
at com.android.tools.r8.utils.O.a(:65)
at com.android.tools.r8.D8.run(:11)
at com.android.builder.dexing.D8DexArchiveMerger.mergeDexArchives(D8DexArchiveMerger.java:117)
... 34 more
Caused by: com.android.tools.r8.utils.b: Error: null, Cannot fit requested classes in a single dex file (# methods: 70023 > 65536)
at com.android.tools.r8.utils.y0.a(:21)
at com.android.tools.r8.dex.K.a(:56)
at com.android.tools.r8.dex.K$h.a(:5)
at com.android.tools.r8.dex.b.b(:15)
at com.android.tools.r8.dex.b.a(:38)
at com.android.tools.r8.D8.d(:87)
at com.android.tools.r8.D8.b(:1)
at com.android.tools.r8.utils.O.a(:30)
... 36 more
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':launcher:mergeDexRelease'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
> com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:
The number of method references in a .dex file cannot exceed 64K.
Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 38s
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8
0x00007ff67f67736c (Unity) StackWalker::GetCurrentCallstack
0x00007ff67f67d509 (Unity) StackWalker::ShowCallstack
0x00007ff67fe6f193 (Unity) GetStacktrace
0x00007ff680d705ba (Unity) DebugStringToFile
0x00007ff67f80750d (Unity) DebugLogHandler_CUSTOM_Internal_Log
0x000001e5a38a2f0b (Mono JIT Code) (wrapper managed-to-native) UnityEngine.DebugLogHandler:Internal_Log (UnityEngine.LogType,UnityEngine.LogOption,string,UnityEngine.Object)
0x000001e5a38a2e5b (Mono JIT Code) UnityEngine.DebugLogHandler:LogFormat (UnityEngine.LogType,UnityEngine.Object,string,object[])
0x000001e5a38a28d0 (Mono JIT Code) UnityEngine.Logger:Log (UnityEngine.LogType,object)
0x000001e5a38a2795 (Mono JIT Code) UnityEngine.Debug:LogError (object)
0x000001e65b81a623 (Mono JIT Code) UnityEditor.Android.GradleInvokationException:ParseAndShowException ()
0x000001e7272b2cf3 (Mono JIT Code) UnityEditor.Android.PostProcessor.PostProcessRunner:RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext)
0x000001e6a04ee4ab (Mono JIT Code) UnityEditor.Android.PostProcessAndroidPlayer:PostProcess (UnityEditor.BuildTarget,string,string,string,string,string,string,UnityEditor.BuildOptions,UnityEditor.RuntimeClassRegistry,UnityEditor.Build.Reporting.BuildReport)
0x000001e6a050f94b (Mono JIT Code) UnityEditor.Android.AndroidBuildPostprocessor:PostProcess (UnityEditor.Modules.BuildPostProcessArgs,UnityEditor.BuildProperties&)
0x000001e6a050f291 (Mono JIT Code) UnityEditor.PostprocessBuildPlayer:Postprocess (UnityEditor.BuildTargetGroup,UnityEditor.BuildTarget,string,string,string,int,int,UnityEditor.BuildOptions,UnityEditor.RuntimeClassRegistry,UnityEditor.Build.Reporting.BuildReport)
0x000001e6a050f589 (Mono JIT Code) (wrapper runtime-invoke) <Module>:runtime_invoke_void_int_int_object_object_object_int_int_int_object_object (object,intptr,intptr,intptr)
0x00007fff733fe640 (mono-2.0-bdwgc) [mini-runtime.c:2812] mono_jit_runtime_invoke
0x00007fff73382ad2 (mono-2.0-bdwgc) [object.c:2921] do_runtime_invoke
0x00007fff7338bb2f (mono-2.0-bdwgc) [object.c:2968] mono_runtime_invoke
0x00007ff67f5c2be4 (Unity) scripting_method_invoke
0x00007ff67f5be251 (Unity) ScriptingInvocation::Invoke
0x00007ff680e83321 (Unity) CallMono
0x00007ff680e8991d (Unity) PostprocessPlayer
0x00007ff680e857d3 (Unity) DoBuildPlayer_PostBuild
0x00007ff680e84370 (Unity) DoBuildPlayer
0x00007ff680e79e45 (Unity) BuildPlayer
0x00007ff680458a05 (Unity) BuildPipeline::BuildPlayerInternalNoCheck
0x00007ff68042b5ac (Unity) BuildPipeline_CUSTOM_BuildPlayerInternalNoCheck
0x000001e72728408a (Mono JIT Code) (wrapper managed-to-native) UnityEditor.BuildPipeline:BuildPlayerInternalNoCheck (string[],string,string,UnityEditor.BuildTargetGroup,UnityEditor.BuildTarget,UnityEditor.BuildOptions,string[],bool)
0x000001e72728386b (Mono JIT Code) UnityEditor.BuildPlayerWindow/DefaultBuildMethods:BuildPlayer (UnityEditor.BuildPlayerOptions)
0x000001e7272806db (Mono JIT Code) UnityEditor.BuildPlayerWindow:CallBuildMethods (bool,UnityEditor.BuildOptions)
0x000001e72718bf93 (Mono JIT Code) UnityEditor.BuildPlayerWindow:GUIBuildButtons (UnityEditor.Modules.IBuildWindowExtension,bool,bool,bool,UnityEditor.Build.BuildPlatform)
0x000001e727174003 (Mono JIT Code) UnityEditor.BuildPlayerWindow:ShowBuildTargetSettings ()
0x000001e727165acb (Mono JIT Code) UnityEditor.BuildPlayerWindow:OnGUI ()
0x000001e6bf072b73 (Mono JIT Code) UnityEditor.HostView:InvokeOnGUI (UnityEngine.Rect,UnityEngine.Rect)
0x000001e6bf0728e3 (Mono JIT Code) UnityEditor.DockArea:DrawView (UnityEngine.Rect,UnityEngine.Rect)
0x000001e6bf0679d3 (Mono JIT Code) UnityEditor.DockArea:OldOnGUI ()
0x000001e554868108 (Mono JIT Code) UnityEngine.UIElements.IMGUIContainer:DoOnGUI (UnityEngine.Event,UnityEngine.Matrix4x4,UnityEngine.Rect,bool,UnityEngine.Rect,System.Action,bool)
0x000001e5548e56db (Mono JIT Code) UnityEngine.UIElements.IMGUIContainer:HandleIMGUIEvent (UnityEngine.Event,UnityEngine.Matrix4x4,UnityEngine.Rect,System.Action,bool)
0x000001e7271576bb (Mono JIT Code) UnityEngine.UIElements.IMGUIContainer:HandleIMGUIEvent (UnityEngine.Event,System.Action,bool)
0x000001e727157543 (Mono JIT Code) UnityEngine.UIElements.IMGUIContainer:HandleIMGUIEvent (UnityEngine.Event,bool)
0x000001e727156d9b (Mono JIT Code) UnityEngine.UIElements.IMGUIContainer:SendEventToIMGUIRaw (UnityEngine.UIElements.EventBase,bool,bool)
0x000001e727154183 (Mono JIT Code) UnityEngine.UIElements.IMGUIContainer:SendEventToIMGUI (UnityEngine.UIElements.EventBase,bool,bool)
0x000001e6b7a9b12b (Mono JIT Code) UnityEngine.UIElements.IMGUIContainer:HandleEvent (UnityEngine.UIElements.EventBase)
0x000001e6b7a89ab8 (Mono JIT Code) UnityEngine.UIElements.CallbackEventHandler:HandleEventAtTargetPhase (UnityEngine.UIElements.EventBase)
0x000001e727151983 (Mono JIT Code) UnityEngine.UIElements.MouseCaptureDispatchingStrategy:DispatchEvent (UnityEngine.UIElements.EventBase,UnityEngine.UIElements.IPanel)
0x000001e6b7a87d8e (Mono JIT Code) UnityEngine.UIElements.EventDispatcher:ApplyDispatchingStrategies (UnityEngine.UIElements.EventBase,UnityEngine.UIElements.IPanel,bool)
0x000001e6b7a87883 (Mono JIT Code) UnityEngine.UIElements.EventDispatcher:ProcessEvent (UnityEngine.UIElements.EventBase,UnityEngine.UIElements.IPanel)
0x000001e6b7a8d833 (Mono JIT Code) UnityEngine.UIElements.EventDispatcher:ProcessEventQueue ()
0x000001e6b7a8bee3 (Mono JIT Code) UnityEngine.UIElements.EventDispatcher:OpenGate ()
0x000001e6b7a8be2b (Mono JIT Code) UnityEngine.UIElements.EventDispatcherGate:Dispose ()
0x000001e6b7a87b13 (Mono JIT Code) UnityEngine.UIElements.EventDispatcher:ProcessEvent (UnityEngine.UIElements.EventBase,UnityEngine.UIElements.IPanel)
0x000001e6b7a871e3 (Mono JIT Code) UnityEngine.UIElements.EventDispatcher:Dispatch (UnityEngine.UIElements.EventBase,UnityEngine.UIElements.IPanel,UnityEngine.UIElements.DispatchMode)
0x000001e6b7a8705b (Mono JIT Code) UnityEngine.UIElements.BaseVisualElementPanel:SendEvent (UnityEngine.UIElements.EventBase,UnityEngine.UIElements.DispatchMode)
0x000001e6b8b2205b (Mono JIT Code) UnityEngine.UIElements.UIElementsUtility:DoDispatch (UnityEngine.UIElements.BaseVisualElementPanel)
0x000001e6b8b21afb (Mono JIT Code) UnityEngine.UIElements.UIElementsUtility:UnityEngine.UIElements.IUIElementsUtility.ProcessEvent (int,intptr,bool&)
0x000001e6b8b218bf (Mono JIT Code) UnityEngine.UIElements.UIEventRegistration:ProcessEvent (int,intptr)
0x000001e6b8b217db (Mono JIT Code) UnityEngine.UIElements.UIEventRegistration/<>c:<.cctor>b__1_2 (int,intptr)
0x000001e6b8b2165d (Mono JIT Code) UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
0x000001e6b8b2170e (Mono JIT Code) (wrapper runtime-invoke) <Module>:runtime_invoke_void_int_intptr_intptr& (object,intptr,intptr,intptr)
0x00007fff733fe640 (mono-2.0-bdwgc) [mini-runtime.c:2812] mono_jit_runtime_invoke
0x00007fff73382ad2 (mono-2.0-bdwgc) [object.c:2921] do_runtime_invoke
0x00007fff7338bb2f (mono-2.0-bdwgc) [object.c:2968] mono_runtime_invoke
0x00007ff67f5c2be4 (Unity) scripting_method_invoke
0x00007ff67f5be251 (Unity) ScriptingInvocation::Invoke
0x00007ff67f5b8615 (Unity) ScriptingInvocation::Invoke<void>
0x00007ff67e89b23a (Unity) Scripting::UnityEngine::GUIUtilityProxy::ProcessEvent
0x00007ff67f9ae0f6 (Unity) GUIView::ProcessRetainedMode
0x00007ff67fe9a8a2 (Unity) GUIView::OnInputEvent
0x00007ff67f9adfe2 (Unity) GUIView::ProcessInputEvent
0x00007ff67fe9b8c9 (Unity) GUIView::ProcessEventMessages
0x00007ff67fe95a08 (Unity) GUIView::GUIViewWndProc
0x00007ffff24ae858 (USER32) CallWindowProcW
0x00007ffff24ae299 (USER32) DispatchMessageW
0x00007ff67fe74d76 (Unity) MainMessageLoop
0x00007ff67fe78af6 (Unity) WinMain
0x00007ff6819a5682 (Unity) __scrt_common_main_seh
0x00007ffff1fd7034 (KERNEL32) BaseThreadInitThunk
0x00007ffff2c22651 (ntdll) RtlUserThreadStart
CommandInvokationFailure: Gradle build failed.
C:\Program Files\Unity\Hub\Editor\2021.1.7f1\Editor\Data\PlaybackEngines\AndroidPlayer\OpenJDK\bin\java.exe -classpath "C:\Program Files\Unity\Hub\Editor\2021.1.7f1\Editor\Data\PlaybackEngines\AndroidPlayer\Tools\gradle\lib\gradle-launcher-5.6.4.jar" org.gradle.launcher.GradleMain "-Dorg.gradle.jvmargs=-Xmx4096m" "bundleRelease"
stderr[
Note: C:\Users\cheth\FlutteringBirds1\Temp\gradleOut\unityLibrary\src\main\java\com\unity3d\player\UnityPlayerActivity.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
D8: Cannot fit requested classes in a single dex file (# methods: 70023 > 65536)
com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:
The number of method references in a .dex file cannot exceed 64K.
Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html
at com.android.builder.dexing.D8DexArchiveMerger.getExceptionToRethrow(D8DexArchiveMerger.java:132)
at com.android.builder.dexing.D8DexArchiveMerger.mergeDexArchives(D8DexArchiveMerger.java:119)
at com.android.build.gradle.internal.transforms.DexMergerTransformCallable.call(DexMergerTransformCallable.java:102)
at com.android.build.gradle.internal.tasks.DexMergingTaskRunnable.run(DexMergingTask.kt:445)
at com.android.build.gradle.internal.tasks.Workers$ActionFacade.run(Workers.kt:348)
at org.gradle.workers.internal.AdapterWorkAction.execute(AdapterWorkAction.java:50)
at org.gradle.workers.internal.DefaultWorkerServer.execute(DefaultWorkerServer.java:47)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1$1.create(NoIsolationWorkerFactory.java:65)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1$1.create(NoIsolationWorkerFactory.java:61)
at org.gradle.internal.classloader.ClassLoaderUtils.executeInClassloader(ClassLoaderUtils.java:98)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1.execute(NoIsolationWorkerFactory.java:61)
at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:44)
at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:41)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
at org.gradle.workers.internal.AbstractWorker.executeWrappedInBuildOperation(AbstractWorker.java:41)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1.execute(NoIsolationWorkerFactory.java:56)
at org.gradle.workers.internal.DefaultWorkerExecutor$3.call(DefaultWorkerExecutor.java:215)
at org.gradle.workers.internal.DefaultWorkerExecutor$3.call(DefaultWorkerExecutor.java:210)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runExecution(DefaultConditionalExecutionQueue.java:215)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runBatch(DefaultConditionalExecutionQueue.java:164)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.run(DefaultConditionalExecutionQueue.java:131)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
at java.lang.Thread.run(Thread.java:748)
Caused by: com.android.tools.r8.CompilationFailedException: Compilation failed to complete
at com.android.tools.r8.utils.O.a(:65)
at com.android.tools.r8.D8.run(:11)
at com.android.builder.dexing.D8DexArchiveMerger.mergeDexArchives(D8DexArchiveMerger.java:117)
... 34 more
Caused by: com.android.tools.r8.utils.b: Error: null, Cannot fit requested classes in a single dex file (# methods: 70023 > 65536)
at com.android.tools.r8.utils.y0.a(:21)
at com.android.tools.r8.dex.K.a(:56)
at com.android.tools.r8.dex.K$h.a(:5)
at com.android.tools.r8.dex.b.b(:15)
at com.android.tools.r8.dex.b.a(:38)
at com.android.tools.r8.D8.d(:87)
at com.android.tools.r8.D8.b(:1)
at com.android.tools.r8.utils.O.a(:30)
... 36 more
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':launcher:mergeDexRelease'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
> com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:
The number of method references in a .dex file cannot exceed 64K.
Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 38s
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8
]
stdout[
Starting a Gradle Daemon, 1 incompatible Daemon could not be reused, use --status for details
> Configure project :launcher
WARNING: The option 'android.enableR8' is deprecated and should not be used anymore.
It will be removed in a future version of the Android Gradle plugin, and will no longer allow you to disable R8.
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.1.7f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\build-tools\28.0.3\package.xml. Probably the SDK is read-only
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.1.7f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\platform-tools\package.xml. Probably the SDK is read-only
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.1.7f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\platforms\android-29\package.xml. Probably the SDK is read-only
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.1.7f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\tools\package.xml. Probably the SDK is read-only
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.1.7f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\build-tools\28.0.3\package.xml. Probably the SDK is read-only
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.1.7f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\platform-tools\package.xml. Probably the SDK is read-only
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.1.7f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\platforms\android-29\package.xml. Probably the SDK is read-only
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.1.7f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\tools\package.xml. Probably the SDK is read-only
> Task :unityLibrary:GoogleMobileAdsPlugin.androidlib:preBuild UP-TO-DATE
> Task :launcher:preBuild UP-TO-DATE
</code></pre>
| 1 | 8,032 |
How to convert an XML elements value to an int using linq- c#
|
<p>I'm trying to get the value out of my XML element and convert it to an integer using linq commands so I can do some mathematical equations using it.</p>
<p>This is how I've tried it so far:</p>
<pre><code>private void buttonTab4Mod1Calculate_Click(object sender, EventArgs e)
{
var document = XDocument.Load(workingDir + @"\Level4.xml");
var assessmentOneWeight = from d in document.Descendants("moduleTitle")
where d.Value == (String)comboBoxTab4Mod8.SelectedItem
select d.Parent.Element("assessmentOneWeight").Value;
int a = 0;
foreach (var item in assessmentOneWeight)
{
a = Convert.ToInt32(item);
}
MessageBox.Show(a.ToString());
}
</code></pre>
<p>but the value is still 0 for some reason.</p>
<p>This is my xml file:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<SoftwareEngineering>
<Module>
<moduleCode>ECSE401</moduleCode>
<moduleTitle>Programming Methodology</moduleTitle>
<credits>15</credits>
<assessmentOne>Coursework</assessmentOne>
<assessmentOneWeight>40</assessmentOneWeight>
<assessmentTwo>Coursework</assessmentTwo>
<assessmentTwoWeight>40</assessmentTwoWeight>
<assessmentThree>Test</assessmentThree>
<assessmentThreeWeight>20</assessmentThreeWeight>
</Module>
<Module>
<moduleCode>ECSC404</moduleCode>
<moduleTitle>Computer Systems Fundamentals</moduleTitle>
<credits>15</credits>
<assessmentOne>Test1</assessmentOne>
<assessmentOneWeight>30</assessmentOneWeight>
<assessmentTwo>Test2</assessmentTwo>
<assessmentTwoWeight>30</assessmentTwoWeight>
<assessmentThree>Test3</assessmentThree>
<assessmentThreeWeight>40</assessmentThreeWeight>
</Module>
<Module>
<moduleCode>EBSY401</moduleCode>
<moduleTitle>Information and Data Modelling</moduleTitle>
<credits>15</credits>
<assessmentOne>Test</assessmentOne>
<assessmentOneWeight>25</assessmentOneWeight>
<assessmentTwo>Coursework1</assessmentTwo>
<assessmentTwoWeight>10</assessmentTwoWeight>
<assessmentThree>Coursework2</assessmentThree>
<assessmentThreeWeight>35</assessmentThreeWeight>
<assessmentFour>Coursework3</assessmentFour>
<assessmentFourWeight>30</assessmentFourWeight>
</Module>
<Module>
<moduleCode>ECSC405</moduleCode>
<moduleTitle>Software Development Principles</moduleTitle>
<credits>15</credits>
<assessmentOne>Test1</assessmentOne>
<assessmentOneWeight>30</assessmentOneWeight>
<assessmentTwo>Coursework</assessmentTwo>
<assessmentTwoWeight>40</assessmentTwoWeight>
<assessmentThree>Test2</assessmentThree>
<assessmentThreeWeight>30</assessmentThreeWeight>
</Module>
<Module>
<moduleCode>ECSC407</moduleCode>
<moduleTitle>Web Technology</moduleTitle>
<credits>15</credits>
<assessmentOne>Tutorials</assessmentOne>
<assessmentOneWeight>20</assessmentOneWeight>
<assessmentTwo>Coursework</assessmentTwo>
<assessmentTwoWeight>20</assessmentTwoWeight>
<assessmentThree>Exam</assessmentThree>
<assessmentThreeWeight>60</assessmentThreeWeight>
</Module>
<Module>
<moduleCode>ECSC409</moduleCode>
<moduleTitle>Software Engineering Principles</moduleTitle>
<credits>15</credits>
<assessmentOne>Coursework1</assessmentOne>
<assessmentOneWeight>40</assessmentOneWeight>
<assessmentTwo>Coursework2</assessmentTwo>
<assessmentTwoWeight>30</assessmentTwoWeight>
<assessmentThree>Coursework3</assessmentThree>
<assessmentThreeWeight>30</assessmentThreeWeight>
</Module>
<Module>
<moduleCode>ECSC408</moduleCode>
<moduleTitle>Mathematics for Computing</moduleTitle>
<credits>15</credits>
<assessmentOne>Coursework</assessmentOne>
<assessmentOneWeight>50</assessmentOneWeight>
<assessmentTwo>Exam</assessmentTwo>
<assessmentTwoWeight>50</assessmentTwoWeight>
</Module>
<Module>
<moduleCode>EBSY400</moduleCode>
<moduleTitle>Communication and Learning Skills</moduleTitle>
<credits>15</credits>
<assessmentOne>Coursework</assessmentOne>
<assessmentOneWeight>30</assessmentOneWeight>
<assessmentTwo>Coursework</assessmentTwo>
<assessmentTwoWeight>70</assessmentTwoWeight>
</Module>
</SoftwareEngineering>
</code></pre>
<p>Would greatly appreciate some help.</p>
| 1 | 2,403 |
How to stop R from leaving zombie processes behind
|
<p>Here is a little reproducible example:</p>
<pre><code>library(doMC)
library(doParallel)
registerDoMC(4)
timing <- system.time( fitall <- foreach(i=1:1000, .combine = "c") %dopar% {
print(i)
})
</code></pre>
<p>I start up <code>R</code> and look at the process table:</p>
<pre><code>> system("ps -efl")
F S UID PID PPID C PRI NI ADDR SZ WCHAN STIME TTY TIME CMD
4 S chbr 1 0 5 80 0 - 21399 wait 10:58 ? 00:00:00 /usr/local/lib/R/bin/exec/R --no-save --no-restore
0 S chbr 9 1 0 80 0 - 1113 wait 10:58 ? 00:00:00 sh -c ps -efl
0 R chbr 10 9 0 80 0 - 4294 - 10:58 ? 00:00:00 ps -efl
</code></pre>
<p>If I use the aformentioned simple for loop <code>doMC</code> or <code>doParallel</code> leave a zombie process behind. Output of <code>ps -efl</code> after running the loop:</p>
<pre><code>> system("ps -efl")
F S UID PID PPID C PRI NI ADDR SZ WCHAN STIME TTY TIME CMD
4 S chbr 1 0 4 80 0 - 25256 wait 11:00 ? 00:00:00 /usr/local/lib/R/b
1 Z chbr 10 1 0 80 0 - 0 exit 11:00 ? 00:00:00 [R] <defunct>
0 S chbr 12 1 0 80 0 - 1113 wait 11:00 ? 00:00:00 sh -c ps -efl
0 R chbr 13 12 0 80 0 - 4294 - 11:00 ? 00:00:00 ps -efl
</code></pre>
<p>If I repeat the loop without issuing <code>registerDoMC(4)</code> again no additional zombie process gets created. However, if I issue <code>registerDoMC(4)</code> an additional zombie process gets created:</p>
<pre><code>> system("ps -efl")
F S UID PID PPID C PRI NI ADDR SZ WCHAN STIME TTY TIME CMD
4 S chbr 1 0 0 80 0 - 25554 wait 11:00 ? 00:00:01 /usr/local/lib/R/b
1 Z chbr 21 1 0 80 0 - 0 exit 11:02 ? 00:00:00 [R] <defunct>
1 Z chbr 22 1 0 80 0 - 0 exit 11:02 ? 00:00:00 [R] <defunct>
0 S chbr 26 1 0 80 0 - 1113 wait 11:03 ? 00:00:00 sh -c ps -efl
0 R chbr 27 26 0 80 0 - 4294 - 11:03 ? 00:00:00 ps -efl
</code></pre>
<p>That's how I figured it could be <code>doMC</code> which is doing something that should not be done. If doMC is causing this is there a way to stop <code>doMC</code> from leaving zombie processes behind? (<code>stopCluster()</code> does not work as no cluster gets created in the first place.)</p>
<pre><code>> sessionInfo()
R Under development (unstable) (2014-08-16 r66404)
Platform: x86_64-unknown-linux-gnu (64-bit)
locale:
[1] LC_CTYPE=en_IE.UTF-8 LC_NUMERIC=C
[3] LC_TIME=en_IE.UTF-8 LC_COLLATE=en_IE.UTF-8
[5] LC_MONETARY=en_IE.UTF-8 LC_MESSAGES=en_IE.UTF-8
[7] LC_PAPER=en_IE.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_IE.UTF-8 LC_IDENTIFICATION=C
attached base packages:
[1] parallel stats graphics grDevices utils datasets methods
[8] base
other attached packages:
[1] doParallel_1.0.8 doMC_1.3.3 iterators_1.0.7 foreach_1.4.2
loaded via a namespace (and not attached):
[1] codetools_0.2-8 compiler_3.2.0
</code></pre>
| 1 | 1,686 |
ValueError: Invalid \escape while running query
|
<p>I am trying to query DBpedia using SPARQLWrapper in Python (v3.3). This is my query:</p>
<pre class="lang-none prettyprint-override"><code>PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?slot WHERE {
<http://dbpedia.org/resource/Week> <http://www.w3.org/2002/07/owl#sameAs> ?slot
}
</code></pre>
<p>It results in an error from the SPARQLWrapper package:</p>
<blockquote>
<p>ValueError: Invalid \escape: line 118 column 74 (char 11126)</p>
</blockquote>
<p>Code: </p>
<pre class="lang-none prettyprint-override"><code>query = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT ?slot WHERE{{ {subject} {predicate} {object} }} "
query = query.format(subject=subject, predicate=predicate, object= objectfield)
self.sparql.setQuery(query)
self.sparql.setReturnFormat(JSON)
results = self.sparql.query().convert() # Error thrown at this line
</code></pre>
<p>Error : </p>
<pre><code>Traceback (most recent call last):
File "getUriLiteralAgainstPredicate.py", line 84, in <module>
sys.exit(main())
File "getUriLiteralAgainstPredicate.py", line 61, in main
entity,predicateURI,result = p.getObject(dataAtURI,predicates, each["entity"])
File "getUriLiteralAgainstPredicate.py", line 30, in getObject
result = self.run_sparql("<"+subjectURI+">","<"+predicateURI+">","?slot")
File "getUriLiteralAgainstPredicate.py", line 24, in run_sparql
results = self.sparql.query().convert()
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/SPARQLWrapper-1.5.2-py3.3.egg/SPARQLWrapper/Wrapper.py", line 539, in convert
return self._convertJSON()
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/SPARQLWrapper-1.5.2-py3.3.egg/SPARQLWrapper/Wrapper.py", line 476, in _convertJSON
return jsonlayer.decode(self.response.read().decode("utf-8"))
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/SPARQLWrapper-1.5.2-py3.3.egg/SPARQLWrapper/jsonlayer.py", line 76, in decode
return _decode(string)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/SPARQLWrapper-1.5.2-py3.3.egg/SPARQLWrapper/jsonlayer.py", line 147, in <lambda>
_decode = lambda string, loads=json.loads: loads(string)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/json/__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/json/decoder.py", line 352, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/json/decoder.py", line 368, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Invalid \escape: line 118 column 74 (char 11126)
</code></pre>
| 1 | 1,129 |
Storing user input into linked list - C
|
<p>I have an assignment for C beginner class: I'm supposed to create a structure that has one variable (named value) and one pointer to the list. I'm supposed to prompt the user for 5 values as input and store them in the linked list. Then print out the list. I can't figure out how to store input into the list. I did manage to write a program in which I initialize the 5 values. But I don't know how to accept input and store it into the list. </p>
<p>Here's the working program where I initialize the values:</p>
<pre><code>#include <stdio.h>
struct list
{
double value;
struct list *nextVal;
};
int main()
{
struct list v1 = {10};
struct list v2 = {17.97};
struct list v3 = {166};
struct list v4 = {2};
struct list v5 = {387.55};
struct list *first;
first = &v1;
v1.nextVal = &v2;
v2.nextVal = &v3;
v3.nextVal = &v4;
v4.nextVal = &v5;
v5.nextVal = NULL;
printf("All the values are: %.2f, %.2f, %.2f, %.2f, %.2f.",
first->value,v1.nextVal->value,v2.nextVal->value,
v3.nextVal->value,v4.nextVal->value);
return 0;
}
</code></pre>
<p>Here's a program where I tried getting user input and storing that into the list. (I only have 2 values instead of 5, cuz it's easier to work with that when trying to make it work.) When I compile this program, I get no errors. When I run it, I am properly prompted for the two input values; however, when the output that the program prints just writes 0 for both values. My assumption is that I'm storing the value into the list wrong - because I don't know how it's actually done. (Can't find any info in my textbook or online.) Last night someone commented on a different question I had to try using breakpoint to find out exactly where the problem is - I've been trying to figure it out since then but don't know how to do that yet. (I'm assuming it's something very simple - but everywhere I looked online, people explain it in a way that seems like I'm supposed to know what they're talking about - which I don't - And honestly, even if I could figure it out, I still wouldn't know what to do with that information, since I just can't find any information on how to store user input into a linked list.) Anyways, so here's my trial program that complies and runs but gives me 0 for both final values:</p>
<pre><code>#include <stdio.h>
struct list
{
double value;
struct list *nextVal;
};
int main()
{
double val1,val2;
printf("Please enter a number: ");
scanf("%f",&val1);
printf("Please enter a number: ");
scanf("%f",&val2);
struct list v1 = {val1};
struct list v2 = {val2};
struct list *first;
first = &v1;
v1.nextVal = &v2;
v2.nextVal = NULL;
printf("The two values entered are %.2f and %.2f.",
first->value,v1.nextVal->value);
return 0;
}
</code></pre>
<p>Thank you in advance! And I'm reaaaally a beginner - so even if you suggest something super easy - I might have no clue what it is..so please explain! Thank you!</p>
| 1 | 1,037 |
Jenkins Pipeline does not run with docker-compose because it cant connect to docker daemon
|
<p>I am trying to build an docker image and start the container with docker-compose inside a Jenkins pipeline. </p>
<p>I have a custom docker image for my Jenkins where I use the Jenkins out of the box image and install Docker CE and docker compose.</p>
<p>The Dockerfile:</p>
<pre><code>FROM jenkins/jenkins:2.159
USER root
# create dir to save jenkins log files
RUN mkdir /var/log/jenkins
RUN chown -R jenkins:jenkins /var/log/jenkins
########################################################################################################################
## install docker based on: https://www.digitalocean.com/community/tutorials/how-to-install-and-use-docker-on-debian-9
########################################################################################################################
RUN apt update
RUN apt -y install apt-transport-https ca-certificates curl gnupg2 software-properties-common
RUN curl -fsSL https://download.docker.com/linux/debian/gpg | apt-key add -
RUN add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/debian $(lsb_release -cs) stable"
RUN apt update
# make sure you are about to install from the Docker repo instead of the default Debian repo
RUN apt-cache policy docker-ce
RUN apt -y install docker-ce
#RUN systemctl status docker
# give jenkins docker rights
RUN apt update
RUN apt-get install acl
#RUN ls /var/run
#RUN setfacl -m user:jenkins:rw /var/run/docker.sock
RUN usermod -aG docker jenkins
RUN gpasswd -a jenkins docker
################################################################################################################################
## install docker-compose based on: https://www.digitalocean.com/community/tutorials/how-to-install-docker-compose-on-debian-9
################################################################################################################################
RUN curl -L https://github.com/docker/compose/releases/download/1.22.0/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
RUN chmod +x /usr/local/bin/docker-compose
RUN docker-compose --version
USER jenkins
RUN id -nG
#tell jenkins to use the created folder to store logs
</code></pre>
<p>I build this image with <code>docker-compose build</code> with this docker-compose file: </p>
<pre><code>version: '3'
volumes:
jenkins-log:
jenkins-data:
networks:
jenkins-net:
services:
master:
build: ./jenkins-master
ports:
- "50000:50000"
volumes:
- jenkins-log:/var/log/jenkins
- jenkins-data:/var/jenkins_home
- /var/run/docker.sock:/var/run/docker.sock
networks:
- jenkins-net
nginx:
build: ./jenkins-nginx
ports:
- "80:80"
networks:
- jenkins-net
</code></pre>
<p>And start it with <code>docker-compose -p jenkins up -d</code></p>
<p>This starts Jenkins and works fine for now. </p>
<p>Then I create a Pipeline Job which uses the following Jenkinsfile:</p>
<pre><code>node {
stage('Build Docker Image') {
sh '''
cd env-ci/
docker-compose --version
docker --version
docker-compose build
'''
}
}
</code></pre>
<p>When I run this pipeline I get the following error: </p>
<pre><code>+ cd env-ci/
+ docker-compose --version
docker-compose version 1.22.0, build f46880fe
+ docker --version
Docker version 18.09.1, build 4c52b90
+ docker-compose build
Couldn't connect to Docker daemon at http+docker://localhost - is it running?
If it's at a non-standard location, specify the URL with the DOCKER_HOST environment variable.
</code></pre>
<p>When I try to run <code>docker info</code> within the pipeline: </p>
<pre><code>node {
stage('Build Docker Image') {
sh '''
cd env-ci/
docker-compose --version
docker --version
docker info
'''
}
}
</code></pre>
<p>I get the following error: </p>
<pre><code>+ cd env-ci/
+ docker-compose --version
docker-compose version 1.22.0, build f46880fe
+ docker --version
Docker version 18.09.1, build 4c52b90
+ docker info
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.39/info: dial unix /var/run/docker.sock: connect: permission denied
</code></pre>
<p>I am currently out of ideas what the issue might be or how I can resolve it.
The Jenkins pipeline is run as user <code>jenkins</code> and this user is added to the docker group. So the permission <em>should</em> be fine?!</p>
<p>Does anyone have an idea what might be wrong?
Thank you!</p>
| 1 | 1,588 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.