Stack Overflow

Subscribe to Stack Overflow feed
most recent 30 from stackoverflow.com 2017-09-23T21:24:57Z
Updated: 2 hours 5 min ago

How do I use the generic error codes enum with system_category error codes from <system_error>?

Fri, 09/22/2017 - 17:55

I have this code (very similar to what is suggested here) that throws an exception:

int accept4(int sockfd, sockaddr *addr, socklen_t *addrlen, int flags) { const int fd = ::accept4(sockfd, addr, addrlen, flags); if (fd < 0) { const auto tmp = errno; throw ::std::system_error(tmp, ::std::system_category(), "accept4(2)"); } else { return fd; } }

And this code for testing for a particular exception reason:

catch (const ::std::system_error &e) { static const auto block_err = ::std::system_error(EWOULDBLOCK, ::std::system_category()); const auto ecode = e.code(); // EWOULBLOCK is fine, everything else, re-throw it. if (block_err.code() != ecode) { throw; } }

This seems kind of needlessly verbose and not quite the right way to do things. There's this whole idea of generic errors and a whole enum (see ::std::errc) full of them along with some kind of system that's supposed to convert between system specific error codes and these generic errors.

I want to use the generic error codes and categories, and I can't seem to get them to work. How do I make that work?

Writing file as Json using Nlog in a programmatic way

Fri, 09/22/2017 - 15:45

I would like write a file as json using Nlog. I am aware it can be done this way.

<target name="jsonFile" xsi:type="File" fileName="${logFileNamePrefix}.json"> <layout xsi:type="JsonLayout"> <attribute name="time" layout="${longdate}" /> <attribute name="level" layout="${level:upperCase=true}"/> <attribute name="message" layout="${message}" /> </layout>

But I would like to do it in my C# code. I started with this:

var config = new LoggingConfiguration(); var fileTarget = new FileTarget(); string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments); string fullPath = Path.Combine(folder, "mylog.json"); fileTarget.FileName = fullPath; config.AddTarget("file", fileTarget); var fileRule = new LoggingRule("*", LogLevel.Error, fileTarget); config.LoggingRules.Add(fileRule); LogManager.Configuration = config;

but It only write it as file but not a Json. Any help or hint will be appreciated

K-Medoids / K-Means Algorithm. Data point with the equal distances between two or more cluster representatives

Fri, 09/22/2017 - 15:33

I have been researching and studying about partition-based clustering algorithms like K-means and K-Medoids. I have learned that K-medoids is more robust to outliers compared to K-means. However I am curious on what will happen if during the assigning of data points, two or more cluster representatives have the same distance on a data point. Which cluster will you assign the data point? Will the assignment of the data point to a cluster greatly affect the clustering results?

How to create .jar (Create Executable) of the Ktor embedded Server

Fri, 09/22/2017 - 13:08

I'm very new to Kotlin and Ktor and Gradle. Was able to create embedded server as explained in Ktor site, with the following code:

BlogApp.kt:

package blog import org.jetbrains.ktor.netty.* import org.jetbrains.ktor.routing.* import org.jetbrains.ktor.application.* import org.jetbrains.ktor.features.* import org.jetbrains.ktor.host.* import org.jetbrains.ktor.http.* import org.jetbrains.ktor.response.* fun Application.module() { install(DefaultHeaders) install(CallLogging) install(Routing) { get("/") { call.respondText("My Example Blog sfs 122", ContentType.Text.Html) } } } fun main(args: Array<String>) { embeddedServer(Netty, 8080, watchPaths = listOf("BlogAppKt"), module = Application::module).start() }

and build.gradle:

group 'Example' version '1.0-SNAPSHOT' buildscript { ext.kotlin_version = '1.1.4-3' repositories { mavenCentral() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } apply plugin: 'java' apply plugin: 'kotlin' sourceCompatibility = 1.8 ext.ktor_version = '0.4.0' repositories { mavenCentral() maven { url "http://dl.bintray.com/kotlin/ktor" } maven { url "https://dl.bintray.com/kotlin/kotlinx" } } dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version" compile "org.jetbrains.ktor:ktor-core:$ktor_version" compile "org.jetbrains.ktor:ktor-netty:$ktor_version" compile "ch.qos.logback:logback-classic:1.2.1" testCompile group: 'junit', name: 'junit', version: '4.12' } compileKotlin { kotlinOptions.jvmTarget = "1.8" } compileTestKotlin { kotlinOptions.jvmTarget = "1.8" } kotlin { experimental { coroutines "enable" } }

The server run fine at: localhost:8080

and the I can see the below files in the out folder:

C:\Users\Home\IdeaProjects\Example\out\production\classes\blog

How can I know create an executable file .jar of this server, so I can distribute it to the user?

Go slice not updating values outside for loop

Fri, 09/22/2017 - 12:13

I'm trying to code an Adaline neurone in Go an I'm having a problem with the scoop of an array, I update the values of it inside a for loop and it looks, like they are being updated, but when I try to access the new values from outside the loop they are always the same, they were just updated in the first iteration. Here is the code:

//This functions creates a [][]float64 and fill it with random numbers weights := initWeights(inputLength) // data is a [][]float 64 and expectedY a []float64 for i := 0; i < 10; i++ { for j := range data { //Calculate estimate var estimate float64 = 0 for x := range data[j]{ estimate += data[j][x] * weights[x] } // Update weights (range passes values as a copy) for x := 0; x < len(weights); x++ { weights[x] = learningRate * (expectedY[j] - estimate) * data[j][x] } //PRINT #1 } //PRINT #2 // //Some more stuff // }

If I print weights before the loop it looks like this:

[-0.6046602879796196 0.6645600532184904 -0.4246374970712657 0.06563701921747622 0.09696951891448456 -0.5152126285020654 0.21426387258237492 0.31805817433032985 0.28303415118044517]

So it was created correctly. After I start the loops to adjust the neurone weights. Here is where the weird thing happens.

If I print in #1 I can see that the array is being updated in each iteration, but when I print in #2 the value of the array is always the same, it's the one was calculated on the first iteration of the weights loop.

PRINT #1

[0.06725611377611064 0 0 0.03490734755724929 0.014819026508554914 0.023919277971577904 0.021858582731470875 0.0051309928461725374 0.06915084698345737] [0.030417970260300468 0.0274737201080031 0 0.02479712906046004 0.01662460439529523 0.014007493148808682 0.029246218179487176 0.004413401238393224 0.05947980105651245] [0.008861875440076036 0 0.01792998206766924 0.017854161778140868 0.004333887749441702 0.020137868898735412 0.0125224790185058 0.008249247500686795 0.030328115811348512].

PRINT #2

[0.007796061340871362 0 0.011035383661848988 0.01289960904315235 0.003797667051516503 0.009918694200771232 0.015234505189042204 0.0008236738380263619 0.023072096303259435] [0.007796061340871362 0 0.011035383661848988 0.01289960904315235 0.003797667051516503 0.009918694200771232 0.015234505189042204 0.0008236738380263619 0.023072096303259435] [0.007796061340871362 0 0.011035383661848988 0.01289960904315235 0.003797667051516503 0.009918694200771232 0.015234505189042204 0.0008236738380263619 0.023072096303259435]

I've been struggling with this for the last two days and I couldn't figure out what's happening, I hope you guys can help me.

-- UPDATE --
Here is a more complete and runnable version https://play.golang.org/p/qyZGSJSKcs

In play, looks that the code is working fine... the exact same code in my computer outputs the exact same slice every iteration.

The only difference is that instead of fixed slices I'm creating them from two csv files with several hundreds of rows, so I'm guessing the problem comes from there, I'll continue investigating.

Here you have the raw data if it's helpfull:
Train data: https://pastebin.com/H3YgFF0a
Validate data: https://pastebin.com/aeK6krxD

Centering a Navbar UL (Unordered List) with Bootstrap 4 on OSX

Fri, 09/22/2017 - 10:22

Hmm, I can't seem to figure this one out on my own. I'm working with the main Navbar and can't seem to center specific things on the page. I already applied '.container' to 'nav .navbar' and set the 'max-width' to control where the "Brand" lines up. But, I'm having problems with centering "Home | Link | Disabled | Dropdown" in the center of the page.

I've tried:

‘.text-center’ on the li tags, inline and: li { text-align: center; } ‘justify-content-center’ on ul tag, inline and .ul { justify-content: center; } Put the ul inside: <div class="row"> <div class="col text-center”> </div> </div>

But, none of it works. Here's the Nav markup and CSS file: HTML:

<nav class="navbar navbar-expand-md navbar-light bg-light fixed-top"> <div class="container"> <a class="navbar-brand" href="#">Brand Here</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarsExampleDefault"> <!-- ul starts here --> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="http://example.com" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a> <div class="dropdown-menu" aria-labelledby="dropdown01"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <a class="dropdown-item" href="#">Something else here</a> </div> </li> </ul> <!-- ul ends here --> </div> </div><!-- container placed within <nav> tag --> </nav>

Sass/CSS

body { padding-top: 56px; nav .container { max-width: 1374px; .navbar-brand { color: $blue-text !important; } .ul { justify-content: center; } } }

Any help would be appreciated. TIA

Writing trigger on one table1 to update table2 and trigger on table2 to update table1

Fri, 09/22/2017 - 09:10

I have two services and I want to keep sync in DB tables, So If service1 update table1 then I want to update table2 as well. And If service2 update table2 then I want to update table1 as well.

Can I write a trigger on table1 to update table2 and again a trigger on table2 to update table1? Will this create a loop?

Linked Bootstrap datetimepicker with max and min date

Fri, 09/22/2017 - 09:10

I have two dateTimePicker forms linked together. I have no problem with the standard behavior, but now i'm trying to put some limit on them.

The first time picker should have as minDate now plus 1 hour and max date a month. The second should have as minDate the date of the first plus 1 hour and max date a month.

So this is the script

$(function() { var newMaxDate = moment().add(31, 'days'); $('#datetimepicker2').datetimepicker({ locale : 'it', format : 'DD/MM/YYYY HH:mm', stepping : 15, maxDate: newMaxDate, minDate: moment().add(1,'hours') }); $('#datetimepicker3').datetimepicker({ locale : 'it', format : 'DD/MM/YYYY HH:mm', stepping : 15, useCurrent: false //Important! See issue #1075 }); $("#datetimepicker2").on("dp.change", function (e) { var newMinDate = moment(e.date).add(45, 'minutes'); console.log('min ' + newMinDate.format()); console.log('max ' + newMaxDate.format()); $('#datetimepicker3').data("DateTimePicker").minDate(newMinDate); $('#datetimepicker3').data("DateTimePicker").maxDate(newMaxDate); }); $("#datetimepicker3").on("dp.change", function (e) { $('#datetimepicker2').data("DateTimePicker").maxDate(e.date); }); });

FIDDLE

in this way i have date validation, but the first picker is not taken into account when clicking on it

Selecting strings and characters from variables in bash

Fri, 09/22/2017 - 09:10

I'm reading text in from a txt file, and I have to create a username from an email. The email address is in a single variable. The username must be the first letter of the users first name, and their entire last name. For example, joe.bloggs@gmail.com's username would be "jbloggs"

How do I select the first letter from the first name, then the entire last name, and concatenante them into 1 variable? I think I use the cut method but I'm unsure how to do it.

Thanks

Sonar false positive immutability rule

Fri, 09/22/2017 - 09:10

Hopefully someone can help clarifying this.

Consider having the following exception type:

public class SomeException extends RuntimeException { private List<String> messages; public SomeException(List<String> messages) { this.messages = Collections.unmodifiableList(messages); } public List<String> getMessages() { return this.messages; } }

For the getMessages method Sonar says that the immutability rule is violated and I should return a copy of the internal list.

However, there is no need for that because Sonar should figure out that the internal List could've been set only via the constructor, thus through calling Collections.unmodifiableList which is by nature cannot be modified.

Has anyone encountered such an issue?

Personally I don't really want to copy the list again.

Could I avoid Array's "Object is possibly 'undefined'" of Typescript Error

Fri, 09/22/2017 - 09:10

I got an error of error TS2532: Object is possibly 'undefined'. in typescript compile with strictNullChecks mode.

interface Hoge { num?: number; } const hoge: Hoge[] = [{ num: 1 }]; if (!!hoge && hoge.length > 0 && !!hoge[0] && !!hoge[0].num) { hoge[0].num.toString() }

playground (please check strictNullChecks)

However, I thought these condition have completely avoided undefined typed hoge already.

I guess non-null assertion operator works well: hoge[0].num!, but I'm wondering if there are other type safed ways.

Subtract year and month

Fri, 09/22/2017 - 09:09

I have the following query

SELECT LEFT(CONVERT(varchar,DATEADD(MONTH,-1, GETDATE()),112),6)

Which will result in: 201708 (as of getdate() today)

I need to also subtract a year from this, so it will be come: 201608

I tried adding another DATEADD function but I can't get it to work.

can anyone point me in the right direction?

Mercurial: How to work with two "main branches"

Fri, 09/22/2017 - 09:09

I have a Mercurial repository for a project that has to split to two branches that will share main functionality, but will have differences in some of their functionality:

---- B / ---source-+----- A

Now I'm wondering how I work with that.

----- new feature ------- / \ ---- B1 ----+ B2 --- B3 ----- bugfix ---+- MERGE --- / ---source-+----- A1 ---- A2 ------------------------------------

Let's assume A1, B1, B2, ... and so on are simple changes that are only supposed to appear in the specific branches (update logo, change texts, ...). However I want to have both the "new feature" and the "bugfix" in both branches.

Obviously I can't just merge branch B into A or I would end up with ALL the changes that I made in B in A (but I don't want the updated logo).

So: How do I do that? Do I really have to use a third branch as suggested in this question? That would force me to adapt a completely new workflow.

Live Objects: Error downloading json package in IDE Arduino

Fri, 09/22/2017 - 09:09

I am following the tutorial https://youtu.be/FP3iz2Hnv2k?list=PLlR5m9QWl2p_EPn3JITOF0pQsFuzOdle1 on how to manage the Orange explorer LoRa Kit. And for choosing the type of card in Tools -> Card types, I get an error like: Error while downloading http://downloads.arduino.cc/packages/package_index.json

SIP SDK(without IPv6 support) integrated in iOS app... Does this app get approval from AppStore?

Fri, 09/22/2017 - 09:09

We have developed iOS app with 3rd party SIP SDK. This SIP SDK not integrated IPv6 support. If we upload our app to AppStore does this app get approval from AppStore?

This IPv6 support applies to only US or all other countries?

For ex in India Internet Service Providers(ISP) still running on IPv4. If I upload my iOS app to only in Indian market will it get approved by Apple AppStore?

Simple Show form button Does nothing

Fri, 09/22/2017 - 09:06

I have this simple button on my webiste that suppose to display my form but the buttons display but on click nothing happens, Weirdly enough it works here on the snippet.

My website link : website

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="container-form"> <br> <input class="btn btn-default" id="buttonEmailForm" type="submit" name="buttonEmailForm" value="Home Cleaning"> <script type="text/javascript"> $("#buttonEmailForm").click(function(e) { $("#EmailForm").show(); e.preventDefault(); }); </script> <form name="EmailForm" id="EmailForm" action="" method="post" style="display:none;"> <label>Number Of Rooms: </label><span></span> <Select class="form-control input-sm error" min="3" name="Hours" id="Hours"> <OPTION value="0">Select Number of Hours</OPTION> <OPTION value="45">3 Hours</OPTION> <OPTION value="60">4 Hours</OPTION> <OPTION value="75">5 hours</OPTION> <OPTION value="90">5 hours</OPTION> <OPTION value="90">6 hours</OPTION> <OPTION value="90">7 hours</OPTION> </select> </form> </div>

Any help would be appreciated thanks.

Crashlytics on Libgdx

Fri, 09/22/2017 - 09:02

I am trying to use Fabric on my current Game Project which is based on Libgdx Framework. I am not sure where should I put instruction codes to which gradle file.

buildscript { repositories { maven { url 'https://maven.fabric.io/public' } } dependencies { // These docs use an open ended version so that our plugin // can be updated quickly in response to Android tooling updates // We recommend changing it to the latest version from our changelog: // https://docs.fabric.io/android/changelog.html#fabric-gradle-plugin classpath 'io.fabric.tools:gradle:1.+' } }

First of all this buildscript block exists in build gradle of Project, not for android. Since I put these into parent gradle file, android gradle file can not recognize the library.

apply plugin: 'io.fabric' repositories { maven { url 'https://maven.fabric.io/public' } } compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') { transitive = true; }

I can only add these code blocks into the whole gradle file again which is shown below.

project(":android") { apply plugin: "android" configurations { natives } dependencies { compile project(":core") compile "com.badlogicgames.gdx:gdx-backend-android:$gdxVersion" natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi" natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi-v7a" natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-arm64-v8a" natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86" natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86_64" compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion" natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi" natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi-v7a" natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-arm64-v8a" natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86" natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86_64" } }

Could you help me to use Fabric into my game properly?

T-SQL Replace HTML tags except for P tags

Fri, 09/22/2017 - 08:58

I have this function that is well documented on the internet to strip out HTML in a SQL query.

CREATE FUNCTION [dbo].[fnStripHTML] (@HTMLText VARCHAR(MAX)) RETURNS VARCHAR(MAX) AS BEGIN DECLARE @Start INT DECLARE @End INT DECLARE @Length INT SET @Start = CHARINDEX('<',@HTMLText) SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText)) SET @Length = (@End - @Start) + 1 WHILE @Start > 0 AND @End > 0 AND @Length > 0 BEGIN SET @HTMLText = STUFF(@HTMLText,@Start,@Length,'') SET @Start = CHARINDEX('<',@HTMLText) SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText)) SET @Length = (@End - @Start) + 1 END RETURN LTRIM(RTRIM(@HTMLText)) END GO

I need to amend this function to strip out all HTML apart from opening and closing p tags <p></p>.

Is anyone able to help as I've been at it for a while and haven't yet had a breakthrough.

Thanks in advance.

Andrew

Tests not running through Maven?

Fri, 09/22/2017 - 08:58

When I run my test in Maven I get this:

[INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] [INFO] Results: [INFO] [INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

My test class, JsonReaderTest.class, is placed in src/test/java and follows the correct name convention as far as I know from maven-surefire-plugin.

Tests run fine when run outside of Maven.

I have this plugin included in my pom:

<!-- Executes tests --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.20.1</version> </plugin>

and this in my dependencies:

<!-- Test --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.0.0</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.0.0</version> </dependency>

and my test class:

package org.avalin.optaplanner.test.java; import org.avalin.optaplanner.json.JsonReader; import org.junit.jupiter.api.*; import java.io.FileNotFoundException; import java.nio.file.Paths; import static org.junit.jupiter.api.Assertions.*; class JsonReaderTest { @Test @DisplayName("Test: No such file at designated path") void testloadFromJsonTest() throws Exception { Throwable exception = assertThrows(FileNotFoundException.class, ()-> JsonReader.loadFromJson(".json")); assertEquals(".json (No such file or directory)", exception.getMessage()); } @Test @DisplayName("Test: Load Shifts from JSON (String instead of number)") void testLoadShiftsFromJson3() { Throwable exception = assertThrows(NumberFormatException.class, ()-> JsonReader.loadFromJson(Paths.get("src/main/resources/org/avalin/optaplanner/json/faultyShift-2.json").toAbsolutePath().toString())); assertEquals("\nOne or more of your \"shift\" elements has a number format exception.\n" + "Check for errors in your JSON-properties.\n" + "(Did you insert a string instead of a number in id?)", exception.getMessage()); } @Test @DisplayName("Test: JSON is correctly loaded") void testJsonIsLoaded() { assertFalse(JsonReader.jsonIsLoaded()); } @AfterEach void cleanJsonReader() { JsonReader.cleanJsonReader(); } }

When I tried googling this problem, it seemed the only thing that could be wrong would be naming convention (class had to end with or start with test, I tested both with no change) and that the test class should be put into the appropriate folder.

When I run: mvn -Dtest=JsonReaderTest test

I get following:

Failed to execute goal org.apache.maven.plugins:maven-surefire- plugin:2.20.1:test (default-test) on project optaplanner: No tests were executed!

The JsonReaderTest.class is also correctly generated inside target/test-classes

What could be the culprit here?

Java - MOOC loops ending remembering

Fri, 09/22/2017 - 08:48

I'm currently stuck with MOOC exercise 36. My problem is I can't make my program store odd and even numbers. I understand I need to use the modulus operator % 2 so the program can find if the reminder is 0 - 1 making is an even or odd number.

// program in this project exercises 36.1-36.5 // actually this is just one program that is split in many parts Scanner reader = new Scanner(System.in); System.out.println("Type numbers: "); int tal; //Min reader funktion int sum = 0; int numbersTyped = 0; double average = 0.0; int even = 0; int odd = 0; while (true) { tal = Integer.parseInt(reader.nextLine()); if (tal == -1){ System.out.println("Thank you and see you later!"); System.out.println("The sum is: " + sum); System.out.println("How many numbers: " + numbersTyped); System.out.println("Average: " + average); System.out.println("Even numbers: " + even); System.out.println("Odd numbers: " + odd); break; } if (tal >= 0){ sum += tal; numbersTyped++; average = (double) sum / (double) numbersTyped; } else if (tal > 0){ tal %= 2; even = tal; } else if (tal > 1) { tal %= 2; odd = tal; } } }

Pages