text:
Q: CoreData general question just needed your expertise in a general coredata Q.
How would u approach this problem?
App (v1.0) with pre-populated data. (model with 8 entities) - (SQLite db)
user can read/write in four of them while the rest (4) are read only and are pre-populated)
(so far so good)
Now App is updated (v1.1) with NEW pre-populated dataset (newSQLite db is provided)(NO CHANGES to the model)
How do you approach this and preserve USER data?
my approach:
1.delete the entities (the 4 that are read only)
2.replace them with the new entities
3.theoretically user data are intact.
4.build and run
is there something wrong with this?
What would you suggest?
thanks

A: If the readonly and readwrite entities do not share relationships, the easiest solution is to put each group in their own configuration and then have separate stores. That way, updating is just a matter of swapping out the readonly persistent store file.
If they do have relationships, then your only option is delete all the existing readonly and repopulate by building new objects on the fly.
If you are designing from scratch the first option is usually best for pre-populated material. You can use objectIDs and/or fetched relationships to form pseudo-relationships across stores.


text:
Q: Node.js changing path to static files When I am other route everything is Ok, but when a subpage is being created dynamically I get an error 500 and I do not have favicon or my js file. Why is this happening?
- My route
app.get("/:id/vehicle", isLoggedIn,  (req, res) => {
  res.render("vehicle", { name: req.user }); <- edited, thanks
});

- Error message, code 500
GET http://localhost:3000/xxx/common/js/main.js net::ERR_ABORTED

- Path to public directory
app.use(express.static(path.join(__dirname, "/public")));
app.use(favicon(__dirname + "/public/favicon.ico"));

A: missing bracket is may be the issue.
res.render("vehicle", { name: req.user }); // you missed the closing ')' here

A: try this code
app.use(express.static(path.join(__dirname, "public")));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to serialize an object to json using GSON -> get huge recursive error My code:
public class Faction implements Serializable {

private static Set<Faction> factions = new HashSet<>();

private transient static Set<UUID> factionOperator = new HashSet<>();

private transient static Map<UUID, Faction> onlineFPlayers = new HashMap<>();

private String announcement;

private String name;

private UUID leader;

private Map<UUID, Boolean> players = new HashMap<>();

private transient Set<UUID> factionChatPlayers = new HashSet<>();

private transient Set<UUID> invitedPlayers = new HashSet<>();

private Power power = new Power(this);

private Region region;

private double credit = 0;

public static void save() {
    Gson gson = new GsonBuilder().create();
    try {
        Writer writer = new FileWriter(Krene.get().getDataFolder() + "\\factions.json");
        gson.toJson(factions, writer);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}
In the class there are a few methods to do other things. But basically I want to serialize these to a json file (the serialization code is in the method save()) - but I get a huge error.
Error:

java.lang.StackOverflowError
          at sun.nio.cs.SingleByte.withResult(Unknown Source) ~[?:1.8.0_121]
          at sun.nio.cs.SingleByte.access$000(Unknown Source) ~[?:1.8.0_121]
          at sun.nio.cs.SingleByte$Encoder.encodeArrayLoop(Unknown Source) ~[?:1.8.0_121]
          at sun.nio.cs.SingleByte$Encoder.encodeLoop(Unknown Source) ~[?:1.8.0_121]
          at java.nio.charset.CharsetEncoder.encode(Unknown Source) ~[?:1.8.0_121]
          at sun.nio.cs.StreamEncoder.implWrite(Unknown Source) ~[?:1.8.0_121]
          at sun.nio.cs.StreamEncoder.write(Unknown Source) ~[?:1.8.0_121]
          at sun.nio.cs.StreamEncoder.write(Unknown Source) ~[?:1.8.0_121]
          at java.io.OutputStreamWriter.write(Unknown Source) ~[?:1.8.0_121]
          at java.io.Writer.write(Unknown Source) ~[?:1.8.0_121]
          at com.google.gson.stream.JsonWriter.string(JsonWriter.java:551) ~[?:?]
          at com.google.gson.stream.JsonWriter.writeDeferredName(JsonWriter.java:402)
  ~[?:?]
          at com.google.gson.stream.JsonWriter.beginObject(JsonWriter.java:307)
  ~[?:?]
          at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.write(MapTypeAdapterFactory.java:205)
  ~[?:?]
          at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.write(MapTypeAdapterFactory.java:145)
  ~[?:?]
          at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
  ~[?:?]
          at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:968) ~[?:?]
          at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
  ~[?:?]
          at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
  ~[?:?]
          at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:968) ~[?:?]
          at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
  ~[?:?]
          at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
  ~[?:?]
          at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:968) ~[?:?]
          at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
  ~[?:?]
          at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
  ~[?:?]
          at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:968) ~[?:?]
          at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
  ~[?:?]
          at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
  ~[?:?]
          at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:968) ~[?:?]
          at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
  ~[?:?]
          at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
  ~[?:?]
          at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:968) ~[?:?]
          at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
  ~[?:?]
          at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
  ~[?:?]
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
  ~[?:?]
          at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:968) ~[?:?]

Why am I receiving this error? Bare in mind, the classes Region and Power both implement Serializable (I think this is necessary, correct me if I am wrong?).
Is it the serialization of UUIDs? Should I serialize them as strings?


text:
Q: Align Text to Down I stated my problem in the title. I want to put the container(ID is about) div
below the image. I tried many methods, but now my brain is burned :D I think it's related to position. I would be very happy if you help. Thanks in advance. (Note: I will make the design responsive near completion. You'll get the best results if you work on a 1920x1080 screen.)
My Code:

window.addEventListener("scroll", function(){
    var header = document.querySelector("nav");
    header.classList.toggle("sticky",window.scrollY > 0);
})
.fs-xl {
    font-size: 3rem;
}

.about{
    position: absolute;
}

.loginbutton {
    border: transparent;
    background-color: transparent;
    display: block !important;
}

.gotham-ultra {
    font-family: 'Montserrat', sans-serif;
    font-weight: 800;
    transform: translate(-50%, 85%) !important;
}

.mainpageanimate {
    animation: mpa 1s ease-in-out forwards;
    animation-delay: 1s;
    opacity: 0;
}

.navbar {
    transition: 0.25 ease;
}

.sticky {
    background-color: #f8f9fa !important;
}

.sticky .container-fluid .collapse ul li a {
    color: #212529 !important;
}

.sticky .container-fluid .collapse ul li .loginbutton {
    display: none !important;
}

@keyframes mpa {
    0% {
        transform: translateY(70px);
        opacity: 0;
    }

    100% {
        transform: translateY(0px);
        opacity: 1;
    }

}
<!DOCTYPE html>

    <title>Yottalogy - Ana Sayfa</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="icon" href="img/icon.ico" type="image/x-icon" />
    <link rel="stylesheet" href="http://fonts.cdnfonts.com/css/montserrat">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css"
        integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">

            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" ria-expanded="false"
                aria-label="Toggle navigation">

            </button>

                        Ana Sayfa

                        Dersler

                        Blog

                        Forum

                        Destek

                        <button type="button" class="nav-link text-light loginbutton">Giriş Yap</button>

                        <button type="button" class="btn btn-success">Hesap Aç</button>

BİLGİNİN
            EFENDİSİ OLMAK İÇİN ÇALIŞMANIN UŞAĞI OLMAK GEREKİR.

Lorem Ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis imperdiet nisi nec lorem dictum
                    pellentesque. Integer semper risus tortor, in ornare nisi interdum nec. Cras sit amet orci eros.
                    Pellentesque pulvinar suscipit turpis, nec sodales turpis tincidunt quis. Integer a ipsum a ligula
                    pharetra maximus sed placerat lectus. Curabitur euismod a est vitae malesuada. Phasellus elementum
                    eleifend risus, non porttitor sapien dictum mattis.

A: There is a lot of position absolute elements in your page that doesn't seem to need it.
Put the image as background and remove the all absolute positioning styles.
You can use flex for centering elements instead.
Also if you want some section to be full height of screen, then use 100vh for that.
Do this and all the issues that burning your head will be gone.
Also if you're a beginner, then try creating some pages from scratch to get an idea how things work, rather that start with a template.


text:
Q: apache2 mod_proxy deny not working I have ubuntu apache2, I have a module called proxy, in the proxy.conf is this : (I have replaced my ip with XXX)
When I do this, the proxy works great,but it seems to be wide open for anyone to use. Any ideas what I could be doing wrong?
thanks
Joel
 <IfModule mod_proxy.c>
   ProxyRequests On

    <Proxy *:8080>
            AddDefaultCharset off
            Order deny,allow
            Deny from all
            Allow from XXX.XXX.XXX.XXX
    </Proxy>

    ProxyVia On
</IfModule>


text:
Q: Replicate groups screen split iOS (when you open an apps folder) When you press on a group on the iPhone, the screen splits, and opens up a black background to show contents.  How is this done (structurally, animations, multiple images???)
I figured it is some sort of animation moving the image up or down, but that foesn't account for cutting the image in two.
Thanks for the help, just getting started with animations

A: You might be looking for something like this:
https://github.com/jwilling/JWFolders


text:
Q: setIcon with switch I have a little question.
I have made a java switch in Netbeans. The switch is attached to a label in my Gui. Whenever i click the Label, i want it to be able to change the image it has.
private void LoopLblMouseReleased(java.awt.event.MouseEvent evt) {
switch(looped)
{
    case 0:
        looped = 1;
        LoopLbl.setIcon("path to image");
        break;

    case 1:
        looped = 0;
        break;
};

This the code i have for the switch untill now, but it gives an error when i fill in the path to the image. Can someone help me with this?

A:
but it gives an error when i fill in the path to the image.

LoopLbl.setIcon("path to image");

Did you read the API? The setIcon() takes an Icon as a parameter, not a String.
If you want to know how to use Icons, read the section from the Swing tutorial on How to Use Icons for working examples.
I suggest you keep the tutorial link handy for learning the basics of Swing.


text:
Q: Append GCLID to url with JavaScript Hello everyone
So, I have a problem with Google AdWords, and the transferring of the GCLID.
A bit of info:
I have a site that generates leads, and I need to be able to tell which lead is coming from my AdWords ads. I can track the number of conversions in AdWords and Analytics no problem, but I need to set the specific leads a part in my backend.
Does anyone know how I can get javascript to append something to the URL, whenever the system finds the GCLID cookie that is stored?
Maybe my explanation is a but fuzzy, but hope you get the idea :-)


text:
Q: How do I show context when searching old messages in Teams? When I search for messages in Microsoft Teams, if the result is recent Teams will show me messages sent before and after for context. However, if the message is more than a few weeks old, Teams will only show the matching result without any context.
Is there a way to jump back in my conversation history to view context for a message in my search results?


text:
Q: Copying files from one directory to another in java throws NoSuchFileException I have a HashSet of Strings, which are names of files that I want to copy from the working direcorory to the "path" directory. I find that the following piece of code should be working, however, I get a java.nio.file.NoSuchFileException: /commits/1/hello.txt exception.
  Hashset<String> stagedQueue = HashSet<String>();
    stagedQueue.put("hello.txt");
    stagedQueue.put("bye.txt");

String path = "/commits/" + commitID;

                for (String file : stagedQueue) {
                    Files.copy((new File(file).toPath()),
                        (new File(path + "/" + file).toPath()));

What can I do to fix this? I can't figure out why I am getting these exceptions. Please note that I am moving these into an empty directory.

A: Don't go through File; you use java.nio.file.
Your problem here is that you try and copy your initial file into a directory which does not exist yet:
String path = "/commits/" + commitID;

First of all, this is the destination directory, so call it dstdir, for instance. Then create the base directory and copy the files into it:
final Path basedir = Paths.get("/commits", commitId);

Files.createDirectories(basedir);

for (final String file: baseQueue)
    Files.copy(Paths.get(file), basedir.resolve(file));


text:
Q: Creating Method for UI Notification in Swift In one of my views, I have a UITableView. I would like to create a function that is called whenever a user selects a cell in the table. I figure I should use "UITableViewSelectionDidChangeNotification", but I am new to iOS and Swift so I don't know how to precede.
Thanks for your help!

A: This is the function you are looking for:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        // The row that I clicked on
        println(indexPath.row)
  }

Did you add the delegate and protocol of a tableview to your viewcontroller and connect the tableview properly? If so the function above should work for you. If not, I can help you out.
Also, here are some resources that I found useful for myself online:
https://www.youtube.com/results?search_query=swift+tableview


text:
Q: OpenCV OMR Sheet - Detect Marked Answers in Python - Getting Proper Binarization While solving an OMR problem I am not completely able to detect all the marked answers correctly.
Here is my input sheet.
Input Image
my code to Binarize the image.
import cv2

image = cv2.imread('input.png')
img = cv2.GaussianBlur(image,(5,5),0)
res, img = cv2.threshold(img, 60, 255, cv2.THRESH_BINARY)
img = 255 - img
cv2.imwrite('output.png',img)

Result I am getting.
Output generated
I have changed the gaussian blur and threshold parameters as follow.
 img = cv2.GaussianBlur(image,(7,7),0)
 res, img = cv2.threshold(img, 90, 255, cv2.THRESH_BINARY)

The result I am getting after this change.
Result after changing Parameters
My Desired result should look something like this.
Desired Result
Here is my complete code to detect the answers.
def solve(img,n_row = 50):
    height, width, channels = img.shape
    n_col = 4
    xShift = int(width/n_col)
    yShift = int(height/n_row)
    img = cv2.resize(img, (n_col * xShift, n_row*yShift))
    img = cv2.GaussianBlur(img,(5,5),0)
    res, img = cv2.threshold(img, 60, 255, cv2.THRESH_BINARY)
    img = 255 - img
    for row in range(0, n_row):
        tmp_img = img [row*yShift + 5:(row+1)*yShift - 5,]
        area_sum = []
        for col in range(n_col):
            area_sum.append(np.sum(tmp_img[1:,col*xShift :(col+1)*xShift]))
        y = str(area_sum > np.median(area_sum) * 1)
        result.append(area_sum > np.median(area_sum) * 5)

Please If anyone can help me solving this problem I will be super thankful.
Answer Suggestions:
How can I Check out the white pixel count inside each bounding rectangle and keep only those bounding rectangles/contours whose area is above a minimum value.
inputImg= cv2.imread('input.jpg')
img = cv2.cvtColor(inputImg, cv2.COLOR_BGR2GRAY)
mask = np.zeros(img.shape[:2], dtype=img.dtype)
ret, otsu_threshold = cv2.threshold(img, 120, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
contours, hierarchy = cv2.findContours(otsu_threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
    x,y,w,h = cv2.boundingRect(c)
    if cv2.contourArea(c) > 1500:
        cv2.rectangle(otsu_threshold, (x, y), (x+w, y+h), (0,255,0), 2)
cv2.imshow('Otsu', otsu_threshold)
cv2.waitKey(0)

A: Here is one way to do that in Python/OpenCV.

*

*Read the input

*Threshold on color

*Apply morphology to fill out the circles

*Get external contours

*For each contour, get the centroids and draw filled circles of radius=20 on the input at the centroid locations

*Save results

Input:

import cv2
import numpy as np

# read image
img = cv2.imread('omr_sheet.jpg')
h, w = img.shape[:2]

# trim 15 from bottom to remove partial answer
img = img[0:h-15, 0:w]

# threshold on color
lower=(120,60,80)
upper=(160,100,120)
thresh = cv2.inRange(img, lower, upper)

# apply morphology close
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (15,15))
morph = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
morph = cv2.morphologyEx(morph, cv2.MORPH_OPEN, kernel)

# get contours
result = img.copy()
centers = []
contours = cv2.findContours(morph, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
contours = contours[0] if len(contours) == 2 else contours[1]
print("count:", len(contours))
print('')
i = 1
for cntr in contours:
    M = cv2.moments(cntr)
    cx = int(M["m10"] / M["m00"])
    cy = int(M["m01"] / M["m00"])
    centers.append((cx,cy))
    cv2.circle(result, (cx, cy), 20, (0, 255, 0), -1)
    pt = (cx,cy)
    print("circle #:",i, "center:",pt)
    i = i + 1

# print list of centers
#print(centers)

# save results
cv2.imwrite('omr_sheet_thresh.png',thresh)
cv2.imwrite('omr_sheet_morph.png',morph)
cv2.imwrite('omr_sheet_result.png',result)
# show results
cv2.imshow("thresh", thresh)
cv2.imshow("morph", morph)
cv2.imshow("result", result)

cv2.waitKey(0)
cv2.destroyAllWindows()

Threshold Image:

Morphology Image:

Results:

Answers:
count: 48

circle #: 1 center: (77, 3151)
circle #: 2 center: (78, 3087)
circle #: 3 center: (77, 3021)
circle #: 4 center: (76, 2959)
circle #: 5 center: (79, 2892)
circle #: 6 center: (77, 2830)
circle #: 7 center: (77, 2762)
circle #: 8 center: (78, 2695)
circle #: 9 center: (77, 2631)
circle #: 10 center: (76, 2566)
circle #: 11 center: (78, 2500)
circle #: 12 center: (77, 2435)
circle #: 13 center: (77, 2373)
circle #: 14 center: (77, 2301)
circle #: 15 center: (79, 2238)
circle #: 16 center: (79, 2178)
circle #: 17 center: (77, 2108)
circle #: 18 center: (78, 2045)
circle #: 19 center: (80, 1980)
circle #: 20 center: (78, 1913)
circle #: 21 center: (78, 1848)
circle #: 22 center: (80, 1786)
circle #: 23 center: (77, 1722)
circle #: 24 center: (77, 1657)
circle #: 25 center: (79, 1593)
circle #: 26 center: (79, 1524)
circle #: 27 center: (80, 1461)
circle #: 28 center: (77, 1395)
circle #: 29 center: (79, 1332)
circle #: 30 center: (76, 1265)
circle #: 31 center: (80, 1203)
circle #: 32 center: (73, 1136)
circle #: 33 center: (77, 1072)
circle #: 34 center: (80, 1007)
circle #: 35 center: (77, 944)
circle #: 36 center: (78, 878)
circle #: 37 center: (75, 815)
circle #: 38 center: (77, 747)
circle #: 39 center: (77, 684)
circle #: 40 center: (79, 618)
circle #: 41 center: (77, 554)
circle #: 42 center: (78, 488)
circle #: 43 center: (80, 423)
circle #: 44 center: (78, 359)
circle #: 45 center: (77, 293)
circle #: 46 center: (78, 232)
circle #: 47 center: (77, 165)
circle #: 48 center: (78, 102)

ADDITION:
This solution is probably less sensitive to color of ink.  Just threshold on white using cv2.inRange() then invert.
import cv2
import numpy as np

# read image
img = cv2.imread('omr_sheet.jpg')
h, w = img.shape[:2]

# trim 15 from bottom and 5 from right to remove partial answer and extraneous red
img = img[0:h-15, 0:w-5]

# threshold on white color
lower=(225,225,225)
upper=(255,255,255)
thresh = cv2.inRange(img, lower, upper)
thresh = 255 - thresh

# apply morphology close
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (15,15))
morph = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7,7))
morph = cv2.morphologyEx(morph, cv2.MORPH_CLOSE, kernel)

# get contours
result = img.copy()
contours = cv2.findContours(morph, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
contours = contours[0] if len(contours) == 2 else contours[1]
print("count:", len(contours))
print('')
i = 1
for cntr in contours:
    M = cv2.moments(cntr)
    cx = int(M["m10"] / M["m00"])
    cy = int(M["m01"] / M["m00"])
    cv2.circle(result, (cx, cy), 20, (0, 255, 0), -1)
    pt = (cx,cy)
    print("circle #:",i, "center:",pt)
    i = i + 1

# save results
cv2.imwrite('omr_sheet_thresh2.png',thresh)
cv2.imwrite('omr_sheet_morph2.png',morph)
cv2.imwrite('omr_sheet_result2.png',result)

# show results
cv2.imshow("thresh", thresh)
cv2.imshow("morph", morph)
cv2.imshow("result", result)

cv2.waitKey(0)
cv2.destroyAllWindows()

Threshold Image:

Morphology Image:

Result:

Centers:
count: 48

circle #: 1 center: (78, 3150)
circle #: 2 center: (77, 3087)
circle #: 3 center: (78, 3020)
circle #: 4 center: (77, 2959)
circle #: 5 center: (78, 2892)
circle #: 6 center: (77, 2826)
circle #: 7 center: (77, 2760)
circle #: 8 center: (78, 2694)
circle #: 9 center: (79, 2630)
circle #: 10 center: (78, 2567)
circle #: 11 center: (78, 2501)
circle #: 12 center: (77, 2435)
circle #: 13 center: (75, 2373)
circle #: 14 center: (78, 2310)
circle #: 15 center: (78, 2240)
circle #: 16 center: (77, 2176)
circle #: 17 center: (78, 2106)
circle #: 18 center: (77, 2042)
circle #: 19 center: (79, 1979)
circle #: 20 center: (78, 1912)
circle #: 21 center: (78, 1848)
circle #: 22 center: (79, 1785)
circle #: 23 center: (78, 1722)
circle #: 24 center: (78, 1656)
circle #: 25 center: (78, 1589)
circle #: 26 center: (78, 1525)
circle #: 27 center: (79, 1458)
circle #: 28 center: (78, 1396)
circle #: 29 center: (78, 1328)
circle #: 30 center: (77, 1264)
circle #: 31 center: (78, 1201)
circle #: 32 center: (76, 1135)
circle #: 33 center: (78, 1071)
circle #: 34 center: (78, 1006)
circle #: 35 center: (77, 944)
circle #: 36 center: (77, 878)
circle #: 37 center: (77, 814)
circle #: 38 center: (77, 746)
circle #: 39 center: (78, 683)
circle #: 40 center: (77, 618)
circle #: 41 center: (77, 553)
circle #: 42 center: (78, 488)
circle #: 43 center: (78, 423)
circle #: 44 center: (77, 359)
circle #: 45 center: (76, 293)
circle #: 46 center: (79, 232)
circle #: 47 center: (75, 165)
circle #: 48 center: (79, 101)

A: Analysis:
The marked bubbles are in blue ink, which is a dominant color in the B-channel of the corresponding LAB color space.

*

*The B-channel captures blue and yellow colors in an image

*While A-channel captured red and green colors

*The L-channel highlights the brightness content in the image

To know more about LAB space go through this page
Code:
The following snippet shows how it is useful here:
img = cv2.imread('omr.jpg')

# convert to LAB space
lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
# store B-channel
b_channel = lab[:,:,2]

Notice how distinct the shaded bubbles are below:

# Otsu threshold on B-channel
th = cv2.threshold(b_channel,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)[1]

# morphological operations to close up the gaps within
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
closing = cv2.morphologyEx(th, cv2.MORPH_CLOSE, kernel, iterations = 2)

# finding contours and drawing those above certain area onto black screen
contours, h = cv2.findContours(closing, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

black = np.zeros((img.shape[0], img.shape[1], 3), np.uint8)
for c in contours:
    area = cv2.contourArea(c)
    if area > 100:
        black = cv2.drawContours(black, [c], -1, (0, 255, 0), -1)

A: you can try this, it splits binary image into cells

and compares to find which cell has most while pixels in the row
https://dontrepeatyourself.org/post/bubble-sheet-multiple-choice-test-with-opencv-and-python/
but you must change the code follow your quiz form


text:
Q: Is there a characterization of smooth $G$-equivariant functions $\mathbb R^n \to \mathbb R^m$? If $G$ is a compact Lie group acting smoothly on $\mathbb R^n$ by orthogonal matrices, a result of G. Schwartz characteriezs the smooth $G$-invariant functions $f : \mathbb R^n \to \mathbb R$ as smooth functions of the $G$-invariant polynomials $P(\mathbb R^n)^G$. (See this MO post for a discussion.)
Here I wondered whether a Riemannian metric descends smoothly through a ramified covering map, which led to a similar problem:

Question. When $G$ is a finite group (more generally, a compact Lie group) with smooth orthogonal actions on $\mathbb R^n$ and $\mathbb R^m$, what is known about $G$-equivariant smooth maps $$f : \mathbb R^n \to \mathbb R^m ?$$

(Schwartz' theorem is the case $m = 1$.)


text: Q: How to set up listener for Stripe's ShippingInfoWidget I'm currently using Stripe's ShippingInfoWidget to collect users' shipping information in Android, however, I couldn't seem to find an API for setting up the listener when users complete all the shipping information in the widget and that all the information is valid. I was wondering if there's a function for that, like the setCardValidCallback function for CardMultilineWidget. Any suggestions would be very appreciated!


text:
Q: solr highlighting: overlapped html tags I HAVE to highlight html text returned from solr v6.6.2
original html stored in body_txt_en field in solr:
I have a strong TCL code

highlight /select parameters:
hl.q=have strong TCL
hl=on
hl.fl=*_txt_en

expected result:
I have a strong TCL code

real result:
I have a strong TCL code

As you can see -  appeared after  that breaks html for large documents.
field configuration:
    <dynamicField name="*_txt_en" type="text_en"  indexed="true"  stored="true"/>
    <fieldType name="text_en" class="solr.TextField" positionIncrementGap="100">
      <analyzer type="index">
        <charFilter class="solr.HTMLStripCharFilterFactory"/>
        <tokenizer class="solr.StandardTokenizerFactory"/>
        <filter class="solr.LowerCaseFilterFactory"/>
      </analyzer>
      <analyzer type="query">
        <charFilter class="solr.HTMLStripCharFilterFactory"/>
        <tokenizer class="solr.StandardTokenizerFactory"/>
        <filter class="solr.LowerCaseFilterFactory"/>
      </analyzer>
    </fieldType>

All other solr parameters/configs are default for version 6.6.2
Analysis on indexing gives:

Can't understand why after solr.StandardTokenizerFactory (ST) end - start = 12 for TCL keyword
Question:
How to solve this "wrong html tag order" issue?


text:
Q: Nested Template and Template Infer Error Code below does not compile. Line 14 and 15 are the problem and I don't know how to fix it. How can the templated function been altered to get this little example to run?
My compiler says:
error: no matching function for call to 'make'

and
note: candidate template ignored: couldn't infer template
      argument 'CONTAINER'

compiling this code:
#include <vector>

template <typename TYPE>
struct Node
{
    Node(TYPE & _value) : value(_value) {};
    TYPE value;
    typename std::vector<Node<TYPE>>::const_iterator first, last;
};

template < template <typename, typename...> class CONTAINER
         , typename TYPE
         , typename... ARGS >
Node<TYPE> & make ( Node<TYPE> & _node
/* not correct */ , typename CONTAINER<TYPE, ARGS...>::const_iterator _first
/* not correct */ , typename CONTAINER<TYPE, ARGS...>::const_iterator _last
                  , unsigned _k )
{
    if (std::distance(_first,_last) < _k)
    {
        _node.first = _first;
        _node.last = _last;
    }
    return _node;
}

int main()
{
    unsigned k = 3;
    std::vector<int> dataset;
    int i = 4;
    Node<int> node(i);
    node = make(node, dataset.begin(), dataset.end(), k);
}

A: template <typename, typename...> class CONTAINER

Loosely speaking, this matches a template itself, like std::vector, that takes the requisite template parameters. It does not match a template instance, like std::vector<int>.
I see no particular need to get so nitty-gritty here. A simple
template <typename ITERATOR, typename TYPE>
Node<TYPE> & make ( Node<TYPE> & _node,
                    ITERATOR first, ITERATOR last, unsigned _k )

should work just fine here. If you do want to try to restrict the template parameters, in the manner that you were originally trying to do, the way to go is to declare this generic template, then try to define an appropriate specialization.


text:
Q: Guardar alguns elementos de um array em outro array Tenho definido um array de inteiro na qual será apontado por um ponteiro e depois tenho um outro array que irá armazenar apenas alguns números na quais são numero pares, eis o código...
void main(void) {

    srand(time(NULL));
    //vetor de dimensao 10
    int vetor [MAX] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    //apontador para vetor
    int *ptr_vetor;
    //novo vetor
    int novo_vetor[MAX];
    //apontador para novo vetor
    int *ptr_novo_vetor;
    //escolher numero
    int escolha = 0;
    //contador
    int contador = 0;

    //ponteiro apontado ao primeiro vetor
    ptr_vetor = &vetor[0];
}

mostra os valores do vetor
printf("\n--- Vetor ---");
    for (int i = 0; i < MAX; i++) {
        //mostra os valores do vetor
        printf("\nvalor : %d ", vetor[i]);
    }

mostra os valores pares apontador ao vetor
printf("\n\n--- Ponteiro Vetor para Numero Pares ---");
    for (int i = 0; i < MAX; i++) {
        //escolha apenas numeros pares
        if (*(ptr_vetor + i) % 2 == 0) {
            //mostra os valores pares apontador ao vetor
            printf("\nNumero Par : %d ", *(ptr_vetor + i));
            //adiciona o numero par ao novo vetor
            novo_vetor[i] = *(ptr_vetor + i);
            //aqui devia receber apenas os dados do novo vetor mas
            //mostra aepnas o endereço
            ptr_novo_vetor = &novo_vetor[i];
            //usei isto para iterar os jogadores, nao deu certo
            //contador++;
        }
    }

mostra os valores do novo vetor
printf("\n\n\n--- Novo Vetor ---");
    for (int i = 0; i < MAX; i++) {
        //mostra os valores do novo vetor
        printf("\nvalor: %d ", novo_vetor[i]);
    }

mostra os valores do novo ponteiro
printf("\n\n--- Ponteiro Novo Vetor ---");
    for (int i = 0; i < MAX; i++) {
        //mostra os valores do novo ponteiro
        printf("\nNovo Vetor : %d ", *(ptr_novo_vetor+i));
    }

ao executar o programa

Como mostrar os dados que foram adicionados ao novo array, ou seja, os números pares?

A: Vou dar uma solução que não sei se é o que deseja. Mas o código não faz muito sentido também, então não sei se fará diferença. Provavelmente está querendo fazer outra coisa e está longe do objetivo. Estou respondendo pelo que deu para entender.
Certamente tem meios melhores de fazer isto, mas não gastei muito tempo pensando no que melhorar, porque não vejo razão para este código todo existir.
#include <stdio.h>
#define MAX 10

int main(void) {

    //vetor de dimensao 10
    int vetor [MAX] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    //apontador para vetor
    int *ptr_vetor;
    //novo vetor
    int novo_vetor[MAX];
    //apontador para novo vetor
    int *ptr_novo_vetor;
    //escolher numero
//    int escolha = 0;
    //contador
//    int contador = 0;

    //ponteiro apontado ao primeiro vetor
    ptr_vetor = &vetor[0];

    printf("\n--- Vetor ---");
    for (int i = 0; i < MAX; i++) {
        //mostra os valores do vetor
        printf("\nvalor : %d ", vetor[i]);
    }

    printf("\n\n--- Ponteiro Vetor para Numero Pares ---");
    for (int i = 0; i < MAX; i++) {
        //escolha apenas numeros pares
        if (*(ptr_vetor + i) % 2 == 0) {
            //mostra os valores pares apontador ao vetor
            printf("\nNumero Par : %d ", *(ptr_vetor + i));
            //adiciona o numero par ao novo vetor
            novo_vetor[i / 2] = *(ptr_vetor + i);
        }
    }
    ptr_novo_vetor = novo_vetor;

    printf("\n\n\n--- Novo Vetor ---");
    for (int i = 0; i < MAX / 2; i++) {
        //mostra os valores do novo vetor
        printf("\nvalor: %d ", novo_vetor[i]);
    }

    printf("\n\n--- Ponteiro Novo Vetor ---");
    for (int i = 0; i < MAX / 2; i++) {
        //mostra os valores do novo ponteiro
        printf("\nNovo Vetor : %d ", *(ptr_novo_vetor+i));
    }
    return 0;
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.

A: Seu vetor resultante tem o tamanho errado. Se ele tem que receber apenas os números pares, ele não pode ter o mesmo tamanho que o vetor original. Se você fizer isso, vai ter que preencher o vetor resultante com valores que indicam vazio. Melhor seria você, já sabendo o conjunto de entrada, simplesmente criar um vetor de 5 posições.
O motivo de estar pulando posições na inserção é que você está inserindo quando i é par e colocando na posição i. Desse jeito, só as posições pares serão prenchidas.
Já o ptr_novo_vetor está mostrando esses valores esquisitos porque você nunca fez ele apontar pra lugar nenhum.


text:
Q: Convert string array values from URLSearchParams How does one convert string array values into a Javascript array object?
var querystring = 'lang[]=EN&lang[]=FR&type[]=1&type[]=2';

Into:
{
    lang: ['EN', 'FR'],
    type: ['2']
}

Below my attempt:
let params = new URLSearchParams(decodeURI(querystring));
let entries = params.entries();

let result = {}
for(let entry of entries) { // each 'entry' is a [key, value]
    result[entry[0]] = entry[1];
}
return result;

Which results in:
[{
    "name": "lang[]",
    "value": "EN"
}, {
    "name": "lang[]",
    "value": "FR"
}, {
    "name": "type[]",
    "value": "2"
}]

A: Simplest version would be to use a library like qs
https://www.npmjs.com/package/qs#parsing-arrays
var withArray = qs.parse('a[]=b&a[]=c');

ressults in
a: ['b', 'c']

A: You should probably test for the [] so your code won't break with entries not ending in []. You can then slice off the [] so your keys don't include it:

var querystring = 'lang[]=EN&lang[]=FR&type[]=1&type[]=2&test=hello';

let params = new URLSearchParams(decodeURI(querystring));
let entries = params.entries();

let result = {}
for(let entry of entries) { // each 'entry' is a [key, value]
    let [key, val] = entry
    if (key.endsWith('[]')){         // array
      key = key.slice(0,-2);         // clean up the key
      (result[key] || (result[key] = [])).push(val)
    } else {
      result[key] = val             // normal parameter
    }
}
console.log(result)

A:

var querystring = 'lang[]=EN&lang[]=FR&type[]=1&type[]=2';
let params = new URLSearchParams(decodeURI(querystring));
let entries = params.entries();

let result = {}
for(let entry of entries) { // each 'entry' is a [key, value]
    var key = entry[0];
    var val = entry[1];
    if(key in result){
        result[key].push(val);
    }else{
        result[key] = [val];
    }
}
console.log(result);


text:
Q: How to read and process millions of XML file and process only those XML files which are modified I have attended one interview where the interviewer asked me that, in a directory millions of XML files are there . I need to read those files and process it in efficient way.
Constraint 1:  Everyday I have to read only modified XML files only.
Constraint 2:  you will not get to know the last modified date and time.
I told him that we can read all XML files to some data structure as it will be faster to read data structure than file reading every-time. And compare everyday by reading XML file contents, if any modified file content files found then process only those files.
But he told me, reading all file contents into memory increases the memory .
So what should be the best approach for the above ?Can someone help me ?


text:
Q: Can accessToken JWT be trusted by AWS lambda if using Authorizer (Cognito) Noob question here but can I fully trust the data in the accessToken in the lambda function if the api is set-up to have the integrated authorizer?
Context: I am trying to read the userName (from the accessToken) which is linked to some db resources and I need to only give access to a specific resource if it is owned by that user (obviously).
Is this approach secure?


text:
Q: Create my own rake test:foo task I have a bunch of tests that aren't unit or functional tests, they're of the format test/foo/special_test.rb
I want to create a rake task like rake test:units that will run all the tests in the foo folder. How do I do this?
Edit: I'd actually like rake test:foo to be a little different from rake test:units, in that I do not want it to run when I do simply rake test.

A: I don't remember where this is from, so unfortunately I can't give proper acknowledgement, but this should work. I say "should" because I've stopped using it, but grabbed it from my git history.
# First, 'reopen' the default :test namespace and create your custom task.
namespace :test do
  Rake::TestTask.new(:foo_tests => ["test:prepare", "other_dependent_rake_tasks"] ) do |t|
    DatabaseCleaner.strategy = :transaction # If using this.

    t.libs << "test"
    # Will also get subfolders within test/foo
    t.test_files = FileList['test/foo/**/*_test.rb', 'test/foo/*_test.rb']
  end
end

You can remove the default "test" task and redefine it so that when you run rake test it will automatically also run rake test:foo_tests.
remove_task "test"

desc 'Adding onto Rails regular tests'
task :test do
  # Add all the names of tests you want run here.
  errors = %w(test:units test:functionals test:integration test:foo_tests).collect do |task|
    begin
      puts "Running: #{task}"
      Rake::Task[task].invoke
      nil
    rescue => e
      task
    end
  end.compact
  abort "Errors running #{errors * ', '}!" if errors.any?
end


text:
Q: Redirect to a previously visited URL I'm working on a MVC 5 (asp) application. One of the requirements I get is to have multiple navigation paths to point at the same destination page. The problem is going back to a previous page after a post according to the navigation history of the user.
Let's consider a basic scenario of three webpages
Customers/ShowAll -> Show a list of all customers
Customers /Search -> Show a list of customers according to a search (name, country …)
Customers /Update/1134 -> Show the update page for a specific customer (i.e. customer_id=1134)
So the navigation path goes like this
ShowAll -> Update
or
Search -> Update
If the user navigates to "Customers /Search" then "Customers /Update/1134", updates the customer information and saves the data, I want the server to redirect to the page "Customers /Search" since it's the path the user uses.
This is a very basic case but it can be more complex like going back many pages and always return a previously visited page (or a default one if no pages match the history).
What I've done so far
I have created a prototype that keeps track of the navigation history of a user on the server side. It uses session storage on the client side to give a unique id for the current browser tab. On each page unload it adds the browser tab id to the cookies. Then on the server side there's a dictionary (in the session) with the tab id (extracted from the cookies) as the key and a list of visited URLs as the value. The current URL is added to the list of URLs. I found this solution to be working but it has some flaws.

*

*If JavaScript is disabled this solution won't work (this is not a very big deal since I can require all the users to turn it on (it's an intranet for a small company))

*If a tab is duplicated the resulting two tabs will have the same id. This is due to the implementation of session storage (at least on Chrome). So the history on the server can get corrupted if the user uses both tabs.

*I store the dictionary of history in a session variable so if the session timed out, the history is lost. I thought about keeping the history in the database but I feel it's a little of overheat for the database.

A last thing is that the dictionary of URLs is limited to the last 30 pages visited since I want to limit the server memory. It's not important to my question but I feel to mention it since I'm sure some of you may see the problem of keep all pages from all users for all tabs in history.
I also thought of a similar solution using cookies to transmit the last 30 pages visited on each request and have the server parse this history when it needs it. Only the pages from the application domain will be kept. This will resolve the problem of persistence after a session times out but it introduce a little more processing to the server since the history will be parsed in about each request.
I want to know if there a better solution to redirect the user according to navigation history. Maybe there's a build-in functionality in MVC 5 that I don't know.
Thanks for any advice.
Regards.

A: Using session state (as you have discovered) is not a very good solution to this problem because:

*

*It times out, in which case the data is lost.

*If the user doesn't navigate to the page the way you expect (for example, coming directly to a page via Google SERP), then it doesn't work.

The only way to make it work 100% of the time is to put all of the navigation identifier information into the URL so the system can determine how to build the navigation links.
There is no built-in functionality for this in MVC 5, but you could use MvcSiteMapProvider to solve your issue. It contains HTML helpers for Menu and SiteMapPath, which acts like a breadcrumb trail.
@Html.MvcSiteMap().Menu()
@Html.MvcSiteMap().SiteMapPath()

It works on a different principle - it loads a single shared hierarchy of nodes (a site map) into memory. Then each request that comes in matches one of the nodes and uses the map to determine how to build the links in the HTML helpers. There is no session state used at all.
The trick to getting it to work in your scenario is to make the Customers/Update/1134 page available on 2 different URLs. Then you can configure 2 different node hierarchies and it will know which one to match based on the routing information.
For example, you could add an additional route value that indicates that the page you are navigating from is the search page.
@Html.ActionLink("Customer 1134", "Update", "Customers", new { source = "Search" }, null)

By default, this will build a URL like Customers/Update/1134?source=Search. You can make it look prettier by adjusting your route configuration.
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "SearchSource",
            url: "Search/{controller}/{action}/{id}",
            defaults: new { source = "Search", controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

        routes.MapRoute(
            name: "ShowAllSource",
            url: "ShowAll/{controller}/{action}/{id}",
            defaults: new { source = "ShowAll", controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

Now with the same ActionLink shown above, you will get the URL /Search/Customers/Update/1134. That's better. Note that when you put the ActionLink on your ShowAll page, it should be like this instead:
@Html.ActionLink("Customer 1134", "Update", "Customers", new { source = "ShowAll" }, null)

Then when you set up the node configuration in MvcSiteMapProvider, you need to make 2 different parent nodes, like this.
<mvcSiteMapNode title="Home" controller="Home" action="Index">

    <!-- Additional nodes here -->

    <mvcSiteMapNode title="Search" controller="Customers" action="Search">
        <mvcSiteMapNode title="Update Customer" controller="Customers" action="Update" source="Search" preservedRouteParameters="id"/>
    </mvcSiteMapNode>
    <mvcSiteMapNode title="Show All Customers" controller="Customers" action="ShowAll">
        <mvcSiteMapNode title="Update Customer" controller="Customers" action="Update" source="ShowAll" preservedRouteParameters="id"/>
    </mvcSiteMapNode>

    <!-- Additional nodes here -->

</mvcSiteMapNode>

You will then get a complete navigation solution:
/Customers/ShowAll                  | Home > Show All Customers
/ShowAll/Customers/Update/1134      | Home > Show All Customers > Update Customer
/Customers/Search                   | Home > Search
/Search/Customers/Update/1134       | Home > Search > Update Customer

Of course, this is just an example. You can make the URLs and navigation links look any way you want.
Redirecting Back
Finally, there is redirecting back to the location the user came from. That's easy because MvcSiteMapProvider keeps track of the parent node.
[HttpPost]
public ActionResult Update(CustomerModel model)
{
    // Update customer here...

    var currentNode = this.GetCurrentSiteMapNode();
    if (currentNode != null)
    {
        var parentNode = currentNode.ParentNode;
        if (parentNode != null)
        {
            return Redirect(parentNode.Url);
        }
    }

    return View(model);
}

You may wish to store some additional information (sort order, search term, etc) from the original parent page, in which case you will need to pass those parameters through the Update page and back to the parent page somehow.
One way is to use session and then use some logical default behavior if they are missing when you get to the redirect page.
Another (easier) approach is to add them as parameters (query string or route values) to the URL of the Customer Update page so they will automatically be built into the return URL. Since you have 2 different routes, you would just need to add the information to the appropriate route. You just need to ensure both the routes of the Search page and the Customer Update page include them so the parent URL is built appropriately.

Full Disclosure: I am a major contributor of the MvcSiteMapProvider project.

See also:

*

*https://github.com/maartenba/mvcsitemapprovider/wiki/Multiple-Navigation-Paths-to-a-Single-Page

*http://www.shiningtreasures.com/post/2013/08/07/MvcSiteMapProvider-40-a-test-drive

*http://www.shiningtreasures.com/post/2013/09/02/how-to-make-mvcsitemapprovider-remember-a-user-position


text:
Q: Redirect code not working I have the ff.code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<title>Videos</title>
<link href="normal.css" rel="stylesheet" />

New Session

Videos

Slide Shows

Forms

Surveys

Websites

Interactive

Admin

I wonder why when I click the videos button, it isn't redirecting. any ideas?

A: Try to uncomment the line:
//window.location.href = "http://stackoverflow.com";
and comment the line:
$(location).attr('href',"google.com");

A: Instead of

Videos

try

Videos

A: Additionally to what Andrew suggests, if you need to have the anchor tag, either remove the href attribute from the anchor or add a preventDefault() to the click handler as:
$('.videos').click(function(e){
    // note that if you redirect to google.com only, it a relative redirect...
    // so to go to the actual www.google.com site, use the full url
    $(location).attr('href',"http://www.google.com");
    e.preventDefault();
});


text:
Q: I cannot setImageBitmap I'm getting an image (string) from my database and then I'm turning this string into a byte array, but it's not showing in ImageView
Below is my Activity code.
protected Void doInBackground(Void... params) {

    try {
        imageString = WallPaper.getWallPapers(); // return the string for image
        runOnUiThread(new Runnable() {
            @Override
            public void run()
            {
                byte [] imageByte = Base64.decode(imageString, Base64.DEFAULT);
                Bitmap bmp = BitmapFactory.decodeByteArray(imageByte, 0, imageByte.length);
                imageView.setImageBitmap(bmp);
            }
        });

    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return null;
}

Layout:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/app_bar_main"
tools:context="com.example.burak.apps.MainActivity">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView2"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />
</RelativeLayout>

A: Try this piece of code instead ....
byte[] imageByte = Base64.decode(imageString,Base64.NO_WRAP);
InputStream inputStream  = new ByteArrayInputStream(imageByte);
Bitmap bmp = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bmp);


text:
Q: How to convert this example from python2 to python3 I'm trying to convert a working example in github from python2 to python3 and running into a problem I don't understand.
The original is https://gist.github.com/EugeneBakin/76c8f9bcec5b390e45df
I apply the following patch and get an error message about too many arguments to the SampleApp init method.  Since I don't understand why the original had its *args and **kwargs when the only call had no arguments at all, something is not adding up for me.  But it worked in python2, so I was hoping it would work in python3 as well, because I recognize that usage as useful.
However, it may not matter because the stack trace on the error message does not include that call, or any call for that matter.  Another puzzle.
I want to solve this without just blindly removing arguments because I may need some when I go to apply this in my real use case.
I also want to remove importing as *, as I regard it as dangerous and as hiding information useful to a reader.
The patch:
--- VSFrame.py  2017-12-16 14:30:33.458923856 -0800
+++ VSFrame3.py 2017-12-16 15:01:21.914423486 -0800
@@ -1,21 +1,21 @@
-#!/usr/bin/python
+#!/usr/bin/env python3
 # -*- coding: utf-8 -*-
-from Tkinter import *   # from x import * is bad practice
-from ttk import *
+import tkinter as tk
+import tkinter.ttk as ttk

 # http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame

-class VerticalScrolledFrame(Frame):
+class VerticalScrolledFrame(ttk.Frame):
     """A pure Tkinter scrollable frame that actually works!
     * Use the 'interior' attribute to place widgets inside the scrollable frame
     * Construct and pack/place/grid normally
     * This frame only allows vertical scrolling
     """
     def __init__(self, parent, *args, **kw):
-        Frame.__init__(self, parent, *args, **kw)
+        super().__init__(self, parent, *args, **kw)

         # create a canvas object and a vertical scrollbar for scrolling it
-        vscrollbar = Scrollbar(self, orient=VERTICAL)
+        vscrollbar = ttk.Scrollbar(self, orient=VERTICAL)
         vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
         canvas = Canvas(self, bd=0, highlightthickness=0,
                         yscrollcommand=vscrollbar.set)
@@ -51,9 +51,9 @@

 if __name__ == "__main__":

-    class SampleApp(Tk):
+    class SampleApp(tk):
         def __init__(self, *args, **kwargs):
-            root = Tk.__init__(self, *args, **kwargs)
+            root = tk.__init__(self, *args, **kwargs)

             self.frame = VerticalScrolledFrame(root)

And after the comment by Willem (thanks for that), it is now
--- VSFrame.py  2017-12-16 14:30:33.458923856 -0800
+++ VSFrame3.py 2017-12-16 16:04:00.938380716 -0800
@@ -1,21 +1,21 @@
-#!/usr/bin/python
+#!/usr/bin/env python3
 # -*- coding: utf-8 -*-
-from Tkinter import *   # from x import * is bad practice
-from ttk import *
+import tkinter as tk
+import tkinter.ttk as ttk

 # http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame

-class VerticalScrolledFrame(Frame):
+class VerticalScrolledFrame(ttk.Frame):
     """A pure Tkinter scrollable frame that actually works!
     * Use the 'interior' attribute to place widgets inside the scrollable frame
     * Construct and pack/place/grid normally
     * This frame only allows vertical scrolling
     """
     def __init__(self, parent, *args, **kw):
-        Frame.__init__(self, parent, *args, **kw)
+        super().__init__(self, parent, *args, **kw)

         # create a canvas object and a vertical scrollbar for scrolling it
-        vscrollbar = Scrollbar(self, orient=VERTICAL)
+        vscrollbar = ttk.Scrollbar(self, orient=VERTICAL)
         vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
         canvas = Canvas(self, bd=0, highlightthickness=0,
                         yscrollcommand=vscrollbar.set)
@@ -51,10 +51,9 @@

 if __name__ == "__main__":

-    class SampleApp(Tk):
+    class SampleApp(tk.Tk):
         def __init__(self, *args, **kwargs):
-            root = Tk.__init__(self, *args, **kwargs)
-
+            root = tk.TK.__init__(self, *args, **kwargs)

             self.frame = VerticalScrolledFrame(root)
             self.frame.pack()

A: I got it working by making it conform more nearly to the style in https://docs.python.org/3.5/library/tkinter.html#a-simple-hello-world-program
Full source follows.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tkinter as tk
import tkinter.ttk as ttk

# Python3 version of http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame

class VerticalScrolledFrame(ttk.Frame):
    """A pure Tkinter scrollable frame that actually works!
    * Use the 'interior' attribute to place widgets inside the scrollable frame
    * Construct and pack/place/grid normally
    * This frame only allows vertical scrolling
    """
    def __init__(self, parent):
        super().__init__(parent)

        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = ttk.Scrollbar(self, orient=tk.VERTICAL)
        vscrollbar.pack(fill=tk.Y, side=tk.RIGHT, expand=tk.FALSE)
        canvas = tk.Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=vscrollbar.set)
        canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=tk.TRUE)
        vscrollbar.config(command=canvas.yview)

        # reset the view
        canvas.xview_moveto(0)
        canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = interior = ttk.Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior,
                                           anchor=tk.NW)

        # track changes to the canvas and frame width and sync them,
        # also updating the scrollbar
        def _configure_interior(event):
            # update the scrollbars to match the size of the inner frame
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the canvas's width to fit the inner frame
                canvas.config(width=interior.winfo_reqwidth())
        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
        canvas.bind('<Configure>', _configure_canvas)

if __name__ == "__main__":

    class SampleApp(ttk.Frame):
        def __init__(self, master=None):
            super().__init__(master)
            self.create_widgets()

        def create_widgets(self):
            self.frame = VerticalScrolledFrame(root)
            self.frame.pack()
            self.label = ttk.Label(text="Shrink the window to activate the scrollbar.")
            self.label.pack()
            buttons = []
            for i in range(10):
                buttons.append(ttk.Button(self.frame.interior, text="Button " + str(i)))
                buttons[-1].pack()

    root = tk.Tk()
    app = SampleApp(master=root)
    app.mainloop()


text:
Q: Alarm manager or sound notification are not working in release mode Android 13 I've built an application that may notify a user after some period in time.
By "notify" I mean to play a sound using flutter_ringtone_player plugin.
The android_alarm_manager_plus is used to schedule a notification.
The problem is that it has stopped to work (to make a sound) after some moment in time.
I suppose it is because of Flutter version upgrade or Android 13 version installed on the phone.
The oneShot method duration is from 30 to 300 seconds I have tried.
Here is code I'm using to schedule method execution:
    var dr = Duration(seconds: config.delay);
    await saveShared(config);
    _scheduled = await AndroidAlarmManager.oneShot(dr, helloAlarmID, playAlarm,
        exact: true, wakeup: true, alarmClock: true, allowWhileIdle: true);
    return _scheduled;

playAlarm method implemented as below
  static void playAlarm() async {
    var config = await loadShared();
    playImpl(config)
        .then((_) => _scheduled = false)
        .onError((error, stackTrace) {
      print("failed to play notification");
      print(error);
      return true;
    });
  }

The whole NotifyModel class is here used to schedule and play notification.
The AndroidManifest file.
The same code is working on

*

*emulator API 29

*emulator API 33

*Pixel 4a phone (Android 13) in debug mode from VSCode

The problem is that it fails to work when built as release and installed from GooglePlay on the same Pixel 4a phone that is used to debug.
I do not have any plugin registration call in the playAlarm or playImpl method implementation.
The playImpl(ConfigNotify? config) method is called from both AlarmManager and UI button click. Both FlutterRingtonePlayer.play and FlutterRingtonePlayer.playNotification are working properly when called form UI.
What should I check to understand the reason of the difference between debug and release application on Android 13?
[✓] Flutter (Channel stable, 3.3.1, on Ubuntu 22.04.1 LTS 5.15.0-48-generic, locale en_US.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
[✓] VS Code (version 1.71.2)

upd
I've just found the similar issue however can't get it working yet using Flutter 3.0.5

A: The @pragma('vm:entry-point') annotation has to be applied to the callback function when using Flutter 3.3 and Alarm manager Plus 2.0.7


text:
Q: Derive standard deviation from mean, sample size and 95% CI I am planning a clinical study and need to determine the needed sample size. My primary endpoint will be measured in blood pressure (mmHg). Many studies already exist for this, but they do not often provide sdev for the measurements of blood pressure in hypertensive patients. I did, find a study in Germany (DEGS) that provided the mean blood pressure for treated hypertension and I based my sample size estimation on this. Specifically, I used the values from Treated hypertension in Table 3 Total, namely 130.3 mmHg (129.2 - 131.4) with a n of 7095*0.154 (see DEGS Table 2 Total lower row)
Following the approach described here, I then used

to arrive at a sdev of 18.55125 mmHg.
My question is now: did I do this right? Thank you all for your guidance!

A: The usual approach is to reverse the computation for the confidence interval so we take the half width of the confidence interval and then divide it by the relevant quantile of the normal or Student's $t$ distribution to give the standard error. Multiplying this by the square root of the sample size yields the standard deviation.
The only reservation about this is that Brown in a paper entitled On the use of a pilot sample for sample size determination suggests that if the standard deviation comes from a small pilot study it might be better to use instead the upper 80% confidence limit. This is because the distribution of the standard deviation is skewed and so the obtained value will under-estimate the true value. If the study being used for the estimate is large this is unlikely to make much difference.


text:
Q: Deleting specific row from ms word table that contains a specific word I am having a table in MS Word and trying to delete some specific rows from it. I have a vba script but it deletes rows from all the tables. I just want to delete rows from table number 2. Here is my code:
Sub DeleteRowWithSpecifiedText()
Selection.Find.ClearFormatting
With .Tables.Find
    .Text = "Moderate"
    .Wrap = wdFindContinue
End With
Do While Selection.Find.Execute
    If Selection.Information(wdWithInTable) Then
        Selection.Rows.Delete
    End If
Loop

End Sub

How do I specify the table in it to delete rows that contain Moderate in column # 3? I am totally new to VBA. Please help me figure this out
Updating Requirements

*

*I need to delete all rows that contain Moderate or Empty in column 3

*I need to sort my tables based on the values in Column 3 which are Critical, High, Moderate
3.Change the colors of cell3/row as critical, high: red, moderate: orange, low: yellow (If possible.)

I am working on the above tasks but not finding a proper way to do it in MS Word. Is there any extension available or something which can do the task or VBA is better or what? Thanks a lot for your time
More Question from your script
How do I remove the row that has no content in Col3 as there is Moderate and Empty? Sorry for being too much dumb,

A: For example:
Sub Demo()
Application.ScreenUpdating = False
Dim Rng As Range, r As Long, Clr As Long, bFit As Boolean
Const StrFnd As String = "|Moderate|Empty"
Const MyColorOrange As Long = 41215
With ActiveDocument.Tables(2)
  bFit = .AllowAutoFit
  .AllowAutoFit = False
  For r = 1 To UBound(Split(StrFnd, "|"))
    Set Rng = .Range
    With .Range
      With .Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = Split(StrFnd, "|")(r)
        .Replacement.Text = ""
        .Format = False
        .Forward = True
        .Wrap = wdFindStop
        .MatchCase = False
        .MatchWholeWord = True
      End With
      Do While .Find.Execute
        If .InRange(Rng) = False Then Exit Do
        If .Cells(1).ColumnIndex = 3 Then .Rows(1).Delete
        .Collapse wdCollapseEnd
      Loop
    End With
  Next
  For r = 2 To .Rows.Count
    With .Cell(r, 3)
      Select Case Split(.Range.Text, vbCr)(0)
        Case "Critical": Clr = wdColorRed
        Case "High": Clr = MyColorOrange
        Case "Moderate": Clr = wdColorYellow: .Range.Text = "X"
        Case "Low": Clr = wdColorBrightGreen: .Range.Text = "Y"
        Case Else: Clr = wdColorAutomatic: .Range.Text = "Z"
      End Select
      .Row.Shading.BackgroundPatternColor = Clr
    End With
  Next
  .Sort ExcludeHeader:=True, FieldNumber:=3, SortFieldType:=wdSortFieldAlphanumeric, SortOrder:=wdSortOrderAscending
  With .Range
    With .Find
      .ClearFormatting
      .Replacement.ClearFormatting
      .Text = "[XYZ]"
      .Replacement.Text = ""
      .Format = False
      .Forward = True
      .Wrap = wdFindStop
      .MatchWildcards = True
    End With
    Do While .Find.Execute
      If .InRange(Rng) = False Then Exit Do
      If .Cells(1).ColumnIndex = 3 Then
        Select Case .Text
          Case "X": .Text = "Moderate"
          Case "Y": .Text = "Low"
          Case "Z": .Rows(1).Delete
        End Select
      End If
      .Collapse wdCollapseEnd
    Loop
  End With
  .AllowAutoFit = bFit
End With
Application.ScreenUpdating = True
End Sub

With a long table, the Find/Replace should be faster than looping through all rows.
Your additional specifications are ambiguous. Your first specification includes deleting all rows containing 'Moderate' in column 3, but in specifications 2 & 3 you say you want those rows sorted and shaded. Specification 3 introduces cells containing 'Low', but these aren't mentioned in your sorting requirements at specification 2. It's also not apparent what shading 'Critical' should have. It's impossible to code to such inconsistent specifications. If you want to keep the 'Moderate' rows, delete '|Moderate' from:
Const StrFnd As String = "|Moderate|Empty"

With your additional specifications, looping though all remaining table rows will still be required. See updated code. I've assumed all retained rows require different shading according to whether they're Critical, High, Moderate, or Low. Change the shading specs (i.e. Clr) to suit whatever your real requirements are.
If you want to shade only the conditional cell, rather than the entire row, change:
.Row.Shading.BackgroundPatternColor = Clr

to:
.Shading.BackgroundPatternColor = Clr

A: You can solve this very easy and straight forward. Try this.
sub deleteRowsWithModerate()
Dim T As Table
Dim r As row
'  Set your 2nd Table as the one to be worked on
Set T = ActiveDocument.Tables(2)

'iterate over all rows, check if the 3rd cell (= 3rd column) of each row has the desired String in it.
For Each r In T.Rows
  If InStr(r.Cells(3).Range.text, "Moderate") Then r.Delete
Next

End sub

Notice that
If r.Cells(3).Range.text = "Moderate" then
wont work, because the text of a cells always has a hidden placeholder in it, so the cell-text is like "moderate" & chr(13) & chr(7).


text:
Q: RabbitMQ and DB transactions Does RabbitMQ support a scenario where a received message acknowledgement is sent on the DB transaction commit?
Currently we send ack after DB transaction commit. If service fails inbetween, we'll get data duplication - service will get the same message again.
Is there a pattern for this problem?
Thanks!

A: Yes it does, but do be aware that RabbitMQ uses its own DB for message storage (at the moment).  To get RabbitMQ to send an ack to the publisher, use TX mode.  This is documented in the spec and on various parts of our web site.
If you want to use your own DB then you may want to set it up as an end consumer for messages.  In this case, you should use your own application-level ack.
Do feel free to email the rabbitmq-discuss for more info and questions.
HTH
alexis


text:
Q: Design pattern usage I have the following design:

*

*I create a class containing properties (like a very big array)

*Later when I parse the file I want some 'extra parameters/functionality' added, based on the content of the properties in above.

What is the best solution?

*

*Derive a class with the extra parameters/functionality (problem: need to copy the big array to the new class)

*Decorator pattern? Or is a decorator not meant for adding extra properties/functions?

*Strategy pattern? Since I need properties likely not usable.

*Another solution?

A: You can create a class for AdditionalValues, add one instance to your array and when you need the new values you can set them to the given object.


text:
Q: GET json data array within a array in Titanium 'This is my JSON messgae. im trying to list item name under the category. Before trying this i just try to print all item name in single window without category in Titanium. But my code is not working.'
  {
     "name" : "Nation",
      {.......
   },
   "menus" : [
   {
          "menuId" : 33,
          "menuName": "Breakfast",
           .........{
          },
         "menuItems": [
          {
          "itemName": "Thrilled Cheese",
                "category": "Entree",
           },
           {
          "itemName": "Today's Soup - Small",
                "category": "Entree",
           },
           {
          "itemName": "Lrg. Fountain Drink",
                "category": "Entree",
           },
           {
          "itemName": "Lemon Juice",
                "category": "Entree",
           },
           ...........}
           ]
        },

       {
          "menuId" : 34,
          "menuName": "Dinner",
           .........{
          },
         "menuItems": [
          {
          "itemName": "Sweepstakes Entry",
                "category": "Entree",
           },
           {
          "itemName": "Veggie Breakfast Burrito",
                "category": "Entree",
           },
           {
          "itemName": "Sm. Fountain Drink",
                "category": "Drink",
           },
           {
          "itemName": "Med. Fountain Drink",
                "category": "Drink",
           },
           ...........
           ]
         ]
     }

'This is my code to print all item name in single window without category '
     var json = JSON.parse(this.responseText);
    for (var i = 0; i < json.menus.length; i++) {

        for (var j = 0; j < json.menus[i].menuitems[j].lenght; j++) {

            var row = Ti.UI.createTableViewRow({
                height: 60,
            });

            var itemLabel = Ti.UI.createLabel({
                text: json.menus[i].menuItems[j].menuItems.itemName,
                height: 'auto',
                left:54,
                top: 5,
                font:{ fontSize:20 }
            });

            row.add(itemLabel);
            data.push(row);

       }
    }

    tableview.setData(data);

A: You have a typo in the second for loop for the length.
 for (var j = 0; j < json.menus[i].menuitems[j].lenght; j++) {

to
 for (var j = 0; j < json.menus[i].menuitems[j].length; j++) {


text:
Q: How do I send a javascript object in a querystring? I want to send this javascript object in a query string so that I can use it as an object when received by the server. Currently, I am using an xhr request:
        const xhr = new XMLHttpRequest();
        var params = {
            searchParams: {name: 'Joe'},
            sortParam: {name: -1},
            skip: 0,
            limit: 50
        };
        xhr.open('get', '/api/endpoint' + formatParams(params));
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xhr.responseType = 'json';
        xhr.addEventListener('load', () => {
            if (xhr.status === 200) {
                ...
            }
            else{
                ...
            }
        });
        xhr.send();

Where formatParams function is as follows:
const formatParams = ( params ) => {
    return "?" + Object
            .keys(params)
            .map(function(key){
                return key+"="+params[key]
            })
            .join("&")
};

On the server I am receiving the request via an Express Router, where the parameters are subsequently used in a MongoDB query:
const express = require('express');
const router = new express.Router();
router.get('/endpoint', (req, res) => {
    console.log(req.query.searchParams);
    ...
});

Currently, the server is showing req.query.searchParams as a string

[object Object]

A: There are a few issues here:

*

*key and params[key] should be url-encoded, you can use encodeURIComponent(...) for this (it's a standard function)

*Since params[key] is an object in two cases (searchParam, sortParam), the string presentation will be [Object object]. Instead try:  return encodeURIComponent(key) + '=' + encodeURIComponent(JSON.stringify(params[key]))

*On the server-side, you probably need to run JSON.parse(req.query.searchParams) to get your object back


text:
Q: Broadcast retrieved results from DB with accessors to socket.io or javascript Problem: I cannot retrieve an accessor argument in javascript file in Laravel 5.4
Scenario:

*

*Get data

*Modify retrieved data with Accessors

*Via Event broadcast to Listeners

*Catch a broadcasted event in javascript with socket.io

In App/SomeModel.php I am doing a manipulation over retrieved data by using Eloquent.
Based on priority number, I assign a correct class name for bootstrap styling.
/**
 * Gets corresponding class name based on priority level.
 *
 * @return string
 */
public function getPriorityClassAttribute(): string
{
    switch ($this->priority) {
        default:
            return '';
        case 1:
            return 'info';
        case 2:
            return 'success';
        case 3:
            return 'warning';
        case 4:
            return 'danger';
    }
}

Then I can access $somedata->priority_class everywhere across the application.
But I cannot pass those data to the Listeners in javascript. I don't know how should I add it to the data object.
Here is a var_dump() in my Event broadcaster:
#attributes: array:2 [
"priority" => 2
"id" => 128

]
Why there is no priority_class while it works if I want to $somedata->priority_class ?
Any tips ?

A: Got it! All I had to do, is to insert an attribute to protected $appends array;
/**
 * Append accessors to JSON response
 *
 * @var array
 */
protected $appends = [
    'priority_class'
];


text:
Q: What am I doing that's unnecessary? (iPhone, OpenGL ES) I'm using OpenGL ES to draw things in my iPhone game.  Sometimes I like to change the alpha of the textures I'm drawing.  Here is the (working) code I use.  What, if anything, in this code sample is unnecessary?  Thanks!
    // draw texture with alpha "myAlpha"
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,GL_COMBINE );
    glTexEnvf(GL_TEXTURE_ENV, GL_COMBINE_RGB,GL_MODULATE);
    glTexEnvf(GL_TEXTURE_ENV, GL_SRC0_RGB,GL_PRIMARY_COLOR);
    glTexEnvf(GL_TEXTURE_ENV, GL_OPERAND0_RGB,GL_SRC_COLOR);
    glTexEnvf(GL_TEXTURE_ENV, GL_SRC1_RGB,GL_TEXTURE);
    glTexEnvf(GL_TEXTURE_ENV, GL_OPERAND1_RGB,GL_SRC_COLOR);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glEnable(GL_BLEND);
    glTexEnvf(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR);
    glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
    glColor4f(myAlpha, myAlpha, myAlpha, myAlpha);

    glPushMatrix();
    glTranslatef(xLoc, yLoc, 0);
    [MyTexture drawAtPoint:CGPointZero];
    glPopMatrix();

    glColor4f(1.0, 1.0, 1.0, 1.0);

Edit:
The above code sample is for drawing w/ a modified alpha value (so I can fade things in and out).  When I just want to draw w/o modifying the alpha value I'd use the last 5 lines of the above sample just without the last call to glColor4f.

A: I'm not a expert but I was reading the Optimizing OpenGL ES for iPhone OS and it had a section on "Optimizing Texturing" which may help you out.

A: You have calls to configure both the Texture Environment and Framebuffer Blending, which are entirely different features.  You are also calling glTexEnvf(GL_TEXTURE_ENV, GL_OPERAND1_RGB, x) twice before drawing, and so only the second call matters.
If all you really want to do is multiply the primary color by the texture color, then it is as simple as glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE).  The rest of the calls to glTexEnv are unnecessary.

A: My drawing looks like:
glBindTexture(GL_TEXTURE_2D, tex->name); // bind to the name
glVertexPointer(3, GL_FLOAT, 0, vertices); // verices is the alignment in triangles
glTexCoordPointer(2, GL_FLOAT, 0, coordinates); // coordinates describes the rectangle
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); //draw

It's hard to know what you can remove without knowing exactly what you're trying to do.
edit:
Unless you are disabling blend at some point, you can get rid of all of the blend calls:
glEnable(GL_BLEND);
glBlendFunc...

Put them in the initialization of your GL state if you need to set it once.  If you need to enable and disable it is better to set the state once for everything you need to draw blended and then set the state again (once) for the unblended.
OpenGL is a state machine so this general idea applies anywhere you need to change the GL state (like setting texture environment with glTexEnvf).
About state machines:

A current state is determined by past
  states of the system. As such, it can
  be said to record information about
  the past, i.e., it reflects the input
  changes from the system start to the
  present moment. A transition indicates
  a state change and is described by a
  condition that would need to be
  fulfilled to enable the transition.


text:
Q: Too many redirects issue [redirect loop] after modifying htaccess to https redirect in SocialEngine 4.2.9 Recently I have installed the ssl certificate for our domain. And as part of https secure redirection, changed the htaccess to redirect to https. It works fine with the home page. But when I am login as a user or as an admin, the redirection fails and getting a message like too many redirects and page loading is failed due to redirect looping back and forth between https and http. Please help me to solve this issue.
Please find the current htaccess file that I am using
<IfModule mod_rewrite.c>
  Options +FollowSymLinks
  RewriteEngine On

  RewriteCond %{SERVER_PORT} 80
  RewriteRule ^(.*)$ https://www.flatparty.com/$1 [R,L]

  RewriteRule ^(blog)($|/) - [L]

  # Get rid of index.php
  RewriteCond %{REQUEST_URI} /index\.php
  RewriteRule (.*) index.php?rewrite=2 [L,QSA]

  # Rewrite all directory-looking urls
  RewriteCond %{REQUEST_URI} /$
  RewriteRule (.*) index.php?rewrite=1 [L,QSA]

  # Try to route missing files
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} public\/ [OR]
  RewriteCond %{REQUEST_FILENAME} \.(jpg|gif|png|ico|flv|htm|html|php|css|js)$
  RewriteRule . - [L]

  # If the file doesn't exist, rewrite to index
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?rewrite=1 [L,QSA]

</IfModule>

When I access https://www.flatparty.com it works fine. But once I logged in gets the redirection issue.

A: Add below code in htaccess file.
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

A: Finally I got the fix for the issue !!. It was not the issue with .htaccess content, it was the issue with the server code. The following code was the reason for the redirect loop issue.
$host = $_SERVER['HTTP_HOST'];
$request_uri = $_SERVER['REQUEST_URI'];
$good_url = "http://" . $host . $request_uri;

header("HTTP/1.1 301 Moved Permanently");
header("Location: $good_url");

The .htaccess code is working fine and whenever htaccess redirects url to https and the above mentioned code gets redirected to http and eventually it leads to an infinite loop and request will never completes.
Thanks for the help and suggestions.


text:
Q: Using function pointers as part of a linked list I am writing a Lisp interpreter and I've decided to store the environment's symbols (true, false, cons, car, cdr, variables etc.) in a linked list, with each "entry" using the same structure used to store lisp atoms (in my code called a "cell").
The following structs and enums are defined:
typedef enum {STRING, FLOAT, SYMBOL, LIST} ctype;
typedef struct { void* data; ctype type; void* next; } cell;

I used a void* with data to point to the atom (or a symbol) so that I didn't have to fiddle with unions. next points to the next cell. Since s-expressions can be nested, data can also point to a cell, meaning that this implementation could have nested lists.
The following fundamental Lisp functions are defined as such:
cell* cons(cell* car, cell* cdr) { car->next = cdr; return car; }
cell* car(cell* head) { return head; }
cell* cdr(cell* head) { return head->next; }

and a function stnode() is defined so that the manual memory allocation can be taken care of and cells can quickly be created:
cell* stnode(void* data, ctype type) {
    cell* tmp = malloc(sizeof(cell));
    tmp->data = malloc(sizeof(data));
    tmp->type = type;
    memcpy(tmp->data, data, sizeof(data));
    return tmp;
}

Finally, I have the function stdenv, which returns a Linked List of cells containing pointers to functions that I would like to use in my lisp. These are cons(), car() and cdr().
cell* stdenv() {
    return cons(stnode(&cons, SYMBOL), cons(stnode(&car, SYMBOL), stnode(&cdr, SYMBOL))); }

There are better recursive ways to achieve the above code, but I'll cross that bridge when I get to it. At this point with so little code it isn't worth adding complexity before I can guarantee the code actually works.
I've tested stnode() with strings, booleans, integers and pointers to other structs, which all work fine (with proper void pointer dereferencing in place, of course) but I can't get function pointers to work. The problematic code is stdenv(), here's the code I tried to use to test it:
cell* symbols = stdenv();
cell* cd = *(*symbols->data)(symbols);
printf("%p\n", cd->data);

...the assumption being that if everything was working as I expected, I should be presented with the memory address in the function (because of how I wrote stdenv in this case it should be cons()).
Compiling with GCC on Ubuntu got me the following warnings and errors:
lisp.c: In function 'main':
lisp.c:26:15: warning: dereferencing 'void *' pointer
   26 |  cell* cd = *(*symbols->data)(symbols);
      |               ^~~~~~~~~~~~~~
lisp.c:26:15: error: called object is not a function or function pointer
   26 |  cell* cd = *(*symbols->data)(symbols);
      |              ~^~~~~~~~~~~~~~~

I can't figure out what's wrong with the code for stdenv, since I've passed the memory address of each function to cons().


text:
Q: Check location settings changes at runtime I'm using a basic location updates behavior to get user location, as explained in this documentation.
It works pretty well, but I'm stuck with something that seemed to be simple:
How can I know if the user disable his location while the app is running?
I can check if location is enabled using Settings Client when starting my activity, but how to do so at runtime?

A: There's a broadcast for that: https://developer.android.com/reference/android/location/LocationManager.html#MODE_CHANGED_ACTION
code is something like:
private final IntentFilter filter =
          new IntentFilter(LocationManager.MODE_CHANGED_ACTION);

private final BroadcastReceiver receiver = new BroadcastReceiver() {
   @Override public void onReceive(Context context, Intent intent) {
       if(LocationManager.MODE_CHANGED_ACTION.equals(intent.getAction()) {
            // check here the new location status
       }
   }
};

// then to register
context.registerReceiver(receiver, filter);
/// and unregister
context.unregisterReceiver(receiver);


text:
Q: Creating a notiftication when function is initiated in a Shiny Application I have the following R Shiny Application:
library(shiny)

shinyApp(
  ui = dashboardPage(
    dashboardHeader(
      title = "Tweetminer",
      titleWidth = 350
    ),
    dashboardSidebar(
      width = 350,
      sidebarMenu(
        menuItem("Menu Item")
      )
    ),
    dashboardBody(
      fluidRow(
        tabBox(
          tabPanel("Select tweets",
                   numericInput("tweet_amount", "Amount of tweets:", 10, min = 1, max = 100),
                   div(style="display:inline-block",numericInput("tweet_long", "Longitude:", 10, min = 1, max = 100)),
                   div(style="display:inline-block",numericInput("tweet_lat", "Latitude:", 10, min = 1, max = 100)),
                   #selectInput("tweet_name", "Account name", choices = c("@realDonaldTrump","@GorgeNails"), width = NULL, placeholder = NULL),
                   selectInput("tweet_name", "Account name", choices = c("@realDonaldTrump","@Yankees"), selected = NULL, multiple = FALSE,
                               selectize = TRUE, width = NULL, size = NULL),
                   actionButton("get_tweets", "Fetch the tweets"),
                   hidden(
                     div(id='text_div',
                         verbatimTextOutput("text")
                     )
                   )
                  )
        )
      )
    )
  ),
  server = function(input, output) {

  test_list <- c(1,2,3)
  run_function <- reactive({
    for(i in test_list){
      Sys.sleep(2)
    }
  })

  observeEvent(input$get_tweets, {
    run_function()
    toggle('text_div')
    output$text <- renderText({"You're now connecting to the API"})
  })
  }
)

This application should allow users to input parameters after which tweets will be scraped. However - because it will take some time Im looking for a way to inform users this will take a while.
Using this function:
 observeEvent(input$get_tweets, {
    run_function()
    toggle('text_div')
    output$text <- renderText({"You're now connecting to the API"})
  })

I inform the user that the function (run_function() in this example, a mockup but just for reproducing purposes) is ready. However Im looking for a notice after you initiate the function and when its done.
So after you press the first time it should say something like - function initiated and after the function is ready -> "You .. api".
Any thoughts on what I should change to get this working?

A: You can use withProgress function, check this example:
output$plot <- renderPlot({
    withProgress(message = 'Calculation in progress', detail = 'This may take a while...', value = 0, {
      for (i in 1:15) {
        incProgress(1/15)
        Sys.sleep(0.25)
      }
    })
    plot(cars)
  })

More info

EDIT: New example:
library(shiny)

ui <- fluidPage(
    actionButton(inputId = 'DoSomething', label = 'Do something'),
    verbatimTextOutput('t1')
)

server <- function(input, output, session) {

    output$t1 <- renderPrint('Doing nothing...')

    run_function <- reactive({

        withProgress(message = "Starting...", max = 60, value = 0, {

            for (i in 1:25) {
                incProgress(1)
                Sys.sleep(0.25)
            }

            setProgress(message = "Connected..")

            for (i in 1:25) {
                incProgress(1)
                Sys.sleep(0.25)
            }

            setProgress(message = "Doing Stuffs...")

            for (i in 1:10) {
                incProgress(1)
                Sys.sleep(0.25)
            }

            setProgress(message = "Disconecting...")
        })

        return('Finish')
    })

    observeEvent(input$DoSomething, {

        output$t1 <- renderPrint(run_function())

    })
}
shinyApp(ui, server)


text:
Q: All controls on a form are invisible I've run into a bizarre problem. Given only this code (that I've cut down to the bare essentials), the form will appear but all controls on it are invisible, even though their individual Visible properties are true:
static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new WaveformWindow());
    }
}

// ...

public partial class WaveformWindow : Form
{
    public WaveformWindow()
    {
        InitializeComponent();
    }
}

// ...

partial class WaveformWindow
{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.label1 = new System.Windows.Forms.Label();
        this.SuspendLayout();
        //
        // label1
        //
        this.label1.AutoSize = true;
        this.label1.Location = new System.Drawing.Point(27, 27);
        this.label1.Name = "label1";
        this.label1.Size = new System.Drawing.Size(35, 13);
        this.label1.TabIndex = 4;
        this.label1.Text = "label1";
        //
        // WaveformWindow
        //
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(398, 373);
        this.Name = "WaveformWindow";
        this.ShowInTaskbar = false;
        this.Text = "WaveformWindow";
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.Label label1;
}

Comparing between working and broken versions of the non-stripped program, the only file that changed is the form designer file.

A: Add the controls to the form to make them visible.
See... this.Controls.Add(this.label1); below
        //
        // WaveformWindow
        //
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(398, 373);
        this.Name = "WaveformWindow";
        this.ShowInTaskbar = false;
        this.Text = "WaveformWindow";
      **this.Controls.Add(this.label1);**
        this.ResumeLayout(false);

Windows forms generates the code to add all the controls to forms automatically. So whenever u face such problem, delete the old control and again drag and drop it. It must be then visible.  (Edit for understanding the issue)