rest api – Get html from custom route api

I created a custom route with the wordpress API which allows me to retrieve the html content of the post
When editing a post, I added an “Export to html” link with the download attribute

echo "<a href='".get_bloginfo('url')."/wp-json/export/post/".$post->ID."' class='button-primary' download>Exporter l'article</a>";

But when I click on the link I get a .json file

How to transform this .json into .html before downloading the file?
My client will use this html export to import it into another site (not a wordpress site)

Thanks

c++ – Pathfinding algorithm isn’t finding correct route

I am attempting an online coding challenge wherein I am to implement a pathfinding algorithm that finds the shortest path between two points on a 2D grid. The code that is submitted is tested against a number of test cases that I, unfortunately, am unable to see, but it will however tell me if my answer for shortest distance is correct or not. My implementation of the A* algorithm returns a correct answer on 2/3 test cases and I cannot seem to figure out what scenario might create an incorrect answer on the third?

I have tried several of my own test cases and have gotten correct answers for all of those and at this point am feeling a little bit lost. There must be something small in my code that I am not seeing that is causing this third case to fail.

More details

  • The grid is w by h and contains only 1’s (passable) and 0’s (impassable) with every edge having a cost of 1 and the pathway cannot move diagonally
    It all starts with the FindPath function which is to return the length of the shortest path, or -1 if no path is available
  • pOutBuffer is used to contain the path taken from beginning to end (excluding the starting point). If multiple paths are available then any will be accepted. So it isnt looking for one path in particular
  • I know the issue is not the result of time or memory inefficiency. I has to be either the distance returned is incorrect, or the values in pOutBuffer are incorrect.

Any help would be greatly appreciated as I am just about out of ideas as to what could possibly be wrong here. Thank you.

#include <set>
#include <vector>
#include <tuple>
#include <queue>
#include <unordered_map>

inline int PositionToIndex(const int x, const int y, const int w, const int h)
{
    return x >= 0 && y >= 0 && x < w  && y < h? x + y * w : -1;
}

inline std::pair<int, int> IndexToPosition(const int i, const int w)
{
    return std::make_pair<int, int>(i % w, i / w);
}

inline int Heuristic(const int xa, const int ya, const int xb, const int yb)
{
    return std::abs(xa - xb) + std::abs(ya - yb);
}

class Map
{
public:
    const unsigned char* mapData;
    int width, height;

    const std::vector<std::pair<int, int>> directions = { {1,0}, {0,1}, {-1,0}, {0,-1} };

    Map(const unsigned char* pMap, const int nMapWidth, const int nMapHeight)
    {
        mapData = pMap;
        width = nMapWidth;
        height = nMapHeight;
    }

    inline bool IsWithinBounds(const int x, const int y) 
    {
        return x >= 0 && y >= 0 && x < width && y < height;
    }

    inline bool IsPassable(const int i)
    {
        return mapData(i) == char(1);
    }


    std::vector<int> GetNeighbours(const int i)
    {
        std::vector<int> ret;

        int x, y, neighbourIndex;
        std::tie(x, y) = IndexToPosition(i, width);

        for (auto pair : directions)
        {
            neighbourIndex = PositionToIndex(x + pair.first, y + pair.second, width, height);
            if (neighbourIndex >= 0 && IsWithinBounds(x + pair.first, y + pair.second) && IsPassable(neighbourIndex))
                ret.push_back(neighbourIndex);
        }

        return ret;
    }
};

int FindPath(const int nStartX, const int nStartY,
    const int nTargetX, const int nTargetY,
    const unsigned char* pMap, const int nMapWidth, const int nMapHeight,
    int* pOutBuffer, const int nOutBufferSize)
{
    int ret = -1;

    // create the map
    Map map(pMap, nMapWidth, nMapHeight);

    // get start and end indecies
    int targetIndex = PositionToIndex(nTargetX, nTargetY, nMapWidth, nMapHeight);
    int startIndex = PositionToIndex(nStartX, nStartY, nMapWidth, nMapHeight);
    
    // if start and end are same exit
    if (targetIndex == startIndex) return 0;
    
    std::unordered_map<int, int> pathway = { {startIndex, startIndex} };
    std::unordered_map<int, int> distances = { {startIndex, 0} };

    // queue for indecies to process
    typedef std::pair<int, int> WeightedLocation;
    std::priority_queue<WeightedLocation, std::vector<WeightedLocation>, std::greater<WeightedLocation>> queue;

    queue.emplace(0, startIndex);
    
    while (!queue.empty())
    {
        int currentWeight, currentIndex;
        std::tie(currentWeight, currentIndex) = queue.top();
        queue.pop();

        if (currentIndex == targetIndex)
            break;

        int newDistance = distances(currentIndex) + 1;
        for (int n : map.GetNeighbours(currentIndex))
        {
            if (distances.find(n) == distances.end() || newDistance < distances(n))
            {
                distances(n) = newDistance;

                int weight = newDistance + Heuristic(n % nMapWidth, n / nMapWidth, nTargetX, nTargetY);
                queue.emplace(weight, n);
                pathway(n) = currentIndex;
            }
        }
    }

    if (pathway.find(targetIndex) != pathway.end())
    {
        int current = targetIndex;

        while (current != startIndex)
        {
            int outIndex = distances(current) - 1;
            pOutBuffer(distances(current) - 1) = current;
            current = pathway(current);
        }
        ret = distances(targetIndex);
    }
    
    return ret;
}

ios – GCDAsyncSocket : “No route to host” error with IPV6 addresses

GCDAsyncSocket works with IPV4 addresses :

self.socket = GCDAsyncSocket(delegate: self, delegateQueue: .main)
try self.socket.connect(toHost: "192.168.0.16", onPort: 60001)
// CONNECTED

However it doesn’t work with IPV6 addresses :

self.socket = GCDAsyncSocket(delegate: self, delegateQueue: .main)
try self.socket.connect(toHost: "fe80::d6ae:5ff:fe43:c6e9", onPort: 60001)
// ERROR : No route to host

I tried with “self.socket.isIPv4PreferredOverIPv6 = false”, but it didn’t solve the problem :

self.socket = GCDAsyncSocket(delegate: self, delegateQueue: .main)
self.socket.isIPv6Enabled = true
self.socket.isIPv4PreferredOverIPv6 = false
try self.socket.connect(toHost: "fe80::d6ae:5ff:fe43:c6e9", onPort: 60001)
// ERROR : No route to host

IDE : Xcode 12.2 (12B45b),
Platform : iOS 14.2,
Device : iPhone SE (2nd generation)

networking – How do I persist a route deletion between reboots?

There are lots of examples of adding a route and making it persist between reboots, but I want to have the deletion of a route persist.

In particular in How to only allow routing to IP range on particular interface? the solution was to delete the default root:

sudo ip route delete default via 172.16.30.1 dev wlan0

…but this doesn’t persist between reboots (or bringing the interface down and then back up).

The subnet of my WiFi network is 172.16.30.0/24, with gateway is 172.16.30.1. I wanted to use only the WiFi for packets on the 172.16.30.0/24 and send all other IP ranges through my eth0 interface.

How do I set up the wlan0 connection (Is it ifup ?), or persist my ip route command so that the default gateway is always removed?

How to create a custom route in Google Maps, then navigate it on a mobile?

Although you can’t do exactly what I wanted, I’ve discovered a way to do something pretty similar.

First, get the directions and the generated route. Next, drag the waypoints into the route. Next, instead of sending to the phone immediately, go through the route, right click on each waypoint in turn, and click “Add a destination”. The waypoint will be added to the end of the destinations list; DO NOT reorder this list yet or the other waypoints will be lost.

Once you’ve added each waypoint as a destination in order, drag the final destination (in the destinations list on the left) to the end. This will have created a route going from your original point A to B, but with the desired waypoints as destinations. When you now “Send directions to your phone”, these destinations will be included in the route that Google Maps navigation follows.

Unfortunately, I still haven’t found a way to save this list of destinations. That would be ideal. If anyone knows a way, please comment and I’ll update this answer to show it.

router – Spring integration route can’t dispatch message

So, problem is with router.
When the router try send message to channel I’l got the error: Dispatcher has no subscribers for channel ‘newTypingNotificationHandler.input’. But I have integrationFlow defenition for this channel name.

 @Bean
public IntegrationFlow routeEcmIncomeRq(AbstractMessageRouter typeNotificationRouter) {
    return IntegrationFlows.from(FROM_CHANNEL)
            .routeToRecipients(r -> r
                    .recipientFlow(p -> p instanceof TypingNotificationDto,
                            f -> f.route(typeNotificationRouter)
                    )
                    .defaultOutputChannel(DEFAULT_SERVICE_CHANNEL)
            ).get();
}

    @Bean
public AbstractMessageRouter typeNotificationRouter(IncomeRepository incomeRepository) {
    return new AbstractMessageRouter() {
        @Override
        protected Collection<MessageChannel> determineTargetChannels(Message<?> message) {
            TypingNotificationDto messagePayload = (TypingNotificationDto) message.getPayload();

            if (!incomeRepository.existsById(StringUtil.ecdFileIdToUuid(messagePayload.getEcdDocumentImage().getDocumentSource()))) {
                return Collections.singleton(MessageChannels.direct("newTypingNotificationHandler.input").get());
            } else {
                return Collections.singleton(MessageChannels.direct("existsTypingNotificationHandler.input").get());
            }
        }
    };
}

    @Bean
public IntegrationFlow newTypingNotificationHandler() {
    return f -> f.log("need's create new Income");
}

@Bean
public IntegrationFlow existsTypingNotificationHandler() {
    return f -> f.log("exist income process");
}

stackTrace cause:

org.springframework.integration.MessageDispatchingException:
Dispatcher has no subscribers at
org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:139)
~(spring-integration-core-5.2.6.RELEASE.jar:5.2.6.RELEASE) at
org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:106)
~(spring-integration-core-5.2.6.RELEASE.jar:5.2.6.RELEASE) at
org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:73)
~(spring-integration-core-5.2.6.RELEASE.jar:5.2.6.RELEASE) at
org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:461)
~(spring-integration-core-5.2.6.RELEASE.jar:5.2.6.RELEASE) at
org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:403)
~(spring-integration-core-5.2.6.RELEASE.jar:5.2.6.RELEASE) at
org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:187)
~(spring-messaging-5.2.6.RELEASE.jar:5.2.6.RELEASE) at
org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:166)
~(spring-messaging-5.2.6.RELEASE.jar:5.2.6.RELEASE) at
org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:47)
~(spring-messaging-5.2.6.RELEASE.jar:5.2.6.RELEASE) at
org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:109)
~(spring-messaging-5.2.6.RELEASE.jar:5.2.6.RELEASE) at
org.springframework.integration.router.AbstractMessageRouter.doSend(AbstractMessageRouter.java:206)
~(spring-integration-core-5.2.6.RELEASE.jar:5.2.6.RELEASE)

javascript – React App with external route table and cookie-based routing

This is a small frontend frame for a React app that is built then served statically via Go.

Because the app uses React-Router for browser-based routing but the server doesn’t know anything about the app I added some code to the backend that reads the list of routes the app uses from a json file and creates dummy handlers for each that place a redirect=/path cookie and redirect to the main page. That code is left out for brevity and because CodeReview doesn’t seem to have many Go users.

Meanwhile, the Javascript React frontend in this question sets ups the app’s React-Router routes based on the same external json file. The main page checks whether there is a redirect cookie set by the server and if so sends the user to that page.

The overall effect between the frontend and backend is that a user can go directly to app.com/widget/4 and without them knowing the server bounces them to the main page to start the browser-routing session and then back to the correct url

routes.json:

{
  "routes": (
    {"path":"/widget/:widgetId", "component": "WidgetContainer", "redirect": true},
    {"path":"/", "component": "MainPageContainer", "exact": true}
  )
}

index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from "react-router-dom";

import  ParseRoutes from "./Utils/ParseRoutes"
import { routes } from "./routes.json"

function AppContainer() {
  const routeProps = ParseRoutes(routes)

  return (
    <Router>
     {routeProps.map((props, i) => (<Route key={i} {...props} /> ))}
    </Router>
  )
}

ReactDOM.render(<AppContainer />, document.getElementById("root"))

ParseRoutes.js:

import  MainPageContainer from "../Components/MainPage"
import  WidgetContainer from "../Components/Widget"

const stringToComp = {
    MainPageContainer: MainPageContainer,
    WidgetContainer: WidgetContainer
}

const ParseRoutes = (routes) => (
    routes.map((props) => ({...props, component: stringToComp(props.component)}))
)

export default ParseRoutes

RedirectIfRequested.js:

import React from "react"
import { Redirect } from "react-router-dom"

const getCookieValue = (a) => {
    var b = document.cookie.match('(^|;)\s*' + a + '\s*=\s*((^;)+)')
    return b ? b.pop() : ''
  }

const RedirectIfRequested = () => {
    const redirectTo = getCookieValue("redirect")

    if ( redirectTo !== "" ) {
        document.cookie = "redirect=''; max-age=-1"
        return <Redirect to={redirectTo} />
    }

    return null
}

export default RedirectIfRequested

MainPage.js:

import React from "react"

import RedirectIfRequested from "../Utils/RedirectIfRequested.js"

export default function MainPageContainer(props) {
    const redirect = RedirectIfRequested()

    return redirect ? redirect : <MainPage /> 
}

function MainPage(props) {
    return <div>Main Page</div>
}

Widget.js:

import React from "react"

import { useParams } from "react-router-dom"

export default function WidgetContainer(props) {
    const id = useParams().widgetId

    return <div> Widget {id} accessed via react-router </div>
}

networking – tplink router: how to route default traffic to another specific IP

I have a tp-link router TD-W8960N 300Mbps Wireless N ADSL2+ Modem Router, which I use to connect to the internet via PPPoE. I have a backup internet connection with its own router, connected to the tp-link one through a LAN cable.

tp-link 192.168.1.1
backup router 192.168.1.2

What I want is changing the routing table when the first PPPoE connection is down, and routing all the incoming traffic on the tp-link to the second router, but I’m not figuring it out how. What I did is connecting via the telnet and do the following:

 > route show
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
81.174.0.21     *               255.255.255.255 UH    0      0        0 ppp2
192.168.1.0     *               255.255.255.0   U     0      0        0 br0
default         *               0.0.0.0         U     0      0        0 ppp2
 > route delete default 0.0.0.0
Invalid destination IP address
 > route add default 0.0.0.0 192.168.1.2
Invalid destination IP address
 > route add 0.0.0.0 0.0.0.0 192.168.1.2
Please at least enter gateway IP or interface

I also tried to add it via the HTTP interface, but it tells me that 0.0.0.0 is an invalid address. Maybe I can’t do it with this specific router and its firmware, but I don’t know. Any help is appreciated.

8 – What is the route in my myModule.routing.yml for myModule.module?

I built my module called myModule with Webforms module.
myModule is defined in webmodulecustommymodule

I introduced some forms (myModuleHeightCalculation, myModuleWidthCalculation…) and defined their route in myModule.routing.yml (see below).
These forms are called from myModule.module in mymodule_from_alter.

Currently, I’m able to compute the surface and display it in a new form myModuleSurfaceResult.
But, I want to display this result in MyModule webform.

What is the route for myModule in myModule.routing.yml?

See below my myModule.routing.yml file:

myModule.height_calculation:
  path: '/myModule-height-calculation'
  defaults:
    _title: 'Height calculation'
    _form: 'DrupalmyModuleFormmyModuleHeightCalculation'
  requirements:
    _role: 'authenticated+administrator'
myModule.width_calculation:
  path: '/myModule-width-calculation'
  defaults:
    _title: 'Width calculation'
    _form: 'DrupalmyModuleFormmyModuleWidthCalculation'
  requirements:
    _role: 'authenticated+administrator'
myModule.surface.result:
  path: '/surface-result/{result}'
  defaults:
    _title: 'Result'
    _form: 'DrupalmyModuleFormmyModuleSurfaceResult::content'
    result: ''
  requirements:
    _role: 'authenticated+administrator'

vpn – route not changing anymore since upgrade to big sur

Since I have upgraded to Big Sur my VPN post script has not been firing.

I have a simple script setup in /etc/ppp/ip-up that allows me to access things outside of the network while still accessing things in the internal network. It has been working for a while now and ever since upgrading to Big Sur I have to run the command manually to be able to access external websites/services.

did something major change with how they handle this file? it set to be executable and everything so I don’t know what the problem is, below is what that file looks like.

#!/bin/sh

/sbin/route change default 192.168.1.1

if I run that command in the terminal it works so I’m curious if Apple broke something or changed how it works.