title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
showing download progress while downloading a file using PHP and jquery
|
<p>I am developing a download manager using PHP and jquery.</p>
<p>Requested a script that will download a file and also show the download progress.</p>
<p>I tried the following, but it not works</p>
<p>Jquery</p>
<pre><code>function downloadFile(){
var fileNameDownloading ="somefile.mp3"
var oReq = new XMLHttpRequest();
oReq.addEventListener("progress", updateProgress, false);
var params = "filename="+fileNameDownloading;
oReq.open("GET", "scripts/download.php?"+params, true);
oReq.responseType = "blob";//blob arraybuffer
function updateProgress (e) {
console.log(e.loaded/e.total);
}
oReq.send();
}
</code></pre>
<p>PHP</p>
<pre><code><?php
$file = $_GET['filename'];
$fileSize = get_size($file);
$packetSize = 262144;//2000
if($packetSize > $fileSize){
$packetSize = $fileSize;
}
download($file,$packetSize);
function download($file,$chunks){
set_time_limit(0);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-disposition: attachment; filename='.basename($file));
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
header('Pragma: public');
$size = get_size($file);
header('Content-Length: '.$size);
$i = 0;
while($i<=$size){
//Output the chunk
get_chunk($file,(($i==0)?$i:$i+1),((($i+$chunks)>$size)?$size:$i+$chunks));
$i = ($i+$chunks);
}
}
//Callback function for CURLOPT_WRITEFUNCTION, This is what prints the chunk
function chunk($ch, $str) {
print($str);
return strlen($str);
}
//Function to get a range of bytes from the remote file
function get_chunk($file,$start,$end){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $file);
curl_setopt($ch, CURLOPT_RANGE, $start.'-'.$end);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'chunk');
$result = curl_exec($ch);
curl_close($ch);
}
//Get total size of file
function get_size($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
return intval($size);
}
?>
</code></pre>
<p>Looking for a suggestion, how we can download a file and also show download progress using PHP and javascript. Thanks</p>
| 0 | 1,106 |
PRESTASHOP NGINX + REWRITE RULES
|
<p>I've being searching for a good solution for this combination and after following these:</p>
<ol>
<li><a href="http://www.phamviet.net/2012/06/03/prestashop-rewrite-url-on-nginx/" rel="nofollow noreferrer">http://www.phamviet.net/2012/06/03/prestashop-rewrite-url-on-nginx/</a></li>
<li><a href="http://www.nginxtips.com/nginx-configuration-for-prestashop/" rel="nofollow noreferrer">Nginx configuration for Prestashop</a></li>
<li><a href="http://www.prestashop.com/forums/topic/307168-prestashop-1562-rewrite-urls-over-nginx-install/?hl=%2Bnginx#entry1554501" rel="nofollow noreferrer">Prestashop 1.5.6.2 rewrite URLs over nginx install</a></li>
</ol>
<p>none of them seemed to work for me at all... so I started experimenting:</p>
<p>After configuring SSL, CloudFlare, etc.... </p>
<p>This is what I tried:</p>
<pre><code>server {
listen 80;
server_name mysuperdomain.com www.mysuperdomain.com;
rewrite ^ https://$server_name$request_uri? permanent;
}
server {
# listen 80 deferred; # for Linux
# listen 80 accept_filter=httpready; # for FreeBSD
listen 443;
# The host name to respond to
server_name mysuperdomain.com *.mysuperdomain.com;
# Path for static files
root /sites/mysuperdomain.com/public;
ssl on;
ssl_certificate /etc/nginx/ssl/ssl.pem;
ssl_certificate_key /etc/nginx/ssl/ssl.key;
# Try static files first, then php
index index.html index.htm index.php;
# Specific logs for this vhost
access_log /sites/mysuperdomain.com/log/log-access.log;
error_log /sites/mysuperdomain.com/log/log-error.log error;
#Specify a charset
charset utf-8;
# Redirect needed to "hide" index.php
location / {
rewrite ^/([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/$1/$1$2$3.jpg break;
rewrite ^/([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/$1/$2/$1$2$3$4.jpg break;
rewrite ^/([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/$1/$2/$3/$1$2$3$4$5.jpg break;
rewrite ^/([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/$1/$2/$3/$4/$1$2$3$4$5$6.jpg break;
rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/$1/$2/$3/$4/$5/$1$2$3$4$5$6$7.jpg break;
rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/$1/$2/$3/$4/$5/$6/$1$2$3$4$5$6$7$8.jpg break;
rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/$1/$2/$3/$4/$5/$6/$7/$1$2$3$4$5$6$7$8$9.jpg break;
rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/$1/$2/$3/$4/$5/$6/$7/$8/$1$2$3$4$5$6$7$8$9$10.jpg break;
if (-e $request_filename){
rewrite ^(.*)$ /index.php break;
}
try_files $uri $uri/ /index.php?q=$uri&$args;
}
location /c {
rewrite ^/c/([0-9]+)(\-[\.*_a-zA-Z0-9-]*)(-[0-9]+)?/.+\.jpg$ /img/$1$2$3.jpg break;
rewrite ^/c/([a-zA-Z_-]+)(-[0-9]+)?/.+\.jpg$ /img/$1$2.jpg break;
}
location /images_ie {
rewrite ^/images_ie/?([^/]+)\.(jpe?g|png|gif)$ /js/jquery/plugins/fancybox/images/$1.$2 break;
}
# Don't log robots.txt or favicon.ico files
location ~* ^/(favicon.ico|robots.txt)$ {
access_log off;
log_not_found off;
}
# Custom 404 page
error_page 404 /index.php?controller=404;
location ~* ^.+.(gif|jpg|jpeg|png|wmv|avi|mpg|mpeg|mp4|htm|html|js|css|mp3|swf|ico|flv|xml) {
access_log off;
expires 30d;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
# With php5-cgi alone:
# fastcgi_pass 127.0.0.1:9000;
# With php5-fpm:
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_intercept_errors on;
fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# Deny access to .htaccess
location ~ /\.ht {
deny all;
}
#PHPMYADMIN
location /phpmyadmin {
root /usr/share/;
index index.php index.html index.htm;
location ~ ^/phpmyadmin/(.+\.php)$ {
try_files $uri =404;
root /usr/share/;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~* ^/phpmyadmin/(.+\.(jpeg|jpg|png|css|gif|ico|js|html|xml|txt))$ {
root /usr/share/;
}
}
location /phpMyAdmin {
rewrite ^/* /phpmyadmin last;
}
# Include the basic h5bp config set
include h5bp/basic.conf;
}
</code></pre>
<p>It seems to only work for categories but not for individual products pages and such.</p>
<p>When you hit the main domain or go to the home page, it will download index.php instead of showing the home page.</p>
<p>So a little bit of help would be amazing!</p>
| 0 | 2,260 |
XSLT condition to check if node exists
|
<p>I have below sample XML in which I want to check if the node exist.</p>
<p>Sample XML is</p>
<pre><code><document>
<item>
<ID>1000909090</ID>
<flex>
<attrGroupMany name="pageinfo">
<row>
<attr name="pagelength">10</attr>
<attr name="pagewidth">20</attr>
<attr name="pageheight">30</attr>
</row>
<row>
<attr name="pagelength">10</attr>
<attr name="pagewidth">20</attr>
</row>
</attrGroupMany>
</flex>
</item>
</document>
</code></pre>
<p>I am using below XSLT but is not getting converted</p>
<pre><code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" />
<xsl:template match="document">
<CatalogItem>
<RelationshipData>
<xsl:for-each select="item">
<Relationship>
<RelationType>PAGEDETAILSINFO</RelationType>
<RelatedItems>
<xsl:attribute name="count">
<xsl:value-of select="count(flex//attrGroupMany[@name = 'pageinfo']/row)"/>
</xsl:attribute>
<xsl:for-each select="flex//attrGroupMany[@name = 'pageinfo']/row">
<xsl:choose>
<xsl:when test="not(string-length(attr[@name = 'pageheight'] )) = 0">
<xsl:variable name="height" select="attr[@name='pageheight']"/>
</xsl:when>
<xsl:otherwise>
<xsl:variable name="height" select="'0'"/>
</xsl:otherwise>
</xsl:choose>
<RelatedItem>
<xsl:attribute name="referenceKey">
<xsl:value-of select="concat('Food_And_Bev_Allergen_MVL','-',ancestor::item/ID,'-',$height)"/>
</xsl:attribute>
</RelatedItem>
</xsl:for-each>
</RelatedItems>
</Relationship>
</xsl:for-each>
</RelationshipData>
</CatalogItem>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>I think the choose condition is incorrect. can you please let me know what will be the correct condition.</p>
| 0 | 1,787 |
Cannot Instantiate class error - Selenium WebDriver
|
<p>I am facing this 'Cannot insantiate class' error on running one of my test cases in selenium webdriver using java.</p>
<p>Below is the class of the functionality of the test,</p>
<pre><code>package Pages;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import Lib.lib;
public class KnowledgeBase extends lib{
By sortBylink = By.xpath("html/body/div[1]/featured-studies-grid/div[2]/featured-studies-toolbar/div/div[2]/div[2]/div/div");
By featuredOption = By.xpath("html/body/div[1]/featured-studies-grid/div[2]/featured-studies-toolbar/div/div[2]/div[2]/div/ul/li[1]");
By mostRcnt = By.xpath("html/body/div[1]/featured-studies-grid/div[2]/featured-studies-toolbar/div/div[2]/div[2]/div/ul/li[2]");
String featOption = driver.findElement(By.xpath("html/body/div[1]/featured-studies-grid/div[2]/featured-studies-toolbar/div/div[2]/div[2]/div/ul/li[1]")).getText();
String mostRecent = driver.findElement(By.xpath("html/body/div[1]/featured-studies-grid/div[2]/featured-studies-toolbar/div/div[2]/div[2]/div/ul/li[2]")).getText();
public void initSBy() throws Exception
{
driver.findElement(sortBylink).click();
Thread.sleep(1500);
}
public void selectfO() throws Exception
{
driver.findElement(featuredOption).click();
Thread.sleep(5000);
}
public void selectMr() throws Exception
{
driver.findElement(mostRcnt).click();
Thread.sleep(5000);
}
public void sortBy(String sProp) throws Exception
{
this.initSBy();
if (sProp == featOption) {
this.selectfO();
}
else if (sProp == mostRecent){
this.selectMr();
}
else {
System.out.println("Incorrect option. Test failed.");
}
}
}
</code></pre>
<p>Below is my Test Case Class</p>
<pre><code>package TestCases;
import org.testng.annotations.Test;
import Lib.lib;
import Pages.KnowledgeBase;
import Pages.LoginPage;
public class sortingTextKB extends lib {
LoginPage uLogin = new LoginPage();
KnowledgeBase sortObj = new KnowledgeBase();
//Logging In
@Test (priority = 1)
public void loggingIn() throws Exception
{
uLogin.loginToKB("uzii@test.com", "uziiiii");
}
//Sorting
@Test (priority = 2)
public void sortIn() throws Exception
{
sortObj.sortBy("Most Recent");
}
}
</code></pre>
<p>Below is my Lib class, that contains the chrome driver configuration</p>
<pre><code>package Lib;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
public class lib {
protected static WebDriver driver = null;
@BeforeTest
public void chrome_extension()
{
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
driver.get("http://www.testsite.com");
}
@AfterTest
public void quit()
{
driver.quit();
}
}
</code></pre>
<p>When I run my test case class, I am getting the following error,</p>
<pre><code>org.testng.TestNGException:
Cannot instantiate class TestCases.sortingTextKB
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:38)
at org.testng.internal.ClassHelper.createInstance1(ClassHelper.java:387)
at org.testng.internal.ClassHelper.createInstance(ClassHelper.java:299)
at org.testng.internal.ClassImpl.getDefaultInstance(ClassImpl.java:110)
at org.testng.internal.ClassImpl.getInstances(ClassImpl.java:186)
at org.testng.internal.TestNGClassFinder.<init>(TestNGClassFinder.java:120)
at org.testng.TestRunner.initMethods(TestRunner.java:409)
at org.testng.TestRunner.init(TestRunner.java:235)
at org.testng.TestRunner.init(TestRunner.java:205)
at org.testng.TestRunner.<init>(TestRunner.java:160)
at org.testng.remote.RemoteTestNG$1.newTestRunner(RemoteTestNG.java:141)
at org.testng.remote.RemoteTestNG$DelegatingTestRunnerFactory.newTestRunner(RemoteTestNG.java:271)
at org.testng.SuiteRunner$ProxyTestRunnerFactory.newTestRunner(SuiteRunner.java:561)
at org.testng.SuiteRunner.init(SuiteRunner.java:157)
at org.testng.SuiteRunner.<init>(SuiteRunner.java:111)
at org.testng.TestNG.createSuiteRunner(TestNG.java:1299)
at org.testng.TestNG.createSuiteRunners(TestNG.java:1286)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
at org.testng.TestNG.run(TestNG.java:1057)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:29)
... 21 more
Caused by: java.lang.NullPointerException
at Pages.KnowledgeBase.<init>(KnowledgeBase.java:22)
at TestCases.sortingTextKB.<init>(sortingTextKB.java:12)
... 26 more
</code></pre>
<p>Following is the 22 line of KnowledgeBase class,</p>
<pre><code>String featOption = driver.findElement(By.xpath("html/body/div[1]/featured-studies-grid/div[2]/featured-studies-toolbar/div/div[2]/div[2]/div/ul/li[1]")).getText();
</code></pre>
<p>Please let me know why I am facing this 'cannot instantiate class' error. Thanks</p>
| 0 | 2,402 |
android - How to mux audio file and video file?
|
<p>i have a 3gp file that is recorded from the microphone and a mp4 video file.
i want to mux audio file and video file in to a mp4 file and save it.
i searched a lot but didn't find any thing helpful for using MediaMuxer api of android.
<a href="http://developer.android.com/reference/android/media/MediaMuxer.html" rel="noreferrer">MediaMuxer api</a></p>
<p>UPDATE : this is my method that mux two files , i have an Exception in it.
and the reason is that the destination mp4 file doesn't have any track!
can someOne help me with adding audio and video track to muxer??</p>
<p>Exception </p>
<pre><code>java.lang.IllegalStateException: Failed to stop the muxer
</code></pre>
<p>my code:</p>
<pre><code>private void cloneMediaUsingMuxer( String dstMediaPath) throws IOException {
// Set up MediaExtractor to read from the source.
MediaExtractor soundExtractor = new MediaExtractor();
soundExtractor.setDataSource(audioFilePath);
MediaExtractor videoExtractor = new MediaExtractor();
AssetFileDescriptor afd2 = getAssets().openFd("Produce.MP4");
videoExtractor.setDataSource(afd2.getFileDescriptor() , afd2.getStartOffset(),afd2.getLength());
//PATH
//extractor.setDataSource();
int trackCount = soundExtractor.getTrackCount();
int trackCount2 = soundExtractor.getTrackCount();
//assertEquals("wrong number of tracks", expectedTrackCount, trackCount);
// Set up MediaMuxer for the destination.
MediaMuxer muxer;
muxer = new MediaMuxer(dstMediaPath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
// Set up the tracks.
HashMap<Integer, Integer> indexMap = new HashMap<Integer, Integer>(trackCount);
for (int i = 0; i < trackCount; i++) {
soundExtractor.selectTrack(i);
MediaFormat SoundFormat = soundExtractor.getTrackFormat(i);
int dstIndex = muxer.addTrack(SoundFormat);
indexMap.put(i, dstIndex);
}
HashMap<Integer, Integer> indexMap2 = new HashMap<Integer, Integer>(trackCount2);
for (int i = 0; i < trackCount2; i++) {
videoExtractor.selectTrack(i);
MediaFormat videoFormat = videoExtractor.getTrackFormat(i);
int dstIndex2 = muxer.addTrack(videoFormat);
indexMap.put(i, dstIndex2);
}
// Copy the samples from MediaExtractor to MediaMuxer.
boolean sawEOS = false;
int bufferSize = MAX_SAMPLE_SIZE;
int frameCount = 0;
int offset = 100;
ByteBuffer dstBuf = ByteBuffer.allocate(bufferSize);
MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
MediaCodec.BufferInfo bufferInfo2 = new MediaCodec.BufferInfo();
muxer.start();
while (!sawEOS) {
bufferInfo.offset = offset;
bufferInfo.size = soundExtractor.readSampleData(dstBuf, offset);
bufferInfo2.offset = offset;
bufferInfo2.size = videoExtractor.readSampleData(dstBuf, offset);
if (bufferInfo.size < 0) {
sawEOS = true;
bufferInfo.size = 0;
bufferInfo2.size = 0;
}else if(bufferInfo2.size < 0){
sawEOS = true;
bufferInfo.size = 0;
bufferInfo2.size = 0;
}
else {
bufferInfo.presentationTimeUs = soundExtractor.getSampleTime();
bufferInfo2.presentationTimeUs = videoExtractor.getSampleTime();
//bufferInfo.flags = extractor.getSampleFlags();
int trackIndex = soundExtractor.getSampleTrackIndex();
int trackIndex2 = videoExtractor.getSampleTrackIndex();
muxer.writeSampleData(indexMap.get(trackIndex), dstBuf,
bufferInfo);
soundExtractor.advance();
videoExtractor.advance();
frameCount++;
}
}
Toast.makeText(getApplicationContext(),"f:"+frameCount,Toast.LENGTH_SHORT).show();
muxer.stop();
muxer.release();
}
</code></pre>
<p><strong>UPDATE 2: problem solved! check my answer to my question.</strong></p>
<p>thanks for your help</p>
| 0 | 1,581 |
Redraw/refresh Itemizedoverlay? (android/google maps api)
|
<p>I am making a GPS tracker using google maps API and displaying the users current position on a map using ItemizedOverylay. As the users position changes regularly, I've set up a CountDownTimer to delete the current Itemizedoverlay and add a new one at the new position every 5 seconds (there is no way of changing an itemizedOverlay's position) but the screen isn't drawing the new positions unless i physically touch the screen! Here is the code for my itemized overlay:</p>
<pre><code>import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.widget.Toast;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class HelloItemizedOverlay extends ItemizedOverlay{
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
Context mContext;
public HelloItemizedOverlay(Drawable defaultMarker) {
/*This passes the defaultMarker up to the default constructor
* to bound its coordinates and then initialize mContext with the given Context.*/
super(boundCenterBottom(defaultMarker));
}
public HelloItemizedOverlay(Drawable defaultMarker, Context context) {
/*This passes the defaultMarker up to the default constructor
* to bound its coordinates and then initialize mContext with the given Context.*/
super(boundCenterBottom(defaultMarker));
mContext = context;
}
@Override
protected boolean onTap(int index) {
/*This uses the member android.content.Context to create
* a new AlertDialog.Builder and uses the tapped OverlayItem's title
* and snippet for the dialog's title and message text. (You'll see the
* OverlayItem title and snippet defined when you create it below.)*/
OverlayItem item = mOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
/*Each time you add a new OverlayItem to the ArrayList, you must
* call populate() for the ItemizedOverlay, which will read each
* of the OverlayItems and prepare them to be drawn.*/
populate();
}
public void addOverlayList(List<OverlayItem> overlayitems) {
Object temp[] = overlayitems.toArray();
try{
for(int i = 0;i<temp.length;i++)
{
mOverlays.add((OverlayItem)temp[i]);
}
}catch(Error e)
{
Toast.makeText(mContext, "Something happened when adding the overlays:"+e.getMessage() ,
Toast.LENGTH_LONG).show();
}
populate();
}
public void removeOverlayList(List<OverlayItem> overlayitems) {
Object temp[] = overlayitems.toArray();
try{
for(int i = 0;i<temp.length;i++)
{
mOverlays.remove((OverlayItem)temp[i]);
}
}catch(Error e)
{
Toast.makeText(mContext, "Something happened when adding the overlays:"+e.getMessage() ,
Toast.LENGTH_LONG).show();
}
populate();
}
public void removeOverlay(OverlayItem overlay){
mOverlays.remove(overlay);
populate();
}
public void doPopulate()
{
populate();
}
@Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return mOverlays.get(i);
}
@Override
public int size() {
/*You must also override the size() method to return the current
* number of items in the ArrayList:*/
return mOverlays.size();
}
}
</code></pre>
<p>Does anyone know if there is a method or something I can call to force a redraw/refresh when I put the new items in?</p>
<p>EDIT: Here is a snippet of the MapsActivity:</p>
<pre><code>public class HelloGoogleMaps extends MapActivity {
/***************************
* map stuff
*****/
HelloItemizedOverlay myPosition;
MapView mapView;
MapController mapController;
List<Overlay> mapOverlays;
OverlayItem myPositionOverlayItem;
public double myLatitude = 0;
public double myLongitude = 0;
public double myCoarseLatitude = 0;
public double myCoarseLongitude = 0;
public boolean isGPS;
public boolean isGPSFix;
public boolean useGPSLocation;
public boolean useNetworkLocation;
public long mLastLocationMillis;//system time of last gps contact
/*boolean so when gps gets your location it will zoom to where you are,
* but will only do this once (once it's set to true)*/
boolean pickedUpLocation;
public MyCount counter;//for timing events
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mymapview);
pickedUpLocation = false;
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setStreetView(true);
/*mapcontroller controls zoom etc*/
mapController = mapView.getController();
mapOverlays = mapView.getOverlays();
Drawable my_icon = this.getResources().getDrawable(R.drawable.androidmarker_teacher);
myPosition = new HelloItemizedOverlay(my_icon, this);
itemizedoverlay = new HelloItemizedOverlay(drawable, this);
/*All overlay elements on a map are held by the MapView, so when you
* want to add some, you have to get a list from the getOverlays() method.
* Then instantiate the Drawable used for the map marker, which was saved in
* the res/drawable/ directory. The constructor for HelloItemizedOverlay
* (your custom ItemizedOverlay) takes the Drawable in order to set the
* default marker for all overlay items.*/
/*Initialise GPS*/
try{
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
//get fine location
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
//get coarse location
mlocManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);
boolean isGPS = mlocManager.isProviderEnabled (LocationManager.GPS_PROVIDER);
MyGPSListener myGPSListener = new MyGPSListener();
mlocManager.addGpsStatusListener(myGPSListener);
}
catch(Error e)
{
Toast.makeText( getApplicationContext(),"Error!"+e.getMessage(),Toast.LENGTH_SHORT).show();
}
GeoPoint point = new GeoPoint((int)(myCoarseLatitude * 1e6),(int) (myCoarseLongitude* 1e6));
myPositionOverlayItem = new OverlayItem(point, "Evening guvna!", "This is where i am");
/*All that's left is to add this OverlayItem to your collection in the
* HelloItemizedOverlay instance, then add the HelloItemizedOverlay to the MapView: */
myPosition.addOverlay(myPositionOverlayItem);
mapOverlays.add(myPosition);
/*begin counting 5 seconds to update positions*/
counter = new MyCount(5000,1000);
counter.start();
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public void updateMyPosition()
{
/*remove my guy*/
mapView.getOverlays().remove(myPosition);
myPosition.removeOverlay(myPositionOverlayItem);
myPosition.doPopulate();
GeoPoint point;
if(useGPSLocation)
{
point = new GeoPoint((int)(myLatitude * 1e6),(int) (myLongitude* 1e6));
}
else
{
point = new GeoPoint((int)(myCoarseLatitude * 1e6),(int) (myCoarseLongitude* 1e6));
}
myPositionOverlayItem = new OverlayItem(point, "You are here", "Awww yeah!");
myPosition.addOverlay(myPositionOverlayItem);
myPosition.doPopulate();
mapOverlays.add(myPosition);
}
public void clearTheMap()
{
mapView.getOverlays().clear();
myPosition.doPopulate();
}
/*******************************************************
* GPS!!!!!!!!
* This method gets the location of you from gps
* ************************************************/
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
String provider = loc.getProvider();
if(provider.equals(LocationManager.GPS_PROVIDER))
{
myLatitude = loc.getLatitude();
myLongitude = loc.getLongitude();
mLastLocationMillis = SystemClock.elapsedRealtime();
if((!pickedUpLocation)&&(myLatitude!=0))
{
mapController.animateTo(new GeoPoint((int)(myLatitude * 1e6),(int) (myLongitude* 1e6)));
pickedUpLocation = true;
}
}
else
{
myCoarseLatitude = loc.getLatitude();
myCoarseLongitude = loc.getLongitude();
if((!pickedUpLocation)&&(myCoarseLatitude!=0))
{
//Toast.makeText(getBaseContext(), "picked up Location with network - "+myCoarseLatitude+" "+myCoarseLongitude, Toast.LENGTH_LONG).show();
mapController.animateTo(new GeoPoint((int)(myCoarseLatitude * 1e6),(int) (myCoarseLongitude* 1e6)));
pickedUpLocation = true;
}
}
/*first time it picks up your location it will animate to where you are*/
/*
String Text = "My current location is: "+
"Latitud = " + loc.getLatitude()+
"Longitud = " + loc.getLongitude();
Toast.makeText( getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
*/
}
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT ).show();
myLatitude = -1;
myLongitude = -1;
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
myLatitude = 0;
myLongitude = 0;
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
/***********************************************
* -GPS Status monitor-
* Will see if the sattelites are still fixed to your phone
* If satellites arent available, it takes network (coarse) location
* If a fix is aquired it will use GPS (fine) location
* **********************************/
private class MyGPSListener implements GpsStatus.Listener {
public void onGpsStatusChanged(int event) {
switch (event) {
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
if (myLatitude != 0)
isGPSFix = (SystemClock.elapsedRealtime() - mLastLocationMillis) < 3000;
if (isGPSFix) { // A fix has been acquired.
useGPSLocation = true;
useNetworkLocation = false;
} else { // The fix has been lost.
useGPSLocation = false;
useNetworkLocation = true;
}
break;
case GpsStatus.GPS_EVENT_FIRST_FIX:
// Do something.
isGPSFix = true;
useGPSLocation = true;
useNetworkLocation = false;
break;
}
}
}
/*************************************************************
* Counter class for timing events
**********/
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
clearTheMap();
updateMyPosition();//redraw my guy
myPosition.doPopulate();
//Toast.makeText( getApplicationContext(),"Sent my position - used ",Toast.LENGTH_SHORT).show();
resetTimer();
}
public void resetTimer()
{
counter = new MyCount(5000,1000);
counter.start();
}
@Override
public void onTick(long millisUntilFinished) {
/*tv.setText(”Left: ” + millisUntilFinished/1000);*/
}
}
}
</code></pre>
| 0 | 4,439 |
Want to add spacing between buttons
|
<p>I have a simple task to add space between buttons in a dialog box like in the example code below obtained from <a href="http://bootboxjs.com/examples.html" rel="noreferrer">http://bootboxjs.com/examples.html</a>. Just imagine that there is more than 1 button is this example. Like save, delete, cancel, confirm.</p>
<pre><code>bootbox.dialog({
title: "This is a form in a modal.",
message: '<div class="row"> ' +
'<div class="col-md-12"> ' +
'<form class="form-horizontal"> ' +
'<div class="form-group"> ' +
'<label class="col-md-4 control-label" for="name">Name</label> ' +
'<div class="col-md-4"> ' +
'<input id="name" name="name" type="text" placeholder="Your name" class="form-control input-md"> ' +
'<span class="help-block">Here goes your name</span> </div> ' +
'</div> ' +
'<div class="form-group"> ' +
'<label class="col-md-4 control-label" for="awesomeness">How awesome is this?</label> ' +
'<div class="col-md-4"> <div class="radio"> <label for="awesomeness-0"> ' +
'<input type="radio" name="awesomeness" id="awesomeness-0" value="Really awesome" checked="checked"> ' +
'Really awesome </label> ' +
'</div><div class="radio"> <label for="awesomeness-1"> ' +
'<input type="radio" name="awesomeness" id="awesomeness-1" value="Super awesome"> Super awesome </label> ' +
'</div> ' +
'</div> </div>' +
'</form> </div> </div>',
buttons: {
success: {
label: "Save",
className: "btn-success",
callback: function () {
var name = $('#name').val();
var answer = $("input[name='awesomeness']:checked").val()
Example.show("Hello " + name + ". You've chosen <b>" + answer + "</b>");
}
}
}
}
);
</code></pre>
<p>I would like to know how to increase the spacing between the buttons so that they are placed more far apart and look spacious and the UI of the dialog box is more beautiful. I am not so good at these stuff. I have searched a lot. Please help me. Your help will be much appreciated. Thank you very much.</p>
<p>Please give some code and live example if possible. Thank you again.</p>
| 0 | 1,466 |
Deactivate a Gem - "you have already activated rake 0.9.3.beta.1, but my Gemfile requires rake 0.9.2"
|
<p>I'm trying to run a migration but I keep getting the error message that is:</p>
<pre><code>rake aborted! Undefined method prerequisite for nil:NilClass.
</code></pre>
<p>It seems that somehow I activated a gem called <code>rake 0.9.3.beta.1</code> - however I have since changed the gem <code>bundle install</code> and run <code>bundle show</code> rake and it shows that <code>rake 0.9.2</code> is installed. I'm using Git for the first time so I thought that maybe it had something to do with the application still using the beta version of rake - but I've done a push and it shows that the gemfile has been updated.</p>
<p>and when I look down into the gem libraries I can only see the <code>rake 0.9.2</code> version. Where should I be looking?</p>
<p>I also have a Rails:Railtie deprecated warning - but I'm thinking that this doesn't have anything to do with my migration problems. Its telling me to use config.app_generators in config/application.rb instead of Railtie - but i can't see that in the file. </p>
<p>This is the Config/application.rb file </p>
<pre><code>require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"
Bundler.require *Rails.groups(:assets) if defined?(Bundler)
module CrowdshareApp
class Application < Rails::Application
config.encoding = "utf-8"
config.filter_parameters += [:password]
config.assets.enabled = true
end
end
</code></pre>
<p>My Gemfile looks like this:</p>
<pre><code>source 'http://rubygems.org'
gem 'rails', '3.1.0.rc5'
gem 'sqlite3'
group :assets do
gem 'sass-rails', "~> 3.1.0.rc"
gem 'coffee-rails', "~> 3.1.0.rc"
gem 'uglifier'
end
gem 'jquery-rails'
group :development do
gem 'rspec-rails', '2.0.0.beta.18'
end
group :test do
gem 'rspec', '2.0.0.beta.18'
end
</code></pre>
<p>and the Gemfile.lock file has the following:</p>
<pre><code>GEM
remote: http://rubygems.org/
specs:
actionmailer (3.1.0.rc5)
actionpack (= 3.1.0.rc5)
mail (~> 2.3.0)
actionpack (3.1.0.rc5)
activemodel (= 3.1.0.rc5)
activesupport (= 3.1.0.rc5)
builder (~> 3.0.0)
erubis (~> 2.7.0)
i18n (~> 0.6)
rack (~> 1.3.1)
rack-cache (~> 1.0.2)
rack-mount (~> 0.8.1)
rack-test (~> 0.6.0)
sprockets (~> 2.0.0.beta.12)
activemodel (3.1.0.rc5)
activesupport (= 3.1.0.rc5)
bcrypt-ruby (~> 2.1.4)
builder (~> 3.0.0)
i18n (~> 0.6)
activerecord (3.1.0.rc5)
activemodel (= 3.1.0.rc5)
activesupport (= 3.1.0.rc5)
arel (~> 2.1.4)
tzinfo (~> 0.3.29)
activeresource (3.1.0.rc5)
activemodel (= 3.1.0.rc5)
activesupport (= 3.1.0.rc5)
activesupport (3.1.0.rc5)
multi_json (~> 1.0)
arel (2.1.4)
bcrypt-ruby (2.1.4-x86-mingw32)
builder (3.0.0)
coffee-rails (3.1.0.rc.5)
actionpack (~> 3.1.0.rc1)
coffee-script (>= 2.2.0)
railties (~> 3.1.0.rc1)
sprockets (>= 2.0.0.beta.9)
coffee-script (2.2.0)
coffee-script-source
execjs
coffee-script-source (1.1.2)
diff-lcs (1.1.2)
erubis (2.7.0)
execjs (1.2.4)
multi_json (~> 1.0)
hike (1.2.0)
i18n (0.6.0)
jquery-rails (1.0.13)
railties (~> 3.0)
thor (~> 0.14)
mail (2.3.0)
i18n (>= 0.4.0)
mime-types (~> 1.16)
treetop (~> 1.4.8)
mime-types (1.16)
multi_json (1.0.3)
nokogiri (1.5.0-x86-mingw32)
polyglot (0.3.2)
rack (1.3.2)
rack-cache (1.0.2)
rack (>= 0.4)
rack-mount (0.8.2)
rack (>= 1.0.0)
rack-ssl (1.3.2)
rack
rack-test (0.6.1)
rack (>= 1.0)
rails (3.1.0.rc5)
actionmailer (= 3.1.0.rc5)
actionpack (= 3.1.0.rc5)
activerecord (= 3.1.0.rc5)
activeresource (= 3.1.0.rc5)
activesupport (= 3.1.0.rc5)
bundler (~> 1.0)
railties (= 3.1.0.rc5)
railties (3.1.0.rc5)
actionpack (= 3.1.0.rc5)
activesupport (= 3.1.0.rc5)
rack-ssl (~> 1.3.2)
rake (>= 0.8.7)
rdoc (~> 3.4)
thor (~> 0.14.6)
rake (0.9.2)
rdoc (3.9.2)
rspec (2.0.0.beta.18)
rspec-core (= 2.0.0.beta.18)
rspec-expectations (= 2.0.0.beta.18)
rspec-mocks (= 2.0.0.beta.18)
rspec-core (2.0.0.beta.18)
rspec-expectations (2.0.0.beta.18)
diff-lcs (>= 1.1.2)
rspec-mocks (2.0.0.beta.18)
rspec-rails (2.0.0.beta.18)
rspec (>= 2.0.0.beta.14)
webrat (>= 0.7.0)
sass (3.1.7)
sass-rails (3.1.0.rc.5)
actionpack (~> 3.1.0.rc1)
railties (~> 3.1.0.rc1)
sass (>= 3.1.4)
sprockets (>= 2.0.0.beta.9)
sprockets (2.0.0.beta.13)
hike (~> 1.2)
rack (~> 1.0)
tilt (!= 1.3.0, ~> 1.1)
sqlite3 (1.3.4-x86-mingw32)
thor (0.14.6)
tilt (1.3.2)
treetop (1.4.10)
polyglot
polyglot (>= 0.3.1)
tzinfo (0.3.29)
uglifier (1.0.0)
execjs (>= 0.3.0)
multi_json (>= 1.0.2)
webrat (0.7.3)
nokogiri (>= 1.2.0)
rack (>= 1.0)
rack-test (>= 0.5.3)
PLATFORMS
x86-mingw32
DEPENDENCIES
coffee-rails (~> 3.1.0.rc)
jquery-rails
rails (= 3.1.0.rc5)
rspec (= 2.0.0.beta.18)
rspec-rails (= 2.0.0.beta.18)
sass-rails (~> 3.1.0.rc)
sqlite3
uglifier
</code></pre>
| 0 | 2,898 |
How are date and datetime supposed to be serialized SOAP (xml) messages
|
<p>We are working on a building a java client with a third party SOAP Webservice, that is I have not access or control off server side code. We are just provided with the WSDL description file of the service. We are using Axis 1 (version 1.4 ). </p>
<p>We have run into following issue related to date vs datetime serialization and deserialization. The said wsdl defines two types DateTime and DateRange</p>
<pre><code><xs:element minOccurs="0" name="DateTime" type="xs:dateTime"/>
<xs:element minOccurs="0" name="DateRange">
<xs:complexType>
<xs:sequence>
<xs:element name="Start" type="xs:date"/>
<xs:element name="End" type="xs:date"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</code></pre>
<p>Where xs prefix denotes XML Schema, that is following is present </p>
<pre><code>xmlns:xs="http://www.w3.org/2001/XMLSchema"
</code></pre>
<p>The axis wsdl2java generates Java Objects whre datetime field is type to Calendar, and start, end fields are typed to java.util.Date</p>
<p>When serialization happens the start and end fields are serialized to yyyy-mm-dd format , for example 2014-02-01
But when the actual call is made to server side we recieve following response</p>
<pre><code><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Server</faultcode>
<faultstring xml:lang="en">JiBX unmarshalling exception; nested exception is org.jibx.runtime.JiBXException: Missing 'T' separator in dateTime</faultstring>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code></pre>
<p>We used SOAP UI to build the request xml payload directly and observed if we pass just the date portion in start and end fields we get exact same response, while if we pass those two fields with time portion like a dateTime field it works, gives no fault message.</p>
<p>This when taken together with what I could gleam from XMLSchema documentation for
<a href="http://www.w3.org/TR/xmlschema-2/#date" rel="nofollow"> xs:date </a> and <a href="http://www.w3.org/TR/xmlschema-2/#dateTime" rel="nofollow">xs:dateTime</a> , in particular lexical and canonical representation section, seems to imply that</p>
<ol>
<li><p>Axis based serialization of start and end field to just yyyy-mm-dd and ignoring the time portion is correct. And client side code generated conforms to WSDL provided to us.</p></li>
<li><p>Server side code does not conform to WSDL provided to us, it expects a dateTime field rather than a date field.</p></li>
<li><p>Since date and dateTime field are required to be serialized in different formats by the schema definition. The result it failure at server side when it attempts to de-serialize
the message </p></li>
</ol>
<p>To validate our hypothesis 1. we used Python's ZSI library to generate python stub and resulting xml from it.<br>
Even that serializes start and end in yyyy-mm-dd format , with an additional 'Z' at the end.
This again fails to get deserialized at server side, even though this serialization format conforms to xs:date as defined by XML Schema</p>
<pre><code><ns1:Start>2014-02-05Z</ns1:Start>
</code></pre>
<p>Can somebody confirm if hypothesis formed by us, based on observed behaviour, documentation and experiment with Python's ZSI is correct. Or if we are missing some detail</p>
| 0 | 1,222 |
Puppet: Passing parameters through classes
|
<p>This is a follow on to my earlier question about <a href="https://stackoverflow.com/questions/21151902/puppet-stopping-service-on-individual-nodes/21153390">parameterized classes</a>. Following on that example a little further, I want to be able to pass running or stopped into the service, but when I add the service to a box, I don't use "include poodle::service", I use "include poodle" which does all of the other stuff Poodle requires to be installed.</p>
<p>So, can I pass the variable along to the service class like this:</p>
<pre><code># SITE.PP
node 'tweedle.example.com' {
include basicstuff
include poodle
}
node 'beetle.example.com' {
include basicstuff
class { 'poodle':
$ensure => 'stopped'
}
}
## POODLE MODULE, manifests/init.pp
class poodle ( $ensure = 'running' ) {
class {'poodle::install': }
class {'poodle::config': }
class {'poodle::service':
ensure => $ensure
}
Class ['poodle::install'] -> Class ['poodle::config'] ~> Class ['poodle::service']
}
...
class poodle::service ( $ensure ) {
service {'poodle':
ensure => $ensure,
enable => true,
restart => "/etc/init.d/poodle stop && sleep 5 && /etc/init.d/poodle start",
subscribe => File['/opt/poodle/poodle.py'],
}
}
</code></pre>
<p>Or should I put the parameter directly on the service class and the explicitly call both the Poodle class and Poodle's service class like this:</p>
<pre><code># SITE.PP
node 'tweedle.example.com' {
include basicstuff
include poodle
}
node 'beetle.example.com' {
include basicstuff
include poodle
class { 'poodle::service':
$ensure => 'stopped'
}
}
## POODLE MODULE, manifests/init.pp
class poodle {
class {'poodle::install': }
class {'poodle::config': }
class {'poodle::service':
ensure => $ensure
}
Class ['poodle::install'] -> Class ['poodle::config'] ~> Class ['poodle::service']
}
...
class poodle::service ( $ensure = 'running') {
service {'poodle':
ensure => $ensure,
enable => true,
restart => "/etc/init.d/poodle stop && sleep 5 && /etc/init.d/poodle start",
subscribe => File['/opt/poodle/poodle.py'],
}
}
</code></pre>
<p>Or is adding the parameter to the service class and including ONLY that enough, because the service class has dependencies, like this:</p>
<pre><code># SITE.PP
node 'tweedle.example.com' {
include basicstuff
include poodle
}
node 'beetle.example.com' {
include basicstuff
class { 'poodle::service':
$ensure => 'stopped'
}
}
## POODLE MODULE, manifests/init.pp
class poodle {
class {'poodle::install': }
class {'poodle::config': }
class {'poodle::service':
ensure => $ensure
}
Class ['poodle::install'] -> Class ['poodle::config'] ~> Class ['poodle::service']
}
...
class poodle::service ( $ensure = 'running') {
service {'poodle':
ensure => $ensure,
enable => true,
restart => "/etc/init.d/poodle stop && sleep 5 && /etc/init.d/poodle start",
subscribe => File['/opt/poodle/poodle.py'],
}
}
</code></pre>
<p>What is the right course and best practice here? Thanks in advance!</p>
| 0 | 1,374 |
Error:exception during working with external system
|
<p>I am trying to build android project in Android studio. While doing gradle sync, I am getting below error.</p>
<p><a href="https://i.stack.imgur.com/e4SrX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e4SrX.png" alt="enter image description here" /></a></p>
<p>with below Error logs.</p>
<pre><code>com.intellij.openapi.externalSystem.model.ExternalSystemException:
at org.jetbrains.plugins.gradle.service.project.AbstractProjectImportErrorHandler.createUserFriendlyError(AbstractProjectImportErrorHandler.java:106)
at org.jetbrains.plugins.gradle.service.project.BaseProjectImportErrorHandler.getUserFriendlyError(BaseProjectImportErrorHandler.java:158)
at org.jetbrains.plugins.gradle.service.project.BaseGradleProjectResolverExtension.getUserFriendlyError(BaseGradleProjectResolverExtension.java:438)
at com.android.tools.idea.gradle.project.AndroidGradleProjectResolver.getUserFriendlyError(AndroidGradleProjectResolver.java:348)
at org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension.getUserFriendlyError(AbstractProjectResolverExtension.java:164)
at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:366)
at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:332)
at org.jetbrains.plugins.gradle.service.project.GradleExecutionHelper.execute(GradleExecutionHelper.java:225)
at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:97)
at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:65)
at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:41)
at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:37)
at com.intellij.openapi.externalSystem.service.remote.AbstractRemoteExternalSystemService.execute(AbstractRemoteExternalSystemService.java:59)
at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl.resolveProjectInfo(RemoteExternalSystemProjectResolverImpl.java:37)
at com.intellij.openapi.externalSystem.service.remote.wrapper.ExternalSystemProjectResolverWrapper.resolveProjectInfo(ExternalSystemProjectResolverWrapper.java:49)
at com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask.doExecute(ExternalSystemResolveProjectTask.java:51)
at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:138)
at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:124)
at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$4.execute(ExternalSystemUtil.java:540)
at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$5$2.run(ExternalSystemUtil.java:621)
at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:563)
at com.intellij.openapi.progress.impl.CoreProgressManager$2.run(CoreProgressManager.java:152)
at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:452)
at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:402)
at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:54)
at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:137)
at com.intellij.openapi.progress.impl.ProgressManagerImpl$1.run(ProgressManagerImpl.java:126)
at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:400)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
at org.jetbrains.ide.PooledThreadExecutor$1$1.run(PooledThreadExecutor.java:56)
[ 46086] WARN - radle.project.ProjectSetUpTask -
[ 47119] WARN - inspections.IntellijLintClient - No projects found for []
[ 130021] WARN - inspections.IntellijLintClient - No projects found for []
</code></pre>
<p>and my development environment is Android studion 1.5.1 in Ubuntu 14.04LTS.</p>
<p>Can any body help me on this?</p>
| 0 | 1,452 |
use Kestrel in .NET Core worker project
|
<p>I created a new .NET Core worker project with the template provided by Visual Studio. I want to listen for incoming TCP messages and HTTP requests. I'm following <a href="https://github.com/davidfowl/MultiProtocolAspNetCore" rel="nofollow noreferrer">David Fowler's "Multi-protocol Server with ASP.NET Core and Kestrel" repository</a> on how to setup Kestrel.</p>
<p>AFAIK all I have to do is to install the <strong>Microsoft.AspNetCore.Hosting</strong> package to get access to the <code>UseKestrel</code> method.</p>
<p>In the <strong>Program.cs</strong> file I'm currently doing this</p>
<pre><code>public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
}
</code></pre>
<p>Unfortunately I can't append <code>UseKestrel</code> to the <code>ConfigureServices</code> method. I think this is because I'm working with the <code>IHostBuilder</code> interface instead of the <code>IWebHostBuilder</code> interface.</p>
<p><em>This project should not be a Web API project, it should remain as a Worker project.</em></p>
<p>Any ideas how to configure Kestrel for this?</p>
<hr />
<p>I tried to change the code to the code from the sample repository</p>
<pre><code>using System.Net;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Service
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
// ...
})
.UseKestrel(options =>
{
// ...
});
}
}
</code></pre>
<p>When doing so it is still not able to resolve <code>WebHost</code> and comes up with these errors</p>
<ul>
<li>
<blockquote>
<p>There is no argument given that corresponds to the required formal parameter 'middleware' of 'ConnectionBuilderExtensions.Run(IConnectionBuilder, Func<ConnectionContext, Task>)'</p>
</blockquote>
</li>
<li>
<blockquote>
<p>The name 'WebHost' does not exist in the current context</p>
</blockquote>
</li>
</ul>
<p>I think this happens because the worker project does not use a Web SDK.</p>
| 0 | 1,038 |
Property or method "$v" is not defined using Vuelidate
|
<p><strong>Error:</strong></p>
<blockquote>
<p>[Vue warn]: Property or method "$v" is not defined on the instance but
referenced during render. Make sure that this property is reactive,
either in the data option, or for class-based components, by
initializing the property. See:
<a href="https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties" rel="nofollow noreferrer">https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties</a>.</p>
<p>found in</p>
<p>---> at resources\assets\js\components\products\Product_create.vue
</p>
</blockquote>
<p>I'm using Vue.js and Vuelidate as validator,
I've copied and pasted this code from here <a href="https://jsfiddle.net/Frizi/b5v4faqf/" rel="nofollow noreferrer">https://jsfiddle.net/Frizi/b5v4faqf/</a> but it still doesn't work :</p>
<p><strong>Vue Component :</strong></p>
<pre class="lang-html prettyprint-override"><code> <template >
<input v-model="$v.text.$model" :class="status($v.text)">
<!-- <pre>{{ $v }}</pre> -->
</template>
<script>
import { required, minLength, between } from 'vuelidate/lib/validators'
export default {
data() {
return {
text: ''
}
},
validations: {
text: {
required,
minLength: minLength(5)
}
},
methods: {
status(validation) {
return {
error: validation.$error,
dirty: validation.$dirty
}
}
}
}
</script>
</code></pre>
<p><strong>App.js</strong></p>
<pre class="lang-js prettyprint-override"><code> require('./bootstrap');
window.Vue = require('vue');
window.VueRouter = require('vue-router').default;
window.VueAxios = require('vue-axios').default;
window.Axios = require('axios').default;
window.VueFormWizard = require('vue-form-wizard');
window.Vuelidate = require('vuelidate').default;
import 'vue-form-wizard/dist/vue-form-wizard.min.css';
Vue.use(VueRouter,VueAxios,axios,VueFormWizard,Vuelidate);
const ProductOptionCreate = Vue.component('po-create',require('./components/products/ProductOption_create.vue'));
const ProgressModal = Vue.component('vue-modal',require('./components/ProgressModal.vue'));
const ProductIndex = Vue.component('product-list',require('./components/products/Product_index.vue'));
const productshow = Vue.component('productshow',require('./components/products/ProductOption_show.vue'));
const ProductCreate = Vue.component('product-create',require('./components/products/Product_create.vue'));
const app = new Vue({
el:'#app',
});
</code></pre>
<p>What's wrong with this code?</p>
| 0 | 1,233 |
Converting a string to LPCWSTR for CreateFile() to address a serial port
|
<p>I seem to be having a bit of a TEXT / UNICODE problem when using the windows CreateFile function for addressing a serial port. Can someone please help point out my error?</p>
<p>I'm writing a Win32 console application in VC++ using VS 2008.</p>
<p>I can create a handle to address the serial port like this:</p>
<pre><code>#include <iostream>
#include <windows.h>
#include <string>
int main()
{
HANDLE hSerial;
hSerial = CreateFile( L"\\\\.\\COM20",
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);`
return 0;
}
</code></pre>
<p>That works just fine (the <code>\\\\.\\</code> bit is required for comports greater than COM9 and works for those up to COM9 also). The problem is that my comport will not always be COM20, so I'd like to have the user specify what it is.</p>
<p>Here are some things I've tried:</p>
<pre><code>#include <iostream>
#include <windows.h>
#include <string>
int main()
{
std::string comNum;
std::cout << "\n\nEnter the port (ex: COM20): ";
std::cin >> comNum;
std::string comPrefix = "\\\\.\\";
std::string comID = comPrefix+comNum;
HANDLE hSerial;
hSerial = CreateFile( comID,
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);`
return 0;
}
</code></pre>
<p>This does not compile and returns the error: <strong>error C2664: 'CreateFileW' : cannot convert parameter 1 from 'std::string' to 'LPCWSTR'</strong></p>
<p>I thought maybe specifying CreateFileA would work then, but that gave basically the same error.</p>
<p>I also tried :</p>
<pre><code>/*
everything else the same
*/
hSerial = CreateFile( TEXT(comID),
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);`
</code></pre>
<p>which also does not compile and returns: <strong>error C2065: 'LcomID' : undeclared identifier</strong></p>
<p>I am not much of an expert but I have been working on this for a while now. Can someone tell me how to replace <code>L"\\\\.\\COM20"</code> in such a way that the user can specify the comport and so that CreateFile will still work? Thanks!</p>
| 0 | 1,225 |
django errno 104 Connection reset by peer
|
<p>I am trying to run my django server on an Ubuntu instance on AWS EC2. I am using gunicorn to run the server like this :</p>
<p><code>gunicorn --workers 4 --bind 127.0.0.1:8000 woc.wsgi:application --name woc-server --log-level=info --worker-class=tornado --timeout=90 --graceful-timeout=10</code></p>
<p>When I make a request I am getting 502, Bad Gateway on the browser. Here is the server log <a href="http://pastebin.com/Ej5KWrWs" rel="noreferrer">http://pastebin.com/Ej5KWrWs</a></p>
<p>Some sections of the settings.py file where behaviour is changed based on hostname are</p>
<p>iUbuntu is the hostname of my laptop</p>
<pre><code>if socket.gethostname() == 'iUbuntu':
'''
Development mode
"iUbuntu" is the hostname of Ishan's PC
'''
DEBUG = TEMPLATE_DEBUG = True
else:
'''
Production mode
Anywhere else than Ishan's PC is considered as production
'''
DEBUG = TEMPLATE_DEBUG = False
if socket.gethostname() == 'iUbuntu':
'''Development'''
ALLOWED_HOSTS = ['*', ]
else:
'''Production Won't let anyone pretend as us'''
ALLOWED_HOSTS = ['domain.com', 'www.domain.com',
'api.domain.com', 'analytics.domain.com',
'ops.domain.com', 'localhost', '127.0.0.1']
</code></pre>
<p>(I don't get what's the purpose of this section of the code. Since I inherited the code from someone and the server was working I didn't bothered removing it without understanding what it does)</p>
<pre><code>if socket.gethostname() == 'iUbuntu':
MAIN_SERVER = 'http://localhost'
else:
MAIN_SERVER = 'http://domain.com'
</code></pre>
<p>I can't figure out what's the problem here. The same code runs fine with gunicorn on my laptop.</p>
<p>I have also made a small hello world node.js to serve on the port 8000 to test nginx configuration and it is running fine. So no nginx errors.</p>
<p>UPDATE:</p>
<p>I set DEBUG to True and copied the Traceback <a href="http://pastebin.com/ggFuCmYW" rel="noreferrer">http://pastebin.com/ggFuCmYW</a></p>
<p>UPDATE:</p>
<p>Thanks to the reply by @ARJMP. This indeed is the problem with celery consumer not getting connected to broker.</p>
<p>I am configuring celery like this : <code>app.config_from_object('woc.celeryconfig')</code> and the contents of celeryconfig.py are:</p>
<p><code>BROKER_URL = 'amqp://celeryuser:celerypassword@localhost:5672/MyVHost'
CELERY_RESULT_BACKEND = 'rpc://'</code></p>
<p>I am running the worker like this :<code>celery worker -A woc.async -l info --autoreload --include=woc.async -n woc_celery.%h</code></p>
<p>And the error that I am getting is:</p>
<p><code>consumer: Cannot connect to amqp://celeryuser:**@127.0.0.1:5672/MyVHost: [Errno 104] Connection reset by peer.</code></p>
| 0 | 1,031 |
Pod has unbound PersistentVolumeClaims but volume claims is bounded
|
<p>I want to create a statefulset elasticsearch in kubernetes on virtualbox. I'm not using cloud provider so i create two persistent volume localy for my two replicas of my statefulset :</p>
<p>pv0:</p>
<pre><code>kind: PersistentVolume
apiVersion: v1
metadata:
name: pv-elk-0
namespace: elk
labels:
type: local
spec:
storageClassName: gp2
capacity:
storage: 5Gi
accessModes:
- ReadWriteOnce
hostPath:
path: "/mnt/data/pv0"
</code></pre>
<p>pv1:</p>
<pre><code>kind: PersistentVolume
apiVersion: v1
metadata:
name: pv-elk-1
namespace: elk
labels:
type: local
spec:
storageClassName: gp2
capacity:
storage: 5Gi
accessModes:
- ReadWriteOnce
hostPath:
path: "/mnt/data/pv1"
</code></pre>
<p>Statefulset :</p>
<pre><code>apiVersion: apps/v1beta1
kind: StatefulSet
metadata:
name: elasticsearch-logging
namespace: elk
labels:
k8s-app: elasticsearch-logging
version: v5.6.2
kubernetes.io/cluster-service: "true"
addonmanager.kubernetes.io/mode: Reconcile
spec:
serviceName: elasticsearch-logging
replicas: 2
selector:
matchLabels:
k8s-app: elasticsearch-logging
version: v5.6.2
template:
metadata:
labels:
k8s-app: elasticsearch-logging
version: v5.6.2
kubernetes.io/cluster-service: "true"
spec:
serviceAccountName: elasticsearch-logging
containers:
- image: gcr.io/google-containers/elasticsearch:v5.6.2
name: elasticsearch-logging
ports:
- containerPort: 9200
name: db
protocol: TCP
- containerPort: 9300
name: transport
protocol: TCP
resources:
limits:
cpu: 0.1
volumeMounts:
- name: elasticsearch-logging
mountPath: /data
env:
- name: "NAMESPACE"
valueFrom:
fieldRef:
fieldPath: metadata.namespace
initContainers:
- image: alpine:3.6
command: ["/sbin/sysctl", "-w", "vm.max_map_count=262144"]
name: elasticsearch-logging-init
securityContext:
privileged: true
volumeClaimTemplates:
- metadata:
name: elasticsearch-logging
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: gp2
resources:
requests:
storage: 5Gi
</code></pre>
<p>It seems like the persistant volume is correctly bounced but the pod are always in crash loop and restart every time. It's it because of the use of the initContainer or something wrong with my yaml ?</p>
<p><a href="https://i.stack.imgur.com/Y0zZg.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Y0zZg.png" alt="Statefulset"></a></p>
<p><a href="https://i.stack.imgur.com/MJL5F.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MJL5F.png" alt="pv,pvc"></a></p>
| 0 | 1,267 |
Deploying WebSite builds to Azure from VSTS Release Management
|
<p>I'm kicking the tires on the preview for the Visual Studio Team Services new Release Management system. My scenario is a classic website (ASP.NET 4.5) with a Git repo hosted in VSTS. The build definition is successful as seen here:</p>
<p><a href="https://i.stack.imgur.com/MIwNS.png"><img src="https://i.stack.imgur.com/MIwNS.png" alt="enter image description here"></a> </p>
<p>It is set up to publish as an artifact that can be picked up by Release Manager as shown here:</p>
<p><a href="https://i.stack.imgur.com/dJn8J.png"><img src="https://i.stack.imgur.com/dJn8J.png" alt="enter image description here"></a></p>
<p>On the Release Manager side I have that artifact linked properly as shown here:</p>
<p><a href="https://i.stack.imgur.com/qBdoF.png"><img src="https://i.stack.imgur.com/qBdoF.png" alt="enter image description here"></a></p>
<p>And here you can see my environments as well as the associated tasks (all 3 are clones)</p>
<p><a href="https://i.stack.imgur.com/9hKp4.png"><img src="https://i.stack.imgur.com/9hKp4.png" alt="enter image description here"></a></p>
<p>When I run the release the build publishes fine, it connects to my subscription but when it attempts to find the package file it has the following error on line 101 of the output log:</p>
<p><strong>"No files were found to deploy with the search pattern 'C:\a\4fe43dd1a***.zip'"</strong></p>
<p>Here is the full output:</p>
<p><a href="https://i.stack.imgur.com/i8jmp.png"><img src="https://i.stack.imgur.com/i8jmp.png" alt="enter image description here"></a></p>
<p>This is where I am stuck as I assumed my artifact link via VSTS should resolve this path for me. Obviously I am missing an important piece of the puzzle somewhere, but I've followed the available documentation as best as I can.</p>
<p>If anyone has a solution or can point me in the right direction it would be much appreciated!</p>
<p><strong>--- EDIT ---</strong></p>
<p>I used the file picker to select a web deploy package (see below). I tried using the root website as well as the bin folder. Both attempts results in an error stating: <strong>"No files were found to deploy with search pattern 'C:\a\4fe43dd1a\Classic Website Definition\drop\ClassicWebsite\bin'"</strong> </p>
<p><a href="https://i.stack.imgur.com/Z2pit.png"><img src="https://i.stack.imgur.com/Z2pit.png" alt="enter image description here"></a></p>
<p><strong>--- EDIT 2 ---</strong></p>
<p>I added an MSBuild task to my BUILD process with the following MSBuildArguments</p>
<p><code>/p:OutDir=$(build.stagingDirectory) /p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true</code></p>
<p>and in my Copy/Publish Artifacts task I limited my output to only copy .zip files. Now in my RELEASE process when I navigate to find a "Web Deploy Package" the "drop" folder is empty. Here is a screenshot:</p>
<p><a href="https://i.stack.imgur.com/QjvMh.png"><img src="https://i.stack.imgur.com/QjvMh.png" alt="enter image description here"></a></p>
<p>I think I'm on the right path, I just need help figuring out to tune my BUILD tasks to generate the right artifacts for my RELEASE process to use. Any help would be appreciated.</p>
| 0 | 1,027 |
Symfony2: class 'Doctrine\Common\Collections\ArrayCollection' was not found in the chain configured namespaces
|
<p>Error occurs when attempting to persist a one-to-many relationship. In particular, a client may have multiple household members; a given household member is associated with one and only one client. [I am new to Symfony so errors are expected!] Your guidance gratefully accepted.</p>
<p>N.B. Alternate controller snippet below yields integrity constraint error by trying to set the client's id in the household table to null.</p>
<h3>Clients Entity snippet</h3>
<pre class="lang-php prettyprint-override"><code>namespace Mana\AdminBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Mana\AdminBundle\Entity\Clients
*
* @ORM\Table(name="clients")
* @ORM\Entity
*/
class Clients
{
protected $members;
public function __construct()
{
$this->members = new ArrayCollection();
}
public function getMembers()
{
return $this->members;
}
public function setMembers(ArrayCollection $members)
{
$this->members = $members;
}
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
* @ORM\OneToMany(targetEntity="Household", mappedBy="clients")
* @ORM\ManyToOne(targetEntity="EthDesc", inversedBy="clients")
* @ORM\JoinColumn(name="eid", referencedColumnName="id")
*/
</code></pre>
<h3>Household Entity snippet</h3>
<pre class="lang-php prettyprint-override"><code>namespace Mana\AdminBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Mana\AdminBundle\Entity\Household
*
* @ORM\Table(name="household")
* @ORM\Entity(repositoryClass="Mana\AdminBundle\Entity\HouseholdRepository")
*/
class Household {
/**
* @var integer $hid
*
* @ORM\Column(name="hid", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
* @ORM\ManyToOne(targetEntity="Clients", inversedBy="members")
* @ORM\JoinColumn(name="cid", referencedColumnName="id")
* @ORM\ManyToOne(targetEntity="EthDesc", inversedBy="members")
* @ORM\JoinColumn(name="eid", referencedColumnName="id")
*/
</code></pre>
<h3>ClientsType snippet</h3>
<pre class="lang-php prettyprint-override"><code> ->add('members', 'collection', array(
'type' => new HouseholdType(),
'allow_add' => true,
'by_reference' => false,
'cascade_validation' => true,
));
</code></pre>
<h3>Controller snippet</h3>
<pre class="lang-php prettyprint-override"><code>public function createAction(Request $request) {
$entity = new Clients();
$form = $this->createForm(new ClientsType(), $entity);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->persist($entity->getMembers());
$em->flush();
return $this->redirect($this->generateUrl('clients_show', array('id' => $entity->getId())));
}
}
</code></pre>
<h3>Alternate controller snippet</h3>
<pre class="lang-php prettyprint-override"><code>public function createAction(Request $request) {
$entity = new Clients();
$form = $this->createForm(new ClientsType(), $entity);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
foreach ($entity->getMembers() as $member)
{
$em->persist($member);
}
$em->flush();
return $this->redirect($this->generateUrl('clients_show', array('id' => $entity->getId())));
}
</code></pre>
| 0 | 1,536 |
Every time button cause full post back, even it is in update panel
|
<p>In my code every DropDownList is inside an Update Panel and they're not postbacking. For each button click full postback occurs, but my buttons are in Update Panel. I tried using the asynpostback trigger, in that case server side message is not displayed. I want that message also.</p>
<p>My code is:</p>
<pre><code><asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
</asp:ScriptManager>
<table align="center" style="border: thin solid #FF0000" width="80%">
<tr>
<th colspan="2" align="center" bgcolor="Black" style="color: #FFFFFF">
Schedule New Batch
</th>
</tr>
<tr>
<td colspan="2" align="center">
<div>
<asp:Label ID="lblError" runat="server" Style="font-weight: 700; color: #FF0000;"
Text="Label" Visible="False"></asp:Label>
<asp:Label ID="lblSucess" runat="server" Style="font-weight: 700; color: #006600;
background-color: #FFFFFF;" Text="Label" Visible="False"></asp:Label>
</div>
</td>
</tr>
<tr>
<td colspan="2">
&nbsp;
</td>
</tr>
<tr>
<td class="style44" align="right">
Technology<span class="style23">*</span> :
</td>
<td class="style45">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddlTechnology" runat="server" Width="155px" Class="valid" OnSelectedIndexChanged="ddlTechnology_SelectedIndexChanged"
AutoPostBack="True" Height="23px">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
<tr>
<td class="style49" align="right">
Courses<span class="style23">*</span> :
</td>
<td class="style50">
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddlCourse" runat="server" Width="155px" Class="valid" OnSelectedIndexChanged="ddlCourse_SelectedIndexChanged"
AutoPostBack="True" Height="23px">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
<tr>
<td class="style9" align="right">
Faculty<span class="style23">*</span> :
</td>
<td class="style47">
<asp:UpdatePanel ID="UpdatePanel3" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddlFaculty" runat="server" Width="155px" Class="valid" OnSelectedIndexChanged="ddlFaculty_SelectedIndexChanged"
AutoPostBack="True" Height="23px">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
<tr>
<td class="style44" align="right">
Timing<span class="style24">*</span> :
</td>
<td class="style45">
<asp:UpdatePanel ID="UpdatePanel4" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddlTiming" runat="server" Width="155px" Height="23px" AutoPostBack="True"
Class="valid" OnSelectedIndexChanged="ddlTiming_SelectedIndexChanged">
</asp:DropDownList>
<asp:Button ID="btnAdd" runat="server" Text="Add" />
<cc1:modalpopupextender id="btnAdd_ModalPopupExtender" runat="server" cancelcontrolid="btnCancleInsertTime"
dynamicservicepath="" enabled="True" popupcontrolid="Panel1" targetcontrolid="btnAdd">
</cc1:modalpopupextender>
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
<tr>
<td class="style44" align="right">
Start Date<span class="style23">*</span> :
</td>
<td class="style45">
<asp:UpdatePanel ID="UpdatePanel6" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtInsertdate" runat="server" Width="150px" Height="16px" Class="valid"></asp:TextBox>
<cc1:calendarextender id="CalendarExtender1" runat="server" targetcontrolid="txtInsertdate"
format="yyyy-MM-dd">
</cc1:calendarextender>
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
<tr>
<td class="style51">
&nbsp;
</td>
<td class="style45">
&nbsp;
</td>
</tr>
<tr>
<td>
<div style="text-align: right">
<asp:Button ID="btnSchedule" runat="server" Text="Schedule" Style="font-weight: 700;
margin-left: 0px;" Width="81px" Height="24px" OnClick="btnSchedule_Click" />
</div>
</td>
<td>
<asp:UpdatePanel ID="UpdatePanel5" runat="server">
<ContentTemplate>
<asp:Button ID="btnreset" runat="server" OnClick="btnreset_Click" Style="font-weight: 700"
Text="Reset" Width="67px" CausesValidation="False" UseSubmitBehavior="false" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnreset" />
</Triggers>
</asp:UpdatePanel>
</td>
</tr>
<tr>
<td colspan="3">
<asp:Panel ID="Panel1" runat="server" aline="center">
<table style="border: thin solid #FF0000; background: #7F8778">
<tr>
<th class="style53">
Please Add a Time
</th>
</tr>
<tr>
<td align="center" style="color: #FF0000" class="style53">
<asp:TextBox ID="txtInsertTime" runat="server" Width="124px"></asp:TextBox>
&nbsp; EX: 09:15AM
</td>
</tr>
<tr>
<asp:UpdatePanel ID="UpdatePanel7" runat="server">
<ContentTemplate>
<td align="center" class="style53">
<asp:Button ID="btnInsertTime" runat="server" Text="Add Time" Width="73px" OnClientClick="return InsertTime()"
OnClick="btnInsertTime_Click" class="cancel" />
&nbsp; &nbsp;
<asp:Button ID="btnCancleInsertTime" Text="Cancel" Width="55px" runat="server" class="cancel" />
</td>
</ContentTemplate>
</asp:UpdatePanel>
</tr>
</table>
</asp:Panel>
</td>
</tr>
</table>
<br />
</form>
</asp:Content>
</code></pre>
| 0 | 5,235 |
java.lang.InternalError: Can't connect to X11 window server for JVisualVM profiling session
|
<p>I have an Ubuntu server VM (<code>myapp01</code>) and have a Java application deployed there. The app has been acting wonky and I would like to profile it with JVisualVM. To do this I need to install X-Windows on my Windows 7 host, and then get the Ubuntu VM to export its X11 connection to my host when I tell it to run JVisualVM on the VM.</p>
<p>So I started by downloading XMing here:</p>
<pre><code>http://sourceforge.net/projects/xming/files/Xming/6.9.0.31/Xming-6-9-0-31-setup.exe/download
</code></pre>
<p>I used all default/recommended installation options, including using a normal PuTTy session and allowing public & private network access. After installing XMing, I launched it and verified it was running on my Windows host. I then opened up Cygwin and SSHed into the Ubuntu server:</p>
<pre><code>$ ssh myuser@myapp01
myuser@myapp01's password:
Welcome to Ubuntu 12.04.4 LTS (GNU/Linux 3.5.0-23-generic x86_64)
* Documentation: https://help.ubuntu.com/
System information as of Tue Jun 10 21:26:15 EDT 2014
System load: 0.0 Processes: 82
Usage of /: 22.5% of 11.81GB Users logged in: 0
Memory usage: 30% IP address for eth0: 10.10.41.108
Swap usage: 0%
Graph this data and manage this system at:
https://landscape.canonical.com/
38 packages can be updated.
30 updates are security updates.
Last login: Tue Jun 10 15:03:35 2014 from 10.10.101.96
</code></pre>
<p>I then export the display to what <em>appears</em> to be my host's IP:</p>
<pre><code>myuser@myapp01:~$ export DISPLAY=10.10.101.96
</code></pre>
<p>I then attempt to run JVisualVM:</p>
<pre><code>myuser@myapp01:~$ cd $JAVA_HOME
myuser@myapp01:/usr/lib/jvm/java-7-oracle-amd64$ ls
bin COPYRIGHT db include jre lib LICENSE man README.html release src.zip THIRDPARTYLICENSEREADME-JAVAFX.txt THIRDPARTYLICENSEREADME.txt
myuser@myapp01:/usr/lib/jvm/java-7-oracle-amd64$ cd bin/
myuser@myapp01:/usr/lib/jvm/java-7-oracle-amd64/bin$ ./jvisualvm
Error: Can't connect to X11 window server using '10.10.101.96' as the value of the DISPLAY variable.
See the /home/myuser/.visualvm/7u14/var/log/messages.log for details.
myuser@myapp01:/usr/lib/jvm/java-7-oracle-amd64/bin$ vim /home/myuser/.visualvm/7u14/var/log/messages.log
</code></pre>
<p>Inside <code>/home/myuser/.visualvm/7u14/var/log/messages.log</code>:</p>
<pre><code>java.lang.InternalError: Can't connect to X11 window server using '10.10.101.96' as the value of the DISPLAY variable.
at sun.awt.X11GraphicsEnvironment.initDisplay(Native Method)
at sun.awt.X11GraphicsEnvironment.access$200(X11GraphicsEnvironment.java:65)
at sun.awt.X11GraphicsEnvironment$1.run(X11GraphicsEnvironment.java:110)
at java.security.AccessController.doPrivileged(Native Method)
at sun.awt.X11GraphicsEnvironment.<clinit>(X11GraphicsEnvironment.java:74)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:190)
at java.awt.GraphicsEnvironment.createGE(GraphicsEnvironment.java:102)
at java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(GraphicsEnvironment.java:81)
at org.netbeans.core.startup.Main.start(Main.java:200)
at org.netbeans.core.startup.TopThreadGroup.run(TopThreadGroup.java:84)
at java.lang.Thread.run(Thread.java:745)
</code></pre>
<p>Ideas? I am VPNed in, could that be affecting anything? Do I have XMing misconfigured somehow? Is my <code>export DISPLAY</code> command wrong?</p>
| 0 | 1,300 |
Ajax - How refresh <DIV> after submit
|
<p>How can I refresh just part of the page ("DIV") after my application releases a submit?
I'm use JQuery with plugin ajaxForm.
I set my target with "divResult", but the page repeat your content inside the "divResult".
Sources:</p>
<pre><code> <script>
$(document).ready(function() {
$("#formSearch").submit(function() {
var options = {
target:"#divResult",
url: "http://localhost:8081/sniper/estabelecimento/pesquisar.action"
}
$(this).ajaxSubmit(options);
return false;
});
})
</script>
</code></pre>
<p>Page</p>
<pre><code> <s:form id="formSearch" theme="simple" class="formulario" method="POST">
...
<input id="btTest" type="submit" value="test" >
...
<div id="divResult" class="quadro_conteudo" >
<table id="tableResult" class="tablesorter">
<thead>
<tr>
<th style="text-align:center;">
<input id="checkTodos" type="checkbox" title="Marca/Desmarcar todos" />
</th>
<th scope="col">Name</th>
<th scope="col">Phone</th>
</tr>
</thead>
<tbody>
<s:iterator value="entityList">
<s:url id="urlEditar" action="editar"><s:param name="id" value="%{id}"/></s:url>
<tr>
<td style="text-align:center;"><s:checkbox id="checkSelecionado" name="selecionados" theme="simple" fieldValue="%{id}"></s:checkbox></td>
<td> <s:a href="%{urlEditar}"><s:property value="name"/></s:a></td>
<td> <s:a href="%{urlEditar}"><s:property value="phone"/></s:a></td>
</tr>
</s:iterator>
</tbody>
</table>
<div id="pager" class="pager">
<form>
<img src="<%=request.getContextPath()%>/plugins/jquery/tablesorter/addons/pager/icons/first.png" class="first"/>
<img src="<%=request.getContextPath()%>/plugins/jquery/tablesorter/addons/pager/icons/prev.png" class="prev"/>
<input type="text" class="pagedisplay"/>
<img src="<%=request.getContextPath()%>/plugins/jquery/tablesorter/addons/pager/icons/next.png" class="next"/>
<img src="<%=request.getContextPath()%>/plugins/jquery/tablesorter/addons/pager/icons/last.png" class="last"/>
<select class="pagesize">
<option selected="selected" value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="<s:property value="totalRegistros"/>">todos</option>
</select>
<s:label>Total de registros: <s:property value="totalRegistros"/></s:label>
</form>
</div>
<br/>
</div>
</code></pre>
<p>Thanks.</p>
| 0 | 2,799 |
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index in C# asp.Net
|
<p>I am implementing Grid View in my application...When i try to delete a record from the Grid View it throws this error:</p>
<p><strong>Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index</strong></p>
<p>This is my Server side Code:</p>
<pre><code>protected void gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
foreach (GridViewRow gv in gridview1.Rows)
{
CheckBox check = (CheckBox)gv.FindControl("deleteall");
if (check.Checked)
{
con.Open();
if (gridview1.DataKeys != null)
{
**In this line only the error occurs**
int RegNo = Convert.ToInt32(gridview1.DataKeys[gv.RowIndex].Value);
}
cmd = new MySqlCommand("delete from studentinfo where Regno='" + 1 + "'", con);
// cmd.Parameters.Add("@id", RegNo);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
</code></pre>
<p>My Client Side Grid :</p>
<pre><code> <asp:GridView ID="gridview1" runat="server" AutoGenerateColumns="False" AllowSorting="True" onrowdeleting="gridview1_RowDeleting" SelectedIndex="1">
<Columns>
<asp:TemplateField HeaderText="Delete All">
<ItemTemplate>
<asp:CheckBox ID="deleteall" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Register Number">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("RegNo") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("RegNo") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Section">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Section") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Section") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />
</Columns>
</asp:GridView>
</code></pre>
<p>Can any one pls help me sove this problem by providing some ideas or sample code...</p>
| 0 | 1,097 |
Error: Cause: compileSdkVersion is not specified
|
<p>I have problem with project in github <a href="https://github.com/joaopedronardari/OpenCV-AndroidSamples" rel="nofollow noreferrer">https://github.com/joaopedronardari/OpenCV-AndroidSamples</a> I clone in my android studio, and error. I don't know that's project maybe expired or what. but it is uploaded 3 years ago. please help with my problem, and I appreciate to everyone that responds to my question (answer and fix my word)
this is the gradle</p>
<p>Build gradle (app):</p>
<pre><code>apply plugin: 'com.android.application'
model {
android {
compileSdkVersion = 22
buildToolsVersion = "23.0.0"
defaultConfig.with {
applicationId = "com.jnardari.opencv_androidsamples"
minSdkVersion.apiLevel = 10
targetSdkVersion.apiLevel = 22
versionCode = 1
versionName = "1.0"
}
}
android.buildTypes {
release {
minifyEnabled = false
proguardFiles += file('proguard-rules.pro')
}
}
/*
* native build settings
*/
android.ndk {
moduleName = "ndklibrarysample"
cppFlags += ["-std=c++11", "-fexceptions", "-frtti"]
cppFlags += "-I${file("C:/Users/jnardari/Desktop/OpenCV-android-sdk/sdk/native/jni/include")}".toString()
ldLibs += ["android", "EGL", "GLESv2", "dl", "log", "z"]
stl = "gnustl_static"
}
android.productFlavors {
create("arm") {
ndk.with {
abiFilters += "armeabi"
File curDir = file('./')
curDir = file(curDir.absolutePath)
String libsDir = curDir.absolutePath + "\\src\\main\\jniLibs\\armeabi\\"
ldLibs += libsDir + "libopencv_java3.so"
}
}
create("armv7") {
ndk.with {
abiFilters += "armeabi-v7a"
File curDir = file('./')
curDir = file(curDir.absolutePath)
String libsDir = curDir.absolutePath + "\\src\\main\\jniLibs\\armeabi-v7a\\"
ldLibs += libsDir + "libopencv_java3.so"
}
}
create("x86") {
ndk.with {
abiFilters += "x86"
File curDir = file('./')
curDir = file(curDir.absolutePath)
String libsDir = curDir.absolutePath + "\\src\\main\\jniLibs\\x86\\"
ldLibs += libsDir + "libopencv_java3.so"
}
}
create("mips") {
ndk.with {
abiFilters += "mips"
File curDir = file('./')
curDir = file(curDir.absolutePath)
String libsDir = curDir.absolutePath + "\\src\\main\\jniLibs\\mips\\"
ldLibs += libsDir + "libopencv_java3.so"
}
}
create("fat") {
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:22.2.1'
compile project(':libraries:opencv')
}
</code></pre>
<p>Build gradle (project):</p>
<pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
mavenCentral()
maven {
url 'https://maven.google.com/'
name 'Google'
}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.3'
}
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
allprojects {
repositories {
jcenter()
}
}
</code></pre>
<p>And this is gradle-wrapper:</p>
<pre><code>#Sun Jul 22 04:30:58 ICT 2018
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
</code></pre>
| 0 | 1,622 |
Cannot read property 'injector' of null jasmine angular 2
|
<p>I'm getting this error when running a jasmine spec in angular 2:</p>
<blockquote>
<p>Cannot read property 'injector' of null jasmine angular 2</p>
</blockquote>
<p>stack trace:</p>
<pre><code>TypeError: Cannot read property 'injector' of null
at TestBed._createCompilerAndModule (http://localhost:3002/node_modules/@angular/core/bundles/core-testing.umd.js:834:48)
at TestBed._initIfNeeded (http://localhost:3002/node_modules/@angular/core/bundles/core-testing.umd.js:800:43)
at TestBed.createComponent (http://localhost:3002/node_modules/@angular/core/bundles/core-testing.umd.js:884:18)
at Function.TestBed.createComponent (http://localhost:3002/node_modules/@angular/core/bundles/core-testing.umd.js:714:33)
at Object.eval (http://localhost:3002/js/app/landing-page/subcomponents/middle-row.component.spec.js:29:49)
at ZoneDelegate.invoke (http://localhost:3002/node_modules/zone.js/dist/zone.js:232:26)
at ProxyZoneSpec.onInvoke (http://localhost:3002/node_modules/zone.js/dist/proxy.js:79:39)
at ZoneDelegate.invoke (http://localhost:3002/node_modules/zone.js/dist/zone.js:231:32)
at Zone.run (http://localhost:3002/node_modules/zone.js/dist/zone.js:114:43)
at Object.eval (http://localhost:3002/node_modules/zone.js/dist/jasmine-patch.js:102:34)
</code></pre>
<p>I have copied this spec from <a href="https://angular.io/docs/ts/latest/guide/testing.html" rel="noreferrer">the official angular 2 testing docs</a>:</p>
<pre><code>let comp: BannerComponent;
let fixture: ComponentFixture<BannerComponent>;
let de: DebugElement;
let el: HTMLElement;
describe('BannerComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ BannerComponent ], // declare the test component
});
fixture = TestBed.createComponent(BannerComponent);
comp = fixture.componentInstance; // BannerComponent test instance
// query for the title <h1> by CSS element selector
de = fixture.debugElement.query(By.css('h1'));
el = de.nativeElement;
});
});
</code></pre>
<p>and adapted it ever so slightly to work with my code:</p>
<pre><code>import 'zone.js/dist/long-stack-trace-zone.js';
import 'zone.js/dist/async-test.js';
import 'zone.js/dist/fake-async-test.js';
import 'zone.js/dist/sync-test.js';
import 'zone.js/dist/proxy.js';
import 'zone.js/dist/jasmine-patch.js';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { MiddleRowComponent } from './middle-row.component';
let comp: MiddleRowComponent;
let fixture: ComponentFixture<MiddleRowComponent>;
let de: DebugElement;
let el: HTMLElement;
describe('MiddleRowComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [MiddleRowComponent], // declare the test component
});
fixture = TestBed.createComponent(MiddleRowComponent);
comp = fixture.componentInstance; // MiddleRowComponent test instance
// query for the title <h1> by CSS element selector
de = fixture.debugElement.query(By.css('h1'));
el = de.nativeElement;
});
it('should display original title', () => {
fixture.detectChanges();
expect(el.textContent).toContain(comp.word);
});
it('should display a different test title', () => {
comp.word = 'Test Title';
fixture.detectChanges();
expect(el.textContent).toContain('Test Title');
});
});
</code></pre>
<p>Why am I getting the error? There is no inject keyword but I guess the <code>TestBed</code> might use it behind the scenes.</p>
| 0 | 1,348 |
failed to execute 'put' on 'idbobjectstore' evaluating the object store's key path did not yield a value
|
<p>A chrome based APP which I am supporting gives us this error.
I tried to find out more about the error but was unsuccessful.
Can someone kindly explain me on what could be the cause of this.</p>
<p>The Error is as below Image</p>
<p><a href="https://i.stack.imgur.com/NZ9LY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NZ9LY.png" alt="enter image description here"></a></p>
<p>The put is happening at this snippet
var ydbRequest = ydbStorage.put(dbName, data);
The dbName: OUTLETS
and the data value is:</p>
<pre><code>1. Action: "Submit"
2. ChannelGroup: "ZC03"
3. City: "LA"
4. CreateDate: Fri Jun 24 2016 10:23:03 GMT-0400 (Eastern Daylight Time)
5. MUValue: Object
6. ModifiedDate: Mon Jun 27 2016 11:16:24 GMT-0400 (Eastern Daylight Time)
7. Mu: "U39 "
8. Name: "54321"
9. OutletId: "0000054321"
10. OutletImage: ""
11. Promotion: Object
12. SignatureImage: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAABLCAYAAABeMdGUAAAFTElEQVR4Xu3azcttUxwH8O8l8pKSDMxIUTJQTEwUiZmZlBEzMyV/gPwBUmZGzJTMzIjIxMTgDqSUGBpISl7y3qqz6/Y4z3nOWXc/Z+3ffj6n7uTe/dvrtz5r3f1tv1yKHwECBAgQ6BC41FGjhAABAgQIRIDYBAQIECDQJSBAutgUESBAgIAAsQcIECBAoEtAgHSxKSJAgAABAWIPECBAgECXgADpYlNEgAABAgLEHiBAgACBLgEB0sWmiAABAgQEiD1AgAABAl0CAqSLTREBAgQICBB7gAABAgS6BARIF5siAgQIEBAg9gABAgQIdAkIkC42RQQIECAgQOwBAgQIEOgSECBdbIoIECBAQIDYAwQIECDQJSBAutgUESBAgIAAsQcIECBAoEtAgHSxKSJAgAABAWIPECBAgECXgADpYlNEgAABAgLEHiBAgACBLgEB0sWmiAABAgQEiD1AgAABAl0CAqSLTREBAgQICBB7gMC6BN5K8mmSt9c1LbNZooAAWeKq6IlAv8C3SR5L8l3/KVQS2E9AgOzn5CgCFQTu3Nx93FWhWT3WFxAg9dfQDAhMAs9t7j6eR0LgGAIC5BjKxiBwHAHvP47jbJSNgACxFQisR8D7j/WsZYmZCJASy6RJAmcKeP9xJpED5hYQIHOLOh+BMQLef4xxv9CjCpALvfwmvyKBv5M8mOTyiuZkKgsXECALXyDtEdhD4PskbyZ5ZY9jHUJgNgEBMhulExEYIvBxkmuSPDpkdINeaAEBcqGXfxGTfy/JI0luTXLdVXb071XWt/JDz/Fbks+TPDHD2Iee4tUkLyS549BCxxOYQ0CAzKHoHLsEvkhyf5Lrk1TYb4cGSJv7lfNq9b8cIVQ+2QTvtbYfgVECFf5Dj7JZ6rivJXlpqc2dERLt4vpnkp+SfJbk6QXPo6e1D5M8nOTmLaHyc5IfknyV5IMkb3QM8H6Sx5PcmKTd+dzUcQ4lBGYTECCzUZ7riX7cPOKpsF4tJP5I8mWSh85VpcbJp1C5IUm7W9i2hs2sfUXVQmbbr9VOofFRkqdqTF2XaxeocEFa+xqcNr+/NhecK//9ny1/d1F91jDvF5M8meS+JLfveP/S7taExhpWfGVzECBjF7R9s3/vifcDJ5+nt8c9t41t0+gECBD4v0CFAGmPQ9rXORV6PSn8a5L2+OGQ3tvjjNeTvGzDEiBAYMkCh1zYRs6jXVTbn/a9+1J/7yR5ZhMWJ12nL3um9wNfJ3lgqRPRFwECBPYRqBIgbS7TFzztc9DRv/ays30B0/y2GbZ3Fe8meXZ0o8YnQIDAeQlUCpApRObsuX1Sec8edza7xmzB9rtPKs9rizovAQJLFZjzYnysObYL9qF9t0dGd2+C4tDaKbjauO2dxi3HmqhxCBAgsGSBnovpEuYzvRPZ1ctpc5tqW6i0zyf9CBAgQKBDoGqATHcFu6Y8BcU3m09lO3iUECBAgMBpApUDxKoSIECAwEABATIQ39AECBCoLCBAKq+e3gkQIDBQQIAMxDc0AQIEKgsIkMqrp3cCBAgMFBAgA/ENTYAAgcoCAqTy6umdAAECAwUEyEB8QxMgQKCygACpvHp6J0CAwEABATIQ39AECBCoLCBAKq+e3gkQIDBQQIAMxDc0AQIEKgsIkMqrp3cCBAgMFBAgA/ENTYAAgcoCAqTy6umdAAECAwUEyEB8QxMgQKCygACpvHp6J0CAwEABATIQ39AECBCoLCBAKq+e3gkQIDBQQIAMxDc0AQIEKgsIkMqrp3cCBAgMFBAgA/ENTYAAgcoCAqTy6umdAAECAwX+AwgEXkzfHpKFAAAAAElFTkSuQmCC"
13. State: "NV"
14. Status: "Signed"
15. Street: "11 ABC"
16. TargetCMAID: "54AAFF2ECAFF4410E1008000A7692971"
17. Year: 2015
18. ZipCode: "89201"
19. _disabledStates: Object
20. _displayOrderLimit: Object
21. _recallState: "fsop.outlet.review-sign.summary"
22. _validationStates: Object
23. __proto__: Object
</code></pre>
<p>Let me know in case I need to add more details.</p>
<p>TIA</p>
| 0 | 1,908 |
Angular How to filter array data by searching in input
|
<p>How to filter an array object in input text - angular
I'm trying to make an search bar to filter where the user can search the location/description which I name it "sensor".</p>
<h3>roomlist.component.ts</h3>
<pre><code> validateForm: FormGroup;
rowData: templogRecord[] = [];
option: any = [];
onLoad() {
this.rowData = record.default.records;
this.option = [];
this.rowData.forEach(room => {
this.option.push({
tooltip: {
formatter: "{a} <br/>{b} : {c}°"
},
toolbox: {
show: true,
feature: {
mark: { show: false },
restore: { show: false },
saveAsImage: { show: false }
}
},
series: [
{
name: room.sensor,
type: 'gauge',
center: ['40%', '70%'],
splitNumber: 10,
radius: '70%',
axisLine: {
lineStyle: {
color: [[0.2, '#48b'], [0.8, '#228b22'], [1, '#ff0000']],
width: 8
}
},
axisTick: {
splitNumber: 10,
length: 12,
lineStyle: {
color: 'auto'
}
},
axisLabel: {
textStyle: {
color: 'auto'
}
},
splitLine: {
show: true,
length: 30,
lineStyle: {
color: 'auto'
}
},
pointer: {
width: 5
},
title: {
show: true,
offsetCenter: [0, '65%'],
textStyle: {
fontWeight: 'bolder'
}
},
detail: {
formatter: '{value}°',
textStyle: {
color: 'auto',
fontWeight: 'bolder'
}
},
data: [{ value: this.tempGenerator(), name: "Temperature" }]
},
{
name: '转速',
type: 'gauge',
center: ['70%', '25%'],
splitNumber: 10,
radius: '40%',
axisLine: {
lineStyle: {
width: 8
}
},
axisTick: {
length: 12,
lineStyle: {
color: 'auto'
}
},
splitLine: {
length: 20,
lineStyle: {
color: 'auto'
}
},
pointer: {
width: 5
},
title: {
show: true,
offsetCenter: [0, '80%'],
textStyle: {
fontWeight: 'bolder',
}
},
detail: {
formatter: '{value}%',
offsetCenter: [0, '55%'],
textStyle: {
color: 'auto',
fontSize: 18,
fontWeight: 'bolder'
}
},
data: [{ value: 1.5, name: "Humidity" }]
}
]
});
});
}
tempGenerator() {
var time = 12;
var num = Math.random() * 100;
var tempBase = Math.round(num);
var fluc = [0, 1, 1, 2, 1, 1, 2.5, 3.5, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
return tempBase * fluc[time];
}
searchData(searchValue: any) {
if (searchValue.length >= 3) {
this.rowData = this.rowData.filter((data: templogRecord) => {
console.log(data['sensor']);
});
} else if (searchValue.length < 1) {
console.log('empty')
}
}
}
</code></pre>
<h3>roomlist.json</h3>
<pre><code>{
"records": [
{
"dateandtime": "2018-06-14 02:24:02",
"sensor": "Nine Seal Area",
"temperature": "25.9",
"humidity": "99.9"
},
{
"dateandtime": "2018-06-14 02:24:02",
"sensor": "Ten Line2",
"temperature": "25.9",
"humidity": "99.9"
},
{
"dateandtime": "2018-06-14 02:22:01",
"sensor": "Eight Line1",
"temperature": "25.9",
"humidity": "99.9"
}
]
}
</code></pre>
<p><strong>room-list.component.html</strong></p>
<pre><code><div class="flex-container">
<div class="date-filter">
<nz-input-group [nzSuffix]="suffixIconSearch">
<input type="text"
nz-input placeholder="Search"
[(ngModel)]="filterSearch"
(ngModelChange)="searchData($event)"
/>
</nz-input-group>
<ng-template #suffixIconSearch>
<i nz-icon nzType="search"></i>
</ng-template>
</div>
<ul class="cards">
<li class="cards__item" *ngFor="let data of option">
<div class="card">
<div echarts [options]="data" [autoResize]="true"></div>
<div class="card__content">
<button class="btn btn--block card__btn">Button</button>
</div>
</div>
</li>
</ul>
</div>
</code></pre>
<p>In the <code>searchData</code> function, I'm trying to make it filtering while typing based in location/description which I named it "sensor".</p>
| 0 | 3,242 |
`java` command is not found from this Python process. Please ensure Java is installed and PATH is set for `java`
|
<p>I don't know how to fix this error when I'm trying to run the following code: </p>
<pre><code>df = wrapper.read_pdf(r'C:\End_to_End\1902\PN\Scenario1_AllCorrectMin\EPR.pdf')
</code></pre>
<p>Log:</p>
<pre><code>FileNotFoundError Traceback (most recent call last)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\tabula\wrapper.py in read_pdf(input_path, output_format, encoding, java_options, pandas_options, multiple_tables, **kwargs)
107 try:
--> 108 output = subprocess.check_output(args)
109
~\AppData\Local\Continuum\anaconda3\lib\subprocess.py in check_output(timeout, *popenargs, **kwargs)
335 return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
--> 336 **kwargs).stdout
337
~\AppData\Local\Continuum\anaconda3\lib\subprocess.py in run(input, timeout, check, *popenargs, **kwargs)
402
--> 403 with Popen(*popenargs, **kwargs) as process:
404 try:
~\AppData\Local\Continuum\anaconda3\lib\subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors)
708 errread, errwrite,
--> 709 restore_signals, start_new_session)
710 except:
~\AppData\Local\Continuum\anaconda3\lib\subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, unused_restore_signals, unused_start_new_session)
996 os.fspath(cwd) if cwd is not None else None,
--> 997 startupinfo)
998 finally:
FileNotFoundError: [WinError 2] The system cannot find the file specified
During handling of the above exception, another exception occurred:
JavaNotFoundError Traceback (most recent call last)
<ipython-input-3-010e34a004ec> in <module>()
----> 1 df = wrapper.read_pdf(r'C:\End_to_End\1902\PN\Scenario1_AllCorrectMin\EPR.pdf')
~\AppData\Local\Continuum\anaconda3\lib\site-packages\tabula\wrapper.py in read_pdf(input_path, output_format, encoding, java_options, pandas_options, multiple_tables, **kwargs)
109
110 except FileNotFoundError as e:
--> 111 raise JavaNotFoundError(JAVA_NOT_FOUND_ERROR)
112
113 except subprocess.CalledProcessError as e:
JavaNotFoundError: `java` command is not found from this Python process. Please ensure Java is installed and PATH is set for `java`
</code></pre>
<p>I tried changing and creating the path in the environmental variables but did not work. Here is the screenshot:</p>
<p><a href="https://i.stack.imgur.com/Hl48o.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Hl48o.jpg" alt="System_Properties"></a></p>
<p>Does anyone know how to fix this? I have java version 8 (Checked through about java)</p>
| 0 | 1,329 |
UICollection View - Segue - did select specific cell , LOG
|
<p>I am starting to use a UICOllectionview to load a custom made photo album, the album loads just fine, and the data is coming from my server (SQL-JSON-NSARRAY-NSDictionary) and been populated in the cell's just fine, However now I would like it when the user selects that cell to load a new UIVIewController with that image in full size (so they can view/print/share etc) </p>
<p>However I am getting stuck in the 'prepare for segue' method, as I cannot pull any information from that specific cell</p>
<p>as a test right now I just want a NSLOG to say "the User selected TITLE OF ALBUM %@ "</p>
<p>Here is my code thus far, any help would greatly be appreciated...</p>
<pre><code>#import "AlbumViewController.h"
#import "AlbumCustomCell.h"
#import "PhotosInAlbumsViewController.h"
@interface AlbumViewController ()
@end
@implementation AlbumViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
/// Grab Photo Album information (pics,title,date) From Server
NSString *myURL1 = [ NSString stringWithFormat: @"http://mywebsiteaddress.com/index.php"];
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:myURL1]];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *items = [json objectForKey:@"users"];
photoalbumarray = items;
// NSLog(@"%@", photoalbumarray);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [photoalbumarray count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellID = @"CelliD";
AlbumCustomCell *myCell = (AlbumCustomCell *) [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
// this above states to setup the cell using the Identifier I specified in Sotry board, so that cell is constantly reused
if (indexPath.section == 0) {
NSDictionary *item = [photoalbumarray objectAtIndex:[indexPath row]];
myCell.titleincell.text = [item objectForKey:@"title"]; // this puts the title in the cell
teststring = [item objectForKey:@"title"];
myCell.dateincell.text = [item objectForKey:@"date"]; // this puts the date in the data label in the cell
// myCell.imageincell1.image = [UIImage imageNamed:[item objectForKey:@"img1"]]; // this puts the picture in the cell
myCell.imageincell2.image = [UIImage imageNamed:[item objectForKey:@"img2"]]; // this puts the picture in the cell
myCell.imageincell3.image = [UIImage imageNamed:[item objectForKey:@"img3"]]; // this puts the picture in the cell
// IMAGE 1
NSString *picture1 = [item objectForKey:@"img1"];
NSURL *imageURL1 = [NSURL URLWithString:picture1];
NSData * imageData1 = [NSData dataWithContentsOfURL:imageURL1];
UIImage * image1 = [UIImage imageWithData:imageData1];
myCell.imageincell1.image = image1;
myCell.imageincell1.alpha = 0.0;
[UIView animateWithDuration:1.5 animations:^{
myCell.imageincell1.alpha = 1.0;
}];
// IMAGE 2
NSString *picture2 = [item objectForKey:@"img2"];
NSURL *imageURL2 = [NSURL URLWithString:picture2];
NSData * imageData2 = [NSData dataWithContentsOfURL:imageURL2];
UIImage * image2 = [UIImage imageWithData:imageData2];
myCell.imageincell2.image = image2;
myCell.imageincell2.alpha = 0.0;
[UIView animateWithDuration:1.5 animations:^{
myCell.imageincell2.alpha = 1.0;
}];
// I MAGE 3
NSString *picture3 = [item objectForKey:@"img3"];
NSURL *imageURL3 = [NSURL URLWithString:picture3];
NSData * imageData3 = [NSData dataWithContentsOfURL:imageURL3];
UIImage * image3 = [UIImage imageWithData:imageData3];
myCell.imageincell3.image = image3;
myCell.imageincell3.alpha = 0.0;
[UIView animateWithDuration:1.5 animations:^{
myCell.imageincell3.alpha = 1.0;
}];
}
return myCell;
}
// SEGUE TRANSITION FROM ALBUMS TO PHOTO
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:@"showPhotoAlbum"]) {
NSLog(@"Prepare for Segue to load Specific Photo Album");
NSLog(@"User Selected this cell or the name of the title in the cell which comes from a NSDictionary =>");
// EXAMPLE NSLOG TO SHOW => User Selected - Album Name
// Where album name is actually the album name grabbed form the server based on the selected row
}
}
@end
</code></pre>
<p>and just so you can see my JSON data from the server coming in, here that is</p>
<pre><code>2012-10-01 13:02:53.856 CB Photo[3957:907] (
{
date = "2012-10-01 07:23:01";
id = 1;
img1 = "http://b2fdev.ca/demo/CBPhoto/pic1.jpg";
img2 = "http://b2fdev.ca/demo/CBPhoto/pic2.jpg";
img3 = "http://b2fdev.ca/demo/CBPhoto/pic3.jpg";
title = "Paul and Jenna's Wedding 2012";
},
{
date = "2012-10-01 05:23:23";
id = 2;
img1 = "http://core1.ca/wp-content/themes/custom-community/images/block4.png";
img2 = "http://core1.ca/wp-content/themes/custom-community/images/block3.png";
img3 = "http://core1.ca/wp-content/themes/custom-community/images/block2.png";
title = "Core 1";
}
)
</code></pre>
| 0 | 2,254 |
Error with GLUT compile in ubuntu
|
<p>I try to compile some "hello world" glut application:</p>
<pre><code>#include <stdlib.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
GLint Width = 512, Height = 512;
const int CubeSize = 200;
void Display(void)
{
int left, right, top, bottom;
left = (Width - CubeSize) / 2;
right = left + CubeSize;
bottom = (Height - CubeSize) / 2;
top = bottom + CubeSize;
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
glColor3ub(255,0,0);
glBegin(GL_QUADS);
glVertex2f(left,bottom);
glVertex2f(left,top);
glVertex2f(right,top);
glVertex2f(right,bottom);
glEnd();
glFinish();
}
void Reshape(GLint w, GLint h)
{
Width = w;
Height = h;
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, w, 0, h, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void Keyboard(unsigned char key, int x, int y)
{
#define ESCAPE '\033'
if( key == ESCAPE )
exit(0);
}
main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB);
glutInitWindowSize(Width, Height);
glutCreateWindow("Red square example");
glutDisplayFunc(Display);
glutReshapeFunc(Reshape);
glutKeyboardFunc(Keyboard);
glutMainLoop();
}
</code></pre>
<p>The compile command is:</p>
<pre><code>gcc -lGL -lGLU hw_opengl.cpp -o hw_opengl
</code></pre>
<p>I've got the following errors:</p>
<pre><code>/tmp/ccbnBFHC.o: In function `Display()':
hw_opengl.cpp:(.text+0x6c): undefined reference to `glClearColor'
hw_opengl.cpp:(.text+0x78): undefined reference to `glClear'
hw_opengl.cpp:(.text+0x94): undefined reference to `glColor3ub'
hw_opengl.cpp:(.text+0xa0): undefined reference to `glBegin'
hw_opengl.cpp:(.text+0xb4): undefined reference to `glVertex2f'
hw_opengl.cpp:(.text+0xc8): undefined reference to `glVertex2f'
hw_opengl.cpp:(.text+0xdc): undefined reference to `glVertex2f'
hw_opengl.cpp:(.text+0xf0): undefined reference to `glVertex2f'
hw_opengl.cpp:(.text+0xf5): undefined reference to `glEnd'
hw_opengl.cpp:(.text+0xfa): undefined reference to `glFinish'
/tmp/ccbnBFHC.o: In function `Reshape(int, int)':
hw_opengl.cpp:(.text+0x134): undefined reference to `glViewport'
hw_opengl.cpp:(.text+0x140): undefined reference to `glMatrixMode'
hw_opengl.cpp:(.text+0x145): undefined reference to `glLoadIdentity'
hw_opengl.cpp:(.text+0x173): undefined reference to `glOrtho'
hw_opengl.cpp:(.text+0x17f): undefined reference to `glMatrixMode'
hw_opengl.cpp:(.text+0x184): undefined reference to `glLoadIdentity'
/tmp/ccbnBFHC.o: In function `main':
hw_opengl.cpp:(.text+0x1c1): undefined reference to `glutInit'
hw_opengl.cpp:(.text+0x1cd): undefined reference to `glutInitDisplayMode'
hw_opengl.cpp:(.text+0x1e4): undefined reference to `glutInitWindowSize'
hw_opengl.cpp:(.text+0x1f0): undefined reference to `glutCreateWindow'
hw_opengl.cpp:(.text+0x1fc): undefined reference to `glutDisplayFunc'
hw_opengl.cpp:(.text+0x208): undefined reference to `glutReshapeFunc'
hw_opengl.cpp:(.text+0x214): undefined reference to `glutKeyboardFunc'
hw_opengl.cpp:(.text+0x219): undefined reference to `glutMainLoop'
collect2: ld returned 1 exit status
</code></pre>
<p>I've install GLUT:
sudo apt-get install freeglut3 freeglut3-dev</p>
<p>There are in /usr/lib:
libglut.a<br>
libglut.so<br>
libglut.so.3<br>
libglut.so.3.9.0 </p>
<pre><code>locate glu.h
/home/goran/QtSDK/QtSources/4.8.0/src/3rdparty/webkit/Source/ThirdParty/glu/internal_glu.h
/usr/include/GL/glu.h
/usr/include/GL/gl.h
locate gl.h
...
/usr/include/GL/gl.h
</code></pre>
<p>What do I do incorrectly?</p>
| 0 | 1,587 |
Load .yml file into hashmaps using snakeyaml (import junit library)
|
<p>I am trying to load opencv's .yml file into arrayLists mean, projection and labels. I ve create those three arraylists and I am trying to parse into them the elements from the .yml file. I ve found <a href="https://code.google.com/p/snakeyaml/wiki/Documentation" rel="noreferrer">snakeYAML documentation </a>. However I didnt find a way to do so properly. I am trying to use </p>
<pre><code> final String fileName = "train.yml";
opencvmatrix mat = new opencvmatrix();
Yaml yaml = new Yaml();
try {
InputStream ios = new FileInputStream(new File(fileName));
// Parse the YAML file and return the output as a series of Maps and Lists
Map<String,Object> result = (Map<String,Object>)yaml.load(ios);
System.out.println(result.toString());
Collection<Object> file = result.values();
} catch (Exception e) {
e.printStackTrace();
}
</code></pre>
<p>}</p>
<p>I am receiving as an error the following:</p>
<pre><code>Exception in thread "main" while scanning a directive
in 'reader', line 1, column 1:
%YAML:1.0
^
expected alphabetic or numeric character, but found :(58)
in 'reader', line 1, column 6:
%YAML:1.0
^
at org.yaml.snakeyaml.scanner.ScannerImpl.scanDirectiveName(ScannerImpl.java:1269)
at org.yaml.snakeyaml.scanner.ScannerImpl.scanDirective(ScannerImpl.java:1221)
at org.yaml.snakeyaml.scanner.ScannerImpl.fetchDirective(ScannerImpl.java:614)
at org.yaml.snakeyaml.scanner.ScannerImpl.fetchMoreTokens(ScannerImpl.java:306)
at org.yaml.snakeyaml.scanner.ScannerImpl.checkToken(ScannerImpl.java:226)
at org.yaml.snakeyaml.parser.ParserImpl$ParseImplicitDocumentStart.produce(ParserImpl.java:195)
at org.yaml.snakeyaml.parser.ParserImpl.peekEvent(ParserImpl.java:158)
at org.yaml.snakeyaml.parser.ParserImpl.checkEvent(ParserImpl.java:143)
at org.yaml.snakeyaml.composer.Composer.getSingleNode(Composer.java:104)
at org.yaml.snakeyaml.constructor.BaseConstructor.getSingleData(BaseConstructor.java:120)
at org.yaml.snakeyaml.Yaml.loadFromReader(Yaml.java:481)
at org.yaml.snakeyaml.Yaml.load(Yaml.java:412)
at projectCV.main(projectCV.java:33)
Java Result: 1
</code></pre>
<p>EDIT1: I ve noticed that my problems stands for assertEquals which is a function of the class assert part of junit library. I cant find a way to import properly the library to my classpath. I am trying two things, download .jar file and ADD/Jar folder and from project properties->libraries->compile tests-> add library -> Junit 4.10. But I am still having issues.</p>
<p>EDIT2: I change the YAML 1.0 to YAML 1.1, but nothing changes. I am still trying to find a suitable way to read the yml file. </p>
<pre><code> final String fileName = "train.yml";
opencvmatrix mat = new opencvmatrix();
Yaml yaml = new Yaml();
try {
InputStream ios = new FileInputStream(new File(fileName));
// Parse the YAML file and return the output as a series of Maps and Lists
Map<String,Object> result = (Map<String,Object>)yaml.load(ios);
System.out.println(result.toString());
Collection<Object> file = result.values();
} catch (Exception e) {
e.printStackTrace();
}
</code></pre>
<p>}</p>
<p>WHen I am trying to run this code I am receiving: </p>
<pre><code>Exception in thread "main" Can't construct a java object for tag:yaml.org,2002:opencv-
matrix; exception=Class not found: opencv-matrix
in 'reader', line 3, column 7:
mean: !!opencv-matrix
^
</code></pre>
<p>EDIT3: I ve created a class opencvmatrix (like the name of .yml properties), with the properties rows, cols, dt, ArrayList data. The .yml file is like:</p>
<pre><code>num_components: 19
num_components: 19
mean: !!opencvmatrix
rows: 1
cols: 3600
dt: d
data: [ 9.6842105263157890e+01, 1.0257894736842104e+02,
1.0557894736842104e+02, 1.0794736842105263e+02,
1.1752631578947367e+02, 1.1631578947368421e+02,
1.1084210526315789e+02, 1.0373684210526315e+02,
1.0052631578947368e+02, 9.5263157894736835e+01,
9.0421052631578945e+01, 8.5631578947368411e+01,
7.8684210526315780e+01, 7.2105263157894740e+01,
6.9315789473684205e+01, 6.9105263157894740e+01,
7.1052631578947370e+01, 7.9631578947368411e+01,
9.0894736842105260e+01, 1.0121052631578947e+02,
....]
projections:
- !!opencvmatrix
rows: 1
cols: 19
dt: d
data: [ 1.6852352677811423e+03, -1.0112905042030820e+03,
-1.3152188243875064e+03, 4.8298990155435700e+02,
9.1980535900698968e+01, 6.5624763621018792e+02,
-1.2380244625181117e+03, -1.8800931631152707e+02,
-4.1473232893431384e+02, 5.7197035514178856e+02,
4.9990276749703435e+02, 4.9062987890888604e+02,
6.1928710580829818e+02, -1.2842392693864540e+03,
2.4907719466932619e+01, 8.0299588479341844e+02,
1.1621501008120421e+02, 1.0410492864645674e+02,
8.5302163830384785e+01 ]
- !!opencvmatrix
rows: 1
cols: 19
dt: d
data: [ -1.0313663745467784e+03, 1.9900404646205566e+03,
-1.2844533156050284e+02, -4.3700867528097513e+02,
6.6145551346834259e+02, -2.0562483671734990e+03,
-1.9643774942432364e+02, 4.9329679854416281e+02,
-2.0003326324501427e+02, 1.0737995038485865e+03,
5.4161214984553695e+01, 4.7932826490658994e+02,
8.6307152262273064e+02, 6.7413046532276610e+02,
6.3835284527337114e+02, 4.1663169960066972e+02,
3.5883912817427905e+01, -1.2935687563770381e+02,
-1.6471877227400194e+03 ]
...
labels: !!opencvmatrix
rows: 1
cols: 19
dt: i
data: [ 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3 ]
</code></pre>
<p>Now without changing the main code I am receiving the following error:</p>
<pre><code> Can't construct a java object for tag:yaml.org,2002:opencvmatrix; exception=No single
argument constructor found for class opencvmatrix
in 'reader', line 1, column 7:
mean: !!opencvmatrix
^
</code></pre>
| 0 | 2,535 |
Airflow on_failure_callback
|
<p>I have an Airflow DAG with two tasks:</p>
<ul>
<li>read_csv</li>
<li>process_file</li>
</ul>
<p>They work fine on their own. I <strong>purposely</strong> created a typo in a pandas Dataframe to learn how <code>on_failure_callback</code> works and to see if it is being triggered. It seems likes from the log that it doesn't:</p>
<pre><code>Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/airflow/models/taskinstance.py", line 1197, in handle_failure
task.on_failure_callback(context)
TypeError: on_failure_callback() takes 0 positional arguments but 1 was given
</code></pre>
<p>Why isn't <code>on_failure_callback</code> working?</p>
<p>Here is a visual representation of the DAG:</p>
<p><a href="https://i.stack.imgur.com/oXp5E.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oXp5E.png" alt="enter image description here" /></a></p>
<p>Here is the code:</p>
<pre class="lang-py prettyprint-override"><code>try:
from datetime import timedelta
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from datetime import datetime
import pandas as pd
# Setting up Triggers
from airflow.utils.trigger_rule import TriggerRule
# for Getting Variables from airlfow
from airflow.models import Variable
print("All Dag modules are ok ......")
except Exception as e:
print("Error {} ".format(e))
def read_csv(**context):
data = [{"name":"Soumil","title":"Full Stack Software Engineer"}, { "name":"Nitin","title":"Full Stack Software Engineer"},]
df = pd.DataFramee(data=data)
dag_config = Variable.get("VAR1")
print("VAR 1 is : {} ".format(dag_config))
context['ti'].xcom_push(key='mykey', value=df)
def process_file(**context):
instance = context.get("ti").xcom_pull(key='mykey')
print(instance.head(2))
return "Process complete "
def on_failure_callback(**context):
print("Fail works ! ")
with DAG(dag_id="invoices_dag",
schedule_interval="@once",
default_args={
"owner": "airflow",
"start_date": datetime(2020, 11, 1),
"retries": 1,
"retry_delay": timedelta(minutes=1),
'on_failure_callback': on_failure_callback,
},
catchup=False) as dag:
read_csv = PythonOperator(
task_id="read_csv",
python_callable=read_csv,
op_kwargs={'filename': "Soumil.csv"},
provide_context=True
)
process_file = PythonOperator(
task_id="process_file",
python_callable=process_file,
provide_context=True
)
read_csv >> process_file
# ====================================Notes====================================
# all_success -> triggers when all tasks arecomplete
# one_success -> trigger when one task is complete
# all_done -> Trigger when all Tasks are Done
# all_failed -> Trigger when all task Failed
# one_failed -> one task is failed
# none_failed -> No Task Failed
# ==============================================================================
# ============================== Executor====================================
# There are Three main types of executor
# -> Sequential Executor run single task in linear fashion wih no parllelism default Dev
# -> Local Exector run each task in seperate process
# -> Celery Executor Run each worker node within multi node architecture Most scalable
# ===========================================================================
</code></pre>
| 0 | 1,511 |
RecyclerView: scrollToPosition not working
|
<p>I have a simple project displaying user text messages. I am currently not able to scroll the RecyclerView to the last received text message.
<br/>
My recyclerView is inside a very simple activity using the Coordinator layout:
<br/></p>
<pre><code><android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:background="@color/background"
tools:context="com.myproject.myproject.MessageActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay"/>
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_message" />
</android.support.design.widget.CoordinatorLayout>
</code></pre>
<p>And the content_message.xml:</p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="beforeDescendants"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.textbutler.textbutler.MessageActivity"
tools:showIn="@layout/activity_message">
<!-- some views here -->
<android.support.v7.widget.RecyclerView
android:id="@+id/content_text"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:scrollbars="vertical" />
<!-- some views here -->
</LinearLayout>
</code></pre>
<p>The activity load the data through a basic loader. I force the access to the recyclerview on the UI thread and with a delay (just in case)</p>
<pre><code>public class MessageActivity extends AppCompatActivity {
private static final int URL_LOADER = 0;
private RecyclerView recyclerView;
private LinearLayoutManager layoutManager;
private MessageAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
initializeList(savedInstanceState);
}
private void initializeList(Bundle savedInstanceState) {
if (recyclerView == null) {
recyclerView = (RecyclerView) findViewById(R.id.content_text);
if (recyclerView == null)
return;
if (layoutManager == null) {
layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
}
recyclerView.setLayoutManager(layoutManager);
final Activity me = this;
if (adapter == null) {
adapter = new MessageAdapter(new ObservableCallback() {
@Override
public void callback() {
// this function is called right after the recyclerview received notifyDataSetChanged
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
me.runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d("ScrollingUI", "scrolltoposition " + adapter.getItemCount());
recyclerView.scrollToPosition(adapter.getItemCount() - 1);
}
});
}
}, 1000);
}
});
SMSByUserLoader loader = new SMSByUserLoader(this, adapter);
getSupportLoaderManager().initLoader(URL_LOADER, savedInstanceState, loader);
}
recyclerView.setAdapter(adapter);
}
}
</code></pre>
<p>}</p>
<p>When I run this code, the RecyclerView is perfectly filled. After a second I have the correct log but the view does not changed.
I already found various answers to this issue, but none of them seems to work in my case.
<br/>
Scrolling in the RecyclerView perfectly works.</p>
| 0 | 1,988 |
Gunicorn not starting throwing gunicorn.service: Failed with result 'exit-code'. error
|
<p>I'm trying a deploy simple Django application on Digital Ocean by following this [link][1] I follow every work step by step and successfully run that project via python manage.py runserver where it's not throwing any error but when I try to implement it with gunicorn its throw following error</p>
<blockquote>
<p>gunicorn.service: Failed with result 'exit-code'.</p>
</blockquote>
<p>Here is my following configuration:</p>
<p><strong>sudo nano /etc/systemd/system/gunicorn.socket</strong></p>
<pre><code>[Unit]
Description=gunicorn socket
[Socket]
ListenStream=/run/gunicorn.sock
[Install]
WantedBy=sockets.target
</code></pre>
<p><strong>sudo nano /etc/systemd/system/gunicorn.service</strong></p>
<pre><code>[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target
[Service]
User=pos
Group=www-data
WorkingDirectory=/home/pos/pos
ExecStart=/home/pos/env/bin/gunicorn \
--access-logfile - \
--workers 3 \
--bind unix:/run/gunicorn.sock \
pos.wsgi:application
[Install]
WantedBy=multi-user.target
</code></pre>
<p><strong>sudo systemctl status gunicorn.socket</strong></p>
<pre><code>● gunicorn.socket - gunicorn socket
Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: enabled)
Active: active (listening) since Tue 2019-11-26 07:39:39 UTC; 12min ago
Listen: /run/gunicorn.sock (Stream)
CGroup: /system.slice/gunicorn.socket
Nov 26 07:39:39 POS systemd[1]: Listening on gunicorn socket.
</code></pre>
<p>When I try to start gunicorn it's throwing this error</p>
<p><strong>sudo systemctl status gunicorn</strong></p>
<pre><code>● gunicorn.service - gunicorn daemon
Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Tue 2019-11-26 07:39:43 UTC; 13min ago
Process: 718 ExecStart=/home/pos/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock pos.wsgi:application (code=exited, status=1/FAILURE)
Main PID: 718 (code=exited, status=1/FAILURE)
Nov 26 07:39:43 POS gunicorn[718]: Arbiter(self).run()
Nov 26 07:39:43 POS gunicorn[718]: File "/home/pos/env/lib/python3.7/site-packages/gunicorn/arbiter.py", line 198, in run
Nov 26 07:39:43 POS gunicorn[718]: self.start()
Nov 26 07:39:43 POS gunicorn[718]: File "/home/pos/env/lib/python3.7/site-packages/gunicorn/arbiter.py", line 155, in start
Nov 26 07:39:43 POS gunicorn[718]: self.LISTENERS = sock.create_sockets(self.cfg, self.log, fds)
Nov 26 07:39:43 POS gunicorn[718]: File "/home/pos/env/lib/python3.7/site-packages/gunicorn/sock.py", line 172, in create_sockets
Nov 26 07:39:43 POS gunicorn[718]: sock_name = sock.getsockname()
Nov 26 07:39:43 POS gunicorn[718]: OSError: getsockaddrlen: bad family
Nov 26 07:39:43 POS systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE
Nov 26 07:39:43 POS systemd[1]: gunicorn.service: Failed with result 'exit-code'.
</code></pre>
<p>Anyone helps me to solve this issue?
[1]: <a href="https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04" rel="nofollow noreferrer">https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04</a></p>
| 0 | 1,269 |
Form submitted twice, due to :remote=>true
|
<p>My form submitted twice, after double checked, it was cause by ':remote=>true'. I removed it, my project works well. Who can show me why? And how to use ':remote=>true'?</p>
<p>My ruby code:</p>
<pre><code><%= form_tag(admin_product_group_product_scopes_path(@product_group), :remote => true, :id => 'new_product_group_form') do %>
<%
options =
grouped_options_for_select(
Scopes::Product::SCOPES.map do |group_name, scopes|
[
t(:name, :scope => [:product_scopes, :groups, group_name]),
scopes.keys.map do |scope_name|
[ t(:name, :scope => [:product_scopes, :scopes, scope_name]), scope_name]
end
]
end
)
%>
<p>
<label for="product_scope_name"><%= t('add_scope') %></label>
<%= select_tag("product_scope[name]", options) %>
<input type="submit" value="<%= t('add') %>" />
</p>
<% end %>
</code></pre>
<p>The final html code in browser.</p>
<pre><code> <form accept-charset="UTF-8" action="/admin/product_groups/17/product_scopes" data-remote="true" id="new_product_group_form" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓"><input name="authenticity_token" type="hidden" value="GocX/l4ZNgF/feKtzC8FuohebM2k5MuIHtdeGp2Oi0A="></div>
<p>
<label for="product_scope_name">Add a scope</label>
<select id="product_scope_name" name="product_scope[name]"><optgroup label="Taxon"><option value="taxons_name_eq">In Taxon(without descendants)</option>
<option value="in_taxons">In taxons and all their descendants</option></optgroup><optgroup label="Text search"><option value="in_name">Product name have following</option>
<option value="in_name_or_keywords">Product name or meta keywords have following</option>
<option value="in_name_or_description">Product name or description have following</option>
<option value="with_ids">Products with IDs</option></optgroup><optgroup label="Values"><option value="with">With value</option>
<option value="with_property">With property</option>
<option value="with_property_value">With property value</option>
<option value="with_option">With option</option>
<option value="with_option_value">With option and value</option></optgroup><optgroup label="Price"><option value="price_between">Price between</option>
<option value="master_price_lte">Master price lesser or equal to</option>
<option value="master_price_gte">Master price greater or equal to</option></optgroup></select>
<input type="submit" value="Add">
</p>
</form>
</code></pre>
| 0 | 1,243 |
Grant Privileges to an user (remotely root logged) in MySQL
|
<p>I have this:</p>
<pre><code>mysql> SELECT CURRENT_USER();
+----------------+
| CURRENT_USER() |
+----------------+
| root@% |
+----------------+
1 row in set (0.00 sec)
mysql> SELECT USER();
+------------------+
| USER() |
+------------------+
| root@CQ2404LA-PC |
+------------------+
1 row in set (0.00 sec)
mysql>
mysql> GRANT ALL PRIVILEGES ON `Company`.* TO 'TheUser'@'%' IDENTIFIED BY PASS
WORD '*3814FFAFF303C7DBB5511684314B57577D754FF9';
ERROR 1044 (42000): Access denied for user 'root'@'%' to database 'Company'
</code></pre>
<p><strong>Access denied for user 'root'@'%' to database 'Company'</strong></p>
<p>Now reviewing the root privileges I have:</p>
<pre><code>mysql> show grants for 'root'@'localhost';
+-------------------------------------------------------------------------------
---------------------------------------------------------+
| Grants for root@localhost
|
+-------------------------------------------------------------------------------
---------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '*158
FB31F24156B52B2408974EF221C5100001544' WITH GRANT OPTION |
| GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION
|
+-------------------------------------------------------------------------------
---------------------------------------------------------+
2 rows in set (0.00 sec)
</code></pre>
<p>Before, I tested (Locally) And Works fine!.</p>
<p>Now Remotely Privileges:</p>
<pre><code>mysql> show grants for 'root'@'%';
+-------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
---------------------------------------------------------------------------+
| Grants for root@%
|
+-------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
---------------------------------------------------------------------------+
| GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, SHUTDOWN, PROCESS,
FILE, REFERENCES, INDEX, ALTER, SHOW DATABASES, SUPER, CREATE TEMPORARY TABLES,
LOCK TABLES, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW, SHOW
VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER ON *.* TO 'root'@'%' IDENTIFIED
BY PASSWORD '*158FB31F24156B52B2408974EF221C5100001544' WITH GRANT OPTION |
| GRANT PROXY ON ''@'' TO 'root'@'%' WITH GRANT OPTION
</code></pre>
<p>Doesn't work!!!, I think that it must work because: "<strong>ON *.* TO 'root'@'%'</strong>"</p>
<p><strong>Looking for the difference:</strong>
'root'@'%' haven't CREATE TABLESPACE, EVENT and TRIGGER</p>
<pre><code>mysql> SELECT Host, Event_priv, Trigger_priv, Create_tablespace_priv,
authentication_string FROM mysql.user WHERE USER = "root";
+-----------+------------+--------------+------------------------+--------------
---------+
| Host | Event_priv | Trigger_priv | Create_tablespace_priv | authenticatio
n_string |
+-----------+------------+--------------+------------------------+--------------
---------+
| localhost | Y | Y | Y |
|
| % | N | N | N | NULL
|
+-----------+------------+--------------+------------------------+--------------
---------+
2 rows in set (0.01 sec)
mysql>
</code></pre>
<p>But, I think that is not root of problem...</p>
<p>Maybe The solution will be, to use: <strong>GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'</strong>, but I think "all privileges" have other thing than "an amount of privileges".</p>
| 0 | 1,362 |
jquery ajax readystate 0 responsetext status 0 statustext error
|
<p>I am getting the following error: <code>jquery ajax readystate 0 responsetext status 0 statustext error</code> when giving it: <code>url(http://www.tutorialspoint.com/prototype/prototype_ajax_response.htm)</code>, however it's working fine when I give it <code>url(localhost:""/embparse_page)</code> on my localhost. </p>
<p>I have tried using the headers which I found on a Google search, and I have used <code>beforeSend:""</code> too, but it's still not working.</p>
<p>I think the main problem is: <code>XMLHttpRequest cannot load http://www.tutorialspoint.com/prototype/prototype_ajax_response.htm. Origin "local server" is not allowed by Access-Control-Allow-Origin.</code> but I don't understand it. </p>
<p>Can anyone please explain the problem to me, as I'm quite new to this.</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns:ng="http://angularjs.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta Access-Control-Allow-Origin="*" />
<title>Page Parsing</title>
<script type="text/javascript" src="/js/jquery-1.9.1.min.js"></script>
<script>
getit=function(){
jQuery.support.cors = true;
$.ajax({
type:"GET",
url:"http://www.tutorialspoint.com/prototype/prototype_ajax_response.htm",
dataType:"html",
crossDomain:true,
beforeSend: function(xhr) {
xhr.overrideMimeType('text/plain;charset=UTF-8');
},
success:function(XMLHttpRequest,jqXHR ,data) {
//alert(data.title);
var starttitl=data.lastIndexOf('<title>');
var endtitl=data.lastIndexOf('</title>');
var title1=data.substring(starttitl+7,endtitl);
alert(title1);
},
error:function(errorStatus,xhr) {
alert("Error"+JSON.stringify(errorStatus));
}
});
}
</script>
</head>
<body>
<div id="siteloader">
<input type="button" onclick="getit()" />
</div>
</body>
</html>
</code></pre>
| 0 | 1,070 |
Click anywhere to close side navbar javascript
|
<p>I am using below snippet within bootstrap to display a sidebar in the navigation bar.</p>
<p>I am able to close the navbar by clicking on the X button in the sidebar. How can I change my closeNav javascript to be able to close the sidebar by clicking anywhere on the page well as the close button using javascript only?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function openNav() {
document.getElementById("mySidenav").style.width = "230px";
document.getElementById("main").style.marginLeft = "250px";
}
/* Set the width of the side navigation to 0 and the left margin of the page content to 0 */
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.getElementById("main").style.marginLeft = "0";
}
</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* The side navigation menu */
.sidenav {
height: 100%; /* 100% Full-height */
width: 0; /* 0 width - change this with JavaScript */
position: fixed; /* Stay in place */
z-index: 1; /* Stay on top */
top: 0;
left: 0;
background-color: #111; /* Black*/
overflow-x: hidden; /* Disable horizontal scroll */
padding-top: 60px; /* Place content 60px from the top */
transition: 0.5s; /* 0.5 second transition effect to slide in the sidenav */
}
/* The navigation menu links */
.sidenav a {
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 25px;
color: #818181;
display: block;
transition: 0.3s
}
/* When you mouse over the navigation links, change their color */
.sidenav a:hover, .offcanvas a:focus{
color: #f1f1f1;
}
/* Position and style the close button (top right corner) */
.sidenav .closebtn {
position: absolute;
top: 0;
right: 25px;
font-size: 36px;
margin-left: 50px;
}
/* Style page content - use this if you want to push the page content to the right when you open the side navigation */
#main {
transition: margin-left .5s;
padding: 20px;
}
/* On smaller screens, where height is less than 450px, change the style of the sidenav (less padding and a smaller font size) */
@media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
</div>
<!-- Use any element to open the sidenav -->
<span onclick="openNav()">Siderbar Button click here</span>
<div id="main">
Body content is here</div></code></pre>
</div>
</div>
</p>
| 0 | 1,087 |
how to declare output array in verilog?
|
<p>I am trying to ADD two array and want output in array in verilog code. But error is occured. which is ERROR:HDLCompiler:1335: Port sum must not be declared to be an array in verilog code . can anyone tell me how to declare output array in verilog code. Thanks.</p>
<pre><code>module array(clk,sum,reset);
input clk,reset;
//input [7:0] din;
//input [7:0] A[3:0];
//input [7:0] B[3:0];
output sum[3:0];
wire [7:0] sum[3:0];
reg [7:0] A[3:0];
reg [7:0] B[3:0];
integer i;
always@(posedge clk)
begin
if(reset==1'b1)
begin
A[0]<=1;
A[1]<=2;
A[2]<=3;
A[3]<=4;
B[0]<=5;
B[1]<=5;
B[2]<=5;
B[3]<=5;
sum[0]<=0;
sum[1]<=0;
sum[2]<=0;
sum[3]<=0;
end
else
begin
for(i=0;i<4;i=i+1)
begin
sum[i]=(A[i] + B[i]);
end
end
end
endmodule
</code></pre>
| 0 | 1,026 |
No operations allowed after connection closed MYSQL
|
<p>Basically I have:</p>
<pre><code>String query = "SELECT * FROM table WHERE UNIQUEID=? AND DIR IS NOT NULL AND NAME IS NOT NULL AND PAGETYPE IS NOT NULL";
DBConnect Database = new DBConnect();
Connection con = null;
PreparedStatement ps = null;
ResultSet rs=null;
try {
con = Database.getcon();
ps = con.prepareStatement(query);
ps.setString(1, URI);
rs=ps.executeQuery();
if(rs.next()){
}
} finally {
if(ps != null)
ps.close();
if(rs != null)
rs.close();
if(con != null)
con.close();
}
query = "SELECT COUNTCOMMENTS FROM videosinfos WHERE UNIQUEID=?";
try {
con = Database.getcon();
ps = con.prepareStatement(query); // Getting error here
rs=ps.executeQuery();
ps.setString(1, URI);
rs=ps.executeQuery();
if(rs.next()){
comments = rs.getInt(1);
}
} finally {
if(ps != null)
ps.close();
if(rs != null)
rs.close();
if(con != null)
con.close();
}
</code></pre>
<p>Note: The line I get the error, have a comment on it.</p>
<p>Connecting to Database:</p>
<pre><code>public DBConnect(){
try{
Class.forName("com.mysql.jdbc.Driver");
String unicode="useSSL=false&autoReconnect=true&useUnicode=yes&characterEncoding=UTF-8";
con = DriverManager.getConnection("jdbc:mysql://localhost:15501/duckdb?"+unicode, "root", "_PWD");
st = con.createStatement();
}catch(Exception ex){
System.out.println(ex.getMessage());
System.out.println("couldn't connect!");
}
}
public Connection getcon(){
DBConnect condb = new DBConnect();
Connection connect = con;
return con;
}
</code></pre>
<p>But in compilation I get this error:</p>
<blockquote>
<p>com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.
at sun.reflect.GeneratedConstructorAccessor18.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.Util.getInstance(Util.java:387)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:917)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:896)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:885)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
at com.mysql.jdbc.ConnectionImpl.throwConnectionClosedException(ConnectionImpl.java:1246)
at com.mysql.jdbc.ConnectionImpl.checkClosed(ConnectionImpl.java:1241)
at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4102)
at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4071)
at duck.reg.pack.DBConnect.getitemfull_details(DBConnect.java:686)
at duck.reg.pack.index.doPost(index.java:73)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)</p>
</blockquote>
<p>I'm Using Debian with MariaDB v10.x/Mysql</p>
| 0 | 2,086 |
Is it possible to refresh partial frequently using Ajax?
|
<p>In background, I want it to reload and shows the number how many unread messages are there.<br>
I want that without refreshing page. I mean using ajax. </p>
<p>If I had this in menu, how can I refresh only this section every 30 secs?</p>
<pre><code><li><%= link_to sanitize('<i class="icon-envelope"></i> ') + "received messages" + sanitize(' <span class="badge badge-info">'+current_user.mailbox.inbox(:read => false).count(:id, :distinct => true).to_s+'</span>'), messages_received_path %></li>
</code></pre>
<p>messages_controller.rb</p>
<pre><code> def received
if params[:search]
@messages = current_user.mailbox.inbox.search_messages(@search).page(params[:page]).per(10)
else
@messages = current_user.mailbox.inbox.page(params[:page]).per(10)
end
add_crumb 'Messages Received', messages_received_path
@box = 'inbox'
render :index
end
</code></pre>
<p>UPDATE:<strong><em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em></strong></p>
<p>assets/javascript/refresh_messages_count.js</p>
<pre><code>$(document).ready(function () {
// will call refreshPartial every 3 seconds
setInterval(refreshPartial, 3000)
});
function refreshPartial() {
$.ajax({
url: "messages/refresh_part";
})
}
</code></pre>
<p>messages_controller.rb</p>
<pre><code>def refresh_part
@message_count = current_user.mailbox.inbox(:read => false).count(:id, :distinct => true)
# get whatever data you need to a variable named @data
respond_to do |format|
format.js {render :action=>"refresh_part.js"}
end
end
</code></pre>
<p>views/layouts/_menu.html.erb</p>
<pre><code><span id="message_received_count"><%= render :partial => "layouts/message_received_count" %></span>
</code></pre>
<p>views/layouts/_message_received_count.html.erb</p>
<pre><code><% if user_signed_in? && current_user.mailbox.inbox(:read => false).count(:id, :distinct => true) > 0 %>
<li><%= link_to sanitize('<i class="icon-envelope"></i> ') + "Received" + sanitize(' <span class="badge badge-info">'+@message_count.to_s+'</span>'), messages_received_path %></li>
<% else %>
<li><%= link_to sanitize('<i class="icon-envelope"></i> ') + "Received", messages_received_path %></li>
<% end %>
</code></pre>
<p>views/messages/refresh_part.js.erb</p>
<pre><code>$('#message_received_count').html("#{escape_javascript(render 'layouts/messages_received_count', data: @message_count)}");
</code></pre>
| 0 | 1,175 |
How can I put my form inside another form and use one submit button?
|
<pre><code> <form action="<?php $self ?>" method="post">
<h2>LundaBlogg</h2>
<div class="fname"><label for="name"><p>Namn:</p></label><input name="name" type="text" cols="20" onkeyup="EnforceMaximumLength(this,12)"/></div>
<div class="femail"><label for="email"><p>Epost:</p></label><input name="email" type="text" cols="20"/></div>
<div class="where"><label for="lund"><p>Skriv ditt blogg ämne:</p></label><input name="lund" type="text" cols="20" onkeyup="EnforceMaximumLength(this,40)"/></div>
<p>Starta tråden med att posta något:</p><textarea name="post" rows="5" cols="40" onkeyup="EnforceMaximumLength(this,110)"></textarea>
</br>
<!-- <form action="uploadImage/upload_file.php" method="post" enctype="multipart/form-data"> -->
<label for="file">Ladda upp en bild med ditt inlägg:</label>
<input type="file" name="file" id="file" />
<!-- <input type="submit" name="submit" value="Submit"/> -->
<!-- </form> -->
</select><br/>
<p>Välj kategori som du vill lägga din post i:</p>
<!-- Skapar en dropdown meny med tre värden/value. -->
<select name="LundaBlogg" size="1"> <!-- Namnet på dropdown menyn + size = hur många rader som ska visas. -->
<option value="Lund">Lund</option>
<option value="Cyklar">Cyklar</option>
<option value="Kultur">Kultur</option>
</select>
<input name="send" type="hidden"/>
<p><input type="submit" value="skicka"/></p>
</form>
</code></pre>
<hr>
<p>I want to be able to use one submit button <code>input type="submit" value="skicka"</code> and I want to have my (code)</p>
<pre><code>form action="uploadImage/upload_file.php" method="post" enctype="multipart/form-data"
label for="file"Ladda upp en bild med ditt inlägg:/label
input type="file" name="file" id="file"
</code></pre>
<p>form</p>
<p>inside my other form like the example above.</p>
| 0 | 1,281 |
Chart.js: Bar Chart Click Events
|
<p>I've just started working with Chart.js, and I am getting very frustrated very quickly. I have my stacked bar chart working, but I can't get the click "events" to work.</p>
<p>I have found a <a href="https://github.com/chartjs/Chart.js/issues/577#issuecomment-55897221">comment on GitHub by <code>nnnick</code></a> from Chart.js stating to use the function <code>getBarsAtEvent</code>, even though this function cannot be found in the <a href="http://www.chartjs.org/docs/#bar-chart-chart-options">Chart.js documentation</a> at all (go ahead, do a search for it). The documentation does mention the <code>getElementsAtEvent</code> function of the <code>chart</code> reference, but that is for Line Charts only.</p>
<p>I set an event listener (the right way) on my canvas element:</p>
<pre><code>canv.addEventListener('click', handleClick, false);
</code></pre>
<p>...yet in my <code>handleClick</code> function, <code>chart.getBarsAtEvent</code> is undefined!</p>
<p>Now, in the Chart.js document, there is a statement about a different way to register the click event for the bar chart. It is much different than <code>nnnick</code>'s comment on GitHub from 2 years ago.</p>
<p>In the <a href="http://www.chartjs.org/docs/#getting-started-global-chart-configuration">Global Chart Defaults</a> you can set an <code>onClick</code> function for your chart. I added an <code>onClick</code> function to my chart configuration, and it did nothing...</p>
<p>So, how the heck do I get the on-click-callback to work for my bar chart?!</p>
<p>Any help would be greatly appreciated. Thanks!</p>
<p><strong>P.S.:</strong> I am not using the master build from GitHub. I tried, but it kept screaming that <code>require is undefined</code> and I was not ready to include CommonJS just so that I could use this chart library. I would rather write my own dang charts. Instead, I downloaded and am using the <a href="https://raw.githubusercontent.com/nnnick/Chart.js/v2.0-dev/dist/Chart.js"><strong>Standard Build</strong></a> version that I downloaded straight from the link at the top of the <a href="http://www.chartjs.org/docs/">documentation page</a>.</p>
<p><strong>EXAMPLE:</strong> Here is an example of the configuration I am using:</p>
<pre><code>var chart_config = {
type: 'bar',
data: {
labels: ['One', 'Two', 'Three'],
datasets: [
{
label: 'Dataset 1',
backgroundColor: '#848484',
data: [4, 2, 6]
},
{
label: 'Dataset 2',
backgroundColor: '#848484',
data: [1, 6, 3]
},
{
label: 'Dataset 3',
backgroundColor: '#848484',
data: [7, 5, 2]
}
]
},
options: {
title: {
display: false,
text: 'Stacked Bars'
},
tooltips: {
mode: 'label'
},
responsive: true,
maintainAspectRatio: false,
scales: {
xAxes: [
{
stacked: true
}
],
yAxes: [
{
stacked: true
}
]
},
onClick: handleClick
}
};
</code></pre>
| 0 | 1,396 |
Android custom ArrayAdapter getView method called multiple times - resetting dynamic TextView value
|
<p>The getView method in my custom ArrayAdapter is getting called multiple times, which I assume it is meant to. Problem is, I have a quantity TextView which is dynamically set but when you scroll and the box goes off screen the value disappears. I am not sure what I am doing wrong and Google is not proving to be much help. Hopefully someone here can help me.</p>
<p>The adapater is called:</p>
<pre><code>adapter = new MenuAdapter(thisActivity, R.layout.menu, list);
setListAdapter(adapter);
</code></pre>
<p>My Custom ArrayAdapter:</p>
<pre><code>public MenuAdapter(Context context, int textViewResourceId, ArrayList<Object> menu) {
super(context, textViewResourceId, menu);
this.menu = menu;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
Object cat = menu.get(position);
if (cat.getClass().equals(Category.class)) {
v = vi.inflate(R.layout.category, null);
Category item = (Category)cat;
v.setOnClickListener(null);
v.setOnLongClickListener(null);
v.setLongClickable(false);
TextView tt = (TextView) v.findViewById(R.id.category);
tt.setText(item.getName());
} else if (cat.getClass().equals(OrderItem.class)) {
v = vi.inflate(R.layout.menu, null);
OrderItem orderItem = (OrderItem)cat;
Item item = orderItem.getItem();
TextView tt = (TextView) v.findViewById(R.id.title);
tt.setText(item.getName());
TextView bt = (TextView) v.findViewById(R.id.desc);
bt.setText(item.getDescription());
TextView qty = (TextView) v.findViewById(R.id.qty);
qty.setId(item.getId());
ImageButton minus = (ImageButton) v.findViewById(R.id.qtyMinus);
minus.setTag(item);
ImageButton plus = (ImageButton) v.findViewById(R.id.qtyPlus);
plus.setTag(item);
}
return v;
}
</code></pre>
<p>The menu layout:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip"
android:background="#FFFFFF">
<RelativeLayout
android:orientation="vertical"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="fill_parent"
android:cacheColorHint="#FFFFFF"
android:background="#FFFFFF">
<TextView
android:id="@+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical"
android:textSize="16px"
android:textColor="#000000"
/>
<TextView
android:id="@+id/desc"
android:layout_below="@id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="11px"
android:textStyle="italic"
android:textColor="#000000"
/>
</RelativeLayout>
<ImageButton
android:id="@+id/qtyMinus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/minus"
android:paddingTop="15px"
android:onClick="minusQty" />
<TextView
android:id="@+id/qty"
android:layout_width="50px"
android:layout_height="50px"
android:textColor="#000000"
android:textSize="18px"
android:gravity="center_vertical|center_horizontal"
android:freezesText="true"
android:background="@android:drawable/editbox_background"/>
<ImageButton
android:id="@+id/qtyPlus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/plus"
android:paddingTop="15px"
android:onClick="addQty" />
</LinearLayout>
</code></pre>
| 0 | 2,445 |
creating a datagridview form in c#
|
<p>I`m new to c# and windows form applications.
Right now, I want to create a Datagridview within my form, whose rows I want to fill with the properties of a business object. I followed the example from this msdn page: <a href="http://msdn.microsoft.com/en-us/library/y0wfd4yz.aspx" rel="nofollow">How to: Bind Objects to Windows Forms DataGridView Controls</a> and created my own program, but instead of getting a similar result as in the msdn example I get a datagridview with three empty rows. What am I doing wrong? Here is my program:</p>
<pre><code>using System;
using System.Windows.Forms;
public class Form3 : Form
{
private DataGridView dataGridView1 = new DataGridView();
private BindingSource bindingSource1 = new BindingSource();
public Form3()
{
this.Load += new System.EventHandler(EnumsAndComboBox_Load);
}
private void EnumsAndComboBox_Load(object sender, System.EventArgs e)
{
// Populate the data source.
bindingSource1.Add(new Test("bli", "bla", "blop", "ha", "ho", "he"));
bindingSource1.Add(new Test("bli", "bla", "blop", "ha", "ho", "he"));
// Initialize the DataGridView.
dataGridView1.AutoGenerateColumns = false;
dataGridView1.AutoSize = true;
dataGridView1.DataSource = bindingSource1;
// Initialize and add a text box column.
DataGridViewColumn column = new DataGridViewTextBoxColumn();
column.DataPropertyName = "Name1";
column.Name = "Name1";
dataGridView1.Columns.Add(column);
// Initialize and add a check box column.
column = new DataGridViewTextBoxColumn();
column.DataPropertyName = "Name2";
column.Name = "Name2";
dataGridView1.Columns.Add(column);
column = new DataGridViewTextBoxColumn();
column.DataPropertyName = "Name3";
column.Name = "Name3";
dataGridView1.Columns.Add(column);
column = new DataGridViewTextBoxColumn();
column.DataPropertyName = "Name4";
column.Name = "Name4";
dataGridView1.Columns.Add(column);
column = new DataGridViewTextBoxColumn();
column.DataPropertyName = "Name5";
column.Name = "Name5";
dataGridView1.Columns.Add(column);
column = new DataGridViewTextBoxColumn();
column.DataPropertyName = "Name6";
column.Name = "Name6";
dataGridView1.Columns.Add(column);
// Initialize the form.
this.Controls.Add(dataGridView1);
this.AutoSize = true;
this.Text = "DataGridView object binding demo";
}
#region "test object"
private class Test
{
private string test1;
private string test2;
private string test3;
private string test4;
private string test5;
private string test6;
public Test(string s1, string s2, string s3, string s4, string s5, string s6)
{
test1 = s1;
test2 = s2;
test3 = s3;
test4 = s4;
test5 = s5;
test6 = s6;
}
public Test()
{
test1 = "bla";
test2 = "bla";
test3 = "bla";
test4 = "bla";
test5 = "bla";
test6 = "bla";
}
public string Test1
{
get
{
return test1;
}
set
{
test1 = value;
}
}
public string Test2
{
get
{
return test2;
}
set
{
test2 = value;
}
}
public string Test3
{
get
{
return test3;
}
set
{
test3 = value;
}
}
public string Test4
{
get
{
return test4;
}
set
{
test4 = value;
}
}
public string Test5
{
get
{
return test5;
}
set
{
test5 = value;
}
}
public string Test6
{
get
{
return test6;
}
set
{
test6 = value;
}
}
}
#endregion
static class Program
{
[STAThread]
public static void Main()
{
Application.Run(new Form3());
}
}
}
</code></pre>
| 0 | 2,432 |
getting all months between 2 dates
|
<p>I created a function that returns an array containing each month, starting from a supplied carbon date and ending on the current date.</p>
<p>Although the function is doing what it is supposed to do, it looks hideous. Clearly my programming skills arent yet what they're supposed to be. Surely there must be a better way to achieve what i want.</p>
<p>My code looks like this:</p>
<pre><code> class DateUtilities {
protected $months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
public function getMonthListFromDate(Carbon $date)
{
$monthArray = array();
$today = Carbon::today();
$currentYear = $today->copy()->format('Y');
$currentMonth = strtolower($today->copy()->format('F'));
$startYear = $date->copy()->format('Y');
$startMonth = strtolower($date->copy()->format('F'));
for($i = $startYear; $i <= $currentYear; $i ++) {
foreach($this->months as $monthIndex => $month) {
if (($monthIndex >= array_search($startMonth, $this->months) && $i == $startYear) ||
($monthIndex <= array_search($currentMonth, $this->months) && $i == $currentYear) ||
($i != $startYear && $i != $currentYear)) {
$formattedMonthIndex = ($monthIndex + 1);
if($formattedMonthIndex < 10) {
$monthArray['0' . $formattedMonthIndex . '-' . $i] = $month . ' ' . $i;
} else {
$monthArray[$formattedMonthIndex . '-' . $i] = $month . ' ' . $i;
}
}
}
}
return $monthArray;
}
}
</code></pre>
<p>and the result is:</p>
<pre><code>array:25 [▼
"03-2013" => "march 2013"
"04-2013" => "april 2013"
"05-2013" => "may 2013"
"06-2013" => "june 2013"
"07-2013" => "july 2013"
"08-2013" => "august 2013"
"09-2013" => "september 2013"
"10-2013" => "october 2013"
"11-2013" => "november 2013"
"12-2013" => "december 2013"
"01-2014" => "january 2014"
"02-2014" => "february 2014"
"03-2014" => "march 2014"
"04-2014" => "april 2014"
"05-2014" => "may 2014"
"06-2014" => "june 2014"
"07-2014" => "july 2014"
"08-2014" => "august 2014"
"09-2014" => "september 2014"
"10-2014" => "october 2014"
"11-2014" => "november 2014"
"12-2014" => "december 2014"
"01-2015" => "january 2015"
"02-2015" => "february 2015"
"03-2015" => "march 2015"
]
</code></pre>
<p>Can anyone help me improve this code?</p>
<p>EDIT:</p>
<p>After the great tips i ended up with the following:</p>
<pre><code>class DateUtilities {
public function getMonthListFromDate(Carbon $start)
{
$start = $start->startOfMonth();
$end = Carbon::today()->startOfMonth();
do
{
$months[$start->format('m-Y')] = $start->format('F Y');
} while ($start->addMonth() <= $end);
return $months;
}
</code></pre>
<p>}</p>
<p>Thank you for the help guys!!</p>
| 0 | 1,492 |
Reading from .data file into Java- how do I store the information in an array of arrays?
|
<p>I have the following Java class, which I'm using to read a .data file:</p>
<pre><code>import java.io.*;
import java.util.Scanner;
public class ReadFile {
static File file;
String[] columns = new String[]{"personID", "lastName", "firstName", "street", "city"};
String[] data = new String[100];
String filename = "D:\\Users\\Elgan Frost\\Desktop\\careers\\Smart Stream Associate Software Engineer (Java) - Bristol\\assessment\\srcPerson.data";
public ReadFile(File f) throws FileNotFoundException {
// TODO Auto-generated constructor stub
try{
//File = new File("D:\\Users\\Elgan Frost\\Desktop\\careers\\Smart Stream Associate Software Engineer (Java) - Bristol\\assessment\\srcPerson.data");
f = new File("D:\\Users\\Elgan Frost\\Desktop\\careers\\Smart Stream Associate Software Engineer (Java) - Bristol\\assessment\\src\\Person.data");
Scanner scanner = new Scanner(f);
while(scanner.hasNextLine()){
System.out.println(scanner.nextLine());
}
scanner.close();
}
finally{
}
}
public void read(File file2) throws IOException{
FileReader fr = new FileReader("D:\\Users\\Elgan Frost\\Desktop\\careers\\Smart Stream Associate Software Engineer (Java) - Bristol\\assessment\\src\\Person.data");
BufferedReader br = new BufferedReader(fr);
String line;
int i = 0;
while((line = br.readLine())!= null){
data[i] = line;
System.out.println(data[i]);
i++;
}
br.close();
String[] dataNew = new String[i];
System.arraycopy(data, 0, dataNew, 0, i);
data = dataNew;
System.out.println("Data length: " + data.length);
}
}
</code></pre>
<p>To give you a more complete understanding of my code, I also have the following Java class, which contains my main method:</p>
<pre><code>import java.io.*;
public class Person {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ReadFile rf = new ReadFile(f);
rf.read(ReadFile.file);
}
static File f;
public String id;
public String lastName;
public String firstName;
public String street;
public String city;
public void readPerson() throws FileNotFoundException{
//File f = new File("Smart Stream Associate Software Engineer (Java) - Bristol/assessment/src/Person.java");
//InputStream IS = new FileInputStream(f);
}
}
</code></pre>
<p>Currently, when I run my program, the console displays two lines that say, "Person.data...." and give the filepath of the .data file that is being read, which will have come from the lines <code>System.out.println(scanner.nextLine());</code> and <code>System.out.println(data[i]);</code> in my ReadFile.java class, as well as the line "Data length: 1", which will have come from the line <code>System.out.println("Data length: " + data.length);</code> at the end of the class.</p>
<p>I assume that this means that the program has read the first two lines of the .data file, but only stored the first.</p>
<p>What I want to happen, is for it to read the first line, store that in a String, then divide the String up into separate Strings wherever a 'space' appears, and store each of those Strings in an element of the array of Strings that I created at the start of the class- by using the line:</p>
<pre><code>String[] columns = new String[]{"personID", "lastName", "firstName", "street", "city"};
</code></pre>
<p>The separate Strings should be stored to each one in that order- so the first String (before the first space in the original String) would be stored in "personID", the second (after the first space, before the second) would be stored in "lastName", etc.</p>
<p>What I then want to do, is read each of the next lines in the file in turn, storing the elements from each line into the next 'row' of my 'columns' String array (basically creating a table of data, using an array of arrays) whereby the first element of each array is a "personID", the second is a "lastName", etc.</p>
<p>I want to do this until I reach the end of the file, and then print the contents of a couple of elements of the 'columns' array, just to show that it has worked.</p>
<p>I'm not sure how I would go about this, and was just wondering if anyone could point me in the right direction?</p>
| 0 | 1,344 |
Laravel 4, how to I create seed data to tables with relationships?
|
<p>I have created a database with two tables, "goals" and "partgoals". The practial use is to make a savings goal (money) and have milestones along the way (partgoals). I want the partgoals obviously be linked to a specific goal. The relationships are created but I run into trouble when trying to create my seed data.</p>
<p>My goal is to set up two goals table like this (GoalsTableSeeder.php):</p>
<pre><code><?php
class GoalsTableSeeder extends Seeder {
public function run()
{
DB::table('goals')->delete();
$goals = array(
array(
'max' => 1850000,
'avgsav' => 3500,
'duedate' => date('2015-03-15'),
'created_at' => new DateTime,
'updated_at' => new DateTime,
),
array(
'max' => 1100000,
'avgsav' => 5000,
'duedate' => date('2013-11-15'),
'created_at' => new DateTime,
'updated_at' => new DateTime,
)
);
DB::table('goals')->insert( $goals );
}
}
</code></pre>
<p>And my partgoals table like this (PartgoalsTableSeeder.php):</p>
<pre><code><?php
class PartgoalsTableSeeder extends Seeder {
public function run()
{
DB::table('partgoals')->delete();
$partgoals = array(
array(
'id' => 1,
'milestone' => 100000,
'duedate' => date('2014-03-15'),
'created_at' => new DateTime,
'updated_at' => new DateTime,
),
array(
'id' => 1,
'milestone' => 20000,
'duedate' => date('2013-06-15'),
'created_at' => new DateTime,
'updated_at' => new DateTime,
),
array(
'id' => 2,
'milestone' => 400000,
'duedate' => date('2013-09-15'),
'created_at' => new DateTime,
'updated_at' => new DateTime,
),
array(
'id' => 2,
'milestone' => 200000,
'duedate' => date('2014-10-15'),
'created_at' => new DateTime,
'updated_at' => new DateTime,
)
);
DB::table('partgoals')->insert( $partgoals );
}
}
</code></pre>
<p>The migration table for "goals":</p>
<pre><code><?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateGoalsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('goals', function(Blueprint $table)
{
$table->increments('id');
$table->integer('max');
$table->float('avgsav');
$table->date('duedate');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('goals');
}
}
</code></pre>
<p>The migration table for partgoals:</p>
<pre><code><?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePartgoalsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('partgoals', function(Blueprint $table)
{
$table->foreign('id')
->references('id')->on('goals')
->onDelete('cascade');
$table->increments('id');
$table->float('milestone');
$table->date('duedate')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('partgoals');
}
}
</code></pre>
<p>What am I doing wrong? I am new to Laravel (and Laravel 4).</p>
| 0 | 2,267 |
Guice JPA - "This connection has been closed." error
|
<p>After DB dropps an idle connection or DB is down and back up I'm receiving the following error in my webapp:</p>
<pre><code>javax.persistence.PersistenceException: org.hibernate.exception.JDBCConnectionException: could not inspect JDBC autocommit mode
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1365)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1293)
at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:265)
... 60 more
Caused by: org.hibernate.exception.JDBCConnectionException: could not inspect JDBC autocommit mode
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:131)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.isAutoCommit(LogicalConnectionImpl.java:395)
at org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl.afterNonTransactionalQuery(TransactionCoordinatorImpl.java:195)
at org.hibernate.internal.SessionImpl.afterOperation(SessionImpl.java:565)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1220)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:256)
... 70 more
Caused by: org.postgresql.util.PSQLException: This connection has been closed.
at org.postgresql.jdbc2.AbstractJdbc2Connection.checkClosed(AbstractJdbc2Connection.java:712)
at org.postgresql.jdbc2.AbstractJdbc2Connection.getAutoCommit(AbstractJdbc2Connection.java:678)
at sun.reflect.GeneratedMethodAccessor138.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.tomcat.jdbc.pool.ProxyConnection.invoke(ProxyConnection.java:126)
at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:99)
at org.apache.tomcat.jdbc.pool.DisposableConnectionFacade.invoke(DisposableConnectionFacade.java:63)
at $Proxy66.getAutoCommit(Unknown Source)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.isAutoCommit(LogicalConnectionImpl.java:392)
</code></pre>
<p>When this starts I get an </p>
<pre><code>SQL Error: 0, SQLState: 08006 - An I/O error occured while sending to the backend.
</code></pre>
<p>but after that it's only:</p>
<pre><code>SQL Error: 0, SQLState: 08003 - This connection has been closed.
</code></pre>
<p>The problem is: I have set testOnBorrow, so I'd expect to get only open connections.</p>
<p>If that helps: the pool ususaly contains a mix of good and bad connections, and the problem seems to clear up over time, but I had the server running for >12h and there were still bad connections returned.
After a restart evertything is working fine (for a time).</p>
<p>I have debugged the problem some more and it seems like pool is returning bad connections, e.g. if after I have all connections killed on DB I get:</p>
<pre><code>SQL Error: 0, SQLState: 57P01
</code></pre>
<p>and then the usual stuff - the killed connections are returned from the pool.
The question is: is it an application problem?</p>
<p>I tried purging the pool via JMX but that doesn't seem to have any effect.
Another weird thing is that even though app is apparently not doing anything (checked via thread dump) the JMX bean is showing 7 active connections and 0 idle connections. When I execute a request requiring DB access I get a response immediately (depite there being no idle connections available), but JMX shows 7 active and 0 idle connections after that.</p>
<p>PS. Maybe I'm missing something obvious and this is a connection management issue on my part? I'm using JPA EntityManager configured via persistence.xml, so maybe I'm doing something wrong and the connections are not closed(returned) properly after use?</p>
| 0 | 1,370 |
Spring Boot YML and StandAlone Tomcat 8 Server
|
<p>I have the following directory structure/config file:</p>
<pre><code>src/main/resource/config:
application.yml
application-dev.yml
application-sit.yml
</code></pre>
<p>Note according to the "<strong>Bootiful Configuration</strong>" <a href="https://spring.io/blog/2015/01/13/configuring-it-all-out-or-12-factor-app-style-configuration-with-spring" rel="noreferrer">https://spring.io/blog/2015/01/13/configuring-it-all-out-or-12-factor-app-style-configuration-with-spring</a>:</p>
<blockquote>
<p>Spring Boot will read the
properties in src/main/resources/application.properties by default. If
a profile is active, it will also automatically reads in the
configuration files based on the profile name, like
src/main/resources/application-foo.properties where foo is the current
profile. If the Snake YML library is on the classpath, then it will
also automatically load YML files.</p>
</blockquote>
<p>Since snake YML jar is in class path if I set <code>--spring.profiles.active=dev</code> as a
program arg in eclipse run configuration and use this as my main method Ever thing works as expected:</p>
<pre><code> public static void main(String[] args) {
SpringApplication app = new SpringApplication(Application.class);
SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
// Check if the selected profile has been set as argument.
// if not the development profile will be added
addDefaultProfile(app, source);
app.run(args);
}
/**
* Set a default profile if it has not been set
*/
private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) {
if (!source.containsProperty("spring.profiles.active")) {
app.setAdditionalProfiles(Constants.SPRING_PROFILE_DEVELOPMENT);
}
}
</code></pre>
<p>(Please note the main method reference above is from the following class used in my code: <a href="https://github.com/jarias/generator-jhipster-ember/blob/master/app/templates/src/main/java/package/_Application.java" rel="noreferrer">https://github.com/jarias/generator-jhipster-ember/blob/master/app/templates/src/main/java/package/_Application.java</a>)</p>
<p>Everything works as expected for spring.profile.active=dev. Which means that both:
<strong>application.yml</strong>(loaded by default) and <strong>application-dev.yml</strong>(active profile) property files are loaded and <strong>excludes</strong> <em>application-sit.yml</em> since sit isn't an active profile.</p>
<p>This embedded container works great for dev testing. However I want to release this into production by generating a war and deploy it to a standalone Tomcat8 Server. </p>
<p>For that I created an implementation of WebApplicationInitializer which is required by Tomcat8 server to automatically detect, bootstrap and start spring application on the standalone server.</p>
<pre><code>@Configuration
public class WebAppInit implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
}
}
</code></pre>
<p>After deploying the war I receive the following error I attempt to start the standalone server and receive the following error :</p>
<blockquote>
<p>Caused by: org.springframework.beans.factory.enter code
hereBeanCreationException: Could not autowire field: private
java.lang.String com.titlefeed.config.db.DbConfigJPA.databaseUrl;
nested exception is java.lang.IllegalArgumentException: Could not
resolve placeholder spring.data.postgres.uri' in string value
"${spring.data.postgres.uri}"</p>
</blockquote>
<p>Which implies the Tomcat Server/Spring <strong>isnt</strong> loading the application-dev.yml since that contains the properties: <strong>spring.data.postgres.uri</strong></p>
<p>So I attempted the following two solutions</p>
<ol>
<li>added <code>-Dspring.profiles.active=dev</code> to JAVA_OPTS in tomcat/bin/catalina.sh</li>
<li>added <code>spring.profiles.active=dev</code> to tomcat/conf/catalina.properties</li>
</ol>
<p>And neither of them worked. How can I get the standalone tomcat server to load the yml file associated with the spring.profiles.active property.</p>
<p>It works fine for the embedded springboot server started from eclipse but doesnt for an standalong server ?</p>
<p><strong>EDIT1: M. Deinum</strong> - Implemented your suggested solution below however still got the following error:</p>
<p><code>Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.data.postgres.uri' in string value "${spring.data.postgres.uri}</code></p>
<p>It seems like the -Dspring.profiles.active=dev isn't getting set.</p>
<pre><code>@Configuration
public class WebAppInit extends SpringBootServletInitializer {
@Override
protected WebApplicationContext createRootApplicationContext(
ServletContext servletContext) {
log.info("Properly INITALIZE spring CONTEXT");
ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
return super.createRootApplicationContext(servletContext);
}
}
</code></pre>
<p><strong>EDIT 2 ACV:</strong> - Adding "--spring.profiles.active=dev" as apart of JAVA_OPTS variable in the startup script: tomcat/bin/catalina.sh is not a viable option</p>
<p>E.g:</p>
<pre><code> JAVA_OPTS="$JAVA_OPTS --spring.profiles.active=dev ...etc
</code></pre>
<p>Gives the following error:</p>
<blockquote>
<p>Unrecognized option: --spring.profiles.active=dev Error: Could not
create the Java Virtual Machine."</p>
</blockquote>
<p><strong>EDIT 3:</strong>
Amended <strong>application.yml</strong> to include the following property</p>
<pre><code>spring:
profiles:
active: dev
</code></pre>
<p>Redeployed the war. Went to the exploded tomcat directory location to ensure the property was present <strong>webapps/feedserver/WEB-INF/classes/config/application.yml</strong></p>
<p>And the issue still occurred.</p>
<p><strong>EDIT 4:</strong> Added application.properties under the tomcat exploded webdir: webapps/feedserver/WEB-INF/classes/application.properties:</p>
<pre><code>spring.profiles.active=dev
spring.data.postgres.uri=jdbc:postgresql://localhost:5432/feedserver
</code></pre>
<p>restarted tomcat and the issue still occurred.</p>
<p>Its seems like its not picking up either <strong>application.properties</strong> or <strong>application.yml</strong></p>
<p><strong>EDIT 5</strong> Used the recommended way to start the spring boot server for an external container:</p>
<pre><code>@Configuration
public class WebAppInit extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
</code></pre>
<p><strong>Edit 6:</strong></p>
<p>I added <strong>-Dspring.profiles.active=dev</strong> to the start command args:</p>
<pre><code>/Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/bin/java -Djava.util.logging.config.file=/Users/shivamsinha/Desktop/Programming/tomcat/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Dlog4j.rootLevel=ERROR -Dlog4j.rootAppender=console -DENV=dev -Dlog4j.configuration=/WEB-INF/classes/properties/log4j.properties -DTOMCAT_DIR=WEB-INF/classes/ -Djava.endorsed.dirs=/Users/shivamsinha/Desktop/Programming/tomcat/endorsed -classpath /Users/shivamsinha/Desktop/Programming/tomcat/bin/bootstrap.jar:/Users/shivamsinha/Desktop/Programming/tomcat/bin/tomcat-juli.jar -Dcatalina.base=/Users/shivamsinha/Desktop/Programming/tomcat -Dcatalina.home=/Users/shivamsinha/Desktop/Programming/tomcat -Djava.io.tmpdir=/Users/shivamsinha/Desktop/Programming/tomcat/temp org.apache.catalina.startup.Bootstrap -Dspring.profiles.active=dev start
</code></pre>
<p>However I stil get the following exception in the logs:</p>
<pre><code>Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String com.titlefeed.config.db.DbConfigJPA.databaseUrl; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.data.postgres.uri' in string value "${spring.data.postgres.uri}"
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 68 more
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.data.postgres.uri' in string value "${spring.data.postgres.uri}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:204)
at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:178)
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$2.resolveStringValue(PropertySourcesPlaceholderConfigurer.java:175)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:801)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:955)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 70 more
02-Sep-2015 03:15:40.472 SEVERE [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Error deploying web application archive /Users/shivamsinha/Desktop/Programming/tomcat/webapps/feedserver-1.0.0.war
java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/feedserver-1.0.0]]
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:728)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:714)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:917)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1701)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</code></pre>
| 0 | 3,677 |
TypeError: Cannot read property 'handle' of undefined --- if (fn.handle && fn.set) mount_app = fn
|
<p>I would appreciate some help with this please. Not certain exactly sure what to this means as this is my first time working with node and express. I set up express to use with node, and tried to follow the information on the site <a href="http://nodejs.org/api/modules.html" rel="nofollow">Express.js</a> . Would appreciate some help understanding what I may be missing here please. </p>
<p><code>...\node_modules\express\lib\application.js:178
if (fn.handle && fn.set) mount_app = fn;
^
TypeError: Cannot read property 'handle' of undefined
at Function.app.use (....\node_modules\express\lib\application.js:178:9)
at Object.<anonymous> (....\app.js:18:5)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
</code></p>
<pre><code>/**
* Module dependencies.
*/
var http = require('http');
//var express = require('../..');
var module = require("module")
var logger = require('morgan');
var express = require('express');
var app = module.exports = express();
var silent = 'test' == process.env.NODE_ENV;
var httpServer = http.createServer(app);
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
// app middleware
app.use(express.static(__dirname + '/public'));
app.use(bodyParser());
app.use(methodOverride());
app.use(logErrors);
app.use(clientErrorHandler);
app.use(errorHandler);
api.use(logger('dev'));
api.use(bodyParser());
/**
* CORS support.
*/
api.all('*', function(req, res, next)
{
if (!req.get('Origin')) return next();// use "*" here to accept any origin
res.set('Access-Control-Allow-Origin', 'http://localhost:3000');
res.set('Access-Control-Allow-Methods', 'GET, POST');
res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
res.set('Access-Control-Allow-Max-Age', 3600);
if ('OPTIONS' == req.method) return res.send(200);
next();
});
// middleware with an arity of 4 are considered error handling middleware. When you next(err)
// it will be passed through the defined middleware in order, but ONLY those with an arity of 4, ignoring regular middleware.
var clientErrorHandler=function(err, req, res, next) {
if (req.xhr) {// whatever you want here, feel free to populate properties on `err` to treat it differently in here.
res.send(err.status || 500, { error: err.message });
}
else
{ next(err);}
};
// create an error with .status. we can then use the property in our custom error handler (Connect repects this prop as well)
var error=function (status, msg) {
var err = new Error(msg);
err.status = status;
return err;
};
var logErrors=function (err, req, res, next) {
console.error(err.stack);
next(err);
};
var errorHandler=function (err, req, res, next) {
res.status(500);
res.render('error', { error: err });
};
// general config
app.set('views', __dirname + '/views');
//app.set('view engine', 'jade');
// our custom "verbose errors" setting which we can use in the templates via settings['verbose errors']
app.enable('verbose errors');// disable them in production use $ NODE_ENV=production node examples/error-pages
if ('production' == app.settings.env) {app.disable('verbose errors');}
silent || app.use(logger('dev'));
// Routes
app.get('/404', function(req, res, next){
next();// trigger a 404 since no other middleware will match /404 after this one, and we're not responding here
});
app.get('/403', function(req, res, next){// trigger a 403 error
var err = new Error('not allowed!');
err.status = 403;
next(err);
});
app.get('/500', function(req, res, next){// trigger a generic (500) error
next(new Error('keyboard cat!'));
});
// Error handlers
// Since this is the last non-error-handling middleware use()d, we assume 404, as nothing else responded.
// $ curl http://localhost:3000/notfound
// $ curl http://localhost:3000/notfound -H "Accept: application/json"
// $ curl http://localhost:3000/notfound -H "Accept: text/plain"
app.use(function(req, res, next){
res.status(404);
if (req.accepts('html')) {// respond with html page
res.render('404', { url: req.url });
return;
}
if (req.accepts('json')) {// respond with json
res.send({ error: 'Not found' });
return;
}
res.type('txt').send('Not found');// default to plain-text. send()
});
// error-handling middleware, take the same form as regular middleware, however they require an
// arity of 4, aka the signature (err, req, res, next).when connect has an error, it will invoke ONLY error-handling middleware.
// If we were to next() here any remaining non-error-handling middleware would then be executed, or if we next(err) to
// continue passing the error, only error-handling middleware would remain being executed, however here
// we simply respond with an error page.
app.use(function(err, req, res, next){
// we may use properties of the error object here and next(err) appropriately, or if we possibly recovered from the error, simply next().
res.status(err.status || 500);
res.render('500', { error: err });
});
if (!module.parent) {// assigning to exports will not modify module, must use module.exports
app.listen(3000);
silent || console.log('Express started on port 3000');
};
</code></pre>
| 0 | 1,760 |
'SEVERE: SAAJ0009: Message send failed error' while sending a message
|
<pre><code>Feb 8, 2011 11:56:49 AM com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPC
onnection post
SEVERE: SAAJ0009: Message send failed
com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: java.security.PrivilegedA
ctionException: com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Message s
end failed
at com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection.cal
l(Unknown Source)
at external.main(external.java:47)
Caused by: java.security.PrivilegedActionException: com.sun.xml.internal.messagi
ng.saaj.SOAPExceptionImpl: Message send failed
at java.security.AccessController.doPrivileged(Native Method)
... 2 more
Caused by: com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Message send f
ailed
at com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection.pos
t(Unknown Source)
at com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection$Pri
viledgedPost.run(Unknown Source)
... 3 more
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown
Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Sour
ce)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown S
ource)
... 5 more
CAUSE:
java.security.PrivilegedActionException: com.sun.xml.internal.messaging.saaj.SOA
PExceptionImpl: Message send failed
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection.cal
l(Unknown Source)
at external.main(external.java:47)
Caused by: com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Message send f
ailed
at com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection.pos
t(Unknown Source)
at com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection$Pri
viledgedPost.run(Unknown Source)
... 3 more
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown
Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Sour
ce)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown S
ource)
... 5 more
CAUSE:
java.security.PrivilegedActionException: com.sun.xml.internal.messaging.saaj.SOA
PExceptionImpl: Message send failed
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection.cal
l(Unknown Source)
at external.main(external.java:47)
Caused by: com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Message send f
ailed
at com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection.pos
t(Unknown Source)
at com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection$Pri
viledgedPost.run(Unknown Source)
... 3 more
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown
Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Sour
ce)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown S
ource)
... 5 more
java.security.PrivilegedActionException: com.sun.xml.internal.messaging.saaj.SOA
PExceptionImpl: Message send failed
</code></pre>
| 0 | 2,340 |
How do I add a footer row in a WPF datagrid?
|
<p>How Do I Add a footer row in WPF datagrid? I had to add a row in a WPF datagrid for the sum of each column, I don't want to use any dll or telerik and some things like that only use Microsoft components to do this. I'm trying to do it this way:</p>
<pre class="lang-xaml prettyprint-override"><code><Style TargetType="{x:Type DataGrid}">
<Setter Property="Foreground"
Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" />
<Setter Property="BorderBrush">
<Setter.Value>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="{DynamicResource BorderLightColor}" Offset="0" />
<GradientStop Color="{DynamicResource BorderDarkColor}" Offset="1" />
</LinearGradientBrush>
</Setter.Value>
</Setter>
<Setter Property="BorderThickness" Value="1" />
<Setter Property="RowDetailsVisibilityMode" Value="VisibleWhenSelected" />
<Setter Property="ScrollViewer.CanContentScroll" Value="true" />
<Setter Property="ScrollViewer.PanningMode" Value="Both" />
<Setter Property="Stylus.IsFlicksEnabled" Value="False" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGrid}">
<Border x:Name="border"
SnapsToDevicePixels="True"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Padding="{TemplateBinding Padding}">
<Border.Background>
<SolidColorBrush Color="{DynamicResource ControlLightColor}" />
</Border.Background>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Disabled">
<Storyboard>
<ColorAnimationUsingKeyFrames Storyboard.TargetName="border"
Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)">
<EasingColorKeyFrame KeyTime="0" Value="{DynamicResource ControlLightColor}" />
</ColorAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Normal" />
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<ScrollViewer x:Name="DG_ScrollViewer" Focusable="false" Background="Black">
<ScrollViewer.Template>
<ControlTemplate TargetType="{x:Type ScrollViewer}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Button Focusable="false"
Command="{x:Static DataGrid.SelectAllCommand}"
Style="{DynamicResource {ComponentResourceKey
ResourceId=DataGridSelectAllButtonStyle,
TypeInTargetAssembly={x:Type DataGrid}}}"
Visibility="{Binding HeadersVisibility,
ConverterParameter={x:Static DataGridHeadersVisibility.All},
Converter={x:Static DataGrid.HeadersVisibilityConverter},
RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
Width="{Binding CellsPanelHorizontalOffset,
RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />
<DataGridColumnHeadersPresenter x:Name="PART_ColumnHeadersPresenter"
Grid.Column="1"
Visibility="{Binding HeadersVisibility,
ConverterParameter={x:Static DataGridHeadersVisibility.Column},
Converter={x:Static DataGrid.HeadersVisibilityConverter},
RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />
<ScrollContentPresenter x:Name="PART_ScrollContentPresenter"
Grid.ColumnSpan="2"
Grid.Row="1"
CanContentScroll="{TemplateBinding CanContentScroll}" />
<ScrollBar x:Name="PART_VerticalScrollBar"
Grid.Column="2"
Grid.Row="1"
Orientation="Vertical"
ViewportSize="{TemplateBinding ViewportHeight}"
Maximum="{TemplateBinding ScrollableHeight}"
Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}"
Value="{Binding VerticalOffset, Mode=OneWay,
RelativeSource={RelativeSource TemplatedParent}}"/>
<TextBlock Grid.Row="2" Grid.Column="1" Text="This is footer!"/>
<Grid Grid.Column="1" Grid.Row="3">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding NonFrozenColumnsViewportHorizontalOffset,
RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ScrollBar x:Name="PART_HorizontalScrollBar"
Grid.Column="1"
Orientation="Horizontal"
ViewportSize="{TemplateBinding ViewportWidth}"
Maximum="{TemplateBinding ScrollableWidth}"
Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}"
Value="{Binding HorizontalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}"/>
</Grid>
</Grid>
</ControlTemplate>
</ScrollViewer.Template>
<ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
</ScrollViewer>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsGrouping" Value="true">
<Setter Property="ScrollViewer.CanContentScroll" Value="false" />
</Trigger>
</Style.Triggers>
</Style>
</code></pre>
<p>I also tried adding a grid instead of textblock, but when resizing datagrid columns, they can't resize and looks very ugly.</p>
| 0 | 5,207 |
Simple webservice with node-soap
|
<p>I am trying to implement a simple web service using SOAP using Node Js and node-soap, but the client side seems to have problems using the server.</p>
<pre><code>assert.js:92
throw new assert.AssertionError({
^
AssertionError: invalid message definition for document style binding
</code></pre>
<p>My wsdl file is:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions name="wscalc1"
targetNamespace="http://localhost:8000/wscalc1"
xmlns="http://localhost:8000/wscalc1"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:http="http://schemas.xmlsoap.org/wsdl/http/"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">
<wsdl:message name="sumarRequest">
<wsdl:part name="a" type="xs:string"></wsdl:part>
<wsdl:part name="b" type="xs:string"></wsdl:part>
</wsdl:message>
<wsdl:message name="multiplicarRequest">
<wsdl:part name="a" type="xs:string"></wsdl:part>
<wsdl:part name="b" type="xs:string"></wsdl:part>
</wsdl:message>
<wsdl:message name="multiplicarResponse">
<wsdl:part name="res" type="xs:string"></wsdl:part>
</wsdl:message>
<wsdl:message name="sumarResponse">
<wsdl:part name="res" type="xs:string"></wsdl:part>
</wsdl:message>
<wsdl:portType name="calcP">
<wsdl:operation name="sumar">
<wsdl:input message="sumarRequest"></wsdl:input>
<wsdl:output message="sumarResponse"></wsdl:output>
</wsdl:operation>
<wsdl:operation name="multiplicar">
<wsdl:input message="multiplicarRequest"></wsdl:input>
<wsdl:output message="multiplicarResponse"></wsdl:output>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="calcB" type="calcP">
<soap:binding style="document"
transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="sumar">
<soap:operation soapAction="sumar"/>
<wsdl:input>
<soap:body use="literal"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</wsdl:input>
<wsdl:output>
<soap:body use="literal"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</wsdl:output>
</wsdl:operation>
<wsdl:operation name="multiplicar">
<soap:operation soapAction="multiplicar"/>
<wsdl:input>
<soap:body use="literal"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</wsdl:input>
<wsdl:output>
<soap:body use="literal"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="ws">
<wsdl:port name="calc" binding="calcB">
<soap:address location="http://localhost:8000/wscalc1"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>
</code></pre>
<p>server.js</p>
<pre><code>var soap = require('soap');
var http = require('http');
var service = {
ws: {
calc: {
sumar : function(args) {
var n = args.a + args.b;
return { res : n };
},
multiplicar : function(args) {
var n = args.a * args.b;
return { res : n }
}
}
}
}
var xml = require('fs').readFileSync('wscalc1.wsdl', 'utf8'),
server = http.createServer(function(request,response) {
response.end("404: Not Found: "+request.url)
});
server.listen(8000);
soap.listen(server, '/wscalc1', service, xml);
</code></pre>
<p>client.js</p>
<pre><code>var soap = require('soap');
var url = 'http://localhost:8000/wscalc1?wsdl';
soap.createClient(url, function(err, client) {
if (err) throw err;
console.log(client.describe().ws.calc);
client.multiplicar({"a":"1","b":"2"},function(err,res){
if (err) throw err;
console.log(res);
});
});
</code></pre>
<p>with that code the output is:</p>
<pre><code>{ sumar:
{ input: { a1: 'Request', b1: 'Request' },
output: { res: 'Response' } },
multiplicar:
{ input: { a2: 'Request', b2: 'Request' },
output: { res: 'Response' } } }
assert.js:92
throw new assert.AssertionError({
^
AssertionError: invalid message definition for document style binding
</code></pre>
<p>any help will be really appreciated </p>
| 0 | 2,343 |
Print results in MySQL format with Python
|
<p>What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like that:</p>
<pre><code>+---------------------+-----------+---------+
| font | documents | domains |
+---------------------+-----------+---------+
| arial | 99854 | 5741 |
| georgia | 52388 | 1955 |
| verdana | 43219 | 2388 |
| helvetica neue | 22179 | 1019 |
| helvetica | 16753 | 1036 |
| lucida grande | 15431 | 641 |
| tahoma | 10038 | 594 |
| trebuchet ms | 8868 | 417 |
| palatino | 5794 | 177 |
| lucida sans unicode | 3525 | 116 |
| sans-serif | 2947 | 216 |
| times new roman | 2554 | 161 |
| proxima-nova | 2076 | 36 |
| droid sans | 1773 | 78 |
| calibri | 1735 | 64 |
| open sans | 1479 | 60 |
| segoe ui | 1273 | 57 |
+---------------------+-----------+---------+
17 rows in set (19.43 sec)
</code></pre>
<p>Notice: I don't know the max width for each column a priori, and yet I would like to be able to that without going over the table twice. Should I add to the query length() for each column? How does MySQL do it, in order to not impact severely the memory or processing time? </p>
<p><em>EDIT</em></p>
<p>I did not think it was relevant to the question but, this is the query I send:</p>
<pre><code>SELECT font.font as font,count(textfont.textid) as documents, count(DISTINCT td.domain) as domains
FROM textfont
RIGHT JOIN font
ON textfont.fontid = font.fontid
RIGHT JOIN (
SELECT text.text as text,url.domain as domain, text.textid as textid
FROM text
RIGHT JOIN url
ON text.texturl = url.urlid) as td
ON textfont.textid = td.textid
WHERE textfont.fontpriority <= 0
AND textfont.textlen > 100
GROUP BY font.font
HAVING documents >= 1000 AND domains >= 10
ORDER BY 2 DESC;
</code></pre>
<p>And this is the python code I use:</p>
<pre><code>import MySQLdb as mdb
print "%s\t\t\t%s\t\t%s" % ("font","documents","domains")
res = cur.execute(query , (font_priority,text_len,min_texts,min_domains))
for res in cur.fetchall():
print "%s\t\t\t%d\t\t%d" % (res[0],res[1],res[2])
</code></pre>
<p>But this code produces a messy output due to different widths.</p>
| 0 | 1,107 |
Adding the ZeroMQ PHP extension to XAMPP on Windows 10 and PHP7
|
<p>I am having issues adding the ZeroMQ PHP extension to XAMPP. </p>
<p>Setup: Windows 10, PHP7, XAMPP (7.0.9)</p>
<p><strong>Steps I already took:</strong></p>
<ol>
<li><p>Added PHP (<code>D:\xampp7\php</code>) and PHP extensions (<code>D:\xampp7\php\ext</code>) directories to system variable (PATH)</p></li>
<li><p>Followed the instructions on <a href="http://zeromq.org/bindings%3Aphp#toc4" rel="noreferrer">zeromq.org</a>. I downloaded <a href="http://windows.php.net/downloads/pecl/releases/zmq/1.1.3/php_zmq-1.1.3-7.0-ts-vc14-x86.zip" rel="noreferrer">x86ts</a> version from the <a href="http://pecl.php.net/package/zmq/1.1.3/windows" rel="noreferrer">pecl repository</a> as the listed snapshot link (<a href="http://snapshot.zero.mq/" rel="noreferrer">http://snapshot.zero.mq/</a>) was down.</p></li>
<li><p>Copied <code>libzmq.dll</code> into PHP directory and <code>php_zmq.dll</code> into the PHP extension directory </p></li>
<li><p>Updated <code>php.ini</code> (<code>D:\xampp7\php\php.ini</code>) by adding <code>extension=php_zmq.dll</code> and checked the extensions directory which is <code>extension_dir="D:\xampp7\php\ext"</code></p></li>
<li><p>Restarted XAMPP via the control panel.</p></li>
</ol>
<p>The Apache error log shows the following:</p>
<pre><code>[Sat Nov 26 18:30:27.461679 2016] [ssl:warn] [pid 15280:tid 588] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Sat Nov 26 18:30:27.546320 2016] [core:warn] [pid 15280:tid 588] AH00098: pid file D:/xampp7/apache/logs/httpd.pid overwritten -- Unclean shutdown of previous Apache run?
[Sat Nov 26 18:30:27.630955 2016] [ssl:warn] [pid 15280:tid 588] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
PHP Warning: PHP Startup: Unable to load dynamic library 'D:\\xampp7\\php\\ext\\php_zmq.dll' - Das angegebene Modul wurde nicht gefunden.\r\n in Unknown on line 0
[Sat Nov 26 18:30:27.662208 2016] [mpm_winnt:notice] [pid 15280:tid 588] AH00455: Apache/2.4.23 (Win32) OpenSSL/1.0.2h PHP/7.0.9 configured -- resuming normal operations
[Sat Nov 26 18:30:27.662208 2016] [mpm_winnt:notice] [pid 15280:tid 588] AH00456: Apache Lounge VC14 Server built: Jul 1 2016 11:09:37
[Sat Nov 26 18:30:27.662208 2016] [core:notice] [pid 15280:tid 588] AH00094: Command line: 'd:\\xampp7\\apache\\bin\\httpd.exe -d D:/xampp7/apache'
[Sat Nov 26 18:30:27.662208 2016] [mpm_winnt:notice] [pid 15280:tid 588] AH00418: Parent: Created child process 964
[Sat Nov 26 18:30:28.363210 2016] [ssl:warn] [pid 964:tid 616] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
</code></pre>
<hr>
<p><strong>Update:</strong></p>
<p>It looks like the module cannot be found, but if I add the x64 Version the Apache error log indicates that the module is not a not a valid Win32 application.</p>
<pre><code>PHP Warning: PHP Startup: Unable to load dynamic library 'D:\\xampp7\\php\\ext\\php_zmq.dll' - %1 ist keine zul\xef\xbf\xbdssige Win32-Anwendung.\r\n in Unknown on line 0
</code></pre>
<hr>
<p><strong>Solution:</strong></p>
<p>Adding <code>LoadFile "D:/xampp7/php/libzmq.dll"</code>to httpd.conf fixed my issue.</p>
| 0 | 1,268 |
Docker - Failed to connect to localhost port 4000: Connection refused
|
<p>Hi I'm very new to Docker, I'm trying to get familiar with Docker by following the tutorial on official site. Now I get stuck at part 2 of the tutorial (where you can check up the link here => <a href="https://docs.docker.com/get-started/part2/#run-the-app" rel="noreferrer">https://docs.docker.com/get-started/part2/#run-the-app</a>)</p>
<p>I have sample application code, Dockerfile, and requirements.txt exactly same as the offical tutorial</p>
<pre><code>$ ls
app.py Dockerfile requriements.txt
</code></pre>
<p>My Dockerfile looks like this</p>
<pre><code>FROM python:2.7-slim
WORKDIR /app
ADD . /app
RUN pip install -r requriements.txt
EXPOSE 80
ENV NAME World
CMD ["python", "app.py"]
</code></pre>
<p>All 3 files have file content/code exactly same as the tutorial also. I was able to build image registry with this command</p>
<pre><code>$ docker build -t friendlyhello .
</code></pre>
<p>Everything looks great. Now I had sample project image registry.</p>
<pre><code>$ docker images
REPOSITORY TAG IMAGE ID CREATED
friendlyhello latest 82b8a0b52e91 39 minutes ago
python 2.7-slim 1c7128a655f6 5 days ago
hello-world latest 48b5124b2768 4 months ago
</code></pre>
<p>I then ran the app according to the official tutorial with this command</p>
<pre><code>$ docker run -d -p 4000:80 friendlyhello
c1893f7eea9f1b708f639653b8eba20733d8a45d3812b442bc295b43c6c7dd5c
</code></pre>
<p><strong>Edit</strong>: This is my container after ran above command</p>
<pre><code>$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS
c1893f7eea9f friendlyhello "python app.py" 15 minutes ago Up 16 minutes
</code></pre>
<p>And the official tutorial guides readers to have a look at <code>http://localhost:4000</code> as they have already mapped machine port <code>4000</code> to container port <code>80</code></p>
<p>Unfortunately, I couldn't get any response from that URL.</p>
<pre><code>$ curl http://localhost:4000
curl: (7) Failed to connect to localhost port 4000: Connection refused
</code></pre>
<p>I'm totally newbie and I have no idea what to do....How can I get it to work ?
Thanks in advance for any response.</p>
<p><strong>Edit</strong>: I did as @johnharris85 suggested. Below is the output</p>
<pre><code>$ curl http://$(echo docker-machine ip default):4000
curl: (6) Couldn't resolve host 'docker-machine'
curl: (6) Couldn't resolve host 'ip'
curl: (6) Couldn't resolve host 'default'
</code></pre>
<p>It seems like it doesn't work either.</p>
<p><strong>Edit</strong>: @johnharris85 corrected his suggestion and @user8023051 clarify how this command come from and what is going on under the hood. It is working now :) Thanks</p>
<pre><code>$ curl http://$(docker-machine ip default):4000
<h3>Hello World!</h3><b>Hostname:</b> c1893f7eea9f<br/><b>Visits:</b> <i>cannot connect to Redis, counter disabled</i>
</code></pre>
| 0 | 1,196 |
Reactjs : Adding element to array object in Json
|
<p>I have just started with reactjs and working on form component(formsy).I am trying to add and element to the existing array element but I am not able to do so. below is what I have tried and what I have got so far.</p>
<p>JSON Object - </p>
<pre><code>{
"details": {
"someInnerObj": "v3",
"innerObj": {
"key1": "",
"key2": ""
},
"ArrayObject": [{
"type": "sometype",
"somedesign": {
"A": "",
"B": "",
"C": "",
"D": ""
},
"somedev": {
"a": "",
"b": "",
"c": "",
"d": ""
}
}
],
"code": "code",
"isThis": "true"
}
}
</code></pre>
<p>what i am trying to achieve here is adding and element to ArrayObject like below</p>
<pre><code>"ArrayObject": [{
"type": "sometype",
"somedesign": {
"A": "",
"B": "",
"C": "",
"D": ""
},
"somedev": {
"a": "",
"b": "",
"c": "",
"d": ""
}
},
{
"type": "sometype1",
"somedesing1": {
"A1": "",
"B1": "",
"C1": "",
"D1": ""
},
"somedev1": {
"a1": "",
"b1": "",
"c1": "",
"d1": ""
}
}
]
</code></pre>
<p>I am putting new element using the field value of json object as
"details.ArrayObject[1]". but it instead of adding the new element is creating new key as given below and removing the existing - </p>
<pre><code>"ArrayObject": {
"[1]": {
"type": "sometype1",
"somedesing1": {
"A1": "",
"B1": "",
"C1": "",
"D1": ""
},
"somedev1": {
"a1": "",
"b1": "",
"c1": "",
"d1": ""
}
}
}
</code></pre>
<p>Could anyone please help out here ?</p>
<p>thanks.</p>
| 0 | 1,683 |
Google API - request for token from Oauth2 returns "invalid_request"
|
<p>I am trying to make an app using Google's calendar API. I'm following the directions <a href="https://developers.google.com/accounts/docs/OAuth2WebServer">here</a>. I can make the request to get the authorization code, but I can not seem to form a valid request to get an access token. I keep getting the response <code>{"error" : "invalid_request"}</code>.
This is the POST request I am making:</p>
<pre><code>POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
code=4/vxQqw9JMYEnXvI8A_93OV7kBSg6h.8r2yJUkMc18dshQV0ieZDAraZNwsbwI&
client_id=[my client id]&
client_secret=[my client secret]&
redirect_uri=http://localhost:8080/auth&
grant_type=authorization_code
</code></pre>
<p>Below is the output from calling the url through curl. My actual app is written in Node.js, but I get the same response from curl as I do through the app. I've searched around and seen people with similar problems, but still can't figure out what I'm doing wrong.</p>
<pre><code>curl -v -k --header "Content-Type: application/x-www-form-urlencoded" --data-urlencode "code=4/vxQqw9JMYEnXvI8A_93OV7kBSg6h.8r2yJUkMc18dshQV0ieZDAraZNwsbwI&client_id=[my client id]&client_secret=[my client secret]&redirect_uri=http://localhost:8080/auth&grant_type=authorization_code" https://accounts.google.com/o/oauth2/token
* About to connect() to accounts.google.com port 443 (#0)
* Trying 173.194.74.84... connected
* Connected to accounts.google.com (173.194.74.84) port 443 (#0)
* SSLv3, TLS handshake, Client hello (1):
* SSLv3, TLS handshake, Server hello (2):
* SSLv3, TLS handshake, CERT (11):
* SSLv3, TLS handshake, Server finished (14):
* SSLv3, TLS handshake, Client key exchange (16):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSL connection using RC4-SHA
* Server certificate:
* subject: C=US; ST=California; L=Mountain View; O=Google Inc; CN=accounts.google.com
* start date: 2011-07-21 00:00:00 GMT
* expire date: 2013-07-18 23:59:59 GMT
* common name: accounts.google.com (matched)
* issuer: C=ZA; O=Thawte Consulting (Pty) Ltd.; CN=Thawte SGC CA
* SSL certificate verify result: unable to get local issuer certificate (20), continuing anyway.
> POST /o/oauth2/token HTTP/1.1
> User-Agent: curl/7.21.3 (i386-apple-darwin8.11.1) libcurl/7.21.3 OpenSSL/0.9.7l zlib/1.2.5 libidn/1.17
> Host: accounts.google.com
> Accept: */*
> Content-Type: application/x-www-form-urlencoded
> Content-Length: 180
>
< HTTP/1.1 400 Bad Request
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: Fri, 01 Jan 1990 00:00:00 GMT
< Date: Tue, 29 May 2012 12:43:49 GMT
< Content-Type: application/json
< X-Content-Type-Options: nosniff
< X-Frame-Options: SAMEORIGIN
< X-XSS-Protection: 1; mode=block
< Server: GSE
< Transfer-Encoding: chunked
<
{
"error" : "invalid_request"
* Connection #0 to host accounts.google.com left intact
* Closing connection #0
* SSLv3, TLS alert, Client hello (1):
}
</code></pre>
| 0 | 1,206 |
Angular2 Error: There is no directive with "exportAs" set to "ngForm"
|
<p>i'm on the RC4 and i'm getting the error <strong>There is no directive with "exportAs" set to "ngForm"</strong> because of my template :</p>
<pre><code><div class="form-group">
<label for="actionType">Action Type</label>
<select
ngControl="actionType"
===> #actionType="ngForm"
id="actionType"
class="form-control"
required>
<option value=""></option>
<option *ngFor="let actionType of actionTypes" value="{{ actionType.label }}">
{{ actionType.label }}
</option>
</select>
</div>
</code></pre>
<p>the boot.ts :</p>
<pre><code>import {disableDeprecatedForms, provideForms} from '@angular/forms';
import {bootstrap} from '@angular/platform-browser-dynamic';
import {HTTP_PROVIDERS, Http} from '@angular/http';
import {provideRouter} from '@angular/router';
import {APP_ROUTER_PROVIDER} from './routes';
import {AppComponent} from './app.component';
bootstrap(AppComponent, [ disableDeprecatedForms(), provideForms(), APP_ROUTER_PROVIDER, HTTP_PROVIDERS]);
</code></pre>
<p>/// so here is my DropdownList :</p>
<pre><code><fieldset ngControlGroup="linkedProcess" >
<div ngControlGroup="Process" >
<label>Linked Process</label>
<div class="form-group">
<select
ngModel
name="label"
#label="ngModel"
id="label"
class="form-control" required
(change)="reloadProcesse(list.value)"
#list>
<option value=""></option>
<!--<option value=`{{ActionFormComponent.getFromString('GET'')}}`></option>-->
<option *ngFor="let processus of linkedProcess?.processList?.list; let i = index"
value="{{ processus[i].Process.label}}">
{{processus.Process.label}}
</option>
</select>
</div>
</div>
</code></pre>
<p>//my component ts :</p>
<p>i was representing it in the old forms like this : </p>
<pre><code> categoryControlGroups:ControlGroup[] = [];
categories:ControlArray = new ControlArray(this.categoryControlGroups);
</code></pre>
<p>and now i'm doing this : </p>
<pre><code>categoryControlGroups:FormGroup[] = [];
categories:FormArray = new FormArray(this.categoryControlGroups);
</code></pre>
<p>you think it's the cause of the prob ??</p>
| 0 | 1,249 |
adding dropdown menu in alert dialog box in flutter
|
<p>I'm having UI rendering issues when I attempt to add a drop down menu with a date and time picker in an alert dialog box in my flutter application. I've been trying to troubleshoot this for quite some time now but to no avail. This is the output that I am getting: </p>
<p><a href="https://i.stack.imgur.com/WUEN4.png" rel="nofollow noreferrer">image output</a></p>
<p>My Code: </p>
<pre><code> import 'dart:async';
import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:test_prep/utils/Reminder.dart';
import 'package:intl/intl.dart';
class RemindersPage extends StatefulWidget {
@override
_RemindersPageState createState() => _RemindersPageState();
}
class _RemindersPageState extends State<RemindersPage> {
final TextEditingController _titleController = new
TextEditingController();
List<DropdownMenuItem<Future>> dateDrop = [];
List<DropdownMenuItem<Future>> timeDrop = [];
int selected = null;
void loadDateData() {
dateDrop = [];
dateDrop.add(new DropdownMenuItem(
child: new Text('Pick Date'),
value: _selectedDate(context),
));
}
void loadTimeData() {
timeDrop = [];
timeDrop.add(new DropdownMenuItem(
child: new Text('Pick a Time'),
value: _selectedTime(context),
));
}
@override
Widget build(BuildContext context) {
</code></pre>
<p>// loadDateData();
// loadTimeData();</p>
<pre><code>return Scaffold(
backgroundColor: Colors.black87,
body: Column(children: <Widget>[]),
// Floating Action button
floatingActionButton: new FloatingActionButton(
tooltip: "Add Item",
backgroundColor: Colors.greenAccent,
child: new ListTile(
title: Icon(
Icons.add,
),
),
onPressed: _showFormDialog),
bottomNavigationBar: new Theme(
data: Theme.of(context)
.copyWith(canvasColor: Colors.grey, primaryColor:
Colors.white),
child: new BottomNavigationBar(
items: [
new BottomNavigationBarItem(
icon: new Icon(Icons.filter_none),
title: new Text("Reminders")),
new BottomNavigationBarItem(
icon: new Icon(Icons.all_out), title: new Text("Quizes"))
],
onTap: (int i) => debugPrint("You tapped $i"),
),
),
);
}
// Alert Dialog
void _showFormDialog() {
var alert = new AlertDialog(
title: Text("Set Reminder"),
content: Column(children: <Widget>[
Expanded(
child: TextField(
controller: _titleController,
autofocus: true,
decoration: InputDecoration(
labelText: 'Name of Reminder',
hintText: "eg. Test on Thursday!",
icon: Icon(Icons.title),
),
),
),
// Date
_dropDownDate(),
// Time
_dropDownTime()
]),
actions: <Widget>[
new FlatButton(
onPressed: () => debugPrint("Save button"), child:
Text('Save')),
new FlatButton(
onPressed: () => Navigator.pop(context), child:
Text('Cancel'))
],
);
showDialog(
context: context,
builder: (_) {
return alert;
});
}
// Date and time picker
DateTime _date = new DateTime.now();
TimeOfDay _time = new TimeOfDay.now();
Future<Null> _selectedDate(BuildContext context) async {
final DateTime picked = await showDatePicker(
context: context,
initialDate: _date,
firstDate: new DateTime(2018),
lastDate: new DateTime(2019));
if (picked != null) {
debugPrint('Date selected: ${_date.toString()}');
setState(() {
_date = picked;
});
}
}
Future<Null> _selectedTime(BuildContext context) async {
final TimeOfDay picked =
await showTimePicker(context: context, initialTime: _time);
if (picked != null && picked != _time) {
debugPrint('Time selected: ${_time.toString()}');
setState(() {
_time = picked;
});
}
}
_dropDownDate() {
var drop_date = Container(
child: Row(mainAxisAlignment: MainAxisAlignment.start, children:
[
DropdownButton(
value: selected,
items: dateDrop,
hint: Text('Pick a date'),
onChanged: (value) {
selected = value;
setState(() {});
}),
]));
return drop_date;
}
_dropDownTime() {
var drop_time = Container(
child: Row(mainAxisAlignment: MainAxisAlignment.start, children:
[
DropdownButton(
value: selected,
items: timeDrop,
hint: Text('Pick a time'),
onChanged: (value) {
selected = value;
setState(() {});
}),
]));
return drop_time;
}
}
</code></pre>
<p>Flutter runtime message: </p>
<pre><code> Syncing files to device iPhone X...
flutter: ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
flutter: The following ArgumentError was thrown during paint():
flutter: Invalid argument(s): 0.0
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0 double.clamp (dart:core/runtime/libdouble.dart:144:7)
flutter: #1 _DropdownMenuPainter.paint (package:flutter/src/material/dropdown.dart:57:33)
flutter: #2 RenderCustomPaint._paintWithPainter (package:flutter/src/rendering/custom_paint.dart:520:13)
flutter: #3 RenderCustomPaint.paint (package:flutter/src/rendering/custom_paint.dart:558:7)
flutter: #4 RenderObject._paintWithContext (package:flutter/src/rendering/object.dart:2085:7)
flutter: #5 PaintingContext.paintChild (package:flutter/src/rendering/object.dart:171:13)
flutter: #6 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.paint (package:flutter/src/rendering/proxy_box.dart:126:15)
flutter: #7 PaintingContext.pushLayer (package:flutter/src/rendering/object.dart:367:12)
flutter: #8 PaintingContext.pushOpacity (package:flutter/src/rendering/object.dart:491:5)
flutter: #9 RenderAnimatedOpacity.paint (package:flutter/src/rendering/proxy_box.dart:904:15)
flutter: #10 RenderObject._paintWithContext (package:flutter/src/rendering/object.dart:2085:7)
flutter: #11 PaintingContext.paintChild (package:flutter/src/rendering/object.dart:171:13)
flutter: #12 RenderShiftedBox.paint (package:flutter/src/rendering/shifted_box.dart:70:15)
flutter: #13 RenderObject._paintWithContext (package:flutter/src/rendering/object.dart:2085:7)
flutter: #14 PaintingContext.paintChild (package:flutter/src/rendering/object.dart:171:13)
flutter: #15 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.paint (package:flutter/src/rendering/proxy_box.dart:126:15)
flutter: #16 RenderObject._paintWithContext (package:flutter/src/rendering/object.dart:2085:7)
flutter: #17 PaintingContext._repaintCompositedChild (package:flutter/src/rendering/object.dart:128:11)
flutter: #18 PaintingContext.repaintCompositedChild (package:flutter/src/rendering/object.dart:96:5)
flutter: #19 PipelineOwner.flushPaint (package:flutter/src/rendering/object.dart:852:29)
flutter: #20 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding.drawFrame (package:flutter/src/rendering/binding.dart:272:19)
flutter: #21 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:654:13)
flutter: #22 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:208:5)
flutter: #23 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:990:15)
flutter: #24 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:930:9)
flutter: #25 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:842:5)
flutter: #26 _invoke (dart:ui/hooks.dart:128:13)
flutter: #27 _drawFrame (dart:ui/hooks.dart:117:3)
flutter:
flutter: The following RenderObject was being processed when the exception was fired:
flutter: RenderCustomPaint#556fb relayoutBoundary=up2
flutter: creator: CustomPaint ← FadeTransition ← _DropdownMenu<Object> ← CustomSingleChildLayout ← Builder
flutter: ← MediaQuery ← Builder ← RepaintBoundary-[GlobalKey#4c3ae] ← IgnorePointer ← AnimatedBuilder ←
flutter: RepaintBoundary ← _FocusScopeMarker ← ⋯
flutter: parentData: <none> (can use size)
flutter: constraints: BoxConstraints(w=148.0, 0.0<=h<=716.0)
flutter: size: Size(148.0, 16.0)
flutter: This RenderObject had the following descendants (showing up to depth 5):
flutter: RenderSemanticsAnnotations#151e5 relayoutBoundary=up3 NEEDS-PAINT
flutter: RenderCustomPaint#b9211 relayoutBoundary=up4 NEEDS-PAINT
flutter: _RenderInkFeatures#13585 relayoutBoundary=up5 NEEDS-PAINT
flutter: RenderRepaintBoundary#ed5d6 relayoutBoundary=up6 NEEDS-PAINT
flutter: RenderCustomPaint#f5290 relayoutBoundary=up7 NEEDS-PAINT
flutter: ════════════════════════════════════════════════════════════════════════════════════════════════════
flutter: Another exception was thrown: Invalid argument(s): 0.0
flutter: Another exception was thrown: Invalid argument(s): 0.0
flutter: Another exception was thrown: Invalid argument(s): 0.0
flutter: Another exception was thrown: Invalid argument(s): 0.0
flutter: Another exception was thrown: Invalid argument(s): 0.0
flutter: Another exception was thrown: Invalid argument(s): 0.0
[C2.1 748F7D32-4C53-4798-B15B-8E3BDB7D9006 2601:196:4801:b518:c076:dbf1:83d3:ada3.50444<->2607:f8b0:4002:c08::8b.443]
Connected Path: satisfied (Path is satisfied), interface: en0
Duration: 121.165s, DNS @0.004s took 0.008s, TCP @0.018s took 0.055s, TLS took 0.137s
bytes in/out: 3879/764, packets in/out: 10/8, rtt: 0.056s, retransmitted packets: 0, out-of-order packets: 0
[C3.1 67E05789-ED99-4A78-A900-D136E04B908C 2601:196:4801:b518:c076:dbf1:83d3:ada3.50445<->2607:f8b0:4002:c08::8b.443]
Connected Path: satisfied (Path is satisfied), interface: en0
Duration: 120.368s, DNS @0.002s took 0.004s, TCP @0.008s took 0.056s, TLS took 0.137s
bytes in/out: 3591/1188, packets in/out: 9/9, rtt: 0.058s, retransmitted packets: 0, out-of-order packets: 0
[C1.1 89EEE9E8-79C7-4861-9FD9-148DA484E6BE 2601:196:4801:b518:c076:dbf1:83d3:ada3.50428<->2607:f8b0:4002:813::200a.443]
Connected Path: satisfied (Path is satisfied), interface: en0
Duration: 240.659s, DNS @0.002s took 0.031s, TCP @0.036s took 0.058s, TLS took 0.563s
bytes in/out: 3394/1027, packets in/out: 10/9, rtt: 0.057s, retransmitted packets: 0, out-of-order packets: 0
</code></pre>
| 0 | 4,499 |
NHibernate mapping - one-to-one (or one-to-zero)
|
<p>NHibernatians!</p>
<p>I have a table [dbo].[Wibble] and another table [dbo].[WibbleExtended].</p>
<p>[Wibble] is the main table and [WibbleExtended] is an optional table where some other fields are stored. There are far fewer entries in the [WibbleExtended] table than the main [Wibble] table. I think this was done back in the day to cure some space issues (Wibble has many rows and WibbleExtened has many columns).</p>
<p>The ID for each table is the same and comes from an external source. </p>
<p>I.e.</p>
<pre><code>[dbo].[Wibble].[WibbleId]
</code></pre>
<p>and </p>
<pre><code>[dbo].[WibbleExtended].[WibbleId]
</code></pre>
<p>are identical and is how the two tables relate.</p>
<p>N.B. I can't change the schema. I'm shoe-horning this onto a legacy system that I have almost no control over.</p>
<p>Searching around it seems that one-to-one mappings are problematic and the prevailing wisdom is to use two many-to-one mappings.</p>
<p>My mappings currently are:</p>
<pre><code><class name="Wibble" table="Wibble" >
<id name="Id" column="WibbleId" type="Int32">
<generator class="assigned"/>
</id>
<many-to-one name="WibbleExtended" class="WibbleExtended" column="WibbleId" not-null="false" cascade="all"/>
</class>
</code></pre>
<p>And</p>
<pre><code><class name="WibbleExtended" table="WibbleExtended" >
<id name="Id" column="WibbleId" type="Int32">
<generator class="assigned" />
</id>
<many-to-one name="Wibble" class="Wibble" column="WibbleId" not-null="true" />
</class>
</code></pre>
<p>The problem with this is I'm getting errors such as </p>
<pre><code>System.IndexOutOfRangeException: Invalid index n for this SqlParameterCollection with Count=n.
</code></pre>
<p>I've looked around and this does look like the correct strategy, it's just falling at the final hurdle.</p>
<p>Is the problem the id generator? Other aspect of the mapping?</p>
<p>Free mince pie for the correct answer.</p>
<p>EDIT: Ok - here's what I did to solve this via @James Gregory.</p>
<ol>
<li><p>Moved the unit tests from the WibbleExtended tests to the Wibble test class and made the necessary modifications.</p></li>
<li><p>Added the following to the Wibble.hbm.xml </p>
<pre><code><join table="WibbleExtended" optional="true">
<key column="WibbleId"/>
<property name="Blah1" column="Blah1" type="String" length="2000" not-null="false" />
<property name="Blah2" column="Blah2" type="String" length="1000" not-null="false" />
</join>
</code></pre></li>
<li><p>Added the corresponding properties to the Wibble POCO.</p></li>
<li><p>Deleted all code relating to WibbleExtended.</p></li>
<li><p>Run tests, all passed, checked in. Build passed. Went for an xmas beer (hence it's been a couple of days before I updated this! :-))</p></li>
</ol>
| 0 | 1,089 |
JavaFX: Apply text color to TableCell using custom style sheet?
|
<p>JavaFX: <strong>How can I apply text color to a TableCell using a custom style sheet?</strong></p>
<p>It works fine, when I use <code>setTextFill()</code> in my CellFactory directly, but I want to apply custom style using an external CSS file. I could prove that my CSS class is applied, since the font becomes bold. The CSS file's font color, however, is not applied.</p>
<pre><code>@Override
protected void updateItem(MyObject item, boolean empty) {
super.updateItem(item, empty);
if (null != item) {
// EITHER:
this.getStyleClass().add("styleImportant"); // Does NOT set color.
// OR:
this.setTextFill(Color.RED); // Does set color.
}
else {
this.getStyleClass().remove("styleImportant");
}
}
</code></pre>
<p>Style sheet:</p>
<pre><code>.styleImportant {
-fx-font-weight: bold; /** Does work. */
-fx-text-fill: red; /** Does NOT work. */
}
</code></pre>
<p>It is somehow related to specificity of CSS selectors, but I did not manage to find any valid setup.</p>
<hr>
<p><strong>Edit:</strong> I managed to apply both, a custom text color and background color, using CSS. My implementation now uses a <code>Label</code> that is wrapped in a <code>VBox</code> to make the background color fill the entire table cell. However, I still had some issues with background color not being cleared when removing the custom style.</p>
<p><strong>Is there any better solution than applying a <em>clear style</em>?</strong></p>
<pre><code>colExample.setCellFactory(new Callback<TableColumn<Example, Example>, TableCell<Example, Example>>() {
@Override
public TableCell<Example, Example> call(TableColumn<Example, Example> tableColumn) {
return new TableCell<Example, Example>() {
private VBox container;
private Label text;
// Anonymous constructor
{
this.container = new VBox();
this.text = this.createLabel();
this.container.getChildren().add(this.text);
this.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
this.setStyle("-fx-padding: -1 -1 -1 -1;"); // Remove padding from cell
this.setGraphic(this.container);
}
private final Label createLabel() {
Label label = new Label();
VBox.setVgrow(label, Priority.ALWAYS);
label.setMaxWidth(Double.MAX_VALUE);
label.setMaxHeight(Double.MAX_VALUE);
label.setAlignment(Pos.CENTER);
return label;
}
@Override
protected void updateItem(Example example, boolean empty) {
super.updateItem(example, empty);
// Reset column styles
if (null != this.text && null != this.text.getStyleClass()) {
String[] possibleStyles = new String[] { "styleImportant", "clearStyle" };
for (String style: possibleStyles) {
if (this.text.getStyleClass().contains(style)) {
// Will not reset background, even though style is removed?
this.text.getStyleClass().remove(style);
}
}
// Apply reset style to clear background color
this.text.getStyleClass().add("clearStyle");
}
if (null != example) {
this.text.setText(example.getContent());
if (example.isImportant()) {
this.text.getStyleClass().add("styleImportant");
}
}
}
};
}
});
</code></pre>
<p>My style sheet:</p>
<pre><code>/** Keep black text color, when user selects row */
.table-row-cell:focused {
-fx-dark-text-color: #000000;
-fx-mid-text-color: #000000;
-fx-light-text-color: #000000;
}
/** Style to reset background color */
.clearStyle {
-fx-background-color: transparent;
}
/** Style for important cells */
.styleImportant {
/** Red text color on any background */
-fx-dark-text-color: #FF0000;
-fx-mid-text-color: #FF0000;
-fx-light-text-color: #FF0000;
-fx-background-color: #FF9999;
}
</code></pre>
| 0 | 1,660 |
WPF datagrid pasting
|
<p>I'm having trouble pasting from a csv into the wpf datagrid - I have followed the suggestions here</p>
<p><a href="https://docs.microsoft.com/en-us/archive/blogs/vinsibal/pasting-content-to-new-rows-on-the-wpf-datagrid" rel="nofollow noreferrer">Link</a></p>
<p>and the code exectues with no problem - however, it seems that all the new rows are created but only the first row gets populated with data. The data seems to be constantly overwritten so that the last item that is in the clipboard data is populated in the first row and all other rows are blank. I know this must be an index issue or something but I cannot track it down.</p>
<p>Also when I have a look at the objects in the grid's bindable collection none of them have any data in. Is there something in the OnPastingCellClipboardContent of the column that is going wrong (data conversion perhaps)?</p>
<p>Any ideas (see the code below)</p>
<pre><code>protected virtual void OnExecutedPaste(object sender, ExecutedRoutedEventArgs args)
{
// parse the clipboard data
List<string[]> rowData = ClipboardHelper.ParseClipboardData();
bool hasAddedNewRow = false;
// call OnPastingCellClipboardContent for each cell
int minRowIndex = Math.Max(Items.IndexOf(CurrentItem), 0);
int maxRowIndex = Items.Count - 1;
int minColumnDisplayIndex = (SelectionUnit != DataGridSelectionUnit.FullRow) ? Columns.IndexOf(CurrentColumn) : 0;
int maxColumnDisplayIndex = Columns.Count - 1;
int rowDataIndex = 0;
for (int i = minRowIndex; i <= maxRowIndex && rowDataIndex < rowData.Count; i++, rowDataIndex++)
{
if (CanUserAddRows && i == maxRowIndex)
{
// add a new row to be pasted to
ICollectionView cv = CollectionViewSource.GetDefaultView(Items);
IEditableCollectionView iecv = cv as IEditableCollectionView;
if (iecv != null)
{
hasAddedNewRow = true;
iecv.AddNew();
if (rowDataIndex + 1 < rowData.Count)
{
// still has more items to paste, update the maxRowIndex
maxRowIndex = Items.Count - 1;
}
}
}
else if (i == maxRowIndex)
{
continue;
}
int columnDataIndex = 0;
for (int j = minColumnDisplayIndex; j < maxColumnDisplayIndex && columnDataIndex < rowData[rowDataIndex].Length; j++, columnDataIndex++)
{
DataGridColumn column = ColumnFromDisplayIndex(j);
column.OnPastingCellClipboardContent(Items[i], rowData[rowDataIndex][columnDataIndex]);
}
}
</code></pre>
<p>}</p>
| 0 | 1,221 |
Spring Boot app deployed to Glassfish is giving strange results
|
<p>As mentioned <a href="https://spring.io/blog/2014/03/07/deploying-spring-boot-applications#comment-1317477696" rel="noreferrer">here</a>, I am having a heck of a time getting my small Spring-Boot project to deploy "correctly" to Glassfish. It runs fine using the embedded Tomcat, but once I try and move it into my organization's environment (Glassfish 3.1.2) I get some strange behavior.</p>
<p>Thinking it was my code, I reverted to the time-tested "Hello World"-approach and built a super-basic app following <a href="https://spring.io/blog/2014/03/07/deploying-spring-boot-applications" rel="noreferrer">this tutorial on Spring's blog</a>.</p>
<p>I did make a few very minor deviations as I went along but nothing that should have affected the app like this at all. </p>
<p>The only major deviation I made was that I found I could not exclude "spring-boot-starter-tomcat" from "spring-boot-starter-web" -- when I tried to that, I got 2 errors in the STS "Markers"-tab:</p>
<pre><code>The project was not built since its build path is incomplete. Cannot find the class file for javax.servlet.ServletContext. Fix the build path then try building this project
The type javax.servlet.ServletContext cannot be resolved. It is indirectly referenced from required .class files Application.java
</code></pre>
<p>If I cleaned the STS project, then ran Maven Clean, Update, Install the Install goal gave the following error:</p>
<pre><code>Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project test: Compilation failure [ERROR] /Users/brandon_utah/Utah Development/sts_workspaces/NidTools Rebooted/test/src/main/java/test/Application.java:[13,8] cannot access javax.servlet.ServletException [ERROR] class file for javax.servlet.ServletException not found
</code></pre>
<p>So what I did instead was include this dependency (which I found mentioned in several other SpringBoot resources):</p>
<pre><code><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
</code></pre>
<p>In this deployed fine to the embedded Tomcat and it did deploy to my Glassfish (local install) -- but with a whole bunch (about a half-dozen) errors similar to this one:</p>
<pre><code>2014-04-03T16:23:48.156-0600|SEVERE: Class [ Lorg/springframework/jdbc/datasource/embedded/EmbeddedDatabase; ] not found. Error while loading [ class org.springframework.boot.autoconfigure.jdbc.EmbeddedDataSourceConfiguration ]
</code></pre>
<p>Most of them are SEVERE, but I am also getting a few with a WARNING:</p>
<pre><code>2014-04-04T06:57:35.921-0600|WARNING: Error in annotation processing: java.lang.NoClassDefFoundError: org/springframework/batch/core/configuration/annotation/BatchConfigurer
</code></pre>
<p>Except that I'm not referencing any of these missing classes anywhere in my project (other than what might be referenced by Spring Boot itself).</p>
<p>Also, the app doesn't quite work as expected. If I hit the RestController, I do get my page rendered as I expect -- but if I put any sort of System.out or Logger.log statement in the controller's method, that line of code seemingly never gets executed; by all appearances, it just gets skipped.</p>
<p>To demonstrate this problem, in my sample app's RestController I created a static counter. Then in the GET-/ method I increment that counter and System.out.println it's value. I also return the value as part of the Response.</p>
<p>And again, from a user's perspective, it seems to be working: the screen renders "Hello World" and in parentheses it shows the counter's value. I refresh the window, the counter increments. But nothing in the STS Console. And if I navigate to the Glassfish log for the app, nothing there either. Nothing. Nada. Zip. From what I can tell, something is mysteriously eating any attempt to log anything. </p>
<p>To add to the mystery, if I add a System.out to the SpringBootServletInitializer#configure(), that does make it to the Console. But if I declare a constructor in my RestController and include a System.out there, that one does not make it to the Console. For good measure, I even tried including a System.err in the constructor and a Logger.getAnonymousLogger.severe in the method; neither of those result in anything.</p>
<p>I should note that this also deploys and runs as expected using an external Tomcat.</p>
<p>I would very much appreciate any input, as it's not likely that I can convince my organization to deploy this to Tomcat nor use the embedded-Tomcat approach (due to politics and an overwhelming existing Glassfish environment).</p>
<p><a href="https://github.com/bane73/Deploying-SpringBoot-to-Glassfish" rel="noreferrer">My test project on Github is here</a>.</p>
| 0 | 1,440 |
error C2220: warning treated as error - no 'object' file generated
|
<p>I have below class</p>
<pre><code>class Cdata12Mnt
{
public:
char IOBname[ID1_IOB_PIOTSUP-ID1_IOB_TOP][BOADNAM_MAX + 4];
char ExIOBname[ID1_MAX_INF-ID1_EXIOB_U1TOP][BOADNAM_MAX + 4];
char cflpath[256];
char basetext[256];
UINT database[ID1_MAX_INF];
int State;
public:
char SelectPath[256];
public:
int GetIOBName(int slt,char *Name);
Cdata12Mnt(char *SelectPath);
virtual ~Cdata12Mnt();
int GetValue(int id);
int GetState() { return State; }
};
</code></pre>
<p>And I have function as below</p>
<pre><code>Cdata12Mnt::Cdata12Mnt(char *SelectPath)
{
SCTReg reg;
char buf[256], *cpnt, *npnt, *bpnt1, *bpnt2;
char *startcode[] = {"CNTL_CODE ","SEGMENT "};
char *stopcode = {"END_CNTL_CODE "};
FILE *fp;
int ii, infl;
State = 0;
for (ii = 0; ii < (ID1_IOB_PIOTSUP - ID1_IOB_TOP); ii++) {
strcpy(IOBname[ii], "");
}
for (ii = 0; ii < (ID1_MAX_INF-ID1_EXIOB_U1TOP); ii++) {
**strcpy(ExIOBname[ii], "");**
}
sprintf(cflpath, "%s\\%s", SelectPath, CDATAFL);
if ((fp = fopen(cflpath,"r"))!=NULL) {
for (ii = 0, infl = 0; fgets(buf, 256, fp) != NULL;) {
if (infl == 0 && strncmp(buf, startcode[0], strlen(startcode[0])) == 0) {
if ((cpnt = strchr(&buf[strlen(startcode[0])],*startcode[1])) != NULL) {
if (strncmp(cpnt,startcode[1], strlen(startcode[1])) == 0) {
infl = 1;
continue;
}
}
}
if (infl == 0) {
continue;
}
if (strncmp(buf,stopcode,strlen(stopcode))==0) {
if (ii == ID1_EXIOB_U1TOP) {
for (int nDataNumber = ii; nDataNumber < ID1_MAX_INF; nDataNumber++) {
database[nDataNumber] = 0;
}
}
infl = 0;
continue;
}
if (strncmp(&buf[14], " DD ", 4) == 0) {
if ((cpnt=strchr(buf, ';')) != NULL) {
*cpnt = '\0';
}
if (ii >= ID1_IOB_TOP && ii < ID1_IOB_PIOTSUP) {
if ((bpnt1 = strchr(cpnt + 1,'(')) != NULL && (bpnt2=strchr(cpnt + 1,')'))!=NULL && bpnt1 < bpnt2) {
*bpnt2 = '\0';
*(bpnt1 + BOADNAM_MAX + 1) = '\0';
strcpy(IOBname[ii-ID1_IOB_TOP], bpnt1 + 1);
}
}
if (ii >= ID1_EXIOB_U1TOP && ii < ID1_MAX_INF) {
if ((bpnt1 = strchr(cpnt + 1, '(')) != NULL && (bpnt2=strchr(cpnt+1,')'))!=NULL && bpnt1 < bpnt2) {
*bpnt2='\0';
*(bpnt1+BOADNAM_MAX+1)='\0';
strcpy(ExIOBname[ii-ID1_EXIOB_U1TOP], bpnt1 + 1);
}
}
for (cpnt = &buf[18]; cpnt != NULL;) {
if ((npnt=strchr(cpnt, ',')) != NULL)
*npnt='\0';
}
if (strchr(cpnt,'H')!=NULL) {
sscanf(cpnt,"%XH",&database[ii]);
} else {
database[ii]=atoi(cpnt);
}
ii++;
cpnt = npnt;
if (cpnt != NULL) {
cpnt++;
}
}
}
}
fclose(fp);
} else {
State=-1;
}
</code></pre>
<p>When I compile this function in Visual studio 2008, it gives me error at <code>strcpy(IOBname[ii],"");</code> as below</p>
<blockquote>
<p>error C2220: warning treated as error - no 'object' file generated</p>
</blockquote>
<p>How to fix this error?</p>
| 0 | 2,404 |
Error While deploying in Oracle weblogic 11g
|
<p>During deployment of my application in Oracle weblogic 11g
Messages</p>
<pre><code>Unable to access the selected application.
Exception in AppMerge flows' progression
Exception in AppMerge flows' progression
All tags must be contained within a single element
All tags must be contained within a single element
</code></pre>
<p>Complete stack trace</p>
<pre><code>Error at Line:3, token:[OPENTAGBEGIN]All tags must be contained within a single element
at weblogic.xml.babel.baseparser.BaseParser.parseProlog(BaseParser.java:417)
at weblogic.xml.babel.baseparser.BaseParser.parseSome(BaseParser.java:328)
at weblogic.xml.stax.XMLStreamReaderBase.advance(XMLStreamReaderBase.java:195)
at weblogic.xml.stax.XMLStreamReaderBase.next(XMLStreamReaderBase.java:237)
at javax.xml.stream.util.StreamReaderDelegate.next(Unknown Source)
at weblogic.application.descriptor.DebugStreamReaderDelegate.next(DebugStreamReaderDelegate.java:89)
at weblogic.application.descriptor.BasicMunger2.next(BasicMunger2.java:442)
at weblogic.application.descriptor.VersionMunger._next(VersionMunger.java:333)
at weblogic.application.descriptor.VersionMunger.next(VersionMunger.java:221)
at weblogic.application.descriptor.VersionMunger.consumeInputStream(VersionMunger.java:499)
at weblogic.application.descriptor.VersionMunger.init(VersionMunger.java:425)
at weblogic.application.descriptor.VersionMunger.<init>(VersionMunger.java:85)
at weblogic.application.descriptor.VersionMunger.<init>(VersionMunger.java:71)
at weblogic.ejb.spi.WeblogicEjbJarReader.<init>(WeblogicEjbJarReader.java:34)
at weblogic.ejb.spi.EjbJarDescriptor$MyWlsEjbJarDescriptor.createXMLStreamReader(EjbJarDescriptor.java:306)
at weblogic.application.descriptor.AbstractDescriptorLoader2.createDescriptorBean(AbstractDescriptorLoader2.java:402)
at weblogic.application.descriptor.AbstractDescriptorLoader2.loadDescriptorBeanWithoutPlan(AbstractDescriptorLoader2.java:759)
at weblogic.application.descriptor.AbstractDescriptorLoader2.loadDescriptorBean(AbstractDescriptorLoader2.java:768)
at weblogic.ejb.spi.EjbJarDescriptor.parseWeblogicEjbJarBean(EjbJarDescriptor.java:164)
at weblogic.ejb.spi.EjbJarDescriptor.parseEditableWeblogicEjbJarBean(EjbJarDescriptor.java:199)
at weblogic.ejb.container.dd.xml.EjbDescriptorReaderImpl.processWLEjbJarXMLWithSchema(EjbDescriptorReaderImpl.java:732)
at weblogic.ejb.container.dd.xml.EjbDescriptorReaderImpl.parseWLDD(EjbDescriptorReaderImpl.java:563)
at weblogic.ejb.container.dd.xml.EjbDescriptorReaderImpl.processWeblogicEjbJarXML(EjbDescriptorReaderImpl.java:402)
at weblogic.ejb.container.dd.xml.EjbDescriptorReaderImpl.createDescriptorFromJarFile(EjbDescriptorReaderImpl.java:184)
at weblogic.ejb.spi.EjbDescriptorFactory.createDescriptorFromJarFile(EjbDescriptorFactory.java:73)
at weblogic.application.compiler.EJBModule.merge(EJBModule.java:174)
at weblogic.application.compiler.flow.MergeModuleFlow.compile(MergeModuleFlow.java:23)
at weblogic.application.compiler.FlowDriver$FlowStateChange.next(FlowDriver.java:69)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:41)
at weblogic.application.compiler.FlowDriver.nextState(FlowDriver.java:36)
at weblogic.application.compiler.FlowDriver$CompilerFlowDriver.compile(FlowDriver.java:96)
at weblogic.application.compiler.ReadOnlyEarMerger.merge(ReadOnlyEarMerger.java:49)
at weblogic.application.compiler.flow.AppMergerFlow.mergeInput(AppMergerFlow.java:88)
at weblogic.application.compiler.flow.AppMergerFlow.compile(AppMergerFlow.java:41)
at weblogic.application.compiler.FlowDriver$FlowStateChange.next(FlowDriver.java:69)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:41)
at weblogic.application.compiler.FlowDriver.nextState(FlowDriver.java:36)
at weblogic.application.compiler.FlowDriver$CompilerFlowDriver.compile(FlowDriver.java:96)
at weblogic.application.compiler.AppMerge.runBody(AppMerge.java:157)
at weblogic.utils.compiler.Tool.run(Tool.java:158)
at weblogic.utils.compiler.Tool.run(Tool.java:115)
at weblogic.application.compiler.AppMerge.merge(AppMerge.java:169)
at weblogic.deploy.api.internal.utils.AppMerger.merge(AppMerger.java:88)
at weblogic.deploy.api.internal.utils.AppMerger.getMergedApp(AppMerger.java:63)
at weblogic.deploy.api.model.internal.WebLogicDeployableObjectFactoryImpl.createDeployableObject(WebLogicDeployableObjectFactoryImpl.java:181)
at weblogic.deploy.api.model.internal.WebLogicDeployableObjectFactoryImpl.createLazyDeployableObject(WebLogicDeployableObjectFactoryImpl.java:156)
at weblogic.deploy.api.tools.SessionHelper.inspect(SessionHelper.java:661)
at com.bea.console.actions.app.install.Flow$2.execute(Flow.java:469)
at com.bea.console.utils.DeploymentUtils.runDeploymentAction(DeploymentUtils.java:5000)
at com.bea.console.actions.app.install.Flow.appSelected(Flow.java:467)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:48)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:600)
at org.apache.beehive.netui.pageflow.FlowController.invokeActionMethod(FlowController.java:870)
at org.apache.beehive.netui.pageflow.FlowController.getActionMethodForward(FlowController.java:809)
at org.apache.beehive.netui.pageflow.FlowController.internalExecute(FlowController.java:478)
at org.apache.beehive.netui.pageflow.PageFlowController.internalExecute(PageFlowController.java:306)
at org.apache.beehive.netui.pageflow.FlowController.execute(FlowController.java:336)
at org.apache.beehive.netui.pageflow.internal.FlowControllerAction.execute(FlowControllerAction.java:52)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)
at org.apache.beehive.netui.pageflow.PageFlowRequestProcessor.access$201(PageFlowRequestProcessor.java:97)
at org.apache.beehive.netui.pageflow.PageFlowRequestProcessor$ActionRunner.execute(PageFlowRequestProcessor.java:2044)
at org.apache.beehive.netui.pageflow.interceptor.action.internal.ActionInterceptors$WrapActionInterceptorChain.continueChain(ActionInterceptors.java:64)
at org.apache.beehive.netui.pageflow.interceptor.action.ActionInterceptor.wrapAction(ActionInterceptor.java:184)
at org.apache.beehive.netui.pageflow.interceptor.action.internal.ActionInterceptors$WrapActionInterceptorChain.invoke(ActionInterceptors.java:50)
at org.apache.beehive.netui.pageflow.interceptor.action.internal.ActionInterceptors$WrapActionInterceptorChain.continueChain(ActionInterceptors.java:58)
at org.apache.beehive.netui.pageflow.interceptor.action.internal.ActionInterceptors.wrapAction(ActionInterceptors.java:87)
at org.apache.beehive.netui.pageflow.PageFlowRequestProcessor.processActionPerform(PageFlowRequestProcessor.java:2116)
at com.bea.console.internal.ConsolePageFlowRequestProcessor.processActionPerform(ConsolePageFlowRequestProcessor.java:261)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)
at org.apache.beehive.netui.pageflow.PageFlowRequestProcessor.processInternal(PageFlowRequestProcessor.java:556)
at org.apache.beehive.netui.pageflow.PageFlowRequestProcessor.process(PageFlowRequestProcessor.java:853)
at org.apache.beehive.netui.pageflow.AutoRegisterActionServlet.process(AutoRegisterActionServlet.java:631)
at org.apache.beehive.netui.pageflow.PageFlowActionServlet.process(PageFlowActionServlet.java:158)
at com.bea.console.internal.ConsoleActionServlet.process(ConsoleActionServlet.java:256)
at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:414)
at com.bea.console.internal.ConsoleActionServlet.doGet(ConsoleActionServlet.java:133)
at org.apache.beehive.netui.pageflow.PageFlowUtils.strutsLookup(PageFlowUtils.java:1199)
at com.bea.portlet.adapter.scopedcontent.ScopedContentCommonSupport.executeAction(ScopedContentCommonSupport.java:686)
at com.bea.portlet.adapter.scopedcontent.ScopedContentCommonSupport.processActionInternal(ScopedContentCommonSupport.java:142)
at com.bea.portlet.adapter.scopedcontent.PageFlowStubImpl.processAction(PageFlowStubImpl.java:106)
at com.bea.portlet.adapter.NetuiActionHandler.raiseScopedAction(NetuiActionHandler.java:111)
at com.bea.netuix.servlets.controls.content.NetuiContent.raiseScopedAction(NetuiContent.java:181)
at com.bea.netuix.servlets.controls.content.NetuiContent.raiseScopedAction(NetuiContent.java:167)
at com.bea.netuix.servlets.controls.content.NetuiContent.handlePostbackData(NetuiContent.java:225)
at com.bea.netuix.nf.ControlLifecycle$2.visit(ControlLifecycle.java:180)
at com.bea.netuix.nf.ControlTreeWalker.walkRecursive(ControlTreeWalker.java:324)
at com.bea.netuix.nf.ControlTreeWalker.walkRecursive(ControlTreeWalker.java:334)
at com.bea.netuix.nf.ControlTreeWalker.walkRecursive(ControlTreeWalker.java:334)
at com.bea.netuix.nf.ControlTreeWalker.walkRecursive(ControlTreeWalker.java:334)
at com.bea.netuix.nf.ControlTreeWalker.walkRecursive(ControlTreeWalker.java:334)
at com.bea.netuix.nf.ControlTreeWalker.walkRecursive(ControlTreeWalker.java:334)
at com.bea.netuix.nf.ControlTreeWalker.walkRecursive(ControlTreeWalker.java:334)
at com.bea.netuix.nf.ControlTreeWalker.walkRecursive(ControlTreeWalker.java:334)
at com.bea.netuix.nf.ControlTreeWalker.walkRecursive(ControlTreeWalker.java:334)
at com.bea.netuix.nf.ControlTreeWalker.walkRecursive(ControlTreeWalker.java:334)
at com.bea.netuix.nf.ControlTreeWalker.walkRecursive(ControlTreeWalker.java:334)
at com.bea.netuix.nf.ControlTreeWalker.walkRecursive(ControlTreeWalker.java:334)
at com.bea.netuix.nf.ControlTreeWalker.walkRecursive(ControlTreeWalker.java:334)
at com.bea.netuix.nf.ControlTreeWalker.walkRecursive(ControlTreeWalker.java:334)
at com.bea.netuix.nf.ControlTreeWalker.walkRecursive(ControlTreeWalker.java:334)
at com.bea.netuix.nf.ControlTreeWalker.walkRecursive(ControlTreeWalker.java:334)
at com.bea.netuix.nf.ControlTreeWalker.walkRecursive(ControlTreeWalker.java:334)
at com.bea.netuix.nf.ControlTreeWalker.walkRecursive(ControlTreeWalker.java:334)
at com.bea.netuix.nf.ControlTreeWalker.walkRecursive(ControlTreeWalker.java:334)
at com.bea.netuix.nf.ControlTreeWalker.walkRecursive(ControlTreeWalker.java:334)
at com.bea.netuix.nf.ControlTreeWalker.walkRecursive(ControlTreeWalker.java:334)
at com.bea.netuix.nf.ControlTreeWalker.walkRecursive(ControlTreeWalker.java:334)
at com.bea.netuix.nf.ControlTreeWalker.walkRecursive(ControlTreeWalker.java:334)
at com.bea.netuix.nf.ControlTreeWalker.walk(ControlTreeWalker.java:130)
at com.bea.netuix.nf.Lifecycle.processLifecycles(Lifecycle.java:395)
at com.bea.netuix.nf.Lifecycle.processLifecycles(Lifecycle.java:361)
at com.bea.netuix.nf.Lifecycle.processLifecycles(Lifecycle.java:352)
at com.bea.netuix.nf.Lifecycle.runInbound(Lifecycle.java:184)
at com.bea.netuix.nf.Lifecycle.run(Lifecycle.java:159)
at com.bea.netuix.servlets.manager.UIServlet.runLifecycle(UIServlet.java:388)
at com.bea.netuix.servlets.manager.UIServlet.doPost(UIServlet.java:258)
at com.bea.netuix.servlets.manager.UIServlet.service(UIServlet.java:199)
at com.bea.netuix.servlets.manager.SingleFileServlet.service(SingleFileServlet.java:251)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at com.bea.console.utils.MBeanUtilsInitSingleFileServlet.service(MBeanUtilsInitSingleFileServlet.java:47)
at weblogic.servlet.AsyncInitServlet.service(AsyncInitServlet.java:130)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:300)
at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at weblogic.servlet.internal.RequestEventsFilter.doFilter(RequestEventsFilter.java:27)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.doIt(WebAppServletContext.java:3684)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3650)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2268)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2174)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1446)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)
</code></pre>
<p>Sample weblogic.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<weblogic-web-app
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd http://www.bea.com/ns/weblogic/weblogic-web-app http://www.bea.com/ns/weblogic/weblogic-web-app/1.0/weblogic-web-app.xsd" xmlns:wls="http://www.bea.com/ns/weblogic/weblogic-web-app" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<session-descriptor>
<timeout-secs>2400</timeout-secs>
<encode-session-id-in-query-params>true</encode-session-id-in-query-params>
</session-descriptor>
<jsp-descriptor>
<keepgenerated>true</keepgenerated>
<page-check-seconds>0</page-check-seconds>
</jsp-descriptor>
<context-root>/</context-root>
</weblogic-web-app>
</code></pre>
<p>My application.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:application="http://java.sun.com/xml/ns/javaee/application_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd" id="Application_ID" version="5">
<display-name>Group Management System</display-name>
<module>
<web>
<web-uri>appWeb</web-uri>
<context-root>/appWeb</context-root>
</web>
</module>
<module>
</application>
</code></pre>
<p>Kindly help me. When deployed in weblogic 9.2 it work perfectly.</p>
| 0 | 5,724 |
Installing Python-2.7 on Ubuntu 10.4
|
<p>I can't seem to install zlib properly, I installed Python from source on Ubuntu10.4 </p>
<p>'######## edit #####################<br>
bobince and Luper helped.<br>
Make sure you install these packages and then recompile Python:<br>
sudo aptitude install zlib1g-dev libreadline6-dev libdb4.8-dev libncurses5-dev<br>
'#################################</p>
<p>After installation, I attempted to install setuptools.py </p>
<pre><code>$ sh setuptools-0.6c11-py2.7.egg
Traceback (most recent call last):
File "<string>", line 1, in <module>
zipimport.ZipImportError: can't decompress data; zlib not available
</code></pre>
<p>I then installed zlib: </p>
<pre><code>$ sudo aptitude install zlibc
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state information
Initializing package states... Done
The following NEW packages will be installed:
zlibc
0 packages upgraded, 1 newly installed, 0 to remove and 44 not upgraded.
Need to get 74.6kB of archives. After unpacking 299kB will be used.
Writing extended state information... Done
Get:1 http://archive.ubuntu.com/ubuntu/ lucid/universe zlibc 0.9k-4.1 [74.6kB]
Fetched 74.6kB in 0s (108kB/s)
Selecting previously deselected package zlibc.
(Reading database ... 19824 files and directories currently installed.)
Unpacking zlibc (from .../zlibc_0.9k-4.1_amd64.deb) ...
Processing triggers for man-db ...
Setting up zlibc (0.9k-4.1) ...
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state information
Initializing package states... Done
</code></pre>
<p>Before recompiling Python: </p>
<p>but setuptools still won't install: </p>
<pre><code>$ sh setuptools-0.6c11-py2.7.egg
Traceback (most recent call last):
File "<string>", line 1, in <module>
zipimport.ZipImportError: can't decompress data; zlib not available
</code></pre>
<p>I'm baffled.</p>
<p>I checked my permissions: </p>
<pre><code>lrwxrwxrwx 1 root 18 Oct 28 18:19 /usr/bin/python -> /usr/bin/python2.7
lrwxrwxrwx 1 root 24 Oct 28 18:26 /usr/bin/python2.7 -> /usr/local/bin/python2.7
lrwxrwxrwx 1 root 9 Oct 28 15:13 /usr/bin/python2 -> python2.6
-rwxr-xr-x 1 root 2613296 Apr 16 2010 /usr/bin/python2.6
</code></pre>
<p>I noticed I'd added an extra step, so I refactored it: </p>
<pre><code>llrwxrwxrwx 1 root 24 Oct 28 18:33 /usr/bin/python -> /usr/local/bin/python2.7
lrwxrwxrwx 1 root 9 Oct 28 15:13 /usr/bin/python2 -> python2.6
-rwxr-xr-x 1 root 2613296 Apr 16 2010 /usr/bin/python2.6
</code></pre>
<p>So now, Python2.7 should be the default version, but it still fails. </p>
<pre><code>$ sh setuptools-0.6c11-py2.7.egg --prefix=/usr/local/bin/python2.7
Traceback (most recent call last):
File "<string>", line 1, in <module>
zipimport.ZipImportError: can't decompress data; zlib not available
</code></pre>
<p>Where should zlib be located to work properly? </p>
<pre><code>$ find / -name zlib 2>/dev/null
/home/username/sources/Python-2.7/Modules/zlib
/home/username/sources/Python-2.7/Demo/zlib
username@servername Thu Oct 28 18:43:17 ~/sources
$ find / -name zlibc 2>/dev/null
/usr/share/lintian/overrides/zlibc
/usr/share/doc/zlibc
</code></pre>
| 0 | 1,348 |
What cause org.hibernate.PropertyAccessException: Exception occurred inside setter
|
<p>What cause this exception, I can't manage to find out.</p>
<pre><code>Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.PropertyAccessException: Exception occurred inside setter of my.Class
</code></pre>
<p>Root cause:</p>
<pre><code>javax.persistence.PersistenceException: org.hibernate.PropertyAccessException: Exception occurred inside setter of my.Class
</code></pre>
<p>Code:</p>
<pre><code>@ManyToMany(fetch = FetchType.EAGER)
public void setTags(Set<Tags> tags) {
this.tags.clear();
for (Tag tag : tags) {
addTag(tag);
}
}
public boolean addTag(final Tag tag) {
if (tags.contains(tag)) {
return false;
}
return tags.add(tag);
}
</code></pre>
<p>I initalize tags in the constructor:</p>
<pre><code>tags = new HashSet<Tag>();
</code></pre>
<p>EDIT</p>
<p>Exception from logging in setter method:</p>
<pre><code>ax.persistence.PersistenceException: org.hibernate.PropertyAccessException: Exception occurred inside setter of com.mycompany.domain.Book.Tags
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1387) ~[hibernate-entitymanager-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.ejb.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:838) ~[hibernate-entitymanager-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.ejb.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:781) ~[hibernate-entitymanager-4.2.0.Final.jar:4.2.0.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:201304051638]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:201304051638]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:201304051638]
at java.lang.reflect.Method.invoke(Method.java:601) ~[na:1.7.0]
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240) ~[spring-orm-3.1.4.RELEASE.jar:3.1.4.RELEASE]
at $Proxy215.find(Unknown Source) ~[na:na]
at com.mycompany.persistence.BookJpaRepository.get(BookJpaRepository.java:22) ~[classes/:na]
at com.mycompany.service.BookService.getBook(BookService.java:44) ~[classes/:na]
at com.mycompany.service.BookService$$FastClassByCGLIB$$d6b91ae6.invoke(<generated>) ~[BookService$$FastClassByCGLIB$$d6b91ae6.class:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:698) ~[spring-aop-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) ~[spring-aop-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) ~[spring-tx-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) ~[spring-aop-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631) ~[spring-aop-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at com.mycompany.service.BookService$$EnhancerByCGLIB$$e6a4e1a3.getBook(<generated>) ~[BookService$$EnhancerByCGLIB$$e6a4e1a3.class:na]
at com.mycompany.rest.controller.BookController.getFeedbackForBook(BookController.java:106) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:201304051638]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:201304051638]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:201304051638]
at java.lang.reflect.Method.invoke(Method.java:601) ~[na:1.7.0]
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219) ~[spring-web-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) ~[spring-web-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) ~[spring-webmvc-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745) ~[spring-webmvc-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686) ~[spring-webmvc-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) ~[spring-webmvc-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925) ~[spring-webmvc-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) ~[spring-webmvc-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:920) [spring-webmvc-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:816) [spring-webmvc-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:668) [javax.servlet-api.jar:3.0.1]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:801) [spring-webmvc-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:770) [javax.servlet-api.jar:3.0.1]
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550) [web-core.jar:3.1.2.1-SNAPSHOT]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281) [web-core.jar:3.1.2.1-SNAPSHOT]
at org.apache.catalina.core.StandardContextValve.__invoke(StandardContextValve.java:175) [web-core.jar:3.1.2.1-SNAPSHOT]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java) [web-core.jar:3.1.2.1-SNAPSHOT]
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655) [web-core.jar:3.1.2.1-SNAPSHOT]
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595) [web-core.jar:3.1.2.1-SNAPSHOT]
at org.apache.catalina.core.StandardHostValve.__invoke(StandardHostValve.java:161) [web-core.jar:3.1.2.1-SNAPSHOT]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java) [web-core.jar:3.1.2.1-SNAPSHOT]
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331) [web-core.jar:3.1.2.1-SNAPSHOT]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231) [web-core.jar:3.1.2.1-SNAPSHOT]
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317) [kernel.jar:3.1.2.1-SNAPSHOT]
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195) [kernel.jar:3.1.2.1-SNAPSHOT]
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860) [grizzly-http.jar:1.9.50]
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757) [grizzly-http.jar:1.9.50]
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056) [grizzly-http.jar:1.9.50]
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229) [grizzly-http.jar:1.9.50]
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137) [grizzly-framework.jar:1.9.50]
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104) [grizzly-framework.jar:1.9.50]
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90) [grizzly-framework.jar:1.9.50]
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79) [grizzly-http.jar:1.9.50]
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54) [grizzly-framework.jar:1.9.50]
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59) [grizzly-framework.jar:1.9.50]
at com.sun.grizzly.ContextTask.run(ContextTask.java:71) [grizzly-framework.jar:1.9.50]
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532) [grizzly-utils.jar:1.9.50]
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513) [grizzly-utils.jar:1.9.50]
at java.lang.Thread.run(Thread.java:722) [na:1.7.0]
Caused by: org.hibernate.PropertyAccessException: Exception occurred inside setter of com.mycompany.domain.Book.Tags
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:88) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.tuple.entity.AbstractEntityTuplizer.setPropertyValues(AbstractEntityTuplizer.java:710) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.tuple.entity.PojoEntityTuplizer.setPropertyValues(PojoEntityTuplizer.java:371) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.setPropertyValues(AbstractEntityPersister.java:4499) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:185) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:137) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1103) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.loader.Loader.processResultSet(Loader.java:960) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.loader.Loader.doQuery(Loader.java:910) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:341) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:311) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.loader.Loader.loadEntity(Loader.java:2111) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:82) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:72) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3917) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:460) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:429) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:206) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:262) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:150) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1091) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.internal.SessionImpl.access$2000(SessionImpl.java:174) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2473) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.internal.SessionImpl.get(SessionImpl.java:987) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.ejb.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:807) ~[hibernate-entitymanager-4.2.0.Final.jar:4.2.0.Final]
... 61 common frames omitted
Caused by: java.lang.reflect.InvocationTargetException: null
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:201304051638]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:201304051638]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:201304051638]
at java.lang.reflect.Method.invoke(Method.java:601) ~[na:1.7.0]
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:65) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
... 85 common frames omitted
Caused by: java.lang.NullPointerException: null
at org.hibernate.engine.internal.StatefulPersistenceContext.getLoadedCollectionOwnerOrNull(StatefulPersistenceContext.java:859) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.event.spi.AbstractCollectionEvent.getLoadedOwnerOrNull(AbstractCollectionEvent.java:75) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.event.spi.InitializeCollectionEvent.<init>(InitializeCollectionEvent.java:36) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:1846) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:549) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:234) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:545) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:124) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.collection.internal.PersistentSet.iterator(PersistentSet.java:180) ~[hibernate-core-4.2.0.Final.jar:4.2.0.Final]
at com.mycompany.domain.Book.setTags(Book.java:185) ~[classes/:na]
... 90 common frames omitted
</code></pre>
| 0 | 5,985 |
WPF MVVM command canexecute enable/disable button
|
<p>I want to enable RibbonButton when textbox property text isn't null. Disable RibbonButton when textbox property text is null. I want to use CanExecute method in ICommand for it. How can I do it?</p>
<p><strong>View:</strong></p>
<pre><code> <Custom:RibbonButton
LargeImageSource="..\Shared\img\save_diskete.png"
Label="Save"
Command="{Binding ButtonCommand}">
</Custom:RibbonButton>
</code></pre>
<p><strong>ViewModel</strong></p>
<pre><code>class KomentarViewModel:BaseViewModel
{
#region Data
private ICommand m_ButtonCommand;
public ICommand ButtonCommand
{
get
{
return m_ButtonCommand;
}
set
{
m_ButtonCommand = value;
}
}
private string textKomentar;
public string TextKomentar
{
get
{
return this.textKomentar;
}
set
{
// Implement with property changed handling for INotifyPropertyChanged
if (!string.Equals(this.textKomentar, value))
{
textKomentar = value;
OnPropertyChanged("TextKomentar");
}
}
}
private ObservableCollection<Komentar> allCommentsInc;
public ObservableCollection<Komentar> AllCommentsInc
{
get
{
return allCommentsInc;
}
set
{
allCommentsInc = value;
OnPropertyChanged("AllCommentsInc");
}
}
public int idIncident { get; private set; }
public Incident incident { get; private set; }
#endregion
#region Constructor
public KomentarViewModel(int id)
{
CC_RK2Entities context = new CC_RK2Entities();
this.idIncident = id;
AllCommentsInc = new ObservableCollection<Komentar>(context.Komentar.Where(a => a.Incident_id == idIncident));
incident = context.Incident.Where(a => a.id == idIncident).First();
//ButtonCommand = new RelayCommand(new Action<object>(ShowMessage));
}
#endregion
#region Methods
//ukaz napsany text
public void ShowMessage(object obj)
{
//MessageBox.Show(obj.ToString());
MessageBox.Show(this.TextKomentar);
}
}
</code></pre>
<p><strong>RelayCommand</strong></p>
<pre><code>namespace Admin.Shared.Commands
{
class RelayCommand : ICommand
{
private Action<object> _action;
public RelayCommand(Action<object> action)
{
_action = action;
}
#region ICommand Members
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_action(parameter);
}
#endregion
}
}
</code></pre>
| 0 | 1,688 |
PHP foreach loop using one entry twice
|
<p>I'm just experimenting a little with PHP and PDO working with a MySQL database and I'm a little stumped as to why after getting the results, storing them correctly in a multi-dimensional array and looping through them it outputs one of the array data twice.</p>
<p>Essentially here's the query to grab the data:</p>
<pre><code>SELECT b.Price, b.ImgURL, m.Name, f.ID, f.Family, f.URL FROM Products AS b INNER JOIN Manufacturers AS m ON m.ID = b.Manufacturer INNER JOIN FamilyLookUp AS l ON l.Product = b.ID INNER JOIN Families AS f ON f.ID = l.Family GROUP BY f.ID ORDER BY b.Price ASC
</code></pre>
<p>I was hoping with this to get 1 row returned for each Family, which it works correctly both in the PHPMyAdmin query and also when print_r() the results.</p>
<p>I then store in:</p>
<pre><code>$families[] = array('ID' => $f['ID'], 'Manufacturer' => $f['Name'], 'Family' => $f['Family'], 'URL' => $f['URL'], 'IMG' => $f['ImgURL'], 'Price' => $f['Price'], 'ScentCount' => 0);
</code></pre>
<p>Which also works correctly when doing a print_r() and when just looping through with a foreach loop echoing out the ID for each entry it returns 1234567 (all 7 Family IDs)</p>
<p>Then I run another query:</p>
<pre><code>try{
$sqlCmd = "SELECT COUNT(*) FROM FamilyLookUp WHERE Family=:fID";
$s = $pdo->prepare($sqlCmd);
foreach($families as &$fam){
$s->bindValue(':fID', $fam['ID']);
$s->execute();
$fam['ScentCount'] = $s->fetchColumn();
}
}
</code></pre>
<p>This also gets the correct counts and properly stores them in the array for the number of items within each family. So all good up to now.</p>
<p>The problem occurs when I:</p>
<pre><code>foreach($families as $fam):
?>
<div class="product-listing">
<?php echo $fam['ID']; ?>
<div class="product-listing-image">
<a href="<?php echo $fam['URL']; ?>"><img alt="" src="<?php echo $fam['IMG']; ?>"></a>
</div>
<div class="product-listing-details">
<a href="<?php echo $fam['URL']; ?>"><h3><?php echo strtoupper($fam['Manufacturer']); if($fam['Family'] != ""){ echo strtoupper(' - ' . $fam['Family']);} ?></h3></a>
<?php if($fam['ScentCount'] == 1): ?>
<span class="product-scent-count"><?php echo $fam['ScentCount']; ?> Scent</span>
<span class="product-price-value">£<?php echo $fam['Price']/100; ?></span>
<?php elseif($fam['ScentCount']>1): ?>
<span class="product-scent-count"><?php echo $fam['ScentCount']; ?> Scents</span>
<span class="product-price-value">From £<?php echo $fam['Price']/100; ?></span>
<?php endif;?>
</div>
</div>
<?php
endforeach;
?>
</code></pre>
<p>After doing this, it outputs correctly for the first 6 families of data, but for some reason it outputs a duplicate of the 6th instead of the actual 7th. When doing a print_r of all the data in the line before the start of the foreach loop, it returns all the correct data and yet within the foreach loop there becomes 1 duplicate array in the place of the 7th originally correct array.</p>
<p>Any advice would be awesome. </p>
<p>Edit for Kohloth's answer(the print_r followed directly by foreach vardump):</p>
<pre><code>Array
(
[0] => Array
(
[ID] => 1
)
[1] => Array
(
[ID] => 7
)
[2] => Array
(
[ID] => 2
)
[3] => Array
(
[ID] => 3
)
[4] => Array
(
[ID] => 4
)
[5] => Array
(
[ID] => 6
)
[6] => Array
(
[ID] => 5
)
)
array(7) {
["ID"]=>
string(1) "1"
}
array(7) {
["ID"]=>
string(1) "7"
}
array(7) {
["ID"]=>
string(1) "2"
}
array(7) {
["ID"]=>
string(1) "3"
}
array(7) {
["ID"]=>
string(1) "4"
}
array(7) {
["ID"]=>
string(1) "6"
}
array(7) {
["ID"]=>
string(1) "6"
}
</code></pre>
| 0 | 2,064 |
i can't solve maven building error failure
|
<p>I get a error when I use maven to build my project.so please help!
thank you for your help</p>
<blockquote>
<p>Failed to execute goal
org.apache.maven.plugins:maven-assembly-plugin:2.2.1:assembly
(make-assembly) on project newstart-app-ithelp: Execution
make-assembly of goal
org.apache.maven.plugins:maven-assembly-plugin:2.2.1:assembly failed:
For artifact {null:null:null:jar}: The groupId cannot be empty. cause
: Execution make-assembly of goal
org.apache.maven.plugins:maven-assembly-plugin:2.2.1:assembly failed:
For artifact {null:null:null:jar}: The groupId cannot be empty. Stack
trace : org.apache.maven.lifecycle.LifecycleExecutionException:
Failed to execute goal
org.apache.maven.plugins:maven-assembly-plugin:2.2.1:assembly
(make-assembly) on project newstart-app-ithelp: Execution
make-assembly of goal
org.apache.maven.plugins:maven-assembly-plugin:2.2.1:assembly failed:
For artifact {null:null:null:jar}: The groupId cannot be empty.</p>
</blockquote>
<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/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.feinno.app</groupId>
<artifactId>root-pom</artifactId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>newstart.app</groupId>
<artifactId>newstart-app-ithelp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>newstart-app-ithelp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2.1</version>
<configuration>
<appendAssemblyId>false</appendAssemblyId>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.newstart.app.ithelp.ITHelpBean</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>assembly</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<verbose>true</verbose>
<fork>true</fork>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>com.feinno.app</groupId>
<artifactId>feinno-app-common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.24</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>0.2.9</version>
</dependency>
<dependency>
<groupId>spring-aop</groupId>
<artifactId>spring-aop</artifactId>
<version>3.2.3</version>
</dependency>
<dependency>
<groupId>spring-beans</groupId>
<artifactId>spring-beans</artifactId>
<version>3.2.3</version>
</dependency>
<dependency>
<groupId>spring-context</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.3</version>
</dependency>
<dependency>
<groupId>spring-core</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.3</version>
</dependency>
<dependency>
<groupId>spring-jdbc</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.2.3</version>
</dependency>
<dependency>
<groupId>spring-tx</groupId>
<artifactId>spring-tx</artifactId>
<version>3.2.3</version>
</dependency>
<dependency>
<groupId>spring-expression</groupId>
<artifactId>spring-expression</artifactId>
<version>3.2.3</version>
</dependency>
<dependency>
<groupId>IKAnalyzer</groupId>
<artifactId>IKAnalyzer</artifactId>
<version>6</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>linq4j</groupId>
<artifactId>linq4j</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
<distributionManagement>
<snapshotRepository>
<id>snapshots</id>
<url>http://10.10.208.92:8081/content/repositories/snapshots</url>
</snapshotRepository>
</distributionManagement>
</code></pre>
<p></p>
| 0 | 4,703 |
task.Wait throwing an exception
|
<p>Largely as a follow-up to this question <a href="https://stackoverflow.com/questions/4380732/test-driven-asynch-tasks">test driven asynch tasks</a> I have come up with some code that works if I don't have the task wait, but fails if I do.</p>
<p>Can anyone explain why?</p>
<p><strong>Exception:</strong></p>
<p>I get this error when the code hits the constructor of a utility class written by Stephen Cleary on his blog <a href="http://nitoprograms.blogspot.com/2010/06/reporting-progress-from-tasks.html" rel="nofollow noreferrer">here</a></p>
<pre><code>public ProgressReporter()
{
_scheduler = TaskScheduler.FromCurrentSynchronizationContext();
}
Test 'Smack.Core.Presentation.Tests.Threading.ProgressReporterTests.OnSuccessFullComplete_ExpectedResultIsReturned_JustWait' failed:
System.AggregateException : One or more errors occurred.
----> System.InvalidOperationException : The current SynchronizationContext may not be used as a TaskScheduler.
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
Threading\ProgressReporterTests.cs(142,0): at Smack.Core.Presentation.Tests.Threading.ProgressReporterTests.OnSuccessFullComplete_ExpectedResultIsReturned_JustWait()
--InvalidOperationException
at System.Threading.Tasks.SynchronizationContextTaskScheduler..ctor()
at System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext()
Threading\ProgressReporter.cs(24,0): at Smack.Core.Lib.Threading.ProgressReporter..ctor()
Threading\ProgressReporterTests.cs(52,0): at Smack.Core.Presentation.Tests.Threading.ProgressReporterTests._startBackgroundTask(Boolean causeError)
Threading\ProgressReporterTests.cs(141,0): at Smack.Core.Presentation.Tests.Threading.ProgressReporterTests.<OnSuccessFullComplete_ExpectedResultIsReturned_JustWait>b__a()
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
</code></pre>
<p><strong>The test (NUnit w/ TestDriven.Net runner):</strong></p>
<pre><code>private class MockSynchContext : SynchronizationContext{}
[Test]
public void OnSuccessFullComplete_ExpectedResultIsReturned_Wait()
{
var mc = new MockSynchContext();
SynchronizationContext.SetSynchronizationContext(mc);
Assert.That(SynchronizationContext.Current, Is.EqualTo(mc));
Assert.DoesNotThrow(() => TaskScheduler.FromCurrentSynchronizationContext());
var task = Task.Factory.StartNew(() => _startBackgroundTask(false));
task.Wait(2000);
_actualResult = 42;
}
</code></pre>
<p><strong>The SuT:</strong></p>
<pre><code>private void _startBackgroundTask(bool causeError)
{
_cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = _cancellationTokenSource.Token;
_progressReporter = new ProgressReporter();
var task = Task.Factory.StartNew(() =>
{
for (var i = 0; i != 100; ++i) {
// Check for cancellation
cancellationToken.ThrowIfCancellationRequested();
Thread.Sleep(30); // Do some work.
// Report progress of the work.
_progressReporter.ReportProgress(
() =>
{
// Note: code passed to "ReportProgress" can access UI elements freely.
_currentProgress = i;
});
}
// After all that work, cause the error if requested.
if (causeError) {
throw new InvalidOperationException("Oops...");
}
// The answer, at last!
return 42;
},
cancellationToken);
// ProgressReporter can be used to report successful completion,
// cancelation, or failure to the UI thread.
_progressReporter.RegisterContinuation(task, () =>
{
// Update UI to reflect completion.
_currentProgress = 100;
// Display results.
if (task.Exception != null)
_actualErrorMessage = task.Exception.ToString();
else if (task.IsCanceled)
_wasCancelled = true;
else
_actualResult = task.Result;
// Reset UI.
_whenCompleted();
});
}
</code></pre>
<p><strong>Just to be clear:</strong> If I comment out task.Wait, that test actually succeeds. Why is that?</p>
<p><strong>Extra points:</strong></p>
<p>I know this is technically another question but it seems a shame to repeat all of this, so:</p>
<p>Why did my MockSynchContext not throw an exception on TaskScheduler.FromCurrentSynchronizationContext() in my test but did in the second task? More importantly, is there a way to pass the context along so I can do the test properly?</p>
| 0 | 1,887 |
Using the same controller on different elements to refer to the same object
|
<p>I figured if I slapped <code>ng-controller="GeneralInfoCtrl"</code> on multiple elements in my DOM they would share the same <code>$scope</code> (or least two-way binding isn't working).</p>
<p>The reason I want to do this is because I have different read-only views with associated modal dialogs in very different parts of the HTML and they don't share a common ancestor (aside from <code><body></code> and <code><html></code>).</p>
<p>Is there a way to make both controllers refer to the same object/make data binding work between them?</p>
<hr>
<p>Here's some code for those who insist on seeing markup, <em>written in <strong>Jade</em></strong>:</p>
<pre><code> .client-box(ng-controller="GeneralInfoCtrl")
.box-header
.box-title
h5 General Information
.box-buttons
button.btn.btn-small(data-target='#editGeneralInfo', data-toggle='modal', data-backdrop='static') <i class="icon-pencil"></i> Edit
.box-body
table.table.table-tight.table-key-value
tr
th Name
td {{client.fullName()}}
tr
th Also Known As
td {{client.aka}}
tr
th Birth Date
td {{client.birthDate|date:'mediumDate'}}
...
#editGeneralInfo.modal.hide.fade(ng-controller="GeneralInfoCtrl")
.modal-header
button.close(type='button', data-dismiss='modal') &times;
h3 Edit General Information
.modal-body
form.form-horizontal.form-condensed
.control-group
label.control-label First Name
.controls
input(type='text', placeholder='First Name', ng-model='client.firstName')
.control-group
label.control-label Last Name
.controls
input(type='text', placeholder='Last Name', ng-model='client.lastName')
.control-group
label.control-label Also Known As
.controls
input(type='text', placeholder='AKA', ng-model='client.aka')
.control-group
label.control-label Birth Date
.controls
input(type='text', placeholder='MM/DD/YYYY', ng-model='client.birthDate')
...
</code></pre>
<p>And my controller:</p>
<pre><code>function GeneralInfoCtrl($scope) {
$scope.client = {
firstName: 'Charlie',
lastName: 'Brown',
birthDate: new Date(2009, 12, 15),
...
}
}
</code></pre>
| 0 | 1,234 |
No embedded stylesheet instruction for file: error using logback
|
<p>I have the following <code>logback.xml</code> configuration: </p>
<pre class="lang-xml prettyprint-override"><code><configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!-- encoders are assigned the type
ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
<encoder>
<pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern>
</encoder>
</appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>logFile.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- daily rollover -->
<fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- keep 30 days' worth of history -->
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%-4relative [%thread] %highlight(%-5level) %cyan(%logger{35}) - %msg%n</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
</root>
</configuration>
</code></pre>
<p>If I edit the config file in eclipse (Juno), I get the following error: </p>
<pre><code>11:02:54,114 INFO [main] Main - javax.xml.transform.TransformerFactory=null
11:02:54,115 INFO [main] Main - java.endorsed.dirs=C:\Program Files\Java\jre7\lib\endorsed
11:02:54,117 INFO [main] Main - launchFile: C:\Users\roberth\Programming_Projects\eclipse\.metadata\.plugins\org.eclipse.wst.xsl.jaxp.launching\launch\launch.xml
11:02:54,145 FATAL [main] Main - No embedded stylesheet instruction for file: file:/C:/Users/roberth/Programming_Projects/eclipse/javaport/src/logback.xml
org.eclipse.wst.xsl.jaxp.debug.invoker.TransformationException: No embedded stylesheet instruction for file: file:/C:/Users/roberth/Programming_Projects/eclipse/javaport/src/logback.xml
at org.eclipse.wst.xsl.jaxp.debug.invoker.internal.JAXPSAXProcessorInvoker.transform(JAXPSAXProcessorInvoker.java:225)
at org.eclipse.wst.xsl.jaxp.debug.invoker.internal.JAXPSAXProcessorInvoker.transform(JAXPSAXProcessorInvoker.java:186)
at org.eclipse.wst.xsl.jaxp.debug.invoker.internal.Main.main(Main.java:73)
Caused by: org.eclipse.wst.xsl.jaxp.debug.invoker.TransformationException: No embedded stylesheet instruction for file: file:/C:/Users/roberth/Programming_Projects/eclipse/javaport/src/logback.xml
at org.eclipse.wst.xsl.jaxp.debug.invoker.internal.JAXPSAXProcessorInvoker.transform(JAXPSAXProcessorInvoker.java:214)
... 2 more
</code></pre>
<p>If I delete and recreate the config, sometimes it works, sometimes not. If I edit the file in Notepad++ or another text editor, it works fine. Is this an eclipse issue or am I missing something? </p>
| 0 | 1,190 |
ngModel for textarea not working in angular 2
|
<p>I am trying to print json object in textarea using <code>ngModel</code>.</p>
<p>I have done following:</p>
<pre><code><textarea style="background-color:black;color:white;" [(ngModel)]='rapidPage' rows="30" cols="120">
</textarea>
</code></pre>
<p>I want to load the json object in textarea. The above code is loading the <code>rapidPage</code> object in textarea but its showing textarea value as <code>[object Object]</code>.</p>
<p>object:</p>
<pre><code> this.rapidPage = {
"pageRows": [
{
"sections": [
{
"sectionRows": [
{
"secRowColumns": [
]
},
{
"secRowColumns": [
{
"colName": "users"
}
]
},
{
"secRowColumns": [
{
"colName": "sample"
}
]
}
],
"width": 0
}
]
}
],
"pageName": "DefaultPage",
"pageLayout": "DEFAULT_LAYOUT",
"editMode": true
};
</code></pre>
<p>I want to load the data as string.
any inputs?</p>
| 0 | 1,191 |
Symfony ArrayCollection vs PersistentCollection
|
<p>As I understood when you query database by repository you get PersistentCollection and when your working with your entities you get ArrayCollection.</p>
<p>so consider I have one to many self referencing relation for my user entity.</p>
<p>and in my user entity I have a setChildren method which get ArrayCollection of users as argument .</p>
<pre><code><?php
namespace UserBundle\Entity;
use Abstracts\Entity\BaseModel;
use CertificateBundle\Entity\Certificate;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use EducationBundle\Entity\Education;
use LanguageBundle\Entity\Language;
use PostBundle\Entity\Post;
use ProfileBundle\Entity\Company;
use RoleBundle\Entity\Role;
use SkillBundle\Entity\Skill;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* User
*
* @ORM\Table(name="users")
* @ORM\Entity(repositoryClass="UserBundle\Repository\Entity\UserRepository")
* @UniqueEntity("email")
* @UniqueEntity("username")
*/
class User implements UserInterface
{
use BaseModel;
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="type", type="string", columnDefinition="ENUM('merchant', 'company', 'customer') ")
*/
private $type;
/**
* @ORM\Column(type="string", unique=true)
* @Assert\NotBlank()
*/
private $username;
/**
* @var string
*
* @ORM\Column(type="string", length=255)
* @Assert\NotBlank()
*/
private $email;
/**
* @var string
* @ORM\Column(type="string", nullable=true)
*/
private $avatar = null;
/**
* @var string
* @ORM\Column(type="string", nullable=true)
*/
private $cover = null;
/**
* @ORM\OneToMany(targetEntity="PostBundle\Entity\Post", mappedBy="user", orphanRemoval=true, cascade={"persist", "remove"})
*/
private $posts;
/**
* @ORM\OneToMany(targetEntity="EducationBundle\Entity\Education" , mappedBy="user" , orphanRemoval=true, cascade={"persist", "remove"})
*/
protected $educations;
/**
* @ORM\OneToMany(targetEntity="SkillBundle\Entity\SkillUser" , mappedBy="user" , orphanRemoval=true, cascade={"persist", "remove"})
*/
protected $skills;
/**
* @ORM\OneToMany(targetEntity="LanguageBundle\Entity\LanguageUser" , mappedBy="user" , orphanRemoval=true, cascade={"persist", "remove"})
*/
protected $languages;
/**
* @ORM\OneToMany(targetEntity="ResumeBundle\Entity\Resume" , mappedBy="user" , cascade={"all"})
*/
protected $resumes;
/**
* @ORM\OneToMany(targetEntity="CertificateBundle\Entity\CertificateUser" , mappedBy="user" , orphanRemoval=true, cascade={"persist", "remove"})
*/
protected $certificates;
/**
* @ORM\OneToOne(targetEntity="ProfileBundle\Entity\Company", mappedBy="user")
*/
protected $company;
/**
* @ORM\OneToOne(targetEntity="ProfileBundle\Entity\Customer", mappedBy="user")
*/
protected $customer;
/**
* @ORM\OneToOne(targetEntity="ProfileBundle\Entity\Merchant", mappedBy="user")
*/
protected $merchant;
/**
* @var string
* @Assert\NotBlank()
* @Assert\Length(min=4)
* @ORM\Column(name="password", type="string", length=255)
*
*/
private $password;
/**
* @ORM\ManyToMany(targetEntity="RoleBundle\Entity\Role", inversedBy="users", cascade={"persist"})
* @ORM\JoinTable(name="user_role", joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")}, inverseJoinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")})
*/
private $roles;
/**
* @ORM\ManyToOne(targetEntity="UserBundle\Entity\User", inversedBy="children")
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="SET NULL")
*/
protected $parent;
/**
* @ORM\OneToMany(targetEntity="UserBundle\Entity\User", mappedBy="parent", orphanRemoval=true, cascade={"persist", "remove"})
*
*/
protected $children;
/**
* @var array
*/
public static $fields = [ 'email', 'username', 'id', 'avatar', 'cover', 'type'];
/**
* User Entity constructor.
*/
public function __construct(/*EncoderFactoryInterface $encoderFactory*/)
{
//$this->encoderFactory = $encoderFactory;
$this->posts = new ArrayCollection();
$this->skills = new ArrayCollection();
$this->languages = new ArrayCollection();
$this->certificates = new ArrayCollection();
$this->educations = new ArrayCollection();
$this->children = new ArrayCollection();
dump($this->children);
die();
}
/**
* @param User $user
* @return $this
*/
public function setParent(User $user)
{
$this->parent = $user;
return $this;
}
/**
* @return $this
*/
public function removeParent()
{
$this->parent = null;
return $this;
}
/**
* @param User $user
* @return $this
*/
public function addChild(User $user)
{
if(!$this->children->contains($user)){
$this->children->add($user);
}
return $this;
}
/**
* @param User $user
* @return bool
*/
public function hasChild(User $user)
{
return $this->children->contains($user);
}
/**
* @param User $user
* @return bool
*/
public function isChildOf(User $user)
{
return $user->getChildren()->contains($this);
}
/**
* @return ArrayCollection
*/
public function getChildren()
{
return $this->children;
}
/**
* @param User $user
* @return $this
*/
public function removeChild(User $user)
{
if($this->children->contains($user)){
$this->children->removeElement($user);
}
return $this;
}
/**
* @param ArrayCollection $users
* @return $this
*/
public function setChildren(ArrayCollection $users)
{
$this->children = $users;
return $this;
}
/**
* @return $this
*/
public function removeChildren()
{
$this->children->clear();
return $this;
}
/**
* @param ArrayCollection $certificates
* @return $this
*/
public function setCertificates(ArrayCollection $certificates)
{
$this->certificates = $certificates;
return $this;
}
/**
* @param Certificate $certificate
* @return $this
*/
public function addCertificate(Certificate $certificate)
{
if(!$this->certificates->contains($certificate))
$this->certificates->add($certificate);
return $this;
}
/**
* @param Certificate $certificate
* @return $this
*/
public function removeCertificate(Certificate $certificate)
{
if($this->certificates->contains($certificate))
$this->certificates->removeElement($certificate);
return $this;
}
/**
* @return $this
*/
public function removeCertificates()
{
$this->certificates->clear();
return $this;
}
/**
* @param ArrayCollection $skills
* @return $this
*/
public function setSkills(ArrayCollection $skills)
{
$this->skills = $skills;
return $this;
}
/**
* @param Skill $skill
* @return $this
*/
public function addSkill(Skill $skill)
{
if(!$this->skills->contains($skill))
$this->skills->add($skill);
return $this;
}
/**
* @param Skill $skill
* @return $this
*/
public function removeSkill(Skill $skill)
{
if($this->skills->contains($skill))
$this->skills->removeElement($skill);
return $this;
}
/**
* @return $this
*/
public function removeSkills()
{
$this->skills->clear();
return $this;
}
/**
* @param ArrayCollection $languages
* @return $this
*/
public function setLanguages(ArrayCollection $languages)
{
$this->languages = $languages;
return $this;
}
/**
* @param Language $language
* @return $this
*/
public function addLanguage(Language $language)
{
if(!$this->languages->contains($language))
$this->languages->add($language);
return $this;
}
/**
* @param Language $language
* @return $this
*/
public function removeLanguage(Language $language)
{
if($this->languages->contains($language))
$this->languages->removeElement($language);
return $this;
}
/**
* @return $this
*/
public function removeLanguages()
{
$this->languages->clear();
return $this;
}
/**
* @param ArrayCollection $posts
* @return $this
*/
public function setPosts(ArrayCollection $posts)
{
$this->posts = $posts;
return $this;
}
/**
* @param Post $post
* @return $this
*/
public function addPost(Post $post)
{
$this->posts->add($post);
return $this;
}
/**
* @param Post $post
* @return $this
*/
public function removePost(Post $post)
{
$this->posts->removeElement($post);
return $this;
}
/**
* @return $this
*/
public function removePosts()
{
$this->posts->clear();
return $this;
}
/**
* @param ArrayCollection $educations
* @return $this
*/
public function setEducations(ArrayCollection $educations)
{
$this->educations = $educations;
return $this;
}
/**
* @param Education $education
* @return $this
*/
public function addEducation(Education $education)
{
$this->educations->add($education);
return $this;
}
/**
* @param Education $education
* @return $this
*/
public function removeEducation(Education $education)
{
$this->educations->removeElement($education);
return $this;
}
/**
* @return $this
*/
public function removeEducations()
{
$this->educations->clear();
return $this;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* @param integer $id
* @return $this
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* @return mixed
*/
public function getType()
{
return $this->type;
}
/**
* @param mixed $type
* @return $this
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Set email
*
* @param string $email
* @return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* @param $username
* @return $this
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* @return mixed
*/
public function getUsername()
{
return $this->username;
}
/**
* @return array
*/
public function getRoles()
{
return ['ROLE_USER', 'IS_AUTHENTICATED_ANONYMOUSLY'];
}
/**
* @param $password
* @return $this
*/
public function setPassword($password)
{
//$password =$this->encoderFactory->getEncoder($this)->encodePassword($password, $this->getSalt());
$this->password = $password;
return $this;
}
/**
* @return string
*/
public function getPassword()
{
return $this->password;
}
/**
*
*/
public function getSalt()
{
return md5(sha1('somesalt'));
}
/**
*
*/
public function eraseCredentials()
{
}
/**
* @param $cover
* @return $this
*/
public function setCover($cover)
{
$this->cover = $cover;
return $this;
}
/**
* @return string
*/
public function getCover()
{
return $this->cover;
}
/**
* @param $avatar
* @return $this
*/
public function setAvatar($avatar)
{
$this->avatar = $avatar;
return $this;
}
/**
* @return string
*/
public function getAvatar()
{
return $this->avatar;
}
/**
* @param Role $roles
*/
public function addRoles(Role $roles)
{
$this->roles[] = $roles;
}
/**
* @return mixed
*/
public function getRoles2()
{
return $this->roles;
}
/**
* @return array
*/
public function getRolesAsArray()
{
$rolesArray = [];
foreach ($this->getRoles2() as $role) {
$rolesArray[] = $role->getName();
}
return $rolesArray;
}
/**
* @return Company
*/
public function getCompany()
{
return $this->company;
}
/**
* @param Company $company
* @return $this
*/
public function setCompany(Company $company)
{
$this->company = $company;
return $this;
}
}
</code></pre>
<p>and this is what I want to do </p>
<pre><code>$new_owner = $this->userRepository->findOneById($user_id, false);
$children = $old_owner->getChildren();
$old_owner->removeChildren();
$new_owner->setChildren($children);
</code></pre>
<p>and I get error which says :</p>
<blockquote>
<p>Argument 1 passed to
Proxies__CG__\UserBundle\Entity\User::setChildren() must be an
instance of Doctrine\Common\Collections\ArrayCollection, instance of
Doctrine\ORM\PersistentCollection given</p>
</blockquote>
<p>should I change my type hint in setChildren method to PersistentCollection ??
or I need to totally change my approach?</p>
| 0 | 6,605 |
Android "No content provider found or permission revoke" with android 4
|
<p>I have an android application that works perfectly on android 2-2 and 2-3. But when i try to install the application on android 4-0 or 4-2-2 i twice get the following error:</p>
<p>No content provider found for permission revoke: file:///data/local/tmp/myapp.apk</p>
<p>I found out that others had a similar problem and i tried the solutions given in the following links:</p>
<p><a href="https://stackoverflow.com/questions/8639873/cannot-install-apk-on-android-device-through-eclipse/8646393#8646393">Cannot install APK on Android device through Eclipse</a>
for this one i have to say that my device is not rooted. i try to run my app on a emulator.</p>
<p><a href="https://stackoverflow.com/questions/9532653/android-4-0-3-emulator-install-fails-with-permission-revoke/9532683#9532683">Android 4.0.3 emulator: install fails with "permission revoke"</a></p>
<p><a href="https://stackoverflow.com/questions/11073358/android-error-message-on-install-no-content-provider-found">Android error message on install "no content provider found"</a>
here i tried another phone for the emulator. originally i used the galaxy nexus but i also tried with nexus 7</p>
<p><a href="https://stackoverflow.com/questions/11550798/android-no-content-provider-found-for-permission-revoke">Android "No content provider found for permission revoke"</a>
last but not least i tried to add the main action to the "androidmanifest.xml" i'm not sure if i did it the right way here is the manifest:</p>
<pre><code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.android.service"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-sdk
android:minSdkVersion="4"
android:targetSdkVersion="6"
android:maxSdkVersion="17"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" android:debuggable="true">
<activity android:name=".SMSReceiver">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.MAIN"/>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
<action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</code></pre>
<p></p>
<p>Is there still something wrong with my manifest.xml file or do you have another idea why i can run this application on android 2 but not on 4?</p>
| 0 | 1,152 |
Ansible provisioning ERROR! Using a SSH password instead of a key is not possible
|
<p>I would like to provision with my three nodes from the last one by using Ansible.</p>
<p>My host machine is Windows 10.</p>
<p>My Vagrantfile looks like:</p>
<pre class="lang-ruby prettyprint-override"><code>Vagrant.configure("2") do |config|
(1..3).each do |index|
config.vm.define "node#{index}" do |node|
node.vm.box = "ubuntu"
node.vm.box = "../boxes/ubuntu_base.box"
node.vm.network :private_network, ip: "192.168.10.#{10 + index}"
if index == 3
node.vm.provision :setup, type: :ansible_local do |ansible|
ansible.playbook = "playbook.yml"
ansible.provisioning_path = "/vagrant/ansible"
ansible.inventory_path = "/vagrant/ansible/hosts"
ansible.limit = :all
ansible.install_mode = :pip
ansible.version = "2.0"
end
end
end
end
end
</code></pre>
<p>My playbook looks like:</p>
<pre class="lang-yaml prettyprint-override"><code>---
# my little playbook
- name: My little playbook
hosts: webservers
gather_facts: false
roles:
- create_user
</code></pre>
<p>My hosts file looks like:</p>
<pre class="lang-ini prettyprint-override"><code>[webservers]
192.168.10.11
192.168.10.12
[dbservers]
192.168.10.11
192.168.10.13
[all:vars]
ansible_connection=ssh
ansible_ssh_user=vagrant
ansible_ssh_pass=vagrant
</code></pre>
<p>After executing <code>vagrant up --provision</code> I got the following error:</p>
<pre><code>Bringing machine 'node1' up with 'virtualbox' provider...
Bringing machine 'node2' up with 'virtualbox' provider...
Bringing machine 'node3' up with 'virtualbox' provider...
==> node3: Running provisioner: setup (ansible_local)...
node3: Running ansible-playbook...
PLAY [My little playbook] ******************************************************
TASK [create_user : Create group] **********************************************
fatal: [192.168.10.11]: FAILED! => {"failed": true, "msg": "ERROR! Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this. Please add this host's fingerprint to your known_hosts file to manage this host."}
fatal: [192.168.10.12]: FAILED! => {"failed": true, "msg": "ERROR! Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this. Please add this host's fingerprint to your known_hosts file to manage this host."}
PLAY RECAP *********************************************************************
192.168.10.11 : ok=0 changed=0 unreachable=0 failed=1
192.168.10.12 : ok=0 changed=0 unreachable=0 failed=1
Ansible failed to complete successfully. Any error output should be
visible above. Please fix these errors and try again.
</code></pre>
<p>I extended my Vagrantfile with <code>ansible.limit = :all</code> and added <code>[all:vars]</code> to the hostfile, but still cannot get through the error.</p>
<p>Has anyone encountered the same issue?</p>
| 0 | 1,092 |
Calculate the accuracy every epoch in PyTorch
|
<p>I am working on a Neural Network problem, to classify data as 1 or 0. I am using Binary cross entropy loss to do this. The loss is fine, however, the accuracy is very low and isn't improving. I am assuming I did a mistake in the accuracy calculation. After every epoch, I am calculating the correct predictions after thresholding the output, and dividing that number by the total number of the dataset. Is there any thing wrong I did in the accuracy calculation? And why isn't it improving, but getting more worse?
This is my code:</p>
<pre class="lang-py prettyprint-override"><code>net = Model()
criterion = torch.nn.BCELoss(size_average=True)
optimizer = torch.optim.SGD(net.parameters(), lr=0.1)
num_epochs = 100
for epoch in range(num_epochs):
for i, (inputs,labels) in enumerate (train_loader):
inputs = Variable(inputs.float())
labels = Variable(labels.float())
output = net(inputs)
optimizer.zero_grad()
loss = criterion(output, labels)
loss.backward()
optimizer.step()
#Accuracy
output = (output>0.5).float()
correct = (output == labels).float().sum()
print("Epoch {}/{}, Loss: {:.3f}, Accuracy: {:.3f}".format(epoch+1,num_epochs, loss.data[0], correct/x.shape[0]))
</code></pre>
<p>And this is the strange output I get:</p>
<pre><code>Epoch 1/100, Loss: 0.389, Accuracy: 0.035
Epoch 2/100, Loss: 0.370, Accuracy: 0.036
Epoch 3/100, Loss: 0.514, Accuracy: 0.030
Epoch 4/100, Loss: 0.539, Accuracy: 0.030
Epoch 5/100, Loss: 0.583, Accuracy: 0.029
Epoch 6/100, Loss: 0.439, Accuracy: 0.031
Epoch 7/100, Loss: 0.429, Accuracy: 0.034
Epoch 8/100, Loss: 0.408, Accuracy: 0.035
Epoch 9/100, Loss: 0.316, Accuracy: 0.035
Epoch 10/100, Loss: 0.436, Accuracy: 0.035
Epoch 11/100, Loss: 0.365, Accuracy: 0.034
Epoch 12/100, Loss: 0.485, Accuracy: 0.031
Epoch 13/100, Loss: 0.392, Accuracy: 0.033
Epoch 14/100, Loss: 0.494, Accuracy: 0.030
Epoch 15/100, Loss: 0.369, Accuracy: 0.035
Epoch 16/100, Loss: 0.495, Accuracy: 0.029
Epoch 17/100, Loss: 0.415, Accuracy: 0.034
Epoch 18/100, Loss: 0.410, Accuracy: 0.035
Epoch 19/100, Loss: 0.282, Accuracy: 0.038
Epoch 20/100, Loss: 0.499, Accuracy: 0.031
Epoch 21/100, Loss: 0.446, Accuracy: 0.030
Epoch 22/100, Loss: 0.585, Accuracy: 0.026
Epoch 23/100, Loss: 0.419, Accuracy: 0.035
Epoch 24/100, Loss: 0.492, Accuracy: 0.031
Epoch 25/100, Loss: 0.537, Accuracy: 0.031
Epoch 26/100, Loss: 0.439, Accuracy: 0.033
Epoch 27/100, Loss: 0.421, Accuracy: 0.035
Epoch 28/100, Loss: 0.532, Accuracy: 0.034
Epoch 29/100, Loss: 0.234, Accuracy: 0.038
Epoch 30/100, Loss: 0.492, Accuracy: 0.027
Epoch 31/100, Loss: 0.407, Accuracy: 0.035
Epoch 32/100, Loss: 0.305, Accuracy: 0.038
Epoch 33/100, Loss: 0.663, Accuracy: 0.025
Epoch 34/100, Loss: 0.588, Accuracy: 0.031
Epoch 35/100, Loss: 0.329, Accuracy: 0.035
Epoch 36/100, Loss: 0.474, Accuracy: 0.033
Epoch 37/100, Loss: 0.535, Accuracy: 0.031
Epoch 38/100, Loss: 0.406, Accuracy: 0.033
Epoch 39/100, Loss: 0.513, Accuracy: 0.030
Epoch 40/100, Loss: 0.593, Accuracy: 0.030
Epoch 41/100, Loss: 0.265, Accuracy: 0.036
Epoch 42/100, Loss: 0.576, Accuracy: 0.031
Epoch 43/100, Loss: 0.565, Accuracy: 0.027
Epoch 44/100, Loss: 0.576, Accuracy: 0.030
Epoch 45/100, Loss: 0.396, Accuracy: 0.035
Epoch 46/100, Loss: 0.423, Accuracy: 0.034
Epoch 47/100, Loss: 0.489, Accuracy: 0.033
Epoch 48/100, Loss: 0.591, Accuracy: 0.029
Epoch 49/100, Loss: 0.415, Accuracy: 0.034
Epoch 50/100, Loss: 0.291, Accuracy: 0.039
Epoch 51/100, Loss: 0.395, Accuracy: 0.033
Epoch 52/100, Loss: 0.540, Accuracy: 0.026
Epoch 53/100, Loss: 0.436, Accuracy: 0.033
Epoch 54/100, Loss: 0.346, Accuracy: 0.036
Epoch 55/100, Loss: 0.519, Accuracy: 0.029
Epoch 56/100, Loss: 0.456, Accuracy: 0.031
Epoch 57/100, Loss: 0.425, Accuracy: 0.035
Epoch 58/100, Loss: 0.311, Accuracy: 0.039
Epoch 59/100, Loss: 0.406, Accuracy: 0.034
Epoch 60/100, Loss: 0.360, Accuracy: 0.035
Epoch 61/100, Loss: 0.476, Accuracy: 0.030
Epoch 62/100, Loss: 0.404, Accuracy: 0.034
Epoch 63/100, Loss: 0.382, Accuracy: 0.036
Epoch 64/100, Loss: 0.538, Accuracy: 0.031
Epoch 65/100, Loss: 0.392, Accuracy: 0.034
Epoch 66/100, Loss: 0.434, Accuracy: 0.033
Epoch 67/100, Loss: 0.479, Accuracy: 0.031
Epoch 68/100, Loss: 0.494, Accuracy: 0.031
Epoch 69/100, Loss: 0.415, Accuracy: 0.034
Epoch 70/100, Loss: 0.390, Accuracy: 0.036
Epoch 71/100, Loss: 0.330, Accuracy: 0.038
Epoch 72/100, Loss: 0.449, Accuracy: 0.030
Epoch 73/100, Loss: 0.315, Accuracy: 0.039
Epoch 74/100, Loss: 0.450, Accuracy: 0.031
Epoch 75/100, Loss: 0.562, Accuracy: 0.030
Epoch 76/100, Loss: 0.447, Accuracy: 0.031
Epoch 77/100, Loss: 0.408, Accuracy: 0.038
Epoch 78/100, Loss: 0.359, Accuracy: 0.034
Epoch 79/100, Loss: 0.372, Accuracy: 0.035
Epoch 80/100, Loss: 0.452, Accuracy: 0.034
Epoch 81/100, Loss: 0.360, Accuracy: 0.035
Epoch 82/100, Loss: 0.453, Accuracy: 0.031
Epoch 83/100, Loss: 0.578, Accuracy: 0.030
Epoch 84/100, Loss: 0.537, Accuracy: 0.030
Epoch 85/100, Loss: 0.483, Accuracy: 0.035
Epoch 86/100, Loss: 0.343, Accuracy: 0.036
Epoch 87/100, Loss: 0.439, Accuracy: 0.034
Epoch 88/100, Loss: 0.686, Accuracy: 0.023
Epoch 89/100, Loss: 0.265, Accuracy: 0.039
Epoch 90/100, Loss: 0.369, Accuracy: 0.035
Epoch 91/100, Loss: 0.521, Accuracy: 0.027
Epoch 92/100, Loss: 0.662, Accuracy: 0.027
Epoch 93/100, Loss: 0.581, Accuracy: 0.029
Epoch 94/100, Loss: 0.322, Accuracy: 0.034
Epoch 95/100, Loss: 0.375, Accuracy: 0.035
Epoch 96/100, Loss: 0.575, Accuracy: 0.031
Epoch 97/100, Loss: 0.489, Accuracy: 0.030
Epoch 98/100, Loss: 0.435, Accuracy: 0.033
Epoch 99/100, Loss: 0.440, Accuracy: 0.031
Epoch 100/100, Loss: 0.444, Accuracy: 0.033
</code></pre>
| 0 | 2,287 |
How to fix "Failed to obtain JDBC Connection" datasource error in my java application
|
<p>I have a little training project running under Java Spring MVC and using MySQL on WAMP Server), it was working but i cloned it and had to reinstall database (restored from a dump) and Wamp64 also, but now my java application cannot connect and i get different errors.</p>
<p>In IntelliJ IDEA when i test the connection to the database, the connection is successfull, even in phpmyadmin, but not when i launch my application.</p>
<p><code>jdbc:mysql://localhost:3306/library?serverTimezone=UTC</code> (i had to use server timezone to fixe timezone error)</p>
<p>It's looking like my java app doesn't use the good datasource configuration, and instead use the old one but i can't figure out why.</p>
<p>My application is using SOAP protocol to connect to my webservices.</p>
<p>The main error is a javaNullPointer exception on the line where i try to get the user from database trough an input form.</p>
<p>The other error is (when i go in debug mode):</p>
<blockquote>
<p>Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Accès refusé pour l'utilisateur: 'root'@'@localhost' (mot de passe: OUI) error.</p>
</blockquote>
<p>This project was cloned from an old project. I suppose there is somewhere an old datasource used by the application.</p>
<p>It looks like my application uses old login settings for mysql (login: root, password: password). I recently changed the login information to my database, to an "admin_library" login that has all the privileges and a password. </p>
<p>I invalidated and restarted the IntelliJ cache, made an "mvn clean install", but when I run my two tomcat servers (one for the webservice, another one for the soap webserviceclient), my login screen appears but I have a null point exception (apparently due to a database connection problem.</p>
<p>Here is my configuration:</p>
<p><strong>pom.xml:</strong></p>
<pre><code><dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
</code></pre>
<p><strong>WEB-INF/SpringMVCDispatcher-servlet.xml:</strong></p>
<pre><code><!-- CONFIG JDBC DATASOURCE // -->
<bean id = "jdbcTemplate"
class = "org.springframework.jdbc.core.JdbcTemplate">
<property name = "dataSource" ref = "dataSource" />
</bean>
<bean id = "dataSource"
class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
<property name = "url" value = "jdbc:mysql://localhost:3306/library"/>
<property name = "username" value = "admin_library"/>
<property name = "password" value = "password"/>
</bean>
</code></pre>
<pre><code>Type Rapport d'exception
message Request processing failed; nested exception is com.sun.xml.ws.fault.ServerSOAPFaultException: Client received SOAP Fault from server: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Accès refusé pour l'utilisateur: 'root'@'@localhost' (mot de passe: OUI) Please see the server log to find more detail regarding exact cause of the failure.
description Le serveur a rencontré une erreur interne qui l'a empêché de satisfaire la requête.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is com.sun.xml.ws.fault.ServerSOAPFaultException: Client received SOAP Fault from server: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Accès refusé pour l'utilisateur: 'root'@'@localhost' (mot de passe: OUI) Please see the server log to find more detail regarding exact cause of the failure.
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:901)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:875)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
cause mère
com.sun.xml.ws.fault.ServerSOAPFaultException: Client received SOAP Fault from server: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Accès refusé pour l'utilisateur: 'root'@'@localhost' (mot de passe: OUI) Please see the server log to find more detail regarding exact cause of the failure.
com.sun.xml.ws.fault.SOAP11Fault.getProtocolException(SOAP11Fault.java:193)
com.sun.xml.ws.fault.SOAPFaultBuilder.createException(SOAPFaultBuilder.java:128)
com.sun.xml.ws.client.sei.StubHandler.readResponse(StubHandler.java:253)
com.sun.xml.ws.db.DatabindingImpl.deserializeResponse(DatabindingImpl.java:206)
com.sun.xml.ws.db.DatabindingImpl.deserializeResponse(DatabindingImpl.java:293)
com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:119)
com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:92)
com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:161)
com.sun.proxy.$Proxy47.findByEmail(Unknown Source)
fr.projet3.library.controller.LoginController.postLogin(LoginController.java:57)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.base/java.lang.reflect.Method.invoke(Method.java:566)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:215)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:142)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:998)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:901)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:875)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
note La trace complète de la cause mère de cette erreur est disponible dans les fichiers journaux de ce serveur.
</code></pre>
<p>A look into the controller:</p>
<pre class="lang-java prettyprint-override"><code>@PostMapping(value = {"/login","/", ""})
public String postLogin(@Valid @ModelAttribute("userLoginForm")UserLoginForm userLoginForm, BindingResult bindingResult, ModelMap modelMap, HttpSession session){
if(!bindingResult.hasErrors()){
UserWS u = libraryWS.findByEmail(userLoginForm.getEmail());
if(u == null){
return "login";
}
session.setAttribute("currentUser", u);
return "redirect:/userloan";
}
return "login";
}
</code></pre>
| 0 | 2,928 |
How to handle errors in fetch() responses with Redux Thunk?
|
<p>I'm making API requests using isomorphic fetch, and using Redux to handle my app's state.</p>
<p>I want to handle both internet connection loss errors, and API errors, by firing off Redux actions.</p>
<p>I have the following (work-in-progress / bad) code, but can't figure out the correct way to fire the Redux actions (rather than just throw an error and stop everything) :</p>
<pre><code>export function createPost(data = {}) {
return dispatch => {
dispatch(requestCreatePost(data))
return fetch(API_URL + data.type, {
credentials: 'same-origin',
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-WP-Nonce': API.nonce
},
body: JSON.stringify(Object.assign({}, data, {status: 'publish'}))
}).catch((err) => {
//HANDLE WHEN HTTP ISN'T EVEN WORKING
return dispatch => Promise.all([
dispatch({type: PRE_FETCH_RESOURCES_FAIL, errorType: 'fatal', message:'Error fetching resources', id: h.uniqueId()}),
dispatch({type: PRE_CREATE_API_ENTITY_ERROR, errorType: 'fatal', id: h.uniqueId(), message: 'Entity error before creating'})
])
}).then((req) => {
//HANDLE RESPONSES THAT CONSTITUTE AN ERROR (VIA THEIR HTTP STATUS CODE)
console.log(req);
if (!req || req.status >= 400) {
return dispatch => Promise.all([
dispatch({type: FETCH_RESOURCES_FAIL, errorType: 'warning', message:'Error after fetching resources', id: h.uniqueId()}),
dispatch({type: CREATE_API_ENTITY_ERROR, errorType: 'warning', id: h.uniqueId(), message: 'Entity error whilst creating'})
])
}
else {
return req.json()
}
}).then((json) => {
var returnData = Object.assign({},json,{
type: data.type
});
dispatch(receiveCreatePost(returnData))
})
}
}
</code></pre>
<p>If I intionally disable the internet connection, in the JS Console, when I log via console.log() (as above), it's outputting this:
<code>
POST http://example.com/post net::ERR_INTERNET_DISCONNECTED(anonymous function)
(dispatch) {
return Promise.all([dispatch({ type: PRE_FETCH_RESOURCES_FAIL, errorType: 'fatal', message: 'Error fetching resources', id: _CBUtils2.default.uniqueId() }), dispatch({ type:…
cb_app_scripts.js?ver=1.0.0:27976 Uncaught (in promise) TypeError: req.json is not a function(…)
</code></p>
<p>Forgive me if this is entirely wrong, but I don't want to do anything but fire off two Redux Actions when there is an error (a general error, and one specific to the action we were performing when the error occurred).</p>
<p>Is what I'm trying to achieve even possible?</p>
<p>It seems that (via my logging to console) the 'then' part of the script is still being executed (as the contents of it are my 'catch' dispatch functions)..</p>
| 0 | 1,299 |
Jquery: Add class to every second visible element
|
<p>I'm trying to create a dynamic portfolio gallery where you can hide show items by clicking categories. Everything works apart from adding a class to elements hidden/showing when categories are clicked.</p>
<p>I currently have:</p>
<pre><code>$(document).ready(function() {
$('ul.filter a').click(function() {
$(this).css('outline','none');
$('ul.filter .current').removeClass('current');
$(this).parent().addClass('current');
var filterVal = $(this).text().toLowerCase().replace(' ','-');
if(filterVal == 'all') {
$('div.portfolio .hidden').fadeIn('slow').removeClass('hidden');
} else {
$('div.portfolio').each(function() {
if(!$(this).hasClass(filterVal)) {
$(this).fadeOut('normal').addClass('hidden');
} else {
$(this).fadeIn('slow').removeClass('hidden').addClass("show");
$('.portfolio:visible').each(function (i) {
if (i % 2 == 0) $(this).addClass("last"); // This is the part that doesn't seem to work
});
}
});
}
return false;
});
});
</code></pre>
<p>It's this part of the code that seems to have the problem:</p>
<pre><code>$('.portfolio:visible').each(function (i) {
if (i % 2 == 0) $(this).addClass("last"); // This is the part that doesn't seem to work
});
</code></pre>
<p>Basically, I'm looking to add the class .last to every second "visible" item in my portfolio list.</p>
<p>Anyone?</p>
<hr>
<p>CSS</p>
<pre><code>/* -------------- Portfolio List ---------------- */
#portfolio-items {
font-size: 11px;
}
#portfolio-items ul, #portfolio-items li {
list-style:none;
}
#portfolio-items .portfolio {
float:left;
width:265px;
height:145px;
margin:0px 60px 50px 0px;
display:block;
}
#portfolio-items .portfolio .portfolio-client {
float:left;
font-size: 11px;
color: #666;
text-decoration: none;
}
#portfolio-items .portfolio.last {
margin-right:0px;
}
#portfolio-items .portfolio img {
border:solid 6px #fff;
-moz-box-shadow: 1px 1px 3px #999; /* Firefox */
-webkit-box-shadow: 1px 1px 3px #999; /* Safari, Chrome */
box-shadow: 1px 1px 3px #999; /* CSS3 */
margin: 0px 0px 5px;
transition: all .3s; /* in Safari, every animatable property triggers an animation in .2s */
-o-transition: all .3s; /* in Safari, every animatable property triggers an animation in .2s */
-webkit-transition: all .3s; /* in Safari, every animatable property triggers an animation in .2s */
-moz-transition: all .3s; /* in Safari, every animatable property triggers an animation in .2s */
transform-origin: centre; /* in Safari, the origin for transformation */
-o-transform-origin: centre; /* in Firefox, the origin for transformation */
-webkit-transform-origin: centre; /* in Safari, the origin for transformation */
-moz-transform-origin: centre; /* in Firefox, the origin for transformation */
}
#portfolio-items .portfolio img:hover {
-moz-box-shadow: 1px 1px 6px #999; /* Firefox */
-webkit-box-shadow: 1px 1px 6px #999; /* Safari, Chrome */
box-shadow: 1px 1px 6px #999; /* CSS3 */
transform: scale(1.05);
-o-transform: scale(1.05);
-webkit-transform: scale(1.05);
-moz-transform: scale(1.05);
box-shadow: 0px 0px 20px #ccc;
-o-box-shadow: 0px 0px 20px #ccc;
-webkit-box-shadow: 0px 0px 20px #ccc;
-moz-box-shadow: 0px 0px 20px #ccc;
}
.view-project {
background: url(/themes/cogo/default_site/images/view-project.png) no-repeat right center;
display: block;
float: right;
height: 14px;
width: 87px;
padding-right: 20px;
text-align: right;
}
</code></pre>
<hr>
<p>HTML</p>
<pre><code><div id="portfolio-items">
<div class="portfolio first cms content-management e-commerce clothing kids shops toys">
<a href="http://ee.dev/portfolio/detail/be-my-bear">
<img src="/images/sized/themes/site_themes/cogo/images/uploads/bemybear-project-254x139.jpg" width="254" height="139" title="Be My Bear" />
</a>
<a href="http://ee.dev/clients/be-my-bear" class="portfolio-client">Be My Bear</a>
<a href="http://ee.dev/portfolio/detail/be-my-bear" class="view-project"><span>View Project</span></a></div>
<div class="portfolio last cms content-management business-services">
<a href="http://ee.dev/portfolio/detail/joloda">
<img src="/images/sized/themes/site_themes/cogo/images/uploads/joloda1-254x139.jpg" width="254" height="139" title="Joloda International Ltd" />
</a>
<a href="http://ee.dev/clients/joloda-international" class="portfolio-client">Joloda International</a>
<a href="http://ee.dev/portfolio/detail/joloda" class="view-project"><span>View Project</span></a></div>
<div class="portfolio first buddypress cms content-management wordpress business-services coaching events training">
<a href="http://ee.dev/portfolio/detail/nwwn">
<img src="/images/sized/themes/site_themes/cogo/images/uploads/nwwn-project-254x139.jpg" width="254" height="139" title="NWWN" />
</a>
<a href="http://ee.dev/clients/north-wales-womens-network" class="portfolio-client">North Wales Women&#8217;s Network</a>
<a href="http://ee.dev/portfolio/detail/nwwn" class="view-project"><span>View Project</span></a></div>
<div class="portfolio last e-commerce jewellery shops">
<a href="http://ee.dev/portfolio/detail/italian-world">
<img src="/images/sized/themes/site_themes/cogo/images/uploads/italianworld-254x139.jpg" width="254" height="139" title="Italian World" />
</a>
<a href="http://ee.dev/clients/italian-world" class="portfolio-client">Italian World</a>
<a href="http://ee.dev/portfolio/detail/italian-world" class="view-project"><span>View Project</span></a></div>
<div class="portfolio first cms content-management drupal designers printers">
<a href="http://ee.dev/portfolio/detail/mms-almac">
<img src="/images/sized/themes/site_themes/cogo/images/uploads/mms-project-254x139.jpg" width="254" height="139" title="MMS Almac" />
</a>
<a href="http://ee.dev/clients/mms-almac-ltd" class="portfolio-client">MMS Almac Ltd</a>
<a href="http://ee.dev/portfolio/detail/mms-almac" class="view-project"><span>View Project</span></a></div>
<div class="portfolio last cms content-management charity community training">
<a href="http://ee.dev/portfolio/detail/europe-direct">
<img src="/images/sized/themes/site_themes/cogo/images/uploads/europedirect-project-254x139.jpg" width="254" height="139" title="Europe Direct" />
</a>
<a href="http://ee.dev/clients/ectarc" class="portfolio-client">Ectarc</a>
<a href="http://ee.dev/portfolio/detail/europe-direct" class="view-project"><span>View Project</span></a></div>
</div>?
</code></pre>
<hr>
<p>FILTER MENU</p>
<pre><code><ul class="filter">
<li class="booking-systems"><a href="http://ee.dev/portfolio/category/booking-systems">Booking Systems</a></li>
<li class="buddypress"><a href="http://ee.dev/portfolio/category/buddypress">Buddypress</a></li>
<li class="cms"><a href="http://ee.dev/portfolio/category/cms">CMS</a></li>
<li class="content-management"><a href="http://ee.dev/portfolio/category/content-management">Content Management</a></li>
<li class="drupal"><a href="http://ee.dev/portfolio/category/drupal">Drupal</a></li>
<li class="e-commerce"><a href="http://ee.dev/portfolio/category/e-commerce">E-Commerce</a></li>
<li class="silverstripe"><a href="http://ee.dev/portfolio/category/silverstripe">Silverstripe</a></li>
<li class="wordpress"><a href="http://ee.dev/portfolio/category/wordpress">Wordpress</a></li>
</ul>
</code></pre>
| 0 | 4,194 |
how to get length of json encoded array in javascript?
|
<p>I have a json encoded array like this:</p>
<pre><code>{
"ar0":"{\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}",
"ar1":"{\"start\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"end\":{\"lat\":23.0420584,\"lng\":72.67145549999998},\"waypoints\":[[23.02237,72.6500747]]}",
"ar2":"{\"start\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"end\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"waypoints\":[[23.0016629,72.58898380000005]]}"
}
</code></pre>
<p>my quetion is : </p>
<p>(1) How to find length of this array? <code>//here it is 3</code></p>
<p>(2) How to use it's value?<br>
<code>//for example:for as0 the value is {\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}</code></p>
<p><code>javascript code where i use upper things :</code></p>
<pre><code> function setroute(os)
{
var wp = [];
for(var i=0;i<os.waypoints.length;i++)
wp[i] = {'location': new google.maps.LatLng(os.waypoints[i][0], os.waypoints[i][1]),'stopover':false }
ser.route({'origin':new google.maps.LatLng(os.start.lat,os.start.lng),
'destination':new google.maps.LatLng(os.end.lat,os.end.lng),
'waypoints': wp,
'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) {
if(sts=='OK')ren.setDirections(res);
})
}
function fetchdata()
{
var jax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
jax.open('POST','process.php');
jax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
jax.send('command=fetch')
jax.onreadystatechange = function(){ if(jax.readyState==4) {
alert(JSON.parse(jax.responseText).ar0);
try {
console.log(jax.responseText);
//it is not work
for(var i=0;i<JSON.parse(jax.responseText).length;i++)
{
setroute( eval('(' + jax.responseText + ')') );
}
}
catch(e){ alert(e); }
}}
}
</code></pre>
| 0 | 1,028 |
org.apache.camel.NoSuchBeanException: No bean could be found in the registry for:
|
<p>I have the following route definition:</p>
<pre><code>@Component
public class CamelRoutes extends RouteBuilder {
@Override
public void configure() throws Exception {
from("seda:second")
.bean("helloWorld?method=smth")
.process(exchange -> {
System.out.println("Message:" + exchange.getIn().getBody());
})
.log("body:${body}");
</code></pre>
<p>and following bean:</p>
<pre><code>public static class HelloWorld {
public void execute(String str){
System.out.println("HelloWorld#execute: " + str);
}
public void smth(String str){
System.out.println("HelloWorld#smth: " + str);
}
}
</code></pre>
<p>But application doesn't start.<br>
trace:</p>
<pre><code>org.apache.camel.RuntimeCamelException: org.apache.camel.FailedToCreateRouteException: Failed to create route route4 at: >>> Bean[ref:helloWorld?method=smth] <<< in route: Route(route4)[[From[seda:second]] -> [Bean[ref:helloWorld?me... because of No bean could be found in the registry for: helloWorld?method=smth
at org.apache.camel.util.ObjectHelper.wrapRuntimeCamelException(ObjectHelper.java:1831) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.spring.SpringCamelContext.start(SpringCamelContext.java:136) ~[camel-spring-2.20.0.jar:2.20.0]
at org.apache.camel.spring.SpringCamelContext.onApplicationEvent(SpringCamelContext.java:174) ~[camel-spring-2.20.0.jar:2.20.0]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:383) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:337) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:882) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:144) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:545) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at SpringBootCamelIntegrationApplication.main(SpringBootCamelIntegrationApplication.java:9) [classes/:na]
Caused by: org.apache.camel.FailedToCreateRouteException: Failed to create route route4 at: >>> Bean[ref:helloWorld?method=smth] <<< in route: Route(route4)[[From[seda:second]] -> [Bean[ref:helloWorld?me... because of No bean could be found in the registry for: helloWorld?method=smth
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:1298) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:204) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.impl.DefaultCamelContext.startRoute(DefaultCamelContext.java:1135) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.impl.DefaultCamelContext.startRouteDefinitions(DefaultCamelContext.java:3714) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.impl.DefaultCamelContext.doStartCamel(DefaultCamelContext.java:3428) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.impl.DefaultCamelContext.access$000(DefaultCamelContext.java:208) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.impl.DefaultCamelContext$2.call(DefaultCamelContext.java:3236) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.impl.DefaultCamelContext$2.call(DefaultCamelContext.java:3232) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.impl.DefaultCamelContext.doWithDefinedClassLoader(DefaultCamelContext.java:3255) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.impl.DefaultCamelContext.doStart(DefaultCamelContext.java:3232) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:61) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:3155) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.spring.SpringCamelContext.start(SpringCamelContext.java:133) ~[camel-spring-2.20.0.jar:2.20.0]
... 15 common frames omitted
Caused by: org.apache.camel.NoSuchBeanException: No bean could be found in the registry for: helloWorld?method=smth
at org.apache.camel.component.bean.RegistryBean.getBean(RegistryBean.java:94) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.component.bean.RegistryBean.createCacheHolder(RegistryBean.java:69) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.model.BeanDefinition.createProcessor(BeanDefinition.java:251) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.model.ProcessorDefinition.makeProcessorImpl(ProcessorDefinition.java:549) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.model.ProcessorDefinition.makeProcessor(ProcessorDefinition.java:510) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.model.ProcessorDefinition.addRoutes(ProcessorDefinition.java:226) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:1295) ~[camel-core-2.20.0.jar:2.20.0]
... 27 common frames omitted
</code></pre>
<p>What wrong with my code base ?</p>
<h2>update:</h2>
<p>According <a href="https://stackoverflow.com/questions/46907227/org-apache-camel-nosuchbeanexception-no-bean-could-be-found-in-the-registry-for/46907355?noredirect=1#comment80761967_46907355">Romat Vottnet advice</a> I've wrote following:</p>
<pre><code>@Component
public class CamelRoutes extends RouteBuilder {
@Override
public void configure() throws Exception {
from("seda:second")
.bean("helloWorld?method=smth()");
}
public static class HelloWorld {
public void execute(String str) {
System.out.println("HelloWorld#execute: " + str);
}
public void smth(String str) {
System.out.println("HelloWorld#smth: " + str);
}
}
@Bean(name = "helloWorld")
public HelloWorld helloWorld() {
return new HelloWorld();
}
}
</code></pre>
<p>But I see:</p>
<pre><code>org.apache.camel.RuntimeCamelException: org.apache.camel.FailedToCreateRouteException: Failed to create route route4 at: >>> Bean[ref:helloWorld?method=smth()] <<< in route: Route(route4)[[From[seda:second]] -> [Bean[ref:helloWorld?me... because of No bean could be found in the registry for: helloWorld?method=smth()
at org.apache.camel.util.ObjectHelper.wrapRuntimeCamelException(ObjectHelper.java:1831) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.spring.SpringCamelContext.start(SpringCamelContext.java:136) ~[camel-spring-2.20.0.jar:2.20.0]
at org.apache.camel.spring.SpringCamelContext.onApplicationEvent(SpringCamelContext.java:174) ~[camel-spring-2.20.0.jar:2.20.0]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:383) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:337) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:882) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:144) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:545) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at SpringBootCamelIntegrationApplication.main(SpringBootCamelIntegrationApplication.java:9) [classes/:na]
Caused by: org.apache.camel.FailedToCreateRouteException: Failed to create route route4 at: >>> Bean[ref:helloWorld?method=smth()] <<< in route: Route(route4)[[From[seda:second]] -> [Bean[ref:helloWorld?me... because of No bean could be found in the registry for: helloWorld?method=smth()
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:1298) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:204) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.impl.DefaultCamelContext.startRoute(DefaultCamelContext.java:1135) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.impl.DefaultCamelContext.startRouteDefinitions(DefaultCamelContext.java:3714) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.impl.DefaultCamelContext.doStartCamel(DefaultCamelContext.java:3428) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.impl.DefaultCamelContext.access$000(DefaultCamelContext.java:208) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.impl.DefaultCamelContext$2.call(DefaultCamelContext.java:3236) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.impl.DefaultCamelContext$2.call(DefaultCamelContext.java:3232) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.impl.DefaultCamelContext.doWithDefinedClassLoader(DefaultCamelContext.java:3255) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.impl.DefaultCamelContext.doStart(DefaultCamelContext.java:3232) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:61) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:3155) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.spring.SpringCamelContext.start(SpringCamelContext.java:133) ~[camel-spring-2.20.0.jar:2.20.0]
... 15 common frames omitted
Caused by: org.apache.camel.NoSuchBeanException: No bean could be found in the registry for: helloWorld?method=smth()
at org.apache.camel.component.bean.RegistryBean.getBean(RegistryBean.java:94) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.component.bean.RegistryBean.createCacheHolder(RegistryBean.java:69) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.model.BeanDefinition.createProcessor(BeanDefinition.java:251) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.model.ProcessorDefinition.makeProcessorImpl(ProcessorDefinition.java:549) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.model.ProcessorDefinition.makeProcessor(ProcessorDefinition.java:510) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.model.ProcessorDefinition.addRoutes(ProcessorDefinition.java:226) ~[camel-core-2.20.0.jar:2.20.0]
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:1295) ~[camel-core-2.20.0.jar:2.20.0]
... 27 common frames omitted
</code></pre>
<p>when application starts.</p>
<p>I checked - method marked as <code>@Bean</code> is invoked.</p>
| 0 | 5,366 |
convert maven pom to gradle build
|
<p>I am converting one of my maven project into gradle. For doing this I am runngin following command where pom.xml is located </p>
<pre><code>gradle init --type pom
</code></pre>
<p>But it is giving me java.lang.NullPointerException</p>
<pre><code> FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':init'.
> Could not convert Maven POM /Users/myname/Documents/oAuth+Angular/workspace/feature-oauth_and_security_69/ui/pom.xml to a Gradle build.
> Unable to create Maven project model using POM /Users/myname/Documents/oAuth+Angular/workspace/feature-oauth_and_security_69/ui/pom.xml.
> java.lang.NullPointerException (no error message)
</code></pre>
<p>is there anything to perform with init or anything else i am missing?</p>
<p>This is my pom.xml : </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>org.test</groupId>
<artifactId>ui</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>ui</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.2.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>1.0.1.BUILD-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<wro4j.version>1.7.6</wro4j.version>
<java.version>1.7</java.version>
</properties>
<build>
<resources>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
</resource>
<resource>
<directory>${project.build.directory}/generated-resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<!-- Serves *only* to filter the wro.xml so it can get an absolute
path for the project -->
<id>copy-resources</id>
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/wro</outputDirectory>
<resources>
<resource>
<directory>src/main/wro</directory>
<filtering>true</filtering>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>ro.isdc.wro4j</groupId>
<artifactId>wro4j-maven-plugin</artifactId>
<version>${wro4j.version}</version>
<executions>
<execution>
<phase>generate-resources</phase>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
<configuration>
<wroManagerFactory>ro.isdc.wro.maven.plugin.manager.factory.ConfigurableWroManagerFactory</wroManagerFactory>
<cssDestinationFolder>${project.build.directory}/generated-resources/static/css</cssDestinationFolder>
<jsDestinationFolder>${project.build.directory}/generated-resources/static/js</jsDestinationFolder>
<wroFile>${project.build.directory}/wro/wro.xml</wroFile>
<extraConfigFile>${basedir}/src/main/wro/wro.properties</extraConfigFile>
<contextFolder>${basedir}/src/main/wro</contextFolder>
</configuration>
<dependencies>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>angularjs</artifactId>
<version>1.3.8</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.2.0</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>http://repo.spring.io/libs-snapshot-local</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>http://repo.spring.io/libs-milestone-local</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>http://repo.spring.io/libs-release-local</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</code></pre>
<p></p>
| 0 | 4,668 |
Content Security Policy directive: “frame-ancestors” missing but there?
|
<p>I am working on a nodejs electron app, in my index.html I have a "Content-Security-Policy" that looks like this </p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Security-Policy"
content="
default-src 'self' https://*.mydomain.tld;
script-src 'self' https://*.mydomain.tld;
style-src 'self' https://*.mydomain.tld;
img-src 'self' https://*.mydomain.tld;
font-src 'self' https://*.mydomain.tld;
connect-src 'self' https://*.mydomain.tld;
media-src 'self' https://*.mydomain.tld;
object-src 'self' https://*.mydomain.tld;
child-src 'self' https://*.mydomain.tld;
frame-ancestors 'self' https://*.mydomain.tld;
frame-src 'self' https://*.mydomain.tld;
worker-src 'self' https://*.mydomain.tld;
form-action 'self' https://*.mydomain.tld;
block-all-mixed-content;
">
</code></pre>
<p>When I run the app it works perfectly fine all assets are loaded just fine but in the console I get the following error</p>
<blockquote>
<p>Content Security Policies delivered via a element may not
contain the frame-ancestors directive. index.html: 4</p>
</blockquote>
<p>I been trying to get rid of the error and looking for what maybe causing it but can't find anything, all to me appears to be correct yet I still receive the error, I also thought that the error maybe caused by the server @https://*.mydomain.tld so I tried this</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Security-Policy"
content="
default-src 'self';
script-src 'self';
style-src 'self';
img-src 'self';
font-src 'self';
connect-src 'self';
media-src 'self';
object-src 'self';
child-src 'self';
frame-ancestors 'self';
frame-src 'self';
worker-src 'self';
form-action 'self';
block-all-mixed-content;
">
</code></pre>
<p>Which caused the exact same error, I could just ignore the error completely as the app does work correctly and the error does not seem to be causing any issues however if someone has any idea what maybe wrong I would really appreciate it.</p>
<p><strong>Edit:</strong> When I removed the frame-ancestors leaving the tag looking like this</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Security-Policy"
content="
default-src 'self' https://*.mydomain.tld;
script-src 'self' https://*.mydomain.tld;
style-src 'self' https://*.mydomain.tld;
img-src 'self' https://*.mydomain.tld;
font-src 'self' https://*.mydomain.tld;
connect-src 'self' https://*.mydomain.tld;
media-src 'self' https://*.mydomain.tld;
object-src 'self' https://*.mydomain.tld;
child-src 'self' https://*.mydomain.tld;
frame-src 'self' https://*.mydomain.tld;
worker-src 'self' https://*.mydomain.tld;
form-action 'self' https://*.mydomain.tld;
block-all-mixed-content;
">
</code></pre>
<p>The error went away, am I not supposed to add that?</p>
| 0 | 1,458 |
Extract Exchange 2007 Public Calendar Appointments using Exchange Web Services API
|
<p>We have a public calendar for our company set up in an Exchange 2007 Public Folder. I am able to retrieve my personal calendar appointments for the current day using the code below. I have searched high and low online and I cannot find one example of someone retrieving calendar information from a Public Folder calendar.</p>
<p>It seems like it should be doable, but I cannot for the life of me get it working. How can I modify the code below to access the calendar? I am not interested in creating any appointments through asp.net, just retrieving a simple list. I am open to any other suggestions as well. Thanks.</p>
<p><strong>ADDED BOUNTY</strong><br>
- I can't be the only person that ever needed to do this. Let's get this problem solved for future generations.</p>
<p><strong>UPDATED AGAIN DUE TO IGNORANCE</strong><br>
- I failed to mention that the project I am working on is .NET 2.0 (very important don't you think?).</p>
<p><strong>* ADDED MY CODE SOLUTION BELOW *</strong><br>
- I have replaced my original code example with the code that ended up working. Many thanks to Oleg for providing the code to find the public folder, which was the hardest part.. I have modified the code using the example from here <a href="http://msexchangeteam.com/archive/2009/04/21/451126.aspx" rel="noreferrer">http://msexchangeteam.com/archive/2009/04/21/451126.aspx</a> to use the simpler FindAppointments method.</p>
<p>This simple example returns an html string with the appointments, but you can use it as a base to customize as needed. You can see our back and forth under his answer below.</p>
<pre><code>using System;
using Microsoft.Exchange.WebServices.Data;
using System.Net;
namespace ExchangePublicFolders
{
public class Program
{
public static FolderId FindPublicFolder(ExchangeService myService, FolderId baseFolderId,
string folderName)
{
FolderView folderView = new FolderView(10, 0);
folderView.OffsetBasePoint = OffsetBasePoint.Beginning;
folderView.PropertySet = new PropertySet(FolderSchema.DisplayName, FolderSchema.Id);
FindFoldersResults folderResults;
do
{
folderResults = myService.FindFolders(baseFolderId, folderView);
foreach (Folder folder in folderResults)
if (String.Compare(folder.DisplayName, folderName, StringComparison.OrdinalIgnoreCase) == 0)
return folder.Id;
if (folderResults.NextPageOffset.HasValue)
folderView.Offset = folderResults.NextPageOffset.Value;
}
while (folderResults.MoreAvailable);
return null;
}
public static string MyTest()
{
ExchangeService myService = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
myService.Credentials = new NetworkCredential("USERNAME", "PASSWORD", "DOMAIN");
myService.Url = new Uri("https://MAILSERVER/ews/exchange.asmx");
Folder myPublicFoldersRoot = Folder.Bind(myService, WellKnownFolderName.PublicFoldersRoot);
string myPublicFolderPath = @"PUBLIC_FOLDER_CALENDAR_NAME";
string[] folderPath = myPublicFolderPath.Split('\\');
FolderId fId = myPublicFoldersRoot.Id;
foreach (string subFolderName in folderPath)
{
fId = Program.FindPublicFolder(myService, fId, subFolderName);
if (fId == null)
{
return string.Format("ERROR: Can't find public folder {0}", myPublicFolderPath);
}
}
Folder folderFound = Folder.Bind(myService, fId);
if (String.Compare(folderFound.FolderClass, "IPF.Appointment", StringComparison.Ordinal) != 0)
{
return string.Format("ERROR: Public folder {0} is not a Calendar", myPublicFolderPath);
}
CalendarFolder AK_Calendar = CalendarFolder.Bind(myService, fId, BasePropertySet.FirstClassProperties);
FindItemsResults<Appointment> AK_appointments = AK_Calendar.FindAppointments(new CalendarView(DateTime.Now,DateTime.Now.AddDays(1)));
string rString = string.Empty;
foreach (Appointment AK_appoint in AK_appointments)
{
rString += string.Format("Subject: {0}<br />Date: {1}<br /><br />", AK_appoint.Subject, AK_appoint.Start);
}
return rString;
}
}
}
</code></pre>
| 0 | 1,595 |
Golang XML attribute and value
|
<p>I can't seem to figure out why this isn't working</p>
<pre><code> type HostProperties struct {
XMLName xml.Name `xml:HostProperties"`
Info []InfoList `xml:"tag"`
}
type InfoList struct {
HostEnd string `xml:",chardata"`
PatchSummary string `xml:",chardata"`
CPE1 string `xml:",chardata"`
CPE0 string `xml:",chardata"`
SystemType string `xml:",chardata"`
OperatingSystem string `xml:",chardata"`
MacAddress string `xml:",chardata"`
Traceroute string `xml:",chardata"`
IP string `xml:",chardata"`
FQDN string `xml:",chardata"`
HostStart string `xml:",chardata"`
}
<HostProperties>
<tag name="HOST_END">Thu Feb 20 12:38:24 2014</tag>
<tag name="patch-summary-total-cves">4</tag>
<tag name="cpe-1">cpe:/a:openbsd:openssh:5.6 -&gt; OpenBSD OpenSSH 5.6</tag>
<tag name="cpe-0">cpe:/o:vmware:esx_server</tag>
<tag name="system-type">hypervisor</tag>
<tag name="operating-system">VMware ESXi</tag>
<tag name="mac-address">00:00:00:00:00:00</tag>
<tag name="traceroute-hop-0">172.28.28.29</tag>
<tag name="host-ip">172.28.28.29</tag>
<tag name="host-fqdn">foobar.com</tag>
<tag name="HOST_START">Thu Feb 20 12:30:14 2014</tag>
</HostProperties>
</code></pre>
<p><strong>Results</strong></p>
<pre><code>{HostEnd:172.28.28.29 PatchSummary: CPE1: CPE0: SystemType: OperatingSystem: MacAddress: Traceroute: IP: FQDN: HostStart:}
</code></pre>
<p>It creates a bunch of new slices with only the first element filled in and even then it's the wrong element. It's not filling out the other variables. The rest of the file seems to parse fine, just can't figure out this part.</p>
| 0 | 2,576 |
Error running pod install - Automatically assigning platform `iOS` with version `8.0` on target `Runner`
|
<p>Hello I am not able to solve this problem with Cocoapods anyone can help me is the first time I am using this import- <strong>import 'package:flutter_vlc_player/flutter_vlc_player.Dart';</strong> and not what might be wrong. </p>
<p>(I’m using android studio on mac)</p>
<p>ERROR:</p>
<p>Launching lib/main.dart on iPhone 11 in debug mode...
Running pod install... 1,3s
CocoaPods' output:
↳
Preparing</p>
<pre><code>Analyzing dependencies
Inspecting targets to integrate
Using `ARCHS` setting to build architectures of target `Pods-Runner`: (``)
Fetching external sources
-> Fetching podspec for `Flutter` from `Flutter`
-> Fetching podspec for `flutter_vlc_player` from `.symlinks/plugins/flutter_vlc_player/ios`
Resolving dependencies of `Podfile`
CDN: trunk Relative path: CocoaPods-version.yml exists! Returning local because checking is only perfomed in repo update
[!] CocoaPods could not find compatible versions for pod "flutter_vlc_player":
In Podfile:
flutter_vlc_player (from `.symlinks/plugins/flutter_vlc_player/ios`)
Specs satisfying the `flutter_vlc_player (from `.symlinks/plugins/flutter_vlc_player/ios`)` dependency were found, but they required a higher minimum deployment target.
/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:328:in `raise_error_unless_state'
/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:310:in `block in unwind_for_conflict'
/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:308:in `tap'
/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:308:in `unwind_for_conflict'
/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:684:in `attempt_to_activate'
/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:254:in `process_topmost_state'
/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:182:in `resolve'
/Library/Ruby/Gems/2.6.0/gems/molinillo-0.6.6/lib/molinillo/resolver.rb:43:in `resolve'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/resolver.rb:94:in `resolve'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/installer/analyzer.rb:1065:in `block in resolve_dependencies'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/user_interface.rb:64:in `section'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/installer/analyzer.rb:1063:in `resolve_dependencies'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/installer/analyzer.rb:124:in `analyze'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/installer.rb:410:in `analyze'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/installer.rb:235:in `block in resolve_dependencies'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/user_interface.rb:64:in `section'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/installer.rb:234:in `resolve_dependencies'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/installer.rb:156:in `install!'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/command/install.rb:52:in `run'
/Library/Ruby/Gems/2.6.0/gems/claide-1.0.3/lib/claide/command.rb:334:in `run'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/command.rb:52:in `run'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/bin/pod:55:in `<top (required)>'
/usr/local/bin/pod:23:in `load'
/usr/local/bin/pod:23:in `<main>'
</code></pre>
<p>Error output from CocoaPods:
↳</p>
<pre><code>[!] Automatically assigning platform `iOS` with version `8.0` on target `Runner` because no platform was specified. Please specify a platform for this target in your Podfile. See `https://guides.cocoapods.org/syntax/podfile.html#platform`.
</code></pre>
<p>Error running pod install
Error launching application on iPhone 11.</p>
| 0 | 1,833 |
Call a javafx fxml controller method from another class to update a tableview
|
<p>I am trying to update a javafx tableview defined in my fxml controller by calling a particular method FXMLDocumentController.onAddSystemMessage() from another application utility class method GlobalConfig.addSystemMessage(). </p>
<p>Here is my main Application class where i load the fxml:</p>
<pre><code>public class Main extends Application {
...
public static void main(String[] args) throws IOException {
Application.launch(args);
}
...
@Override
public void start(Stage primaryStage) throws IOException {
AnchorPane page = (AnchorPane) FXMLLoader.load(Main.class.getResource("FXMLDocument.fxml"));
Scene scene = new Scene(page, initWidth, initHeight);
primaryStage.setScene(scene);
currentPane(scene, page);
primaryStage.show();
}
</code></pre>
<p>So here are some parts of FXMLDocumentController:</p>
<pre><code>public class FXMLDocumentController implements Initializable {
...
@FXML
private TableView<SystemMessage> systemMessages;
@FXML
private TableColumn<SystemMessage, DateTime> dateSysReceived;
@FXML
private TableColumn<SystemMessage, String> messageText;
@FXML
private TableColumn<SystemMessage, String> messageType;
...
private ObservableList<SystemMessage> messagesData;
...
private GlobalConfig globalConfig;
...
@Override
@FXML
public void initialize(URL url, ResourceBundle rb) {
config = new GlobalConfig();
...
messagesData = FXCollections.observableArrayList();
messagesData = getAllMessages();
systemMessages.getItems().setAll(messagesData);
dateSysReceived.setCellValueFactory(new PropertyValueFactory<>("dateSysReceived"));
messageText.setCellValueFactory(new PropertyValueFactory<>("messageText"));
messageType.setCellValueFactory(new PropertyValueFactory<>("messageType"));
...
}
...
private ObservableList<SystemMessage> getAllMessages() {
ObservableList<SystemMessage> data = FXCollections.observableArrayList();
data = FXCollections.observableArrayList();
SystemMessageDAO msgDAO = new SystemMessageDAOImpl();
List<SystemMessage> allMessages = new ArrayList<>();
allMessages = msgDAO.listSystemMessage();
for(SystemMessage msg: allMessages) {
data.add(msg);
}
return data;
}
... // and here is the method that i would like to call to add new record to tableview
public void onAddSystemMessage(SystemMessage systemMessage) {
log.info("Add System Message called!");
// to DO ... add item to tableview
//this method should be called when inserting new systemMessage (DAO)
}
</code></pre>
<p>Here is also my utility class with a method for adding a system message to database. Additionally I would like to call FXMLDocumentController.onAddSystemMessage(...) method to update tableview with a new item:</p>
<pre><code>public final class GlobalConfig {
...
//constructor
public GlobalConfig () {
...
}
public void addSystemMessage(String messageText, String messageType) {
SystemMessage msg = new SystemMessage();
DateTime cur = DateTime.now();
try {
msg.setDateSysReceived(cur);
msg.setMessageText(messageText);
msg.setMessageType(messageType);
SystemMessageDAO msgDAO = new SystemMessageDAOImpl();
msgDAO.addSystemMessage(msg);
FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocumentController.fxml"));
FXMLDocumentController controller = (FXMLDocumentController)loader.getController();
//just call my Controller method and pass msg
controller.onAddSystemMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
</code></pre>
<ul>
<li>GlobalConfig is a utility class which have some methods for fetching parameters from db as also doing some jobs such as adding some new values to db tables. It is called from several parts of my application and i would like to grab current FXMLDocumentController object and call its method onAddSystemMessage() for updating UI.</li>
</ul>
<p>Above implementation is according to: <a href="https://stackoverflow.com/questions/10751271/accessing-fxml-controller-class">Accessing FXML controller class</a> however i am getting a:</p>
<pre><code>java.lang.NullPointerException
at com.npap.utils.GlobalConfig.addSystemMessage(GlobalConfig.java:85)
at com.npap.dicomrouter.FXMLDocumentController.startDcmrcvService(FXMLDocumentController.java:928)
at com.npap.dicomrouter.FXMLDocumentController.initialize(FXMLDocumentController.java:814)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
at com.npap.dicomrouter.Main.start(Main.java:141)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$163(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$176(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$174(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$175(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$149(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)
</code></pre>
<p>Hope my objective is clear and the approach above is not out of scope. </p>
| 0 | 2,246 |
Using Log4J 1.*, how can I write two packages to two separate files?
|
<p>I have the following two packages:</p>
<p>com.mycorp.project.first<br>
com.mycorp.project.second</p>
<p>I'd like to configure Log4J (SLF4J) to write the logs from one package to one file, and from the other package to a second file. I do not want them to be mixed in together. </p>
<p>To be clear, this is one project/one process running.</p>
<p>I've tried filtering and with loggers but they seem to be ignored by log4j. Both files are always identical.</p>
<p>Edit: Thank you for the answers so far, this is what I've got and it's not working. Both output files are identical.</p>
<pre><code><configuration debug="true">
<contextName>dev</contextName>
<appender name="FIRST_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>A:/dev/LogTesting/logs/first.log</file>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>INFO</level>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>A:/dev/LogTesting/logs/first.%d{yyyyMMdd}%d{_HHmmss,aux}.log.gz</fileNamePattern>
</rollingPolicy>
<encoder>
<pattern>%d{MMM dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<appender name="SECOND_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>A:/dev/LogTesting/logs/second.log</file>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>INFO</level>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>A:/dev/LogTesting/logs/second.%d{yyyyMMdd}%d{_HHmmss,aux}.log.gz</fileNamePattern>
</rollingPolicy>
<encoder>
<Pattern>%d{MMM dd HH:mm:ss.SSS} %property{HOSTNAME} [%thread] %level %logger{36} %msg%n</Pattern>
</encoder>
</appender>
<!-- =============================================================== -->
<logger name="com.test.apples" additivity="false">
<level value="DEBUG" />
<appender-ref ref="FIRST_FILE" />
</logger>
<logger name="com.test.oranges" additivity="false">
<level value="DEBUG" />
<appender-ref ref="SECOND_FILE" />
</logger>
<!-- =============================================================== -->
<category name="com.test.apples" additivity="false">
<priority value="DEBUG"/>
<appender-ref ref="FIRST_FILE"/>
</category>
<category name="com.test.oranges" additivity="false">
<priority value="DEBUG"/>
<appender-ref ref="SECOND_FILE"/>
</category>
<!-- =============================================================== -->
<!-- default -->
<root level="WARN">
<appender-ref ref="FIRST_FILE" />
<appender-ref ref="SECOND_FILE" />
</root>
</code></pre>
<p></p>
| 0 | 1,321 |
How to implement OnScrollListener to a listview??
|
<p>i am getting 500 records from server..i want to display 10 items in a listview and when listview reaches end i need to load another 10 and so on..
I have seen many examples in the net but i am unable to resolve it
Pls help me.</p>
<p>Here is my code:</p>
<pre><code>public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.form);
Seen = (ImageView) findViewById(R.id.SeenStatus);
new GetDescendingDate().execute();
userArray = new ArrayList<listmodel>();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String Id = ((TextView) view.findViewById(R.id.txtId))
.getText().toString();
// Starting single activity
Intent in = new Intent(getApplicationContext(),
details.class);
in.putExtra("TAG_Id", Id);
startActivity(in);
});
}
}
private class GetDescendingDate extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Atab.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
protected Void doInBackground(Void... arg0) {
JSONParser jParser = new JSONParser();
// Getting JSON Array node
JSONArray json;
session = new SessionManager(getApplicationContext());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
String email = user.get(SessionManager.KEY_EMAIL);
String Status = "New";
String get;
get = URL.Get;
String url_new = get + email + "/" + Status + "/" + "SODD"
+ "/" + "null" + "/" + "0" + "/" + "10";
try {
json = jParser.getJSONFromUrl(url_new);
if (json != null) {
// looping through All Orders
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String number = c.getString("No");
String By = c.getString("By");
String Type = c.getString("Type");
String Descripton = c.getString("Desc");
String Date = c.getString("DateTime");
String Id = c.getString("Id");
String ONo = c.getString("ONo");
String FirstName = c .getString("FirstName");
String Price = c.getString("Price");
listmodel list = new listmodel();
list.setId(Id);
list.setBy(By);
list.setType(Type);
list.setDescription(Descripton);
list.setDate(Date);
list.setPrice(Price);
list.setName(FirstName);
userArray.add(list);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
else {
Log.e("New", "Couldn't get any data from the url");
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
adapter = new adapter(Atab.this,userArray);
setListAdapter(adapter);
}
}
</code></pre>
| 0 | 2,056 |
Queuing Actions in Redux
|
<p>I've currently got a situation whereby I need Redux Actions to be run consecutively. I've taken a look at various middlewares, such a redux-promise, which seem to be fine <em>if you know what the successive actions are at the point of the root (for lack of a better term) action being triggered</em>.</p>
<p>Essentially, I'd like to maintain a queue of actions that can be added to at any point. Each object has an instance of this queue in its state and dependent actions can be enqueued, processed and dequeued accordingly. I have an implementation, but in doing so I'm accessing state in my action creators, which feels like an anti-pattern.</p>
<p>I'll try and give some context on use case and implementation.</p>
<h2>Use Case</h2>
<p>Suppose you want to create some lists and persist them on a server. On list creation, the server responds with an id for that list, which is used in subsequent API end points pertaining to the list:</p>
<pre><code>http://my.api.com/v1.0/lists/ // POST returns some id
http://my.api.com/v1.0/lists/<id>/items // API end points include id
</code></pre>
<p>Imagine that the client wants to perform optimistic updates on these API points, to enhance UX - nobody likes looking at spinners. So when you create a list, your new list instantly appears, with an option at add items:</p>
<pre><code>+-------------+----------+
| List Name | Actions |
+-------------+----------+
| My New List | Add Item |
+-------------+----------+
</code></pre>
<p>Suppose that someone attempts to add an item before the response from the initial create call has made it back. The items API is dependent on the id, so we know we can't call it until we have that data. However, we might want to optimistically show the new item and enqueue a call to the items API so that it triggers once the create call is done.</p>
<h2>A Potential Solution</h2>
<p>The method I'm using to get around this currently is by giving each list an action queue - that is, a list of Redux actions that will be triggered in succession.</p>
<p>The reducer functionality for a list creation might look something like this:</p>
<pre><code>case ADD_LIST:
return {
id: undefined, // To be filled on server response
name: action.payload.name,
actionQueue: []
}
</code></pre>
<p>Then, in an action creator, we'd enqueue an action instead of directly triggering it:</p>
<pre><code>export const createListItem = (name) => {
return (dispatch) => {
dispatch(addList(name)); // Optimistic action
dispatch(enqueueListAction(name, backendCreateListAction(name));
}
}
</code></pre>
<p>For brevity, assume the backendCreateListAction function calls a fetch API, which dispatches messages to dequeue from the list on success/failure.</p>
<h2>The Problem</h2>
<p>What worries me here is the implementation of the enqueueListAction method. This is where I'm accessing state to govern the advancement of the queue. It looks something like this (ignore this matching on name - this actually uses a clientId in reality, but I'm trying to keep the example simple):</p>
<pre><code>const enqueueListAction = (name, asyncAction) => {
return (dispatch, getState) => {
const state = getState();
dispatch(enqueue(name, asyncAction));{
const thisList = state.lists.find((l) => {
return l.name == name;
});
// If there's nothing in the queue then process immediately
if (thisList.actionQueue.length === 0) {
asyncAction(dispatch);
}
}
}
</code></pre>
<p>Here, assume that the enqueue method returns a plain action that inserts an async action into the lists actionQueue. </p>
<p>The whole thing feels a bit against the grain, but I'm not sure if there's another way to go with it. Additionally, since I need to dispatch in my asyncActions, I need to pass the dispatch method down to them.</p>
<p>There is similar code in the method to dequeue from the list, which triggers the next action should one exist:</p>
<pre><code>const dequeueListAction = (name) => {
return (dispatch, getState) => {
dispatch(dequeue(name));
const state = getState();
const thisList = state.lists.find((l) => {
return l.name === name;
});
// Process next action if exists.
if (thisList.actionQueue.length > 0) {
thisList.actionQueue[0].asyncAction(dispatch);
}
}
</code></pre>
<p>Generally speaking, I can live with this, but I'm concerned that it's an anti-pattern and there might be a more concise, idiomatic way of doing this in Redux.</p>
<p>Any help is appreciated.</p>
| 0 | 1,462 |
How to decrypt md5 passwords in php with substr?
|
<p>I am sharing my 2 file's code.for insert username and passwords and to retrieve data. My scenario is something different. if username :
<strong>abc</strong> and password: <strong>123456789</strong></p>
<p><strong>on login screen user have to enter only 3 digits from his password.But that will be random numbers from his password.</strong> if now system will ask me for 1st,3rd and 9th digit from password.after reload page it will change randomly. it will display 2nd,5th and 4th etc etc.</p>
<p>I am done this task earlier with my code. but now i am thinking to insert password with md5 encryption method.</p>
<p>I am stuck here if i used md5 for encryption then how to retrive password.</p>
<p>insert.php :</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="post">
<label>username</label>
<input type="text" name="username">
<label>pin</label>
<input type="password" name="pin">
<label>password</label>
<input type="password" name="password">
<button name="submit">Submit</button>
</form>
</body>
</html>
<?php
include 'conn.php';
if (isset($_POST['submit']))
{
$name = $_POST['username'];
$pass = md5($_POST['password']);
$sql = mysqli_query($conn,'INSERT INTO `emp`(`name`, `pass`) VALUES ("'.$name.'","'.$pass.'")');
if ($sql>0)
{
header('Location: index.php');
}
}
?>
</code></pre>
<p>index.php:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
include 'conn.php';
if (isset($_POST['submit'])) {
$name = $_POST['username'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
$pass3 = $_POST['pass3'];
$char1 = $_POST['char1'];
$char2 = $_POST['char2'];
$char3 = $_POST['char3'];
$sql = 'SELECT name,pass,pin from `emp` '
. 'where `name` = "'.$name.'" '
. 'AND SUBSTR(pass, '.($char1).', 1) = \''.$pass1.'\' '
. 'AND SUBSTR(pass, '.($char2).', 1) = \''.$pass2.'\' '
. 'AND SUBSTR(pass, '.($char3).', 1) = \''.$pass3.'\' ';
$sql = mysqli_query($conn,$sql);
$data = mysqli_fetch_assoc($sql);
if ($data)
{
echo 'success';
}
else
{
echo 'Fail';
}
}
// generate unique, not equal numbers
$char_pos = range(1, 9);
shuffle($char_pos);
$char_pos = array_slice($char_pos, 0, 3);
sort($char_pos);
?>
<form action="" method="post">
<input type="hidden" name="char1" value="<?php echo $char_pos[0]; ?>">
<input type="hidden" name="char2" value="<?php echo $char_pos[1]; ?>">
<input type="hidden" name="char3" value="<?php echo $char_pos[2]; ?>">
Username:
<input type="text" name="username" value="">
Password:
<input type="password" class="inputs" maxlength="1" name="pass1" placeholder='<?php echo $char_pos[0]; ?>st' value="">
<input type="password" class="inputs" maxlength="1" name="pass2" placeholder='<?php echo $char_pos[1]; ?>th' value="">
<input type="password" class="inputs" maxlength="1" name="pass3" placeholder='<?php echo $char_pos[2]; ?>th' value="">
<button name="submit">Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(".inputs").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).next('.inputs').focus();
}
});
</script>
</body>
</html>
</code></pre>
| 0 | 1,728 |
How to show text over image?
|
<p>I have to show two line text as attached image .</p>
<p><a href="https://i.stack.imgur.com/JvwnD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JvwnD.jpg" alt="enter image description here"></a></p>
<p>In this image I have to show text "Hotel Seawoods, Mahalaxmi
20% Cashback" over image .</p>
<p>Please tell me how to do this ?</p>
<p>activity_home.xml</p>
<pre><code> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/tools"
android:orientation="vertical">
<include
layout="@layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="@+id/test_image"
android:layout_width="match_parent"
android:layout_height="240dp"
android:scaleType="fitXY"
android:src="@drawable/test" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:textSize="40dp"
android:text="Neeraj" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Shah"
android:layout_gravity="bottom"
android:gravity="right"
android:textColor="#"
android:textSize="50dp" />
</FrameLayout>
<android.support.v7.widget.CardView
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
card_view:cardBackgroundColor="@color/cardview_1_background"
android:elevation="3dp"
card_view:cardCornerRadius="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:src="@drawable/ic_eye"
android:paddingLeft="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="Explore"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal"
android:weightSum="1">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:layout_width="64dp"
android:layout_height="64dp"
android:src="@drawable/location"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Location"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:layout_width="64dp"
android:layout_height="64dp"
android:src="@drawable/deals"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Deals"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:layout_width="64dp"
android:layout_height="64dp"
android:src="@drawable/cuisine"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Cusine"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:layout_width="64dp"
android:layout_height="64dp"
android:src="@drawable/drive"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Drive-in"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="@+id/card_view1"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_gravity="center"
android:layout_margin="10dp"
card_view:cardBackgroundColor="@color/cardview_1_background"
android:elevation="3dp"
card_view:cardCornerRadius="4dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:src="@drawable/recent"
android:paddingLeft="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="Recents"
android:textStyle="bold" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
</code></pre>
<p>Note : In this xml <code>"test_image"</code>(test) is image, where i have to show text.</p>
<p>i am getting now after changes while i was getting earlier cardview
<a href="https://i.stack.imgur.com/wyzcG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wyzcG.png" alt="enter image description here"></a></p>
| 0 | 4,600 |
Maven Build error "Expected root element project but found html"
|
<p>I am new to maven. I am trying to build a project given to me. But I keep getting the following error. I have deleted the .m2 directory multiple times with no luck.</p>
<p>I read through a few post suggestions the ISP was sending HTML file instead of HTTP code.</p>
<p>Here is a log from the run.</p>
<pre><code>Apache Maven 3.2.1 (ea8b2b07643dbb1b84b6d16e1f08391b666bc1e9; 2014-02-14T12:37:52-05:00)
[INFO] Scanning for projects...
[ERROR] The build could not read 1 project -> [Help 1]
org.apache.maven.project.ProjectBuildingException: Some problems were encountered while processing the POMs:
[WARNING] 'parent.relativePath' points at com.psystems:ps-framework instead of com.psystems:super-pom, please verify your project structure @ line 2, column 10
[FATAL] Non-parseable POM /root/.m2/repository/com/psystems/super-pom/1.0.0/super-pom-1.0.0.pom: Expected root element 'project' but found 'html' (position: START_TAG seen ..." "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>... @1:127) @ /root/.m2/repository/com/psystems/super-pom/1.0.0/super-pom-1.0.0.pom, line 1, column 127
at org.apache.maven.project.DefaultProjectBuilder.build(DefaultProjectBuilder.java:364)
at org.apache.maven.DefaultMaven.collectProjects(DefaultMaven.java:672)
at org.apache.maven.DefaultMaven.getProjectsForMavenReactor(DefaultMaven.java:663)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:250)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:155)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:584)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:213)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:157)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
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)
[ERROR]
[ERROR] The project com.psystems:ps-etl-framework:3.2.19-SNAPSHOT (/home/hadoop/proclitivity/etl/pom.xml) has 1 error
[ERROR] Non-parseable POM /root/.m2/repository/com/psystems/super-pom/1.0.0/super-pom-1.0.0.pom: Expected root element 'project' but found 'html' (position: START_TAG seen ..." "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>... @1:127) @ /root/.m2/repository/com/psystems/super-pom/1.0.0/super-pom-1.0.0.pom, line 1, column 127 -> [Help 2]
org.apache.maven.model.io.ModelParseException: Expected root element 'project' but found 'html' (position: START_TAG seen ..." "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>... @1:127)
at org.apache.maven.model.io.DefaultModelReader.read(DefaultModelReader.java:127)
at org.apache.maven.model.io.DefaultModelReader.read(DefaultModelReader.java:91)
at org.apache.maven.model.building.DefaultModelProcessor.read(DefaultModelProcessor.java:77)
at org.apache.maven.model.building.DefaultModelBuilder.readModel(DefaultModelBuilder.java:453)
at org.apache.maven.model.building.DefaultModelBuilder.readParentExternally(DefaultModelBuilder.java:864)
at org.apache.maven.model.building.DefaultModelBuilder.readParent(DefaultModelBuilder.java:669)
at org.apache.maven.model.building.DefaultModelBuilder.build(DefaultModelBuilder.java:307)
at org.apache.maven.project.DefaultProjectBuilder.build(DefaultProjectBuilder.java:411)
at org.apache.maven.project.DefaultProjectBuilder.build(DefaultProjectBuilder.java:380)
at org.apache.maven.project.DefaultProjectBuilder.build(DefaultProjectBuilder.java:344)
at org.apache.maven.DefaultMaven.collectProjects(DefaultMaven.java:672)
at org.apache.maven.DefaultMaven.getProjectsForMavenReactor(DefaultMaven.java:663)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:250)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:155)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:584)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:213)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:157)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
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.codehaus.plexus.util.xml.pull.XmlPullParserException: Expected root element 'project' but found 'html' (position: START_TAG seen ..." "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>... @1:127)
at org.apache.maven.model.io.xpp3.MavenXpp3ReaderEx.read(MavenXpp3ReaderEx.java:4348)
at org.apache.maven.model.io.xpp3.MavenXpp3ReaderEx.read(MavenXpp3ReaderEx.java:560)
at org.apache.maven.model.io.DefaultModelReader.read(DefaultModelReader.java:118)
... 24 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/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/ModelParseException
</code></pre>
| 0 | 2,160 |
How to remove unwanted spaces at the right of CheckBox?
|
<p>I am working on a custom list view. I want to show a <code>CheckBox</code> at the custom view. There is no text for the <code>CheckBox</code>. I found it always have some spaces at the right of the <code>CheckBox</code>.</p>
<p>Here is my layout xml file:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="horizontal" android:background="#fa9654"
android:paddingTop="65dp" android:paddingBottom="65dp">
<TextView android:id="@+id/bus_route_list_item_num"
android:layout_height="wrap_content" android:layout_width="0dip"
android:gravity="center" android:layout_gravity="center_vertical|center_horizontal"
android:layout_weight="0.15"></TextView>
<TextView android:id="@+id/bus_route_list_item_station"
android:layout_height="wrap_content" android:layout_width="0dip"
android:gravity="left" android:layout_gravity="center_vertical|center_horizontal"
android:layout_weight=".5"></TextView>
<TextView android:id="@+id/bus_route_list_item_fee"
android:layout_height="wrap_content" android:layout_width="0dip"
android:gravity="center" android:layout_gravity="center_vertical|center_horizontal"
android:layout_weight=".15"></TextView>
<CheckBox android:id="@+id/bus_route_list_item_reminder" android:layout_height="wrap_content"
android:layout_width="0dip" android:layout_weight=".20" android:gravity="center"
android:layout_gravity="center" android:paddingRight="0dp" android:paddingLeft="0dp"
android:paddingTop="0dp" android:paddingBottom="0dp" android:background="#0066ff"
android:text=""
/>
</LinearLayout>
</code></pre>
<p>The result looks like:</p>
<p><img src="https://i.stack.imgur.com/RdlPe.jpg" alt="Checkbox result" /></p>
<p>As you can see there are some space at the right of the checkbox. What I want is put the checkbox at the middle of the blue area.</p>
<p>Is it possible to remove the unwanted space? thanks</p>
| 0 | 1,041 |
How to upgrade SQLite database in Android?
|
<p>In the first time I have created one Table <code>DEPTS</code>. After that I want to create another two tables <code>FEEDS</code> and <code>ARTICLES</code>.</p>
<p>But I see that the commends for creating new tables never executed, why?</p>
<p>Here is my code:</p>
<pre><code>package com.android.database;
// ... imports ...
public class DatabaseHelper extends SQLiteOpenHelper{
static final String dbName = "appDB";
static int dbVersion = 3;
private static final String DEBPT_TABLE = "Dept";
private static final String COL_DEPT_ID = "DeptID";
private static final String COL_DEPT_NAME = "DeptName";
private static final String COL_DEPT_LAT = "DeptLat";
private static final String COL_DEPT_LNG = "DeptLng";
private static final String FEEDS_TABLE = "feeds";
private static final String COL_FEED_ID = "feed_id";
private static final String COL_FEED_TITLE = "title";
private static final String COL_FEED_URL = "url";
private static final String ARTICLES_TABLE = "articles";
private static final String COL_ARTICLE_ID = "article_id";
private static final String COL_ARTICLE_FEED_ID = "feed_id";
private static final String COL_ATRICLE_TITLE = "title";
private static final String COL_ATRICLE_URL = "url";
public DatabaseHelper(Context context) {
super(context, dbName, null, dbVersion);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
/*onCreate(SQLiteDatabase db): invoked when the database is created,
this is where we can create tables and columns to them, create views or triggers. */
db.execSQL("CREATE TABLE "+DEBPT_TABLE+
"("+COL_DEPT_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
COL_DEPT_NAME+" TEXT NOT NULL, "+
COL_DEPT_LAT+" REAL NOT NULL, "+
COL_DEPT_LNG+" REAL NOT NULL);");
db.execSQL("CREATE TABLE "+ FEEDS_TABLE+
" ("+COL_FEED_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
COL_FEED_TITLE +" TEXT NOT NULL,"+
COL_FEED_URL+" TEXT_NOT_NULL);");
db.execSQL("CREATE TABLE "+ ARTICLES_TABLE+
" ("+COL_ARTICLE_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
COL_ARTICLE_FEED_ID+ " INTEGER NOT NULL, "+
COL_ATRICLE_TITLE+" TEXT NOT NULL, "+
COL_ATRICLE_URL+" TEXT NOT NULL);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
/*onUpgrade(SQLiteDatabse db, int oldVersion, int newVersion): invoked when we make a modification to
the database such as altering, dropping , creating new tables. */
db.execSQL("DROP TABLE IF EXISTS "+DEBPT_TABLE);
db.execSQL("DROP TABLE IF EXISTS "+FEEDS_TABLE);
db.execSQL("DROP TABLE IF EXISTS "+ARTICLES_TABLE);
onCreate(db);
}
public boolean insertDept(Department dept){
SQLiteDatabase db = this.getReadableDatabase();// open database for read/write
ContentValues cv = new ContentValues();
cv.put(COL_DEPT_NAME, dept.getName());
cv.put(COL_DEPT_LAT, dept.getLat());
cv.put(COL_DEPT_LNG, dept.getLng());
long result = db.insert(DEBPT_TABLE, COL_DEPT_ID, cv);
// result : the row ID of the newly inserted row, or -1 if an error occurred
db.close();
return (result>0);
}
public boolean updateDept(Department dept){
SQLiteDatabase db = this.getReadableDatabase();
ContentValues cv = new ContentValues();
cv.put(COL_DEPT_NAME, dept.getName());
cv.put(COL_DEPT_LAT, dept.getLat());
cv.put(COL_DEPT_LNG, dept.getLng());
int result = db.update(DEBPT_TABLE, cv,COL_DEPT_ID+"=?", new String []{String.valueOf(dept.getID())});
//String[] args: The arguments of the WHERE clause
db.close();
return (result>0);
}
public boolean deleteDept(Department dept){
SQLiteDatabase db = this.getWritableDatabase();
int re = db.delete(DEBPT_TABLE, COL_DEPT_ID+"=?", new String[]{String.valueOf(dept.getID())});
db.close();
return (re>0);
}
public ArrayList<Department> getAllDepts(){
ArrayList<Department> depts = new ArrayList<Department>();
Department dept = null;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cur = db.rawQuery("SELECT "+COL_DEPT_ID+ " as _id,"+
COL_DEPT_NAME+", "+COL_DEPT_LAT+", "+COL_DEPT_LNG+" from "+DEBPT_TABLE,
new String[]{});
cur.moveToFirst();
while(cur.moveToNext()){
dept = new Department();
dept.setID(cur.getInt(cur.getColumnIndex("_id")));
dept.setName(cur.getString(cur.getColumnIndex(COL_DEPT_NAME)));
dept.setLat(cur.getDouble(cur.getColumnIndex(COL_DEPT_LAT)));
dept.setLat(cur.getDouble(cur.getColumnIndex(COL_DEPT_LNG)));
depts.add(dept);
}
db.close();
return depts;
}
public int GetDeptID(String Dept)
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor c=db.query(DEBPT_TABLE, new String[]{COL_DEPT_ID+" as _id",COL_DEPT_NAME},
COL_DEPT_NAME+"=?", new String[]{Dept}, null, null, null);
//Cursor c=db.rawQuery("SELECT "+COL_DEPT_ID+" as _id FROM "+DEBPT_TABLE+"
//WHERE "+COL_DEPT_NAME+"=?", new String []{Dept});
c.moveToFirst();
return c.getInt(c.getColumnIndex("_id"));
}
public boolean insertFeed(String title, URL url) {
SQLiteDatabase db=this.getReadableDatabase();
ContentValues values = new ContentValues();
values.put(COL_FEED_TITLE, title);
values.put(COL_FEED_URL, url.toString());
return (db.insert(FEEDS_TABLE, null, values) > 0);
}
public boolean deleteFeed(Feed feed) {
SQLiteDatabase db=this.getReadableDatabase();
return (db.delete(FEEDS_TABLE, COL_FEED_ID+ "=" + feed.feedId, null) > 0);
}
public ArrayList<Feed> getFeeds() {
SQLiteDatabase db=this.getReadableDatabase();
ArrayList<Feed> feeds = new ArrayList<Feed>();
try {
Cursor c = db.query(FEEDS_TABLE, new String[] { COL_FEED_ID, COL_FEED_TITLE,
COL_FEED_URL }, null, null, null, null, null);
int numRows = c.getCount();
c.moveToFirst();
for (int i = 0; i < numRows; ++i) {
Feed feed = new Feed();
feed.feedId = c.getLong(0);
feed.title = c.getString(1);
feed.url = new URL(c.getString(2));
feeds.add(feed);
c.moveToNext();
}
} catch (SQLException e) {
Log.e("FEEDS DB", e.toString());
} catch (MalformedURLException e) {
Log.e("FEEDS DB", e.toString());
}
return feeds;
}
public boolean insertArticle(Long feedId, String title, URL url) {
SQLiteDatabase db=this.getReadableDatabase();
ContentValues values = new ContentValues();
values.put(COL_ARTICLE_FEED_ID, feedId);
values.put(COL_ATRICLE_TITLE, title);
values.put(COL_ATRICLE_URL, url.toString());
return (db.insert(ARTICLES_TABLE, null, values) > 0);
}
public boolean deleteAricles(Long feedId) {
SQLiteDatabase db=this.getReadableDatabase();
return (db.delete(ARTICLES_TABLE, COL_ARTICLE_FEED_ID+"=" + feedId.toString(), null) > 0);
}
public List<Article> getArticles(Long feedId) {
SQLiteDatabase db=this.getReadableDatabase();
ArrayList<Article> articles = new ArrayList<Article>();
try {
Cursor c = db.query(ARTICLES_TABLE, new String[] { "article_id",
"feed_id", "title", "url" },
"feed_id=" + feedId.toString(), null, null, null, null);
int numRows = c.getCount();
c.moveToFirst();
for (int i = 0; i < numRows; ++i) {
Article article = new Article();
article.articleId = c.getLong(0);
article.feedId = c.getLong(1);
article.title = c.getString(2);
article.url = new URL(c.getString(3));
articles.add(article);
c.moveToNext();
}
} catch (SQLException e) {
Log.e("ARTICLES DB", e.toString());
} catch (MalformedURLException e) {
Log.e("ARTICLES DB", e.toString());
}
return articles;
}
}
</code></pre>
| 0 | 4,082 |
Facebook not able to scrape my url
|
<p>I have the HTML structure for my page as given below. I have added all the meta og tags, but still facebook is not able to scrape any info from my site. </p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html;" charset=utf-8"></meta>
<title>My Site</title>
<meta content="This is my title" property="og:title">
<meta content="This is my description" property="og:description">
<meta content="http://ia.media-imdb.com/images/rock.jpg" property="og:image">
<meta content="<MYPAGEID>" property="fb:page_id">
.......
</head>
<body>
.....
</code></pre>
<p>When I input the URL in facebook debugger(https://developers.facebook.com/tools/debug), I get the following messages:</p>
<pre><code>Scrape Information
Response Code 404
Critical Errors That Must Be Fixed
Bad Response Code URL returned a bad HTTP response code.
Errors that must be fixed
Missing Required Property The 'og:url' property is required, but not present.
Missing Required Property The 'og:type' property is required, but not present.
Missing Required Property The 'og:title' property is required, but not present.
Open Graph Warnings That Should Be Fixed
Inferred Property The 'og:url' property should be explicitly provided, even if a value can be inferred from other tags.
Inferred Property The 'og:title' property should be explicitly provided, even if a value can be inferred from other tags.
</code></pre>
<p>Why is facebook not reading the meta tags info? The page is accessible and not hidden behind login etc.</p>
<p><strong>UPDATE</strong></p>
<p>Ok I did bit of debugging and this is what I found. I have htaccess rule set in my directory- I am using PHP Codeigniter framework and have htaccess rule to remove index.php from the url. </p>
<p>So, when I feed the url to facebook debugger(https://developers.facebook.com/tools/debug) without index.php, facebook shows a 404, but when I feed url with index.php, it is able to parse my page. </p>
<p>Now how do I make facebook scrape content when the url doesn't have index.php?</p>
<p>This is my htaccess rule:</p>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
#Removes access to the system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#'system' can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
#When your application folder isn't in the system folder
#This snippet prevents user access to the application folder
#Submitted by: Fabdrol
#Rename 'application' to your applications folder name.
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn't true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
# Submitted by: ElliotHaughin
ErrorDocument 404 /index.php
</IfModule>
</code></pre>
| 0 | 1,317 |
Node Sass does not yet support Windows 64-bit
|
<p>I am running protractor UI automation project and try to run test with <code>yarn test</code> and received following build error</p>
<p><code>Module build failed: Error: Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime</code></p>
<p>I am on Windows 10 (64). below are the related entries in <code>package.json</code></p>
<p><code>"sass-lint": "^1.10.2",
"sass-loader": "6.0.6",
"sasslint-webpack-plugin": "^1.0.4",
"node-sass": "^4.0.0"</code></p>
<p><code>npm - 5.6.0
node - v9.11.1
yarn - 1.5.1</code></p>
<pre><code>{
"name": "Avatarwebapps",
"version": "3.0.0",
"description": "Avatar Apps",
"private": true,
"author": "Avatar DST",
"sasslintConfig": ".sass-lint.yml",
"contributors": [
"Brian Kinch<brian.finch@Avatar.com.au>"
],
"repository": {
"type": "git",
"url": "https://github.com/Avatartest/Avatar.Digital.Apps.git"
},
"bugs": {
"url": "https://Avatartest.atlassian.net/"
},
"scripts": {
"clean": "rimraf node_modules",
"docs": "typedoc --options typedoc.json src/app/app.component.ts",
"e2e": "protractor protractor.e2e.conf.js --params.environment",
"smoke": "protractor protractor.smoke.conf.js --params.environment",
"css:local:test": "cd backstop/development/maui && backstop test",
"css:local:approve": "cd backstop/development/maui && backstop approve",
"extractCustomer": "node extractCustomer.js",
"lint:ts:fix": "tslint -p tsconfig.json -c tslint.json --fix",
"lint:ts": "tslint -p tsconfig.json -c tslint.json",
"lint:sass": "sass-lint -v",
"lint:cpd": "rimraf reports/cpd && mkdir reports/cpd && jscpd -o reports/cpd/report.json -l 20 --limit 10 > reports/cpd/report.txt",
"postinstall": "yarn webdriver:update && npm rebuild node-sass",
"server": "webpack-dev-server --inline --progress --port 8080",
"start": "webpack-dev-server --config config/webpack/webpack.config.myaccount.js --inline --progress --port 8080 --https --cert ./ssl/server.crt --key ./ssl/server.key",
"start:e2e": "webpack-dev-server --config config/webpack/webpack.config.e2e.js --inline --quiet --https --port 8080",
"build": "rimraf dist/non-prod && webpack --config config/webpack/webpack.config.build.js --progress --profile --bail",
"build:e2e": "rimraf config/dist && webpack --config config/webpack/webpack.config.localhost.js --progress --profile --bail",
"build:prod": "rimraf dist/prod && webpack --config config/webpack/webpack.config.prod.js --progress --profile --bail",
"build:prod:analysis": "rimraf dist/prod && webpack --config config/webpack/webpack.config.prod.analyzer.js --progress --profile --bail",
"build:aot": "rimraf aot/ dist/aot && node --max_old_space_size=6244 ./node_modules/webpack/bin/webpack.js --config webpack.config.aot.js --progress --profile --bail --display-error-details",
"test": "karma start",
"test:debug": "karma start --browsers Chrome",
"test:ci": "karma start --browsers ChromeHeadless",
"test:watch": "karma start --no-single-run --auto-watch",
"test:watch:debug": "karma start --no-single-run --auto-watch --browsers Chrome",
"test:mockserver": "ts-node ./server-ts/tests/runMockserverTests.ts",
"webdriver:start": "webdriver-manager start",
"webdriver:update": "webdriver-manager update --ie",
"webdriver:clean": "webdriver-manager clean",
"build:service:nonprod": "rimraf dist/non-prod && webpack --config config/webpack/webpack.config.build-cache.js --progress --profile --bail",
"build:dev:cache:nonprod": "yarn build:service:nonprod && yarn precache:nonprod && yarn server:nonprod",
"build:cache:nonprod": "yarn build && yarn precache:nonprod",
"build:cache:prod": "yarn build:prod && yarn precache:prod",
"build:cache:aot": "yarn build:aot && yarn precache:aot",
"server:aot": "node tools/simple-server.js",
"server:aot:start:bg": "forever start -t -p . -al server.log tools/simple-server.js -p 8080",
"server:aot:stop:bg": "forever stop tools/simple-server.js -p 8080",
"precache:nonprod": "sw-precache --verbose --config=config/precacheConfig-nonprod.js",
"precache:prod": "sw-precache --verbose --config=config/precacheConfig-prod.js",
"precache:aot": "sw-precache --verbose --config=config/precacheConfig-aot.js",
"mockserver": "ts-node-dev ./server-ts/index.ts",
"mockserver:start:bg": "forever start -t -p . --workingDir . -al stub.log --id mockserver ./node_modules/ts-node/dist/bin.js ./server-ts/index.ts",
"mockserver:stop:bg": "forever stop mockserver",
"reports:plato": "yarn compile:ts && rimraf reports/plato && plato -r -d reports/plato -n -t \"My Account\" srcJs",
"reports:complexity": "yarn compile:ts && rimraf reports/complexity && mkdir reports/complexity && cd srcJs && ../node_modules/jscomplexity/bin/jscomplexity-cli.js > ../reports/complexity/report.txt",
"compile:ts": "rimraf srcJs && tsc -p src/tsc.json --outDir srcJs",
"compile:e2e": "tsc --project e2etsc.json",
"preflight": "yarn && yarn lint:sass && yarn lint:ts && yarn test:mockserver && yarn test:ci && yarn build:aot && yarn precache:aot && echo 'Preflight checks PASSED!' || echo 'Preflight checks FAILED!'"
},
"dependencies": {
"@angular/animations": "^5.2.0",
"@angular/common": "^5.2.0",
"@angular/compiler": "^5.2.0",
"@angular/core": "^5.2.0",
"@angular/forms": "^5.2.0",
"@angular/http": "^5.2.0",
"@angular/material": "^5.2.0",
"@angular/cdk": "^5.2.0",
"@angular/platform-browser": "^5.2.0",
"@angular/platform-browser-dynamic": "^5.2.0",
"@angular/router": "^5.2.0",
"@typed/hashmap": "^1.0.1",
"@types/body-parser": "^1.16.8",
"@types/express-fileupload": "^0.1.1",
"angular-progress-http": "1.0.0",
"angular2-text-mask": "^8.0.1",
"angulartics2": "^2.2.2",
"bootstrap": "3.3.7",
"core-js": "^2.4.1",
"css-element-queries": "^0.4.0",
"hammerjs": "2.0.8",
"jwt-decode": "^2.1.0",
"jwt-simple": "^0.5.1",
"lodash": "^4.17.4",
"moment": "^2.17.1",
"reflect-metadata": "0.1.10",
"rxjs": "5.5.7",
"zone.js": "^0.8.19"
},
"devDependencies": {
"@angular-devkit/core": "0.3.2",
"@angular/cli": "~1.7.3",
"@angular/compiler-cli": "^5.2.0",
"@angular/language-service": "^5.2.0",
"@ngtools/webpack": "1.10.2",
"@octopusdeploy/octopackjs": "0.0.7",
"@types/core-js": "^0.9.40",
"@types/express": "^4.11.0",
"@types/form-data": "0.0.33",
"@types/hammerjs": "^2.0.34",
"@types/jasmine": "~2.8.3",
"@types/jasminewd2": "~2.0.2",
"@types/lodash": "^4.14.66",
"@types/node": "^7.0.5",
"@types/request": "^0.0.44",
"@types/source-map": "^0.5.0",
"@types/uglify-js": "^2.0.27",
"@types/webpack": "~3.8.11",
"adal-node": "^0.1.27",
"angular-router-loader": "^0.8.2",
"angular2-template-loader": "^0.6.0",
"assets-webpack-plugin": "^3.5.1",
"autoprefixer": "^7.2.3",
"azure-keyvault": "^3.0.1-preview",
"backstopjs": "^3.0.36",
"body-parser": "^1.17.2",
"case-sensitive-paths-webpack-plugin": "^2.1.1",
"chai": "^4.0.2",
"circular-dependency-plugin": "^4.2.1",
"codelyzer": "^4.0.1",
"command-line-args": "^4.0.1",
"command-line-usage": "^4.0.0",
"concurrently": "^3.1.0",
"copy-webpack-plugin": "~4.4.1",
"css-loader": "^0.28.4",
"ejs-compiled-loader": "^1.1.0",
"express": "^4.15.3",
"express-fileupload": "^0.1.4",
"extract-text-webpack-plugin": "3.0.0",
"file-loader": "^1.1.5",
"forever": "^0.15.3",
"fs": "0.0.2",
"git-rev-2": "^0.1.0",
"html-loader": "^0.4.4",
"html-webpack-plugin": "^2.29.0",
"http-proxy-middleware": "^0.17.4",
"inversify": "^4.10.0",
"istanbul-instrumenter-loader": "^3.0.0",
"jasmine-bamboo-reporter": "0.0.2",
"jasmine-core": "~2.8.0",
"jasmine-reporters": "^2.2.0",
"jasmine-spec-reporter": "~4.2.1",
"jscomplexity": "^2.0.0",
"jscpd": "^0.6.15",
"json-loader": "^0.5.4",
"jsonfile": "^3.0.0",
"karma": "~2.0.0",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage": "^1.1.1",
"karma-coverage-istanbul-reporter": "^1.3.0",
"karma-jasmine": "~1.1.0",
"karma-junit-reporter": "^1.2.0",
"karma-mocha-reporter": "^2.2.0",
"karma-remap-coverage": "^0.1.4",
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "2.0.4",
"mkdirp": "^0.5.1",
"mocha": "^3.1.2",
"mocha-junit-reporter": "^1.12.0",
"node-sass": "^4.0.0",
"ntypescript": "^1.201609302242.1",
"null-loader": "0.1.1",
"octopus-deploy": "^2.0.0",
"open-browser-webpack-plugin": "0.0.3",
"optimize-css-assets-webpack-plugin": "^3.1.1",
"optimize-js-plugin": "^0.0.4",
"plato": "^1.7.0",
"postcss-loader": "^1.0.0",
"protractor": "~5.1.2",
"protractor-browser-logs": "^1.0.351",
"protractor-jasmine2-html-reporter": "0.0.7",
"raw-loader": "0.5.1",
"request": "^2.83.0",
"rimraf": "^2.5.4",
"sass-lint": "^1.10.2",
"sass-loader": "6.0.6",
"sasslint-webpack-plugin": "^1.0.4",
"should": "^11.1.1",
"strip-loader": "^0.1.2",
"style-loader": "^0.19.1",
"sw-precache": "^5.1.1",
"ts-loader": "^2.3.3",
"ts-md5": "^1.2.2",
"ts-mocks": "^0.2.2",
"ts-node": "~4.1.0",
"ts-node-dev": "^1.0.0-pre.16",
"tslib": "^1.5.0",
"tslint": "~5.9.1",
"tslint-eslint-rules": "4.1.1",
"tslint-loader": "3.5.3",
"typedoc": "^0.7.1",
"typescript": "~2.5.3",
"uglifyjs-webpack-plugin": "^1.1.8",
"url-loader": "^0.6.2",
"webpack": "3.11.0",
"webpack-bundle-analyzer": "^2.4.0",
"webpack-dev-server": "~2.11.0",
"webpack-dll-bundles-plugin": "^1.0.0-beta.5",
"zip-dir": "^1.0.2"
}
}
</code></pre>
| 0 | 4,754 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.