title
stringlengths 10
150
| body
stringlengths 17
64.2k
| label
int64 0
3
|
---|---|---|
Parsing json directly using input stream | <p>I am doing a api call and in response i am getting json. So for that I want to parse it directly through input stream so that there would not be need of storing it in memory.
For this I am trying to use JSONReader but that i am unable use for api's less than 11.
So i dont know how to proceed with. I want it to be done from 2.0 version onwards. Even parsing through JsonReader is not working.
I was thing of having GSON parser but i am not getting how to implement the same with Inputstream.</p>
<p>EDIT:
My code for the same:</p>
<pre><code>HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
Log.e("123", "Status code ----------- "+statusCode);
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
// for showing it on textview i am storing in in builder
BufferedReader bReader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = bReader.readLine()) != null) {
builder.append(line);
}
////////////
JsonReader reader = new JsonReader(new InputStreamReader(content));
reader.setLenient(true);
readGson(reader);
} else {
Log.e("TAG", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
private void readGson(JsonReader reader) {
// TODO Auto-generated method stub
Log.e("TAG", "inidde readgson"+reader);
try {
Log.e("TAG", "inside try");
reader.beginObject();
Log.e("123", "inside try ");
while(reader.hasNext()){
Log.e("TAG", "reader values"+reader);
String name = reader.nextName();
if (name.equals("max_id")) {
long max_id = reader.nextLong();
Log.e("TAG", "sdbfhsajfgsdjbgksdfjv------------------"+max_id);
} else {
Log.e("TAG", "c skfnvklsfvn skip value");
reader.skipValue();
}
}
reader.endObject();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("TAG", "inside catch");
e.printStackTrace();
}
}
</code></pre>
<p>output:</p>
<pre><code> 01-28 10:20:53.519: E/TAG(420): Status code ----------- 200
01-28 10:20:53.679: E/TAG(420): inidde readgsonJsonReader at line 1 column 1
01-28 10:20:53.679: E/TAG(420): inside try
01-28 10:20:53.679: E/TAG(420): inside catch
01-28 10:20:53.679: W/System.err(420): java.io.EOFException: End of input at line 1 column 1
01-28 10:20:53.689: W/System.err(420): at com.google.gson.stream.JsonReader.nextNonWhitespace(JsonReader.java:954)
01-28 10:20:53.689: W/System.err(420): at com.google.gson.stream.JsonReader.consumeNonExecutePrefix(JsonReader.java:405)
01-28 10:20:53.689: W/System.err(420): at com.google.gson.stream.JsonReader.peek(JsonReader.java:364)
01-28 10:20:53.689: W/System.err(420): at com.google.gson.stream.JsonReader.expect(JsonReader.java:337)
01-28 10:20:53.689: W/System.err(420): at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:322)
01-28 10:20:53.689: W/System.err(420): at com.example.httpconnectiondemo.MainActivity.readGson(MainActivity.java:136)
01-28 10:20:53.699: W/System.err(420): at com.example.httpconnectiondemo.MainActivity.readTwitterFeed(MainActivity.java:116)
01-28 10:20:53.699: W/System.err(420): at com.example.httpconnectiondemo.MainActivity.onCreate(MainActivity.java:64)
01-28 10:20:53.699: W/System.err(420): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-28 10:20:53.699: W/System.err(420): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
01-28 10:20:53.699: W/System.err(420): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
01-28 10:20:53.699: W/System.err(420): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
01-28 10:20:53.699: W/System.err(420): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
01-28 10:20:53.699: W/System.err(420): at android.os.Handler.dispatchMessage(Handler.java:99)
01-28 10:20:53.699: W/System.err(420): at android.os.Looper.loop(Looper.java:123)
01-28 10:20:53.699: W/System.err(420): at android.app.ActivityThread.main(ActivityThread.java:3683)
01-28 10:20:53.710: W/System.err(420): at java.lang.reflect.Method.invokeNative(Native Method)
01-28 10:20:53.710: W/System.err(420): at java.lang.reflect.Method.invoke(Method.java:507)
01-28 10:20:53.710: W/System.err(420): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-28 10:20:53.710: W/System.err(420): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-28 10:20:53.710: W/System.err(420): at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p>Thanks in advance.</p> | 0 |
ZXing convert Bitmap to BinaryBitmap | <p>I am using OpenCV and Zxing, and I'd like to add 2d code scanning. I have a few types of images that I could send. Probably the best is Bitmat (the other option is OpenCV Mat).</p>
<p>It looks like you used to be able to convert like this:</p>
<pre><code>Bitmap frame = //this is the frame coming in
LuminanceSource source = new RGBLuminanceSource(frame);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
//then I can use reader.decode(bitmap) to decode the BinaryBitmap
</code></pre>
<p>However, RGBLuminaceSource looks like it no longer takes a bitmap as an input. So how else can I convert an input image to BinaryBitmap???</p>
<h1>Edit:</h1>
<p>Ok so I believe I've made some progress, but I'm still having an issue. I think I have the code that converts the Bitmap into the correct format, however I am now getting an arrayIndexOutOfBounds</p>
<pre><code>public void zxing(){
Bitmap bMap = Bitmap.createBitmap(frame.width(), frame.height(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(frame, bMap);
byte[] array = BitmapToArray(bMap);
LuminanceSource source = new PlanarYUVLuminanceSource(array, bMap.getWidth(), bMap.getHeight(), 0, 0, bMap.getWidth(), bMap.getHeight(), false);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Reader reader = new DataMatrixReader();
String sResult = "";
try {
Result result = reader.decode(bitmap);
sResult = result.getText();
Log.i("Result", sResult);
}
catch (NotFoundException e) {
Log.d(TAG, "Code Not Found");
e.printStackTrace();
}
}
public byte[] BitmapToArray(Bitmap bmp){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 50, stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
</code></pre>
<p>I get the error</p>
<pre><code>02-14 10:19:27.469: E/AndroidRuntime(29736): java.lang.ArrayIndexOutOfBoundsException: length=33341; index=34560 02-14 10:19:27.469: E/AndroidRuntime(29736): at
com.google.zxing.common.HybridBinarizer.calculateBlackPoints(HybridBinarizer.java:199)
</code></pre>
<p>I have logged the size of the byte[], and it is the length shown above. I cant figure out why zxing is expecting it to be bigger</p> | 0 |
Bundle ID in android | <p>What is meant by <strong>bundle ID</strong> in android, What is its usage, And can two android apps have same bundle ID? if YES then why? and if NO then why</p> | 0 |
"sdkmanager: command not found" after installing Android SDK | <p>I installed via <code>apt-get install android-sdk</code>.</p>
<p>However, doing a <code>find / -name sdkmanager</code> reveals there is no such binary anywhere on the system.</p>
<p>On my Mac, the binary exists in <code>$ANDROID_HOME/tools/bin</code>.</p>
<p>However, on the Ubuntu system (the system with the issue), the binary does not exist there:</p>
<pre><code>$ ls $ANDROID_HOME/tools/bin
e2fsck
fsck.ext4
mkfs.ext4
resize2fs
screenshot2
tune2fs
</code></pre>
<p>Where is the <code>sdkmanager</code>?</p>
<p><strong>Edit:</strong></p>
<p>Not sure why the above didn't install <code>sdkmanager</code>, however, one solution I found was to install manually (instead of via apt-get) by downloading the Linux files at <a href="https://developer.android.com/studio/#downloads" rel="noreferrer">https://developer.android.com/studio/#downloads</a> under the "Command line tools only" header.</p> | 0 |
Switch Case in c++ | <p>How can I compare an array of char in c++ using switch-case?
Here is a part of my code:</p>
<pre><code>char[256] buff;
switch(buff){
case "Name": printf("%s",buff);
break;
case "Number": printf("Number "%s",buff);
break;
defaul : break
}
</code></pre>
<p>I receive the error :" error: switch quantity not an integer".How can I resolve it?</p> | 0 |
Adding new property to each document in a large collection | <p>Using the mongodb shell, I'm trying to add a new property to each document in a large collection. The collection (Listing) has an existing property called Address. I'm simply trying to add a new property called LowerCaseAddress which can be used for searching so that I don't need to use a case-insensitive regex for address matching, which is slow.</p>
<p>Here is the script I tried to use in the shell:</p>
<pre><code>for( var c = db.Listing.find(); c.hasNext(); ) {
var listing = c.next();
db.Listing.update( { LowerCaseAddress: listing.Address.toLowerCase() });
}
</code></pre>
<p>It ran for ~6 hours and then my PC crashed. Is there a better way to add a new property to each documentin a large collection (~4 million records)?</p> | 0 |
How to create dialog which will be full in horizontal dimension | <p>When I use in layout, which specifies this dialog <code>android:layout_width="match_parent"</code> I get this dialog:</p>
<p><img src="https://i.stack.imgur.com/UzjUR.png" alt="small dialog"></p>
<p>I need dialog which will be wider. Any ideas?</p> | 0 |
Kotlin 2d Array initialization | <p>Please take a look at my 2D-Array-Initialization. The code works.</p>
<pre><code>class World(val size_x: Int = 256, val size_y: Int = 256) {
var worldTiles = Array(size_x, { Array(size_y, { WorldTile() }) })
fun generate() {
for( x in 0..size_x-1 ) {
for( y in 0..size_y-1 ) {
worldTiles[x][y] = WorldTile()
}
}
}
}
</code></pre>
<p>The problem is that it runs the initialization twice. Basically I want to instantiate the WorldTile-Object in the generate() function. So Line 3 shouldn't call "new WorldTile" there. How can I do that?</p>
<p>Also is that the proper Kotlin way of traversing a 2d-Array?</p> | 0 |
Oracle 11g - query appears to cache even with NOCACHE hint | <p>I'm doing some database benchmarking in Python using the cx_Oracle module. To benchmark results, I'm running 150 unique queries and timing the execution of each one. I'm running something like this:</p>
<pre><code>c = connection.cursor()
starttime = time.time()
c.execute('SELECT /*+ NOCACHE */ COUNT (*) AS ROWCOUNT FROM (' + sql + ')')
endtime = time.time()
runtime = endtime - starttime
</code></pre>
<p>Each query is passed in through the variable <code>sql</code>, and they vary significantly in length, runtime, and the tables they access. That being said, all queries exhibit the following behavior:</p>
<p><strong>1st run:</strong> very slow (relatively)</p>
<p><strong>2nd run:</strong> significantly faster (takes anywhere from 1/2 - 1/5 the time)</p>
<p><strong>3rd run:</strong> marginally faster than 2nd run</p>
<p><strong>All subsequent runs >= 4:</strong> approximately equal to 3rd run</p>
<p>I need the cache disabled to get accurate results, but the first few runs are really throwing off my data; it's as if <code>NOCACHE</code> isn't working at all... what's going on here?</p>
<p>Edit: Allan answered my question, but for anyone who might be interested, I did a little more research and came across these two pages which were also helpful:</p>
<p><a href="https://stackoverflow.com/questions/2147456/how-to-clear-all-cached-items-in-oracle">How to clear all cached items in Oracle</a></p>
<p><a href="http://www.dba-oracle.com/t_flush_buffer_cache.htm" rel="nofollow noreferrer">http://www.dba-oracle.com/t_flush_buffer_cache.htm</a></p> | 0 |
Gradle: Project "x" not found in root project "myProject" | <p>Having upgraded to Android Studio from Eclipse I wanted to update my TouchDB library which is now <a href="https://github.com/couchbase/couchbase-lite-android" rel="nofollow">Coubasebase-lite-android</a>. I removed TouchDB from my project, git cloned couchbase-lite-android added to my project in Android Studio via File -> Import Module.</p>
<p>Everything looks good in the IDE and all the references look good. But when I try and compile it I receive the error in Android Studio: <code>Gradle: Project "x" not found in root project "myProject"</code> "x" being each module(?) inside couchbaselite...i.e CBLite, CBLiteEktrop etc</p>
<p>I really don't know where to start with this one?</p>
<p>Here's my project tree:</p>
<pre><code>myProject
---myProject
---CouchbaseLiteProject
------CBLite
------CBLiteEktorp
------Gradle
------.Gradle
------gradlew
------CouchbaseLiteProject
---------build
---------libs
---------src
</code></pre>
<p>here's the contents of <code>gradlew</code> from CouchBaseLiteProject:</p>
<pre><code>#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# For Cygwin, ensure paths are in UNIX format before anything is touched.
if $cygwin ; then
[ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
fi
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >&-
APP_HOME="`pwd -P`"
cd "$SAVED" >&-
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\" \"-Xmx1024m\" \"-Xms256m\" \"-XX:MaxPermSize=1024m\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
</code></pre>
<p>`
There is no gradlew file under myProject as it was originally a Eclipse project</p>
<p><strong>update</strong>
following on from buzeeg's advice and not being able to export my project from Eclipse to generate the gradle files I decided to create a new project in Android Studio and manually copy my original project files into it, so Android Studio would create the gradle files for me. </p>
<p>After importing couchbase-lite-android as a module and trying to build the project I get exactly the same errors as I originally encountered. <code>Gradle: Project "x" not found in root project "myProject"</code> "x" relating to all the sub modules (?) under the CouchbaseLiteProject tree...</p> | 0 |
Permanently Delete Empty Rows Apache POI using JAVA in Excel Sheet | <p>I'd like to permanently delete those rows that are empty have no data of any type! I am doing this like:</p>
<pre><code> private void shift(File f){
File F=f;
HSSFWorkbook wb = null;
HSSFSheet sheet=null;
try{
FileInputStream is=new FileInputStream(F);
wb= new HSSFWorkbook(is);
sheet = wb.getSheetAt(0);
int rowIndex = 0;
int lastRowNum = sheet.getLastRowNum();
if (rowIndex >= 0 && rowIndex < lastRowNum) {
sheet.shiftRows(rowIndex, lastRowNum, 500);
}
FileOutputStream fileOut = new FileOutputStream("C:/juni.xls");
wb.write(fileOut);
fileOut.close();
}
catch(Exception e){
System.out.print("SERRO "+e);
}
}
</code></pre>
<p>after shiftRows() i write my new file. But my code has now effect. I just need to remove/delete the empty rows that come inside my data (any ever). so is it possible doing so? if yes, am i doing right? if no can anybody please help me doing so? Thanks in advance! </p> | 0 |
How to get IP Address of Docker Desktop VM? | <p>I'm in a team where some of us use docker toolbox and some user docker desktop. We're writing an application that needs to communicate to a docker container in development. </p>
<p>On docker toolbox, I know the docker-machine env command sets the docker host environment variable and I can use that to get the ip of the virtual machine that's running the docker engine. From there I just access the exposed ports. </p>
<p>What's the equivalent way to get that information on docker desktop? (I do not have a machine that has docker desktop, only docker toolbox but I'm writing code that should be able to access the docker container on both)</p> | 0 |
Getting application version from within application | <p>Is there a simple way of obtaining the application version information from the resource file at runtime? </p>
<p>Effectively what I'd like to do is be able to have a "Version X.Y.Z" displayed at runtime without having a separate variable somewhere that I'd have to keep in sync with my ProductVersion and FileVersion.</p>
<p>To clarify: yes this is a standard C++ Windows project. I am aware of the <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms647003%28v=vs.85%29.aspx" rel="noreferrer">GetFileVersionInfo</a> method but it seems silly to have to open the binary from within the version in memory just to query the version information - I'm sure I'm missing something obvious here :-)</p> | 0 |
Trigger control's event programmatically | <p>Assume that I have a WinFoms project. There is just one button (e.g. <code>button1</code>). </p>
<p>The question is: is it possible to trigger the <code>ButtonClicked</code> event via code without really clicking it?</p> | 0 |
How to change width and height of Button in Android | <pre><code><Button android:text="Layer 1"
android:layout_width="wrap_content"
android:id="@+id/button1"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="50dp"
android:width="100dp"
android:height="20dp">
</Button>
</code></pre>
<p>I'm unable to change width and height of a Button. What's the problem?</p> | 0 |
Android MediaPlayer error -1004 (ERROR_IO) | <p>My application plays audio stream<br>
Here the code: </p>
<pre><code>MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
mediaPlayer.start();
</code></pre>
<p>url is local file (127.0.0.1)<br>
I use my own HttpServer which runs on the same phone.<br>
After call to </p>
<pre><code>mediaPlayer.prepare();
</code></pre>
<p>I get the error:
error (1, -1004) which is ERROR_IO<br>
Any idea what is this error? </p>
<p>Thanks, Costa.</p> | 0 |
How to hex edit an exe file safely? | <p>I am working on a small puzzle/wargame which involves coding <strong>Windows Forms in C#</strong>.. </p>
<p>To get to a certain level I need a password which is stored in an exe. The same exe allows me send that password to a default person which is stored in a <strong>variable</strong>. The password sending is accomplished by updating the given user's data in a MySQL database.</p>
<p>The challenge was that a user should hex edit the exe and change the default recipient to the user desired username. But when I <strong>hex edited</strong> the file and put the desired user name and tried to run it, it showed an error "<strong>x.exe not a valid win32 application</strong>"..</p>
<p>Is there a way to safely hex edit a file without encountering this error. Or is there a way to modify the source so that, just one variable may be safely edited using a hex editor.. </p> | 0 |
Docker: How to fix "Job for docker.service failed because the control process exited with error code" | <p>I'm trying to use docker in Manjaro (my kernel version is 4.19) and it is not working.</p>
<p>After running <code>sudo pamac install docker</code> I run <code>sudo systemctl start docker.service</code> and receive this message:</p>
<pre><code>Job for docker.service failed because the control process exited with error code.
See "systemctl status docker.service" and "journalctl -xe" for details.
</code></pre>
<p>So <code>sudo systemctl status docker.service</code> returns:</p>
<pre><code>● docker.service - Docker Application Container Engine
Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; vendor preset: disabled)
Active: failed (Result: exit-code) since Mon 2019-04-29 12:28:44 -03; 39s ago
Docs: https://docs.docker.com
Process: 17769 ExecStart=/usr/bin/dockerd -H fd:// (code=exited, status=1/FAILURE)
Main PID: 17769 (code=exited, status=1/FAILURE)
abr 29 12:28:44 tamer-pc systemd[1]: docker.service: Service RestartSec=100ms expired, scheduling restart.
abr 29 12:28:44 tamer-pc systemd[1]: docker.service: Scheduled restart job, restart counter is at 3.
abr 29 12:28:44 tamer-pc systemd[1]: Stopped Docker Application Container Engine.
abr 29 12:28:44 tamer-pc systemd[1]: docker.service: Start request repeated too quickly.
abr 29 12:28:44 tamer-pc systemd[1]: docker.service: Failed with result 'exit-code'.
abr 29 12:28:44 tamer-pc systemd[1]: Failed to start Docker Application Container Engine.
</code></pre>
<p>and <code>journalctl -xe</code> returns:</p>
<pre><code>-- Defined-By: systemd
-- Support: https://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- The unit docker.service has entered the 'failed' state with result 'exit-code'.
abr 29 12:28:44 tamer-pc systemd[1]: Failed to start Docker Application Container Engine.
-- Subject: A unidade docker.service falhou
-- Defined-By: systemd
-- Support: https://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- A unidade docker.service falhou.
--
-- O resultado é failed.
abr 29 12:28:44 tamer-pc systemd[1]: docker.socket: Failed with result 'service-start-limit-hit'.
-- Subject: Unit failed
-- Defined-By: systemd
-- Support: https://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- The unit docker.socket has entered the 'failed' state with result 'service-start-limit-hit'.
abr 29 12:29:02 tamer-pc dbus-daemon[650]: [system] Activating via systemd: service name='org.freedesktop.resolve1' unit='>
abr 29 12:29:02 tamer-pc dbus-daemon[650]: [system] Activation via systemd failed for unit 'dbus-org.freedesktop.resolve1.>
abr 29 12:29:24 tamer-pc sudo[17879]: tamer : TTY=pts/0 ; PWD=/etc/docker ; USER=root ; COMMAND=/usr/bin/systemctl stat>
abr 29 12:29:24 tamer-pc sudo[17879]: pam_unix(sudo:session): session opened for user root by (uid=0)
abr 29 12:29:24 tamer-pc sudo[17879]: pam_unix(sudo:session): session closed for user root
lines 1703-1725/1725 (END)
</code></pre>
<p>I'm looking for resolution for two days but whatever I read seems not to be exactly the same as my problem.</p> | 0 |
FragmentTransaction.replace() not working | <p>I have a <code>ListFragment</code> displaying a list of items that created by the user. I have a <code>ListView</code> with it's id set to "@android:id/list" and a <code>TextView</code> with the id "@android:id/empty". </p>
<p>I have an action bar button to display a fragment to allow the user to create more entries for the list. Here is the <code>onOptionsItemSelected()</code> method:</p>
<pre><code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
Fragment frag = null;
// Right now I only have code for the addCourse() fragment, will add more soon
switch (item.getItemId()) {
case R.id.addCourse:
frag = new AddCourseFragment();
break;
default:
return super.onOptionsItemSelected(item);
}
// The support library is being dumb and replace isn't actually
getFragmentManager().beginTransaction()
.remove(this).add(getId(), frag).addToBackStack(null).commit();
return true;
}
</code></pre>
<p>The AddCourseFragment code is as follows: </p>
<pre><code>public class AddCourseFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_addcourse, container, false);
// if (view.findViewById(R.id.timesFrame)!=null) {
Fragment timesFrag = new TimesFragment();
getChildFragmentManager().beginTransaction()
.add(R.id.timesFrame, timesFrag).commit();
// }
return view;
}
}
</code></pre>
<p>As expected, when the list is unpopulated, android shows the text in the <code>TextView</code>. I then hit the add course button and this happens: <img src="https://i.stack.imgur.com/JW79g.png" alt="enter image description here"><br>
It shows the empty text as well as the new fragment.</p> | 0 |
open source image filter library like Instagram? | <p>I am developing an application(android) that want to do some image filter effect like in Instagram, just wondering if there is any open source library available?</p> | 0 |
How to use sed to remove the last n lines of a file | <p>I want to remove some <em>n</em> lines from the end of a file. Can this be done using sed?</p>
<p>For example, to remove lines from 2 to 4, I can use</p>
<pre><code>$ sed '2,4d' file
</code></pre>
<p>But I don't know the line numbers. I can delete the last line using </p>
<pre><code>$sed $d file
</code></pre>
<p>but I want to know the way to remove <em>n</em> lines from the end. Please let me know how to do that using sed or some other method.</p> | 0 |
sSMTP no longer works - 'Invalid response: 501 5.5.4 HELO/EHLO argument MYEMAILADDRESS@gmail.com invalid, closing connection.' | <p>As the title/tags say, I run sSMTP on Linux for a PHP server.</p>
<p>Whenever I try to send an email, I get these errors (that do not show up in PHP, only in the logs/ 'sudo service sendmail status' or 'sudo service php5-fpm status')</p>
<p>From /var/log/mail.log</p>
<pre><code>Mar 31 03:34:34 ip-172-31-22-38 sSMTP[2004]: Creating SSL connection to host
Mar 31 03:34:34 ip-172-31-22-38 sSMTP[2004]: Invalid response: 501 5.5.4 HELO/ELO argument MYEMAILADDRESS@gmail.com invalid, closing connection. v74sm9147441pfa.7- gsmtp (MYEMAILADDRESS@gmail.com)
Mar 31 03:34:34 ip-172-31-22-38 sSMTP[2004]: SSL connection using (null)
Mar 31 03:34:34 ip-172-31-22-38 sSMTP[2004]: Cannot open smtp.gmail.com:587
</code></pre>
<p>From /var/log/mail.err and mail.warn</p>
<pre><code>Mar 31 03:34:10 ip-172-31-22-38 sSMTP[1997]: Cannot open smtp.gmail.com:587
Mar 31 03:34:34 ip-172-31-22-38 sSMTP[2004]: Invalid response: 501 5.5.4 HELO/EHLO argument MYEMAILADDRESS@gmail.com invalid, closing connection. v74sm9147441pfa.7 - gsmtp (MYEMAILADDRESS@gmail.com)
Mar 31 03:34:34 ip-172-31-22-38 sSMTP[2004]: Cannot open smtp.gmail.com:587
</code></pre>
<p>My /etc/ssmtp/ssmtp.conf</p>
<pre><code>#
# Config file for sSMTP sendmail
#
# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
root=MYEMAILADDRESS@gmail.com
# The place where the mail goes. The actual machine name is required no
# MX records are consulted. Commonly mailhosts are named mail.domain.com
mailhub=smtp.gmail.com:587
# Where will the mail seem to come from?
#rewriteDomain=
# The full hostname
hostname=MYEMAILADDRESS@gmail.com
AuthUser=MYEMAILADDRESS@gmail.com
AuthPass=[removed]
UseSTARTTLS=YES
# Are users allowed to set their own From: address?
# YES - Allow the user to specify their own From: address
# NO - Use the system generated From: address
FromLineOverride=YES
</code></pre>
<p>My revaliases</p>
<pre><code>root:MYEMAILADDRESS@gmail.com:smtp.gmail.com:587
localusername:MYEMAILADDRESS@gmail.com:smtp.gmail.com:587
</code></pre> | 0 |
NuGet Package Restore Not Working on Build Server | <p>I have set up NuGet Package Restore on my solution and it works nicely on my local machine. I followed the instructions supplied here:</p>
<p><a href="http://docs.nuget.org/docs/workflows/using-nuget-without-committing-packages">http://docs.nuget.org/docs/workflows/using-nuget-without-committing-packages</a></p>
<p>The problem I have is on my build server where the following error occurs:</p>
<p><em>Package restore is disabled by default. To give consent, open the Visual Studio Options dialog, click on Package Manager node and check 'Allow NuGet to download missing packages during build.' You can also give consent by setting the environment variable 'EnableNuGetPackageRestore' to 'true'.</em></p>
<p>Unfortunately I dont have access to the build server as it is controlled off site so cant update the environment variable. Is there any other way around this? Anything I can add to the solution file or similar that would allow the package restore?</p> | 0 |
Setting text color in ComboBoxItem | <p>I want to set the text color for <em><code>PASS</code></em> as <code>GREEN</code> and the text color for <em><code>FAIL</code></em> as <code>RED</code>. I can't seem to find the solution. I need to do this in pure XAML.</p>
<pre><code><ComboBox x:Name="LocatedCorrectly" Width="100"
Height="25" Grid.Column="1" Grid.Row="2"
HorizontalAlignment="Left"
IsSynchronizedWithCurrentItem="True">
<ComboBoxItem Content="PASS" Tag="PASS" IsSelected="True"/>
<ComboBoxItem Content="FAIL" Tag="FAILED" />
</ComboBox>
</code></pre> | 0 |
R - Extract summary table from Survfit with Strata | <p>I'm new to R and survival analysis, and I am interested to export into a dataframe the results from survfit where there is strata. </p>
<p>This site has provided an excellent solution but not to one with strata (<a href="https://stat.ethz.ch/pipermail/r-help/2014-October/422348.html" rel="noreferrer">https://stat.ethz.ch/pipermail/r-help/2014-October/422348.html</a>). How can i append (or stack) each strata with an extra column which contains the strata type.
solution in the link offered is not applicable to strata groupings</p>
<pre><code>library(survival)
data(lung)
mod <- with(lung, survfit(Surv(time, status)~ 1))
res <- summary(mod)
str(res)
# Extract the columns you want
cols <- lapply(c(2:6, 8:10) , function(x) res[x])
# Combine the columns into a data frame
tbl <- do.call(data.frame, cols)
str(tbl)
</code></pre>
<p>Thank you in advanced,
R newbie</p> | 0 |
How to remove the cause of an unexpected indentation warning when generating code documentation? | <p>The documentation code with the problem is at the beginning of a method:</p>
<pre><code>"""
Gtk.EventBox::button-release-event signal handler.
:param widget: The clicked widget (The Gtk.EventBox).
:param event: Gdk.EventButton object with information regarding
the event.
:param user_data: The Gtk.LinkButton that should be opened when
the Gtk.EventBox is clicked.
:return: None
"""
</code></pre>
<p>The warnings are:</p>
<pre><code>C:/msys64/home/hope/python+gtk/test/main.py:docstring of main.Builder.advertisem
ent_clicked:4: WARNING: Unexpected indentation.
C:/msys64/home/hope/python+gtk/test/main.py:docstring of main.Builder.advertisem
ent_clicked:5: WARNING: Block quote ends without a blank line; unexpected uninde
nt.
</code></pre>
<p>What can be done to remove these warnings and their cause(s)?</p> | 0 |
C# .net Make checkboxes to behave as a radio button | <p>I have a group box which has some radio buttons. I am trying to implement serialization with the help of a tutorial from Code Project. That tutorial supports serialization of checkboxes and not radio buttons. So i need to make the radio buttons in my app as checkboxes (that is they should be check boxes but work like a radiobutton). </p>
<p>I tried writing code, but what happens is when I find that a particular checkbox is checked and I go to uncheck or vice versa, it triggers that checked_changed event handler and this goes into an infinite loop.</p>
<p>Can someone help me out with this? </p>
<p>Thanks</p>
<p>UPDATE:</p>
<p>After seeing your replies, I would like to say thanks a lot. Yes, You are all right that we should not be messing with the basic properties. I will work with changing the serialization method. </p>
<p>P.S The link for the tutorial is <a href="http://www.codeproject.com/KB/dialog/SavingTheStateOfAForm.aspx" rel="nofollow">http://www.codeproject.com/KB/dialog/SavingTheStateOfAForm.aspx</a></p>
<p>Final Update:</p>
<p>After following the replies posted here, I decided not to change the default properties but to change the serializer code. I did that and it now works perfectly. Thanks a lot, everyone.</p> | 0 |
Singleton pattern with combination of lazy loading and thread safety | <p>I was doing some research about singletons, specifically regarding lazy vs eager initialization of singletons.</p>
<p>An example of eager initialization:</p>
<pre><code>public class Singleton
{
//initialzed during class loading
private static final Singleton INSTANCE = new Singleton();
//to prevent creating another instance of Singleton
private Singleton(){}
public static Singleton getSingleton(){
return INSTANCE;
}
}
</code></pre>
<p>but as shown above that it is eager initialization and thread safety is left to jvm
but now, I want to have this same pattern but with lazy initialization.</p>
<p>so I come up with this approach: </p>
<pre><code>public final class Foo {
private static class FooLoader {
private static final Foo INSTANCE = new Foo();
}
private Foo() {
if (FooLoader.INSTANCE != null) {
throw new IllegalStateException("Already instantiated");
}
}
public static Foo getInstance() {
return FooLoader.INSTANCE;
}
}
</code></pre>
<p>As shown above Since the line </p>
<pre><code>private static final Foo INSTANCE = new Foo();
</code></pre>
<p>is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread safe.</p>
<p><strong>Is this correct?</strong></p> | 0 |
How to solve the error: assignment to expression with array type | <p>I am asked to create a <code>carinfo</code> structure and a <code>createcarinfo()</code> function in order to make a database. But when trying to allocate memory for the arrays of the brand and model of the car, the terminal points out two errors. </p>
<p>For: </p>
<pre><code>newCar->brand =(char*)malloc(sizeof(char)*(strlen(brand) + 1));
newCar->model = (char*)malloc(sizeof(char)*(strlen(model) + 1));
</code></pre>
<p>it says that there is an error: assignment to expression with array type and an arrow pointing to the equal sign.</p>
<pre><code>struct carinfo_t {
char brand[40];
char model[40];
int year;
float value;
};
struct carinfo_t *createCarinfo(char *brand, char *model, int year, float value){
struct carinfo_t *newCar;
newCar=(struct carinfo_t*)malloc( sizeof( struct carinfo_t ) );
if (newCar){
newCar->brand =(char*)malloc(sizeof(char)*(strlen(brand) + 1));
newCar->model = (char*)malloc(sizeof(char)*(strlen(model) + 1));
strcpy(newCar->brand, brand);
strcpy(newCar->model, model);
//newCar->brand=brand;
//newCar->model=model;
newCar->year=year;
newCar->value=value;
}
return newCar;
};
</code></pre> | 0 |
Is it possible to pass parameters to a .dtsx package on the command line? | <p>I am currently executing an SSIS package (package.dtsx) from the command line using <code>Dtexec</code>.
This is as simple as:</p>
<pre><code>dtexec /f Package.dtsx
</code></pre>
<p>However, I have some parameters that I would like to pass to the package for it to use during execution. The documentation implies that this might be possible (i.e. the /Par parameter), but it is not clear.
Is it possible to pass parameters to a <code>.DTSX</code> file using <code>dtexec</code>?</p> | 0 |
How to assign a new class attribute via __dict__? | <p>I want to assign a class attribute via a string object - but how?</p>
<p>Example:</p>
<pre><code>class test(object):
pass
a = test()
test.value = 5
a.value
# -> 5
test.__dict__['value']
# -> 5
# BUT:
attr_name = 'next_value'
test.__dict__[attr_name] = 10
# -> 'dictproxy' object does not support item assignment
</code></pre> | 0 |
(Rails) What is "RJS"? | <p>I've seen "RJS" and "RJS templates" mentioned in passing in blog posts and tutorials. I did a search, but I'm still unsure about it. Is it a technology specific to Rails, rather than a standard like JSON or YAML?</p>
<p>I understand it's used for "generating JavaScript." Does it generate generic JS or Rails-specific JS requiring the Prototype and Scriptaculous libraries?</p> | 0 |
Static constructor equivalent in Objective-C? | <p>I'm new to Objective C and I haven't been able to find out if there is the equivalent of a static constructor in the language, that is a static method in a class that will automatically be called before the first instance of such class is instantiated. Or do I need to call the Initialization code myself?</p>
<p>Thanks</p> | 0 |
Effect of NOLOCK hint in SELECT statements | <p>I guess the real question is: </p>
<p>If I don't care about dirty reads, will adding the <strong>with (NOLOCK)</strong> hint to a SELECT statement affect the performance of:</p>
<ol>
<li>the current SELECT statement </li>
<li>other transactions against the given table</li>
</ol>
<p>Example:</p>
<pre><code>Select *
from aTable with (NOLOCK)
</code></pre> | 0 |
Since SQL Server doesn't have packages, what do programmers do to get around it? | <p>I have a SQL Server database that has a huge proliferation of stored procedures. Large numbers of stored procedures are not a problem in my Oracle databases because of the Oracle "package" feature.</p>
<p>What do programmers do to get around the lack of a "package" feature like that of Oracle?</p> | 0 |
Stop Excel from automatically converting certain text values to dates | <p>Does anyone happen to know if there is a token I can add to my csv for a certain field so Excel doesn't try to convert it to a date?</p>
<p>I'm trying to write a .csv file from my application and one of the values happens to look enough like a date that Excel is automatically converting it from text to a date. I've tried putting all of my text fields (including the one that looks like a date) within double quotes, but that has no effect.</p> | 0 |
SUM() based on a different condition to the SELECT | <p>Hi is there a way that I can do the SUM(total_points) based on a different condition to the rest of the SELECT statement, so I want the SUM(total_points) for every row which is <= to $chosentrack? but the rest of the conditions of the SELECT statement to be what they are below. I need them to all be returned together..as I am populating a league table.</p>
<p>Thanks a lot for any help.</p>
<pre><code>SELECT
members.member_id,
members.teamname,
SUM(total_points) as total_points,
total_points as last_race_points
FROM
members,
members_leagues,
member_results
WHERE
members.member_id = members_leagues.member_id
AND members_leagues.league_id = '$chosenleague'
AND member_results.track_id = '$chosentrack'
AND members_leagues.start_race = '$chosentrack'
AND member_results.member_id = members_leagues.member_id
GROUP BY
members.member_id
ORDER BY
member_results.total_points DESC,
last_race_points DESC,
members.teamname DESC
</code></pre> | 0 |
An efficient way of making a large random bytearray | <p>I need to create a large bytearry of a specific size but the size is not known prior to run time. The bytes need to be fairly random. The bytearray size may be as small as a few KBs but as large as a several MB. I do not want to iterate byte-by-byte. This is too slow -- I need performance similar to numpy.random. However, I do not have the numpy module available for this project. Is there something part of a standard python install that will do this? Or do i need to <a href="http://docs.python.org/extending/">compile my own using C</a>?</p>
<p>for those asking for timings:</p>
<pre><code>>>> timeit.timeit('[random.randint(0,128) for i in xrange(1,100000)]',setup='import random', number=100)
35.73110193696641
>>> timeit.timeit('numpy.random.random_integers(0,128,100000)',setup='import numpy', number=100)
0.5785652013481126
>>>
</code></pre> | 0 |
How to get rid of zeros in the section numbering in LATEX report document class? | <p>So I'm writing a report using Latex and the document class I am using is report:
\documentclass[a4paper]{report}</p>
<p>But for some reason the section numbering is written so that it is preceded with "0.", for example it looks like:</p>
<pre><code>0.1 Introduction
0.2 Theory
0.3 Experimental Method
</code></pre>
<p>and so on.</p>
<p>Can somebody help me get rid of those zeros so that it appears how it is supposed to be?</p> | 0 |
Submit form to action php file | <p>I have a form where when the user clicks submit, I need a php file to be ran. below is the form and the php file.</p>
<pre><code><form action="php_scripts/test.php" method="POST">
<input name="feature" type = "text" placeholder="Feature" />
<input name="feature2" type = "text" placeholder="Feature2" />
<input type="submit" value = "submit"/>
</form>
</code></pre>
<p>test.php</p>
<pre><code><?php
if( isset($_GET['submit']) )
{
$feature = $_POST['feature'];
// do stuff (will send data to database)
}
?>
</code></pre>
<p>The problem I am having is that when I press Submit on the form, </p>
<pre><code>if( isset($_GET['submit']) )
</code></pre>
<p>Always returns false. </p>
<p>Can anyone explain why that is? Have I totally misunderstood how to implement form sending data to php scripts?</p>
<p>Apologies if I have made any syntax errors and many thanks for any help you can give.</p> | 0 |
Pattern matching string prefixes in Haskell | <p>Let's say I want to make a special case for a function that matches strings that start with the character 'Z'. I could easily do it using pattern matching by doing something like the following:</p>
<pre><code>myfunc ('Z' : restOfString) = -- do something special
myfunc s = -- do the default case here
</code></pre>
<p>But what if I want to match strings with a longer prefix? Say I want to have a special case for strings that start with the word "toaster". What's the best way to write a pattern to match such a string?</p> | 0 |
What is the best way to manage configuration data | <p>I am working on a product suite which has 4 products. Right now, all of the configuration data is either in the XML or properties files.This approach is not maintainable as we have to manage different configuration file for different environment(for e.g. Production, Development etc).</p>
<p>So, <strong>what is the best way to handle configuration data?</strong></p>
<p>Also, can we modularize this into a separate module? So that all products can use this module.
We don't want to use the property files. I am looking for a solution in which we can move all of the configuration specific code as a new configuration module and persist all the configuration data in database.</p> | 0 |
What is a good 64bit hash function in Java for textual strings? | <p>I'm looking for a hash function that:</p>
<ol>
<li>Hashes <strong>textual strings</strong> well (e.g. few collisions)</li>
<li>Is written in Java, and widely used</li>
<li>Bonus: works on several fields (instead of me concatenating them and applying the hash on the concatenated string)</li>
<li>Bonus: Has a 128-bit variant.</li>
<li>Bonus: Not CPU intensive.</li>
</ol> | 0 |
HTTP debugging proxy for Linux and Mac | <p>I use the <a href="http://www.fiddler2.com/fiddler2/" rel="noreferrer">Fiddler</a> proxy to debug all kinds of HTTP issues on Windows. It's great for inspecting headers and responses across multiple pages.</p>
<p>Is there a good HTTP debugging proxy for Mac and Linux? I found <a href="http://www.charlesproxy.com/" rel="noreferrer">Charles</a>, but it's $50 once the trial runs out and it crashed on me. I could use <a href="http://www.wireshark.org/" rel="noreferrer">Wireshark</a>, but it's a pain.</p> | 0 |
SPARQL query to get all class label with namespace prefix defined | <p>I want to get all class that stored in sesame repository. </p>
<p>This is my query</p>
<pre><code>SELECT ?class ?classLabel
WHERE {
?class rdf:type rdfs:Class.
?class rdfs:label ?classLabel.
}
</code></pre>
<p>It's return all URI of class with label. For example, </p>
<pre><code>"http://example.com/A_Class" "A_Class"
"http://example.com/B_Class" "B_Class"
</code></pre>
<p>But, if namespace prefix already defined I want to get label with namespace defined. For example if I already defined namespace prefix "ex" for "<a href="http://example.com/" rel="nofollow">http://example.com/</a>", the result become</p>
<pre><code>"http://example.com/A_Class" "ex:A_Class"
"http://example.com/B_Class" "ex:B_Class"
</code></pre> | 0 |
Accept a word then print every letter of that word on new line in java? | <p>I need to write a program in Java that will accept a string/word then print every letter of that word on a new line. For example, the machine accepts <code>zip</code> then outputs:</p>
<pre><code>Z
I
P
</code></pre>
<p>How do you do this in java? Any simple method or way of doing this would be appreciated.</p>
<p>Here's what I have so far:</p>
<pre><code>import java.util.Scanner;
public class exercise_4{
public static void main(String [] args){
Scanner scan = new Scanner(System.in);
int a;
a = 0;
System.out.println("Please enter your words");
String word = scan.nextLine();
System.out.println(word.charAt(a));
}
}
</code></pre> | 0 |
Using Distinct with Linq to SQL | <p>How would this query be changed from sql to linq?</p>
<pre><code>category
select distinct prodCategory from table4
subcategory
SELECT distinct [prodSubCat] FROM [table4] WHERE ([prodCategory] = @prodCategory)
prodCategory prodSubCat
-------------------------------------
Home Cassette Receiver
Home Receiver
Home cd player
Home cd player
Home Receiver
Car dvd player
Car GPS
</code></pre>
<p>Ex.</p>
<p>My Goal is to get prodSubCat for prodCategory = "Car"</p>
<pre><code>Car dvd player
Car GPS
</code></pre> | 0 |
"img" must be terminated by the matching end-tag | <p>When parsing some an XSL XML file using docx4j, I keep receiving this error: </p>
<blockquote>
<p>'The element type "img" must be terminated by the matching end-tag <code>"</img>"</code>. Exception Error in Docx4JException'</p>
</blockquote>
<p>I have tried all sorts of combinations to solve the issue but nothing seems to work apart from putting some text in between the <code>img</code> tags. I don't want the text to display. Is there anything else that can be done?</p>
<p>This is the piece of xsl that is causing the error: </p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:prettyprint="http://xml.apache.org/xslt" xmlns:xalan="http://xml.apache.org/xalan" version="1.0">
<xsl:output method="html" />
<!-- Main entry template -->
<xsl:template match="Email">
<html>
<body>
<img width="100" height="100" src="http://thumbs.dreamstime.com/x/sun-logo-6350903.jpg" border="0" class="MyImage" />
<div style="font-family:Verdana, Arial; font-size:9.5pt; font-weight:normal">
<xsl:variable name="PTPTotalAmt" select="Issue_PTPTotalAmount_C" />
<xsl:variable name="LetterDate" select="LetterDate" />
<xsl:variable name="LtrDate" select="substring($LetterDate, 1, 11)" />
<br>
<xsl:text />
</br>
<xsl:value-of select="Contact_Title_R" />
<xsl:text />
<xsl:value-of select="Contact_LastName_X" />
<br>
<xsl:text />
</br>
<xsl:value-of select="Contact_DispAddrLine1_X" />
<br>
<xsl:text />
</br>
<xsl:value-of select="Contact_DispAddrLine3_X" />
<br>
<xsl:text />
</br>
<xsl:value-of select="Contact_DispAddrLine4_X" />
<br>
<xsl:text />
</br>
<xsl:value-of select="Contact_DispAddrLine5_X" />
<br>
<xsl:text />
</br>
<xsl:value-of select="Contact_DispAddrPostCode_X" />
<br>
<xsl:text />
</br>
<xsl:text />
<xsl:text />
<xsl:value-of select="$LtrDate" />
</div>
<br>
<xsl:text />
</br>
<br>
<xsl:text />
</br>
<br>
<xsl:text />
</br>
<br>
<xsl:text />
</br>
<div style="font-family:Verdana, Arial; font-size:8.5pt; font-weight:normal">
<br>
<xsl:text>Address Here</xsl:text>
</br>
</div>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
</code></pre> | 0 |
cmake is not working in opencv c++ project | <p>I need your help !
I have this C++ code in this link </p>
<p>[link] <a href="https://github.com/royshil/FoodcamClassifier" rel="noreferrer">https://github.com/royshil/FoodcamClassifier</a></p>
<p>and I've been trying since two days to compaile it , and I've failed
they say that I have to use cmake , I've tried the "GUI version and it gave me errors realted to the cmake itself .
so I took the cpp and header files and made a new project but I have now 100 errors related to the opencv library and I swear to god I'm sure of the include folders and the libs of it in my project ! don't know what's the matter with it !</p>
<h2>any idea ?</h2>
<p>Here's the errors : </p>
<pre>
'CMake Error: Unable to open cache file for save. C:/Program Files/CMake 2.8/bin/CMakeCache.txt
CMake Error at CMakeLists.txt:4 (FIND_PACKAGE):
Could not find module FindOpenCV.cmake or a configuration file for package
OpenCV.
Adjust CMAKE_MODULE_PATH to find FindOpenCV.cmake or set OpenCV_DIR to the
directory containing a CMake configuration file for OpenCV. The file will
have one of the following names:
OpenCVConfig.cmake
opencv-config.cmake
OpenCV_DIR-NOTFOUND
Configuring incomplete, errors occurred!
CMake Error: Unable to open cache file for save. C:/Program Files/CMake 2.8/bin/CMakeCache.txt
CMake Error: : System Error: Permission denied
CMake Error: : System Error: Permission denied '
</pre> | 0 |
PCL: Visualize a point cloud | <p>I'm trying to visualize a point cloud using <a href="http://pointclouds.org/" rel="nofollow noreferrer">PCL</a> CloudViewer. The problem is that I'm quite new to C++ and I have found two tutorials <a href="https://pcl.readthedocs.io/projects/tutorials/en/latest/writing_pcd.html#writing-pcd" rel="nofollow noreferrer">first</a> demonstrating the creation of PointCloud and <a href="https://pcl.readthedocs.io/projects/tutorials/en/latest/cloud_viewer.html#cloud-viewer" rel="nofollow noreferrer">second</a> demonstrating the visualization of a PointCloud. However, I'm not able to combine these two tutorials.</p>
<p>Here is what I have come up with:</p>
<pre><code>#include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/visualization/cloud_viewer.h>
int main (int argc, char** argv)
{
pcl::PointCloud<pcl::PointXYZ> cloud;
// Fill in the cloud data
cloud.width = 5;
cloud.height = 1;
cloud.is_dense = false;
cloud.points.resize (cloud.width * cloud.height);
for (size_t i = 0; i < cloud.points.size (); ++i)
{
cloud.points[i].x = 1024 * rand () / (RAND_MAX + 1.0f);
cloud.points[i].y = 1024 * rand () / (RAND_MAX + 1.0f);
cloud.points[i].z = 1024 * rand () / (RAND_MAX + 1.0f);
}
pcl::visualization::CloudViewer viewer ("Simple Cloud Viewer");
viewer.showCloud (cloud);
while (!viewer.wasStopped ())
{
}
return (0);
}
</code></pre>
<p>but that even do not compile:</p>
<pre><code>error: no matching function for call to
‘pcl::visualization::CloudViewer::showCloud(pcl::PointCloud<pcl::PointXYZ>&)’
</code></pre> | 0 |
SQLite: group_concat() multiple columns | <p>I has a problem:</p>
<p>In my SQLite (sqlite3 on android) database I have a table like so</p>
<pre><code>company | name | job
--------------------------
1 | 'Peter' | 'Manager'
1 | 'Jim' | (null)
2 | 'John' | 'CEO'
2 | 'Alex' | 'Developer'
3 | 'Lisa' | (null)
</code></pre>
<p>and I'd like to get to</p>
<pre><code>company | formated
--------------------------------------
1 | 'Peter (Manager), Jim'
2 | 'John (CEO), Alex (Developer)'
3 | 'Lisa'
</code></pre>
<p>What I got so far is</p>
<pre><code>SELECT group_concat(concat) FROM (
SELECT
CASE
WHEN job IS NULL THEN name
ELSE name || ' (' || job || ')'
END AS concat
FROM jobs
)
</code></pre>
<p>which gives me all in one string</p>
<pre><code>'Peter (Manager), Jim, John (CEO), Alex (Developer), Lisa'
</code></pre>
<p>Although that is quite good already, it's still not what I want. And at that point I fail to understand how I have to combine things to get what I want.</p>
<p>On a sidenote: Is there any good tutorial on complexer queries? So far I've only found some snippets but nothing that really explains how such a thing can be built</p> | 0 |
Hangfire recurring job daily on specific time | <p>I am trying to run hangfire recurring job daily on 9.00 AM. Here is what I want to do-</p>
<pre><code>RecurringJob.AddOrUpdate(() => MyMethod(), "* 9 * * *");
</code></pre>
<p>Where should I put this line of code?</p>
<p>Sorry if this is a foolish question.</p> | 0 |
Exclude file from "git diff" | <p>I am trying to exclude a file (<code>db/irrelevant.php</code>) from a Git diff. I have tried putting a file in the <code>db</code> subdirectory called <code>.gitattributes</code> with the line <code>irrelevant.php -diff</code>
and I have also tried creating a file called <code>.git/info/attributes</code> containing <code>db/irrelevant.php</code>. </p>
<p>In all cases, the <code>db/irrelevant.php</code> file is included in the diff as a Git binary patch. What I want is for the changes to that file to be ignore by the diff command. What am I doing wrong?</p> | 0 |
Xampp : server certificate does NOT include an ID which matches the server name | <p>I had both apache and mysql ok and running in xampp control panel. But then when i tried to load one of my php pages i was getting a fatal error : </p>
<pre><code>Call to undefined function mysql_connect().
</code></pre>
<p>Upon searching about this error i came across some answers. Mostly people suggested in the file php.ini to change extension_dir = "./" to extension_dir = "C:\php\ext" and uncomment the line ;extension=php_mysql.dll. </p>
<p>I tried that, but now when i try to restart apache i get </p>
<pre><code>error:apache shutdown unexpectedly
</code></pre>
<p>and in the logs it shows:</p>
<pre><code>server certificate does NOT include an ID which matches the server name
</code></pre>
<p>Does anybody know what i am suppose to do next? I have spent hours trying to solve this problem but to no avail. Your help will be appreciated.</p> | 0 |
How does setMaxResults(N) in Hibernate work? | <p>I am using MS SQL server 2008 with Hibernate. the question I have is how Hibernate implements <code>setMaxResults</code></p>
<p>Take the following simple scenario. </p>
<p>If I have a query that returns 100 rows and if I pass 1 to <code>setMaxResults</code>, will this affect the returned result from the SQL server itself(as if running a <code>select top 1</code> statement) or does Hibernate get all the results first (all 100 rows in this case) and pick the top one itself? </p>
<p>Reason I am asking is that it would have a huge performance issue when the number of rows starts to grow. </p>
<p>Thank you. </p> | 0 |
<GoogleMaps/GoogleMaps.h> file not found Google Maps SDK for iOS | <p>Yesterday I recived an email from google saying that I could acces to the map api for ios, I generated my key from the app console and I follow the steps of <a href="https://developers.google.com/maps/documentation/ios/start" rel="noreferrer">https://developers.google.com/maps/documentation/ios/start</a> but xcode throw this error.</p>
<pre><code>#import <GoogleMaps/GoogleMaps.h> //file not found
</code></pre>
<p>Thanks for your support.</p>
<p>It is normal that appears the Headers executable instead of the folder?</p>
<p><img src="https://i.stack.imgur.com/hMBBa.jpg" alt="enter image description here"></p>
<p>SOLVED!</p> | 0 |
Finding out the version of git on remote server | <p>I am looking for the git command on my local machine which i can run to find out the version of git running on the remote server?
If this is even possible.</p> | 0 |
How to rotate an image using Flutter AnimationController and Transform? | <p>I have star png image and I need to rotate the star using Flutter AnimationController and Transformer. I couldn't find any documents or example for image rotation animation. </p>
<p>Any idea How to rotate an image using Flutter AnimationController and Transform?</p>
<p>UPDATE:</p>
<pre><code>class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
AnimationController animationController;
@override
void initState() {
super.initState();
animationController = new AnimationController(
vsync: this,
duration: new Duration(milliseconds: 5000),
);
animationController.forward();
animationController.addListener(() {
setState(() {
if (animationController.status == AnimationStatus.completed) {
animationController.repeat();
}
});
});
}
@override
Widget build(BuildContext context) {
return new Container(
alignment: Alignment.center,
color: Colors.white,
child: new AnimatedBuilder(
animation: animationController,
child: new Container(
height: 80.0,
width: 80.0,
child: new Image.asset('images/StarLogo.png'),
),
builder: (BuildContext context, Widget _widget) {
return new Transform.rotate(
angle: animationController.value,
child: _widget,
);
},
),
);
}
}
</code></pre> | 0 |
Amazon WorkSpaces client "unable to connect" error message after login screen | <p>WorkSpaces client is showing the above error message after giving credentials in loginscreen and clicking on login.</p>
<pre><code>Amazon WorkSpaces
Unable to connect
We couldn't launch your WorkSpace. Please try again.
If you need help, contact your administrator.
</code></pre> | 0 |
cannot unpack non-iterable object / iteraing through array of objects in python | <p>I want to iterate through all objects in an array of URL objects I've got </p>
<pre><code>class Url(object):
pass
a = Url()
a.url = 'http://www.heroku.com'
a.result = 0
b = Url()
b.url = 'http://www.google.com'
b.result = 0
c = Url()
c.url = 'http://www.wordpress.com'
c.result = 0
urls = [a, b, c]
for i, u in urls:
print(i)
print(u)
</code></pre>
<p>However, when I run this script, it comes back with the following error:</p>
<pre><code>TypeError: cannot unpack non-iterable Url object
</code></pre>
<p>How do I fix this? </p> | 0 |
Nothing to commit, working tree clean after calling git checkout | <p>I tried to delete my last commit. I thought that <code>git checkout</code> followed by the hash of the <code>commit</code> would replace my current code with the code of the <code>commit</code>. This didn't work and I get now a message which says <code>Nothing to commit, working tree clean</code>. How can I get rid of this message and delete my last commit?</p> | 0 |
how to call href in Link Button in asp.net | <p>How to call href tag in Link Button</p>
<p>Suppose </p>
<pre><code> <asp:LinkButton ID="lnkViewAll" CssClass="button" runat="server" >
<span>View All</span>
</asp:LinkButton>
</code></pre>
<p>then How to Call The follow href in </p>
<pre><code> <a href="#dialog" name="modal">Simple Window Modal</a>
</code></pre>
<p>in Link Button onClientClick</p> | 0 |
Searching for HTML elements in Chrome DevTools | <p>On this website, there's a <code>div</code> with the attribute <code>class="item"</code>. When I clicked <kbd>F12</kbd> to bring up the Developer Tools. I pressed <kbd>Ctrl</kbd> + <kbd>F</kbd> and typed in <code>class="item"</code> and no results came back. I also tried <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>F</kbd> but nothing returned. Here is a screenshot:</p>
<p><img src="https://i.stack.imgur.com/b8kNC.png" alt="enter image description here"></p>
<p>Even if I search for <code>class=</code>, only text within HTML comments are found. <a href="https://english.stackexchange.com/a/49224/46898">Thanks in advance for any help you are able to provide.</a></p> | 0 |
Protect PDF docs from being directly accessed in URL | <p>I want to protect a pdf file from being directly linked but instead have my logged in users be able to access it. I have a link which currently goes to a javascript function which posts a form:
$('nameofdoc').setProperty('value',doc);
document.getElementById('sendme').submit();</p>
<p>where sendme is the name of the form and nameof doc the index of the document I want to display.</p>
<p>This then goes to a php file:</p>
<pre><code> $docpath = $holdingArray[0].$holdingArray[1];
$file = $holdingArray[0]; //file name
$filename = $holdingArray[1]; //path to the file]
header( 'Location:'.$docpath ) ;
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="'.$filename . '"');
readfile($filename)
</code></pre>
<p>This all works fine it loads up the file and outputs the pdf. What I can't do is protect the directory from direct linking - ie www.mydomain.com/pathToPdf/pdfname.pdf</p>
<p>I've thought of using .htaccess to protect the directory but it's on a shared host so I'm not sure about the security and anyway when I've tried I can't get it to work.</p>
<p>Any help would be great since this is my fourth day of trying to fix this.</p>
<p>thanks</p>
<p>Update</p>
<p>I've had a lot of help thank you but I'm not quite there yet.</p>
<p>I've got an .htaccess file that now launches another php file when a pdf is requested from the directory:</p>
<pre><code> RewriteEngine on
RewriteRule ^(.*).(pdf)$ fileopen.php
</code></pre>
<p>When the fileopen.php file lauches it fails to open the pdf</p>
<pre><code> $path = $_SERVER['REQUEST_URI'];
$paths = explode('/', $path);
$lastIndex = count($paths) - 1;
$fileName = $paths[$lastIndex];
$file = basename($path);
$filepath = $path;
if (file_exists($file)) {
header( 'Location: http://www.mydomain.com'.$path ) ;
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=".$file);
readfile($filepath);
}else{
echo "file not found using path ".$path." and file is ".$file;
}
</code></pre>
<p>The output is
file not found using path /documents/6/Doc1.pdf and file is Doc1.pdf</p>
<p>but the file does exist and is in that direcotry - any ideas??</p>
<p>OKAY I'm happy to report that Jaroslav really helped me sort out the issue. His method works well but it is tricky to get all the directory stuff lined up. In the end I spent a few hours playing about with combinations to get it working but the principle he gave works well. Thanks</p> | 0 |
'CSV does not exist' - Pandas DataFrame | <p>I'm having difficulty reading a csv file into the pandas data frame. I am a total newcomer to pandas, and this is preventing me from progressing. I have read the documentation and searched for solutions, but I am unable to proceed. I have tried the following to no avail...</p>
<pre><code>import pandas as pd
import numpy as np
pd.read_csv('C:\Users\rcreedon\Desktop\TEST.csv')
pd.read_csv("C:\Users\rcreedon\Desktop\TEST.csv")
</code></pre>
<p>and similar permutations with/without quotation marks. </p>
<p>It spits out a large composite error that ends in:</p>
<pre><code>IOError: File C:\Users
creedon\Desktop\TEST.csv does not exist
</code></pre>
<p>It seems strange that in the error it misses of the "r" from "rcreedon". Is this what's causing the problem?</p>
<p>Just for the sake of it i also tried</p>
<pre><code>pd.read_csv('C:\rcreedon\Desktop\TEST.csv')
</code></pre>
<p>And again the 'r' was missed when the error was returned.</p>
<p>Sorry to be such a block head, but I'm struggling here....</p>
<p>Any help appreciated. </p> | 0 |
Curl authorization | <p>I have spring security with https settings.</p>
<p>I'm seeing an unexpected behavior when trying to run curl GET on a URL in a secure way.</p>
<p>When curl first sends a request to the server, it does it with no authorization data (why? I specifically added it). Then, the server reply with Authentication Error (401).
The client then re-transmits the request, this time with authorization data, and the server replies properly with the required data.</p>
<p>Any idea why this happens?</p>
<p>Curl command:</p>
<blockquote>
<p>curl -v --insecure --anyauth --user username:password -H "Accept: application/json" -H "Content-Type: application/json" -X GET localhost:8443/myresource</p>
</blockquote>
<p><strong>Request 1:</strong></p>
<pre><code>> GET /myresource HTTP/1.1
> User-Agent: curl/7.21.3 (x86_64-redhat-linux-gnu) libcurl/7.21.3 NSS/3.13.1.0 zlib/1.2.5 libidn/1.19 libssh2/1.2.7
> Host: localhost:8443
> Accept: application/json
> Content-Type: application/json
</code></pre>
<p><strong>Response 1:</strong></p>
<pre><code>< HTTP/1.1 401 Unauthorized
< Server: Apache-Coyote/1.1
< Set-Cookie: JSESSIONID=B56A7F49E715795B5D1158DB192710AA; Path=/myresource ; Secure; HttpOnly
< WWW-Authenticate: Digest realm="Protected", qop="auth", nonce="MTM0Njg2MjYwMjY0ODozNDk5ZDkxNTYxNjMxMDJmNDA4MWQ1NTBmZjk5OGQ5Nw=="
< Content-Type: text/html;charset=utf-8
< Content-Length: 1119
< Date: Wed, 05 Sep 2012 16:29:52 GMT
</code></pre>
<p><strong>Request 2:</strong></p>
<pre><code>> GET /myresource HTTP/1.1
> Authorization: Digest username="username", realm="Protected", nonce="MTM0Njg2MjYwMjY0ODozNDk5ZDkxNTYxNjMxMDJmNDA4MWQ1NTBmZjk5OGQ5Nw==", uri="/myresource", cnonce="ODczNjg0", nc=00000001, qop="auth", response="58faded9ae5f639ba0056fb86edca71f"
> User-Agent: curl/7.21.3 (x86_64-redhat-linux-gnu) libcurl/7.21.3 NSS/3.13.1.0 zlib/1.2.5 libidn/1.19 libssh2/1.2.7
> Host: localhost:8443
> Accept: application/json
> Content-Type: application/json
</code></pre>
<p><strong>Response 2:</strong></p>
<pre><code>< HTTP/1.1 200 OK
< Server: Apache-Coyote/1.1
< Set-Cookie: JSESSIONID=37F375C5663C4A049D95D49C7C1CF0FD; Path=/myresource ; Secure; HttpOnly
< Content-Type: application/json
< Transfer-Encoding: chunked
< Date: Wed, 05 Sep 2012 16:29:52 GMT
</code></pre> | 0 |
Springboot could not extract ResultSet | <p>Currently I am getting a problem with fetching mysql data for my springboot project:</p>
<p>There was an unexpected error (type=Internal Server Error, status=500).
could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet</p>
<p><strong>TestEntity.java</strong></p>
<pre><code>@Entity
public class TestEntity implements Serializable {
@Id
private int id;
private String p1;
private String p2;
private String p3;
public TestEntity() {
}
public TestEntity(int id, String p1, String p2, String p3){
this.id = id;
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getP1() {
return p1;
}
public void setP1(String p1) {
this.p1 = p1;
}
public String getP2() {
return p2;
}
public void setP2(String p2) {
this.p2 = p2;
}
public String getP3() {
return p3;
}
public void setP3(String p3) {
this.p3 = p3;
}
}
</code></pre>
<p><strong>TestService.java</strong></p>
<pre><code>@Service
public class TestService {
@Autowired
private TestRepository testRepository;
public ArrayList<TestEntity> getAllTestEntities(){
ArrayList<TestEntity> list = new ArrayList();
testRepository.findAll().forEach(list::add);
return list;
}
public Optional getTestEntity(int id){
return testRepository.findById(id);
}
public void addTestEntity(TestEntity t){
testRepository.save(t);
}
public void removeTestEntity(int index){
testRepository.deleteById(index);
}
}
</code></pre>
<p><strong>TestRepository.java</strong></p>
<pre><code>@Repository("mysql")
public interface TestRepository extends CrudRepository<TestEntity,Integer> {
}
</code></pre>
<p><strong>TestController.java</strong></p>
<pre><code>@RestController
public class TestController {
@Autowired
private TestService testService;
@RequestMapping("/test/AllUnits")
public ArrayList<TestEntity> getAllTestUnits(){
return testService.getAllTestEntities();
}
@RequestMapping("/test/{id}")
public Optional getAllTestUnit(@PathVariable int id){
return testService.getTestEntity(id);
}
@RequestMapping(method=RequestMethod.POST,value = "/test" )
public void addTestUnit(@RequestBody TestEntity t){
testService.addTestEntity(t);
}
@RequestMapping(method=RequestMethod.DELETE,value = "/test/{id}" )
public void deleteTestUnit(@RequestBody Integer id){
testService.removeTestEntity(id);
}
@RequestMapping("/test/welcome")
public String welcome(){
return "welcome to springboot";
}
}
</code></pre>
<p><strong>Edit</strong>: <strong>application.properties</strong></p>
<pre><code>cloud.aws.region.auto=true
cloud.aws.region.static=us-east-2
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://alyxdev.czcdgqfkwsnr.us-east-2.rds.amazonaws.com:3306/CryptoCurrency
spring.datasource.username=*******
spring.datasource.password=*******
</code></pre>
<p>I am able to get the /test/welcome mapping working so I believe my implementation of the service and controller is correct. So I am wondering if I made a mistake for accessing my database in my repository or should I use a JpaRepository instead of a CrudRepository and use an explicit query?</p>
<p><strong>Edit Stack Trace</strong>:
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'CryptoCurrency.test_entity' doesn't exist</p> | 0 |
Add http(s) to URL if it's not there? | <p>I'm using this regex in my model to validate an URL submitted by the user. I don't want to force the user to type the http part, but would like to add it myself if it's not there.</p>
<pre><code>validates :url, :format => { :with => /^((http|https):\/\/)?[a-z0-9]+([-.]{1}[a-z0-9]+).[a-z]{2,5}(:[0-9]{1,5})?(\/.)?$/ix, :message => " is not valid" }
</code></pre>
<p>Any idea how I could do that? I have very little experience with validation and regex..</p> | 0 |
merge two arrays (keys and values) into an object | <p>Is there a common Javascript/Coffeescript-specific idiom I can use to accomplish this? Mainly out of curiosity.</p>
<p>I have two arrays, one consisting of the desired keys and the other one consisting of the desired values, and I want to merge this in to an object.</p>
<pre><code>keys = ['one', 'two', 'three']
values = ['a', 'b', 'c']
</code></pre> | 0 |
LINQ to find the closest number that is greater / less than an input | <p>Suppose I have this number list:</p>
<pre><code>List<int> = new List<int>(){3,5,8,11,12,13,14,21}
</code></pre>
<p>Suppose that I want to get the closest number that is less than 11, it would be 8
Suppose that I want to get the closest number that is greater than 13 that would be 14.</p>
<p>The numbers in list can't be duplicated and are always ordered. How can I write Linq for this?</p> | 0 |
OpenCV Kalman Filter python | <p>Can anyone provide me a sample code or some sort of example of Kalman filter implementation in python 2.7 and openCV 2.4.13 </p>
<p>I want to implement it in a video to track a person but, I don't have any reference to learn and I couldn't find any python examples.</p>
<p>I know Kalman Filter exists in openCV as cv2.KalmanFilter but I have no idea how to use it. Any guidance would be appreciated </p> | 0 |
Disable editing in a JTextPane while allowing visible cursor movement | <p>I have a <code>JTextPane</code> which is populated by reading from a file, after which the data is parsed and formatted. The user is not allowed to edit the <code>JTextPane</code>, but I want them to be able to navigate in it with a visible cursor.</p>
<p>If I use <code>setEditable(false)</code>, the cursor is invisible, although it is possible to indirectly observe the position of the invisible cursor by holding down <strong><em>Shift</em></strong> and using the arrow keys to select a block of text.</p>
<p>To enable a visible cursor while disallowing editing, instead of <code>setEditable(false)</code> I created a dummy <code>DocumentFilter</code> that simply does nothing for its <code>insertString()</code>, <code>remove()</code>, and <code>replace()</code> methods. But then I have to swap in a regular filter in order to programmatically populate the <code>JTextPane</code> from a file, then put back the dummy filter right before returning control to the user.</p>
<p>So far this seems to work, but is there a simpler solution? If I leave this as is, is there any sequence of keystrokes or mouse activity that could somehow allow the user to edit the text pane, given that it is technically editable as per <code>setEditable</code>?</p> | 0 |
Codeigniter, Call SweetAlert in Controller | <p>I have searching in various webpages, but no one has clear or solve my problem... I come with the expertes, because i need your help... :(</p>
<p>This is my User Controller Method</p>
<pre><code><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class UserController extends CI_Controller {
function __construct()
{
parent::__construct();
}
function new_user_register(){
$this->form_validation->set_rules('primernombre', 'First Name','trim|required|alpha|min_length[3]|max_length[100]|xss_clean');
$this->form_validation->set_rules('primerapellido', 'Last Name', 'trim|required|alpha|min_length[3]|max_length[100]|xss_clean');
$this->form_validation->set_rules('nombreusuario','Username','trim|required|xss_clean');
$this->form_validation->set_rules('email','Email','trim|required|valid_email|is_unique[cat_tbl_usuario.email]|xss_clean');
$this->form_validation->set_rules('clave','Password','trim|required|matches[claveConfirmacion]|md5');
$this->form_validation->set_rules('claveConfirmacion','Confirm Password','trim|required|md5|matches[clave]');
if ($this->form_validation->run() == FALSE) {
echo "<script language=\"javascript\">
swal('Please adjust the values in user' , 'Bad data format', 'error');
</script>";
}
}
?>
</code></pre>
<p>Basically i load my view into a iFrame(FANCYBOX), and i click in the OK button, call the Method new_user_register, and if the validation it's false, then the SWEETALERT, should come out saying the error, except that in the console said that swald isn't defined. And the examples i search aren't too clear to me.</p> | 0 |
NLTK tokenize - faster way? | <p>I have a method that takes in a String parameter, and uses NLTK to break the String down to sentences, then into words. Afterwards, it converts each word into lowercase, and finally creates a dictionary of the frequency of each word.</p>
<pre><code>import nltk
from collections import Counter
def freq(string):
f = Counter()
sentence_list = nltk.tokenize.sent_tokenize(string)
for sentence in sentence_list:
words = nltk.word_tokenize(sentence)
words = [word.lower() for word in words]
for word in words:
f[word] += 1
return f
</code></pre>
<p>I'm supposed to optimize the above code further to result in faster preprocessing time, and am unsure how to do so. The return value should obviously be exactly the same as the above, so I'm expected to use nltk though not explicitly required to do so.</p>
<p>Any way to speed up the above code? Thanks.</p> | 0 |
ComboBox DataBinding causes ArgumentException | <p><br>
I several objects of class:</p>
<pre><code>class Person
{
public string Name { get; set; }
public string Sex { get; set; }
public int Age { get; set; }
public override string ToString()
{
return Name + "; " + Sex + "; " + Age;
}
}
</code></pre>
<p>and a class that has a property of type <code>Person</code>:</p>
<pre><code>class Cl
{
public Person Person { get; set; }
}
</code></pre>
<p>And I want to bind <code>Cl.Person</code> to combobox. When I try to do it like this:</p>
<pre><code>Cl cl = new cl();
comboBox.DataSource = new List<Person> {new Person{Name = "1"}, new Person{Name = "2"}};
comboBox.DataBindings.Add("Item", cl, "Person");
</code></pre>
<p>I get an <code>ArgumentException</code>. How should I modify my binding to get the correct program behavior?<br>
Thanks in advance!</p> | 0 |
Java Extracting values from text files | <p>I have many text files (up to 20) and each file has it's contents like this </p>
<pre><code>21.0|11|1/1/1997
13.3|12|2/1/1997
14.6|9|3/1/1997
</code></pre>
<p>and every file has approximately more than 300 lines.</p>
<p>so the problem I'm facing is this, how can I extract all and only the first values
of the file's content. </p>
<p>for example I want to extract the values (21.0,13.3,14.6.....etc) so I can decide the max number and minimum in all of the 20 files.</p>
<p>I have wrote this code from my understanding to experience it on of the files
but it didn't work </p>
<pre><code> String inputFileName = "Date.txt";
File inputFile = new File(inputFileName);
Scanner input = new Scanner(inputFile);
int count = 0;
while (input.hasNext()){
double line = input.nextDouble(); //Error occurs "Exception in thread "main" java.util.InputMismatchException"
count++;
double [] lineArray= new double [365];
lineArray[count]= line;
System.out.println(count);
for (double s : lineArray){
System.out.println(s);
System.out.println(count);
</code></pre>
<p>and this one too</p>
<pre><code> String inputFileName = "Date.txt";
File inputFile = new File(inputFileName);
Scanner input = new Scanner(inputFile);
while (input.hasNext()){
String line = input.nextLine();
String [] lineArray = line.split("//|");
for (String s : lineArray){
System.out.println(s+" ");
}
</code></pre>
<ul>
<li>Note: I'm still kind of a beginner in Java</li>
</ul>
<p>I hope I was clear and thanks </p> | 0 |
printf raw data -- get printf or print to NOT send characters | <p>I have a Xilinx Virtex-II Pro FPGA board that is attached via RS232 to an iRobot Create.</p>
<p>The iRobot takes a stream of byte integers as commands.</p>
<p>I've found that printf will actually send over the serial port (Hypterminal is able to pick up whatever I print), and I figure that I can use printf to send my data to the iRobot.</p>
<p>The problem is that printf seems to format the data for ascii output, but I'd REALLY like it to simply send out the data raw.</p>
<p>I'd like something like:</p>
<pre><code>printf(%x %x %x, 0x80, 0x88, 0x08);
</code></pre>
<p>But instead of the hexadecimal getting formatted, I'd like it to be the actual 0x80 value sent.</p>
<p>Any ideas?</p> | 0 |
AWS Glue Crawler - Reading a gzip file of csv | <p>Can you please help me with reading a tar.gz file using Glue Data crawler please? I have a tar.gz file which contains couple of files in different schema in my S3, and when I try to run a crawler, I don't see the schema in the data catalogue. Should we use any custom classifiers? The AWS Glue FAQ specifies that gzip is supported using classifiers, but is not listed in the classifiers list provided in the Glue Classifier sections.</p> | 0 |
Local Temporary table in Oracle 10 (for the scope of Stored Procedure) | <p>I am new to oracle. I need to process large amount of data in stored proc. I am considering using Temporary tables. I am using connection pooling and the application is multi-threaded. </p>
<p>Is there a way to create temporary tables in a way that different table instances are created for every call to the stored procedure, so that data from multiple stored procedure calls does not mix up?</p> | 0 |
What is the difference between wsHttpBinding and ws2007HttpBinding? | <p>On the MSDN we can read :</p>
<blockquote>
<p>The WS2007HttpBinding class adds a system-provided binding similar to WSHttpBinding but uses the Organization for the Advancement of Structured Information Standards (OASIS) standard versions of the ReliableSession, Security, and TransactionFlow protocols. No changes to the object model or default settings are required when using this binding.</p>
</blockquote>
<p>But I don't find any documentation which can explain me WHY I would like to move wsHttpBinding to ws2007HttpBinding, it seems to me that the standard are the same.</p>
<p>Can someone can give me a good explanation ?</p> | 0 |
What is best practice for serializing Java enums to XML? | <p>Hi I have a Java enum and I want serialize a variable containing an enum value back and forth from XML for persistence. My enum is defined like this...</p>
<pre><code>public enum e_Type
{
e_Unknown,
e_Categoric,
e_Numeric
}
</code></pre>
<p>My variable is declared like this...</p>
<pre><code>private e_Type type;
</code></pre>
<p>I want it to go into an XML tag like this...</p>
<pre><code><type>value</type>
</code></pre>
<p>What's the best practice for persisting values of enums in XML?</p> | 0 |
How would I use ON DUPLICATE KEY UPDATE in my CodeIgniter model? | <p>I have a CodeIgniter/PHP Model and I want to insert some data into the database.</p>
<p>However, I have this set in my 'raw' SQL query:</p>
<pre><code>ON DUPLICATE KEY UPDATE duplicate=duplicate+1
</code></pre>
<p>I am using CodeIgniter and am converting all my previous in-controller SQL queries to <strong>ActiveRecord</strong>. Is there any way to do this from within the ActiveRecord-based model?</p>
<p>Thanks!</p>
<p>Jack</p> | 0 |
How to load ~/.bash_profile when entering bash from within zsh? | <p>I've used bash for two years, and just tried to switch to zsh shell on my OS X via homebrew. And I set my default (login) shell to zsh, and I confirmed it's set properly by seeing that when I launch my Terminal, it's zsh shell that is used in default.</p>
<p>However, when I try to enter bash shell from within zsh, it looks like not loading <code>~/.bash_profile</code>, since I cannot run my command using aliases, which is defined in my <code>~/.bash_profile</code> like <code>alias julia="~/juila/julia"</code>, etc.. Also, the prompt is not what I set in the file and instead return <code>bash-3.2$</code>.</p>
<p>For some reasons, when I set my login shell to bash, and enter zsh from within bash, then <code>~/.zshrc</code> is loaded properly.</p>
<p>So why is it not loaded whenever I run <code>bash</code> from within zsh? My <code>~/.bash_profile</code> is symbolic linked to <code>~/Dropbox/.bash_profile</code> in order to sync it with my other computers. Maybe does it cause the issue?</p> | 0 |
PHP iMagick image compression | <p>I'm fairly new to iMagick and have only found very limited documentation on the PHP library. I'm happily resizing images and writing them back to the hard drive, but I'm failing completely to compress the images using JPG for instance.</p>
<p>This is the code I'm using so far:</p>
<pre><code>function scale_image($size = 200,$extension)
{
if(!file_exists(ALBUM_PATH . $this->path . $this->filename . $extension))
{
$im = new imagick(ALBUM_PATH . $this->path . $this->filename);
$width = $im->getImageWidth();
$height = $im->getImageHeight();
if($width > $height)
$im->resizeImage($size, 0, imagick::FILTER_LANCZOS, 1);
else
$im->resizeImage(0 , $size, imagick::FILTER_LANCZOS, 1);
$im->setImageCompression(true);
$im->setCompression(Imagick::COMPRESSION_JPEG);
$im->setCompressionQuality(20);
$im->writeImage(ALBUM_PATH . $this->path . $this->filename . $extension);
$im->clear();
$im->destroy();
}
}
</code></pre> | 0 |
How to get all the variables of a groovy object or class? | <p>To see list of methods in a class I can do this - </p>
<pre><code>String.methods.each {println it}
</code></pre>
<p>How do I list all the variables of an instance or all the static variables of a class?</p>
<p><strong>Edit1:</strong></p>
<p><img src="https://i.stack.imgur.com/hWDJJ.png" alt="enter image description here"></p>
<p><img src="https://i.stack.imgur.com/0JCJd.png" alt="enter image description here"></p>
<p><strong>Edit2:</strong></p>
<p>HoneyBadger.java</p>
<pre><code>public class HoneyBadger {
public int badassFactor;
protected int emoFactor;
private int sleepTime;
}
</code></pre>
<p>test.groovy - </p>
<pre><code>HoneyBadger.metaClass.properties.each {println it.name }
</code></pre>
<p>Output - </p>
<pre><code>class
</code></pre> | 0 |
Using Google Guice to inject java properties | <p>I want to use google guice to make properties available in all classes of my application. I defined a Module which loads and binds the properties file <em>Test.properties</em>.</p>
<pre><code>Property1=TEST
Property2=25
</code></pre>
<p>package com.test;</p>
<pre><code>import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import com.google.inject.AbstractModule;
import com.google.inject.name.Names;
public class TestConfiguration extends AbstractModule {
@Override
protected void configure() {
Properties properties = new Properties();
try {
properties.load(new FileReader("Test.properties"));
Names.bindProperties(binder(), properties);
} catch (FileNotFoundException e) {
System.out.println("The configuration file Test.properties can not be found");
} catch (IOException e) {
System.out.println("I/O Exception during loading configuration");
}
}
}
</code></pre>
<p>I'm using a main class where I create a injector to inject the properties.</p>
<pre><code>package com.test;
import com.google.inject.Guice;
import com.google.inject.Injector;
public class Test {
public static void main(String[] args) {
TestConfiguration config = new TestConfiguration();
Injector injector = Guice.createInjector(config);
TestImpl test = injector.getInstance(TestImpl.class);
}
}
package com.test;
import com.google.inject.Inject;
import com.google.inject.name.Named;
public class TestImpl {
private final String property1;
private final Integer property2;
@Inject
public TestImpl(@Named("Property1") String property1, @Named("Property2") Integer property2) {
System.out.println("Hello World");
this.property1 = property1;
this.property2 = property2;
System.out.println(property1);
System.out.println(property2);
}
}
</code></pre>
<p>Now my question. If my TestImpl creates other classes where I also need to inject properties, and those classes also need to inject properties what is the correct way to do this?</p>
<ol>
<li><p>Pass the injector to all subclasses and then use injector.getInstance(...) to create the subclasses?</p></li>
<li><p>Instanciate a new injector like</p>
<pre><code>TestConfiguration config = new TestConfiguration();
Injector injector = Guice.createInjector(config);
TestImpl test = injector.getInstance(TestImpl.class);
</code></pre></li>
</ol>
<p>in all nested classes?</p>
<ol>
<li>Is there an other approach to make the properties available in all classes? </li>
</ol> | 0 |
List all websites in IIS c# | <p>Is there a way to list all active websites that exist within IIS using c#?</p>
<p>Thanks</p>
<p>Sp</p> | 0 |
Is there a data structure like the Java Set in JavaScript? | <p>I want to use a data structure in JavaScript that can be used to store number of IDs. I should be able to check if a key already exists in that set, something like Java Sets.</p>
<p>I want to achive same behaviours as follows (this code is in Java):</p>
<pre><code>Set<String> st = new HashSet<String>();
//add elemets
if(st.contains("aks") ){
//do something
}
</code></pre>
<p>I want a JavaScript/dojo equivalent of the above code.</p> | 0 |
How can I always round up decimal values to the nearest integer value? | <p>On a report I have the following code for a field:</p>
<pre><code>=Sum([PartQty]*[ModuleQty])
</code></pre>
<p>Example results are <code>2.1</code> and <code>2.6</code>. What I need is for these value to round up to the value of <code>3</code>. How can I change my field code to always round up the results of my current expression?</p> | 0 |
HTML5 Audio stop function | <p>I am playing a small audio clip on click of each link in my navigation</p>
<p>HTML Code:</p>
<pre><code><audio tabindex="0" id="beep-one" controls preload="auto" >
<source src="audio/Output 1-2.mp3">
<source src="audio/Output 1-2.ogg">
</audio>
</code></pre>
<p>JS code:</p>
<pre><code>$('#links a').click(function(e) {
e.preventDefault();
var beepOne = $("#beep-one")[0];
beepOne.play();
});
</code></pre>
<p>It's working fine so far.</p>
<p><strong>Issue is when a sound clip is already running and i click on any link nothing happens.</strong></p>
<p>I tried to stop the already playing sound on click of link, but there is no direct event for that in HTML5's Audio API</p>
<p>I tried following code but it's not working</p>
<pre><code>$.each($('audio'), function () {
$(this).stop();
});
</code></pre>
<p>Any suggestions please?</p> | 0 |
Prevent p:inputNumber adding a decimal point and 2 zeros when not explicitly entered? | <p>need help with primefaces input number</p>
<pre><code><p:inputNumber id="test" value="#{test}" thousandSeparator=""/>
</code></pre>
<p>If my input is like this:</p>
<pre><code>100
</code></pre>
<p>The number field adds a decimal point and 2 zeros like this:</p>
<pre><code>100.00
</code></pre>
<p>Is there a way of restricting this? The user can input decimal points but if the user didn't, there is no need to add a decimal point and the 2 zeros.</p>
<p>Thanks!</p> | 0 |
experimental_list_devices attribute missing in tensorflow_core._api.v2.config | <p>Am using tensorflow 2.1 on Windows 10. On running</p>
<pre><code>model.add(Conv3D(16, (22, 5, 5), strides=(1, 2, 2), padding='valid',activation='relu',data_format= "channels_first", input_shape=input_shape))
</code></pre>
<p>on spyder, I get the this error:</p>
<pre><code>{ AttributeError: module 'tensorflow_core._api.v2.config' has no attribute 'experimental_list_devices' }
</code></pre>
<p>How can I solve this error?</p> | 0 |
Redux Toolkit and Axios | <p>I'm using Redux Toolkit to connect to an API with Axios.
I'm using the following code:</p>
<pre><code>const products = createSlice({
name: "products",
initialState: {
products[]
},
reducers: {
reducer2: state => {
axios
.get('myurl')
.then(response => {
//console.log(response.data.products);
state.products.concat(response.data.products);
})
}
}
});
</code></pre>
<p>axios is connecting to the API because the commented line to print to the console is showing me the data. However, the state.products.concat(response.data.products); is throwing the following error:</p>
<p>TypeError: Cannot perform 'get' on a proxy that has been revoked</p>
<p>Is there any way to fix this problem?</p> | 0 |
Spring Rest Controller find by id/ids methods | <p>I have the following method in my Spring RestController:</p>
<pre><code>@RequestMapping(value = "/{decisionId}", method = RequestMethod.GET)
public DecisionResponse findById(@PathVariable @NotNull @DecimalMin("0") Long decisionId) {
....
}
</code></pre>
<p>Right now I need to add the possibility to find a set of DecisionResponse by <code>{decisionIds}</code>.. something like this:</p>
<pre><code>@RequestMapping(value = "/{decisionIds}", method = RequestMethod.GET)
public List<DecisionResponse> findByIds(@PathVariable @NotNull @DecimalMin("0") Set<Long> decisionIds) {
....
}
</code></pre>
<p>The following two methods don't work together.</p>
<p>What is a correct way of implementing this functionality? Should I leave only one method(second) that waits for <code>{decisionIds}</code> and returns a collection even when I need only 1 <code>Decision</code> object? Is there another proper way to implement this?</p> | 0 |
remote: Forbidden fatal: unable to access | <p>I have access to repo, I clone it by https, then I made my changes and I commit those change and create <code>new_branch</code> and try to push I got this:</p>
<pre><code>git push origin new_branch
remote: Forbidden
fatal: unable to access 'https://username@bitbucket.org/main-account/repo.git/': The requested URL returned error: 403
</code></pre>
<p>I already setup my SSH key, git global config and already logged</p>
<pre><code>ssh -T username@bitbucket.org
logged in as username
You can use git or hg to connect to Bitbucket. Shell access is disabled
</code></pre>
<p>also, I tried to change the url</p>
<pre><code>git remote set-url origin git@bitbucket.org:main-account/repo.git
</code></pre>
<p>and when I push I got this</p>
<pre><code>git push origin new_branch
Forbidden
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
</code></pre>
<p>and finally my <code>~/.ssh/config</code></p>
<pre><code>Host *
UseKeychain yes
Host bitbucket.org
HostName bitbucket.org
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa
</code></pre>
<p>Any help?
Thanks in advance </p> | 0 |
sencha touch :: adding a background-image to a Panel | <p>I try to add an image to the background of a panel. the image comes from loaded data.
i tried the following code, which did not work:</p>
<pre><code>var topPanel = new Ext.Panel({
flex:1,
title:'topPanel',
style:'style="background-image: url('+this.jsonData.picURL+');'
});
</code></pre>
<p>when I create a list it work great with 'itemTpl'.</p>
<p>I also tried </p>
<pre><code>style:'background-image: url({picURL});'
</code></pre>
<p>together with</p>
<pre><code>store: {
fields: ['firstName','lastName', 'picURL'],
data: this.jsondData
}
</code></pre>
<p>but then I get the message</p>
<blockquote>
<p>[[object Object]] is not a valid
argument for
'Function.prototype.apply'.</p>
</blockquote>
<p>any thoughts could help!
thnx</p> | 0 |
phpunit mock method multiple calls with different arguments | <p>Is there any way to define different mock-expects for different input arguments? For example, I have database layer class called DB. This class has method called "Query ( string $query )", that method takes an SQL query string on input. Can I create mock for this class (DB) and set different return values for different Query method calls that depends on input query string?</p> | 0 |
Is there a WEBGL Manual? | <p>Is there some kind of WebGL manual that lists all the functions etc. ? I tried Google but found nothing.</p> | 0 |
How to change text color and console color in code::blocks? | <p>I am writing a program in C. I want to change the text color and background color in the console. My sample program is - </p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <dos.h>
#include <dir.h>
int main(int argc,char *argv[])
{
textcolor(25);
printf("\n \n \t This is dummy program for text color ");
getch();
return 0;
}
</code></pre>
<p>When I compile this program code::blocks gives me an error - textcolor not defined. Why is this so? I work in a GNU GCC compiler and Windows Vista. If it is not going to work what is the duplicate of textcolor. Like that I want to change the background color of the console. The compiler gives me the same error just the name of the function is different. How to change the color of the console and text. Please help.</p>
<p>I am okay even if the answer is in C++.</p> | 0 |
Get list of filenames in assets folder with Typescript | <p>How do I get all filenames in a folder using Typescript?
It's for an angular 2 project.</p>
<p>To be more specific, what I'm trying to do is set the images for a bootstrap carousel using images from my photos folder. Currently I'm doing this:</p>
<pre><code>private _images: Image[] = []
ngOnInit(): void {
this._images = [
{ "title": "Slide 1", "url": "../photos/carousel/gg_slide 1.jpg" },
{ "title": "Slide 2", "url": "../photos/carousel/gg_slide 2.jpg" },
{ "title": "Slide 3", "url": "../photos/carousel/gg_slide 3.jpg" },
{ "title": "Slide 4", "url": "../photos/carousel/gg_slide 4.jpg" },
{ "title": "Slide 5", "url": "../photos/carousel/gg_slide 5.jpg" }
]
}//ngOnInit
</code></pre>
<p>Then using the the images array in the html file like this:</p>
<pre><code><carousel>
<slide *ngFor="let img of _images">
<img src="{{img.url}}" alt="{{img.title}}">
</slide>
</carousel>
</code></pre>
<p>I'd like to be able to just loop through whatever files are in the photos folder and add them to the images array.
That way all I have to do to update the carousel is to change the photos in the photos folder.</p> | 0 |