text:
Q: error: incompatible types: SnekEngine cannot be converted to Context I am building a snake game in android studios after following a guide online now I am trying to add onto it by adding a "pop-up" box after you die to play again but I am running into an issue.
I got an error on in my AlertDialog,
AlertDialog.Builder alert = new AlertDialog.Builder( this );

I am getting told that
error: incompatible types: SnekEngine cannot be converted to Context

and the error is pointing to the this.
Here is the whole class the bit that is giving me trouble is at the bottom.
package com.example.snek;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetFileDescriptor;
import android.graphics.Point;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.IOException;
import java.util.Random;
import android.content.res.AssetManager;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

public class SnekEngine extends SurfaceView implements Runnable
{
    // Our game thread for the main game loop
    private Thread thread = null;

    // To hold a reference to the Activity
    private Context context;

    // for playing sound effects
    private SoundPool soundPool;
    private int eat_food = -1;
    private int snake_crash = -1;

    // For tracking movement Heading
    public enum Heading {UP, RIGHT, DOWN, LEFT}
    // Start by heading to the right
    private Heading heading = Heading.RIGHT;

    // To hold the screen size in pixels
    private int screenX;
    private int screenY;

    // How long is the snake
    private int snakeLength;

    // Where is Food hiding?
    private int foodX;
    private int foodY;

    // The size in pixels of a snake segment
    private int blockSize;

    // The size in segments of the playable area
    private final int NUM_BLOCKS_WIDE = 40;
    private int numBlocksHigh;

    // Control pausing between updates
    private long nextFrameTime;
    // Update the game 10 times per second
    private final long FPS = 10;
    // There are 1000 milliseconds in a second
    private final long MILLIS_PER_SECOND = 1000;
// We will draw the frame much more often

    // How many points does the player have
    private int score;
    private int highscore;

    // The location in the grid of all the segments
    private int[] snakeXs;
    private int[] snakeYs;

    // Everything we need for drawing
// Is the game currently playing?
    private volatile boolean isPlaying;

    // A canvas for our paint
    private Canvas canvas;

    // Required to use canvas
    private SurfaceHolder surfaceHolder;

    // Some paint for our canvas
    private Paint snekcolor;
    private Paint textcolor;
    private Paint foodcolor;

    public SnekEngine(Context context, Point size) {

        super(context);

        context = context;

        screenX = size.x;
        screenY = size.y;

        // Work out how many pixels each block is
        blockSize = screenX / NUM_BLOCKS_WIDE;
        // How many blocks of the same size will fit into the height
        numBlocksHigh = screenY / blockSize;

        // Set the sound up
        soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
        try {
            // Create objects of the 2 required classes
            // Use m_Context because this is a reference to the Activity
            AssetManager assetManager = context.getAssets();
            AssetFileDescriptor descriptor;

            // Prepare the two sounds in memory
            descriptor = assetManager.openFd("get_mouse_sound.ogg");
            eat_food = soundPool.load(descriptor, 0);

            descriptor = assetManager.openFd("death_sound.ogg");
            snake_crash = soundPool.load(descriptor, 0);

        } catch (IOException e) {
            // Error
        }

        // Initialize the drawing objects
        surfaceHolder = getHolder();
        snekcolor = new Paint();
        textcolor = new Paint();
        foodcolor = new Paint();

        // If you score 200 you are rewarded with a crash achievement!
        snakeXs = new int[200];
        snakeYs = new int[200];

        // Start the game
        newGame();

    }

    @Override
    public void run() {

        while (isPlaying) {

            // Update 10 times a second
            if(updateRequired()) {
                update();
                draw();
            }

        }
    }

    public void pause() {
        isPlaying = false;
        try {
            thread.join();
        } catch (InterruptedException e) {
            // Error
        }
    }

    public void resume() {
        isPlaying = true;
        thread = new Thread(this);
        thread.start();
    }

    public void newGame() {
        // Start with a single snake segment
        snakeLength = 1;
        snakeXs[0] = NUM_BLOCKS_WIDE / 2;
        snakeYs[0] = numBlocksHigh / 2;

        // Get Food ready for dinner
        spawnFood();

        // Setting the high score
        if (score > highscore)
            highscore = score;

        // Reset the score
        score = 0;

        // Setup nextFrameTime so an update is triggered
        nextFrameTime = System.currentTimeMillis();
    }

    public void spawnFood() {
        Random random = new Random();
        foodX = random.nextInt(NUM_BLOCKS_WIDE - 1) + 1;
        foodY = random.nextInt(numBlocksHigh - 1) + 1;
    }

    private void eatFood(){
        //  Got him!
        // Increase the size of the snake
        snakeLength++;
        //replace Bob
        // This reminds me of Edge of Tomorrow. Oneday Bob will be ready!
        spawnFood();

        //add to the score
        score = score + 1;

        // Setting the high score
        if (score > highscore)
            highscore = score;

        soundPool.play(eat_food, 1, 1, 0, 0, 1);
    }

    private void moveSnake(){
        // Move the body
        for (int i = snakeLength; i > 0; i--) {
            // Start at the back and move it
            // to the position of the segment in front of it
            snakeXs[i] = snakeXs[i - 1];
            snakeYs[i] = snakeYs[i - 1];

            // Exclude the head because
            // the head has nothing in front of it
        }

        // Move the head in the appropriate heading
        switch (heading) {
            case UP:
                snakeYs[0]--;
                break;

            case RIGHT:
                snakeXs[0]++;
                break;

            case DOWN:
                snakeYs[0]++;
                break;

            case LEFT:
                snakeXs[0]--;
                break;
        }
    }

    private boolean detectDeath(){
        // Has the snake died?
        boolean dead = false;

        // Hit the screen edge
        if (snakeXs[0] == -1) dead = true;
        if (snakeXs[0] >= NUM_BLOCKS_WIDE) dead = true;
        if (snakeYs[0] == -1) dead = true;
        if (snakeYs[0] == numBlocksHigh) dead = true;

        // Eaten itself?
        for (int i = snakeLength - 1; i > 0; i--) {
            if ((i > 4) && (snakeXs[0] == snakeXs[i]) && (snakeYs[0] == snakeYs[i])) {
                dead = true;
            }
        }

        return dead;
    }

    public void update() {
        // Did the head of the snake eat Food?
        if (snakeXs[0] == foodX && snakeYs[0] == foodY) {
            eatFood();
        }

        moveSnake();

        if (detectDeath()) {
            //start again
            soundPool.play(snake_crash, 1, 1, 0, 0, 1);

            newGame();
        }
    }

    public void draw() {
        // Get a lock on the canvas
        if (surfaceHolder.getSurface().isValid()) {
            canvas = surfaceHolder.lockCanvas();

            // Fill the screen with Game Code School blue
            canvas.drawColor(Color.argb(255, 0, 0, 0));

            // Set the color of the paint to draw the snake white
            textcolor.setColor(Color.argb(255, 153, 255, 153));

            snekcolor.setColor(Color.argb(255, 153, 255, 153));

            // Scale the HUD text
            textcolor.setTextSize(90);
            canvas.drawText("High Score:" + highscore, 10, 70, textcolor);
            canvas.drawText("Score:" + score, 10, 150, textcolor);

            // Draw the snake one block at a time
            for (int i = 0; i < snakeLength; i++) {
                canvas.drawRect(snakeXs[i] * blockSize,
                        (snakeYs[i] * blockSize),
                        (snakeXs[i] * blockSize) + blockSize,
                        (snakeYs[i] * blockSize) + blockSize,
                        snekcolor);
            }

            // Set the color of the paint to draw Food red
            foodcolor.setColor(Color.argb(255, 0, 255, 255));

            // Draw Food
            canvas.drawRect(foodX * blockSize,
                    (foodY * blockSize),
                    (foodX * blockSize) + blockSize,
                    (foodY * blockSize) + blockSize,
                    foodcolor);

            // Unlock the canvas and reveal the graphics for this frame
            surfaceHolder.unlockCanvasAndPost(canvas);
        }
    }

    public boolean updateRequired() {

        // Are we due to update the frame
        if(nextFrameTime <= System.currentTimeMillis()){
            // Tenth of a second has passed

            // Setup when the next update will be triggered
            nextFrameTime =System.currentTimeMillis() + MILLIS_PER_SECOND / FPS;

            // Return true so that the update and draw
            // functions are executed
            return true;
        }

        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent motionEvent) {

        switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_UP:
                if (motionEvent.getX() >= screenX / 2) {
                    switch(heading){
                        case UP:
                            heading = Heading.RIGHT;
                            break;
                        case RIGHT:
                            heading = Heading.DOWN;
                            break;
                        case DOWN:
                            heading = Heading.LEFT;
                            break;
                        case LEFT:
                            heading = Heading.UP;
                            break;
                    }
                } else {
                    switch(heading){
                        case UP:
                            heading = Heading.LEFT;
                            break;
                        case LEFT:
                            heading = Heading.DOWN;
                            break;
                        case DOWN:
                            heading = Heading.RIGHT;
                            break;
                        case RIGHT:
                            heading = Heading.UP;
                            break;
                    }
                }
        }
        return true;
    }

    public void showNewGameDialog()
    {
        AlertDialog.Builder alert = new AlertDialog.Builder( this );
        alert.setTitle( "This is fun" );
        alert.setMessage( "Play again?" );
        PlayDialog playAgain = new PlayDialog();
        alert.setPositiveButton( "YES", playAgain );
        alert.setNegativeButton( "No", playAgain );
        alert.show();
    }

    private class PlayDialog implements DialogInterface.OnClickListener
    {
        public void onClick( DialogInterface dialog, int id)
        {
            if ( id == -1 ) // yes button
            {
                newGame();
            }

            else if ( id == -2 ) //no button
                //figure out how to exit game.
        }
    }
}

A: Instead of this use context
AlertDialog.Builder alert = new AlertDialog.Builder( context );


text:
Q: Can I bypass organizational authentication for a WebAPI controller inside an MVC app? I have an MVC5, EF6 app which uses organizational authentication (Azure AD) and all is working fine except for one thing. There is a requirement for a WebAPI controller to process requests from unauthenticated clients. The clients are normally Android devices issuing AJAX requests.
Before I added organizational authentication to my MVC app, my WebAPI controller was being called and functioned correctly so I know my routing is correct. Now I've added organizational authentication, my WebAPI controller is no longer called and the client's AJAX request times out.
I understand there are attributes such as [Authorize] to specify access to controllers/methods but when using organizational authentication, it appears that WebAPI controllers without the [Authorize] attribute do not get called.
My question is, can I mark my WebAPI controller to allow requests from unauthenticated clients, if so how can I do it?
Many thanks.

A: The answer is to allow anonymous connections to a specific controller by entering the xml below into the root Web.config file.
If your controller is called "PersonController", then the name you should enter into the path attribute is "person" NOT "personcontroller".
In my case, because I want to allow anonymous requests to a WebAPI controller, I need to prefix my controller name in the path attribute with "api/".
Hope this helps others who may run into the same issue.
<location path="api/my-controller-name">
  <system.web>
    <authorization>
      <allow users="?" />
    </authorization>
  </system.web>
</location>

A: If you want to allow anonymous access you can use the [AllowAnonymous] attribute.
You can either add this above the ApiController to mark the whole controller for anonymous acces like:
[AllowAnonymous]
public class MyApiController : ApiController
{
}

Or you can give a specific method this attribute, to allow that method to be called anonymously:
[Authorize]
public class MyApiController : ApiController
{
    [AllowAnonymous]
    public string GetData()
    {

    }
}

This will block access to all methods when a user is not authorized, except the GetData() method which can be called anonymously.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Struts: The method getDispatcherType() is undefined for the type HttpServletRequest I'm running a Struts project (built in other machine) in NetBeans 8.0.2. I'm not using Maven.
Here's the trace:
      org.apache.jasper.JasperException: Unable to compile class for JSP:

     An error occurred at line: [43] in the generated java file: [/home/sys6002/.netbeans/8.0.2/apache-tomcat-8.0.15.0_base/work/Catalina/localhost/PublisherTruepush/org/apache/jsp/home_005fpage_jsp.java]
     The method getDispatcherType() is undefined for the type HttpServletRequest
              Stacktrace:
        org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:103)
    org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:199)
    org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:450)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:361)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:336)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:323)
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:564)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:88

What can I do to solve this?
The code in /jsp/home_005fpage_jsp.java]
at Line 43
final java.lang.String _jspx_method = request.getMethod();
if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method) && !javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) {
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET POST or HEAD");
return;
}

A: ServletRequest.getDispatcherType() was defined in Servlet 3.0 API.
The error indicates that you are either running the application with an older version of the Servlet API or that your application includes an servlet jar which is imcompatible with your runtime.
Since you are running Tomcat 8.0 I would check if your app includes jar files which contain an older servlet version.


text:
Q: Object.entries() not iterating through all values passed to it I am calling alpaca api, and storing results in a state array. Shown here, but am having trouble iterating through the JS object an displaying it in another component. I'm only able to display the first key/value pair, but not the rest. Any input is greatly appreciated.
Clock. Js
const Clock = () => {
    const initialState = {
        timestamp: "",
        is_open: false,
        next_open: "",
        next_close: "",
}
    const [timestamps, setTimestamp] = useState(
        {
            timestamp: "",
            is_open: false,
            next_open: "",
            next_close: "",
        }
    )

    const clearState = () => {
        setTimestamp({...initialState});
    }

    const printState = () => {
        console.log("Current Time: ", timestamps.timestamp);

    }

    const fetchData = async() => {
        let result = await alpacaIdentifier.getClock();
        setTimestamp(result);
    }

    useEffect(()=> {
        fetchData()
    }, [])

    return(

            <Button onClick={printState}></Button>
            <ClockComponent
                timestamps={timestamps.timestamp.length > 0 ? timestamps : ' '}
            />

    )
};

export default Clock;

ClockComponent.js
import React from 'react'
import {timestamps, isOpen, nextOpen, nextClose} from '../historical/Clock.js'

const ClockComponent = ({timestamps}) => {
    console.log("test", timestamps)

    for (const [key, value] of Object.entries(timestamps)) {

            return (

Key: {JSON.stringify(key)}

Value: {JSON.stringify(value)}

            )
    }
}

export default ClockComponent;

The intended area for outputs is under 'Details'.
The output only returns the timestamp value/key. Not the rest of the items (is_open, nextOpen, nextClose).
What can I do to reformat this in order to make the API calls/data formatting easier, or at least get it to display the other values from the API endpoint.
The API for reference is: https://alpaca.markets/docs/api-references/trading-api/clock/

A: Try pushing the divs in the loop to an array in memory, then return the array after the loop completes. You cannot simply return each row from within the loop.


text:
Q: Create new album in facebook using Javascript I'm using the following code to upload a photo:
FB.api('/photos', 'post', {
  message: fbMessage,
  access_token: response.session.access_token,
  url: imgURL
}, function (response) {
  //do something
if (!response || response.error) {
} else {
  //do something
}
});

this code will upload the photo in an album that has the name of the App,
I want to choose the album name, should I create an album and upload the photos in it and how ?


text:
Q: Adobe Flash not working I have a user on a MacBook Pro with Yosemite that tried to install Flash.  She downloaded the installer and ran it.  It said it completed, but Flash is not working in Chrome or Safari.  I downloaded the uninstaller from Adobe and ran it to uninstall Flash.  It said it was successful.  I then redownloaded the Flash installer and ran it successfully.  Still, Flash is not working in either browser.
Ideas?

A: One place to check is chrome://plugins/ in Google Chrome. Just type that into the address bar and hit ENTER. You should see a list of all the plugins that are available through Chrome. If you've downloaded and installed Flash, you should see two entries there. One for your own install and one for the version of Flash that comes bundled with Chrome. It will also tell you there if the plugin is disabled or enabled.
Also if you go into Settings in Chrome and search for "Flash" it will highlight the "Content Settings..." button under Privacy. Check Plug-Ins under there and see whether "Block all" has been chosen from the available "Run automatically|Click to play|Block all" options.
Another thing to check for are ClickToPlugin or ClickToFlash extensions that can be set to selectively block Flash plugins. You can find the installed Chrome extensions with "Extensions" from the Window menu and the installed Safari extensions with "Safari Extensions..." under the Safari application menu.

A: There are 2 types of Adobe Flash.
One is already a part of the Browsers, called Plugin
To check in Chrome type chrome://plugins/ in the address bar, and see if it is enabled.
The other one is the Stand alone version of Flash player that will show up in your System Preferences.


text:
Q: WordPress - проблема с меню В выпадающем меню WordPress если активный родительский пункт, то один из дочерних пунктов стает некликабельным. Встречал такое уже на нескольких сайтах на WP. В чем может быть причина. Для примера можно посмотреть сайт http://www.giottoclub.ru/menu/
При активном пункте Меню, его подпункт "Паста и Ризотто" стает некликабельным.
UPD. Изменил данный пункт - сделал его произвольной ссылкой и вставил ссылку на нужную категорию. Но хотелось бы на будущее все таки решить в чем проблема


text:
Q: How to calculate a monthly mean? I have the daily weather report like this. What I want is to calculate the monthly mean of the max, min and observation temperature and then plot these three lines. I already convert the date format like this:
Date = as.POSIXlt(Weather2011$Date, format = "%m/%d/%Y")
Year = as.numeric(format(Date, format = "%Y"))
Month = as.numeric(format(Date, format = "%m"))
Week = as.numeric(format(Date, format = "%U"))
Weekday = as.numeric(format(Date, format = "%w"))

Weather2011 looks like this:
Date      Max.Temp  Min.Temp  Temp  Date        Year   Month  Week  Weekday
6/3/2010  87        63        63    2010-06-03  2010   6      22    4
6/4/2010  83        63        73    2010-06-04  2010   6      22    5

A: I find that tapply works well. Ex.
x <- seq(from=as.Date("2000-01-01"), to=as.Date("2004-12-31"), by="day")
y <- sin(seq(from=0, to=2*pi*5,length.out=length(x)))+rnorm(length(x))
yyyymm <- paste(format(as.POSIXlt(x), format="%Y-%m"), "01", sep="-")
MEAN <- tapply(y, yyyymm, mean)
MAX <- tapply(y, yyyymm, max)
MIN <- tapply(y, yyyymm, min)
#plots
x11()
par(mfcol=c(1,2))
plot(x,y, ylim=range(MEAN, MAX, MIN), ylab="", xlab="")
plot(as.POSIXlt(names(MEAN)), MEAN, t="l", ylim=range(MEAN, MAX, MIN), ylab="", xlab="")
lines(as.POSIXlt(names(MEAN)), MAX, lty=2)
lines(as.POSIXlt(names(MEAN)), MIN, lty=2)


text:
Q: Ceiling of Long Integer division in c++ I was trying to solve some problem which involves division of large numbers. I stumbled upon certain scenario where  I'm getting wrong results using:
LL result = (LL)ceil((double)(a-b)/c), where a,b and c are long long integers(LL).
#include <stdio.h>      /* printf */
#include <math.h>       /* ceil */
#define LL long long

int main ()
{
    LL a= 10000000000000000;
    LL aa = 10000000000000000-1;
    LL aaa = 10000000000000000+1;
    int b = 1;
    int c = 1;
    printf ( "%Ld\n", (LL)ceil((double)(a-b)/c) );
    printf ( "%Ld\n", (LL)ceil((double)(aa-b)/c) );
    printf ( "%Ld\n", (LL)ceil((double)(aaa-b)/c) );
    return 0;
}

Output:
10000000000000000
9999999999999998
10000000000000000

This starts to happen to integers which are greater than or equal to 10^16 and is divisible by 10.
The upper bound of long long is ~10^18.
So What is causing this error?
I'm using GCC 5.1 in C++14 mode (on ideone.com).

A: Although it can store numbers with much larger magnitude, a typical implementation of double can only maintain around 15-16 digits of precision.
Subtraction with floating point can also be something of a problem, especially if the two numbers are of nearly the same magnitude. If both inputs are (say) 50 bits, but the first 40 bits are identical, those will cancel out, and the result will only have about 10 bits.
So, first of all, you probably want to do all the math with long long if that's the type you want for the result. Second, you might at least want to consider rearranging your (a-b)/c to a/c-b/c to delay the subtraction as long as possible.

A: If you know that both values are positive, you can calculate the ceil in purely integer (or long long) with:
    (x + y-1)/y

So, in your case:
    (a - b + c-1)/c

Handling negative numbers is left as an exercise for the reader (it can be a bit fiddly deciding exactly what you want it to do, and you usually don't need it anyway).


text:
Q: Firebug console keeps printing postmessage message type required I use Firebug to test CSS, Sizzle and Xpath selectors, so I can use them in Selenium.
In every selector I test, I get the message postmessage message type required.
What does it mean, and can i get rid of it?
I am using Firefox 26 and Firebug 1.12.5.
In the Firebug console i type for example
$$("button#gbqfba") eg. for Google page, and the element is highlighted.
This is used to be done without popping the postmessage.


text:
Q: Re-rendering after sending a delete request in react not working I have React.js in the front-end and Express.js in the back-end. At the moment I am trying to delete a post from React with a Delete request and it works but I have to go to the url and hit enter before it shows the new list after deleting. I would like the page to re-render without having to hit refresh.
class Rentals extends Component {

    constructor(props) {
        super(props);
        this.state = {
            completelist: [],
            apiLoaded: false,
        }
        this.conditionalRentList = this.conditionalRentList.bind(this);
        this.handleDeleteButton = this.handleDeleteButton.bind(this);
        this.fetchAllRentals = this.fetchAllRentals.bind(this);
    }

    componentDidMount() {
        this.fetchAllRentals();
    }

    fetchAllRentals() {
        fetch('api/listofrentals')
            .then((res) => {
                return res.json()
            })
            .then((fullrental) => {
                this.setState((prevState) => {
                    return {
                        completelist: fullrental.rentalsData,
                        apiLoaded: true
                    }
                })
            })
    }

    conditionalRentList() {
        if (this.state.apiLoaded === true) {
            return (
                <RentalsComp
                    completelist={this.state.completelist}
                    handleDeleteButton={this.handleDeleteButton}
                />
            );
        } else {
            return <p> Loading </p>
        }
    }

    handleDeleteButton(idToBeDeleted) {
        fetch(`api/listofrentals/${idToBeDeleted}`, {
            method: 'DELETE'
        }).then((res) => {
            if (res.json === 200) {
                this.fetchAllRentals();
            }
        })
    }

}

the function handleDeleteButton should fetch all the listings and render it without having to refresh since it calls the fetchAllRentals function but its not working for some reason.

A: Was supposed to be resp.status===200 but was doing resp.json===200 instead.


text:
Q: Best way of running two threads alternatively? Update: see bottom of this question for a complete answer.
I want to run a secondary thread, so that my main thread and my secondary thread perform operations alternatively (no, I don't want to do all the operations in the main thread, it is for a unit test).
I came up to two different solutions, I don't know which is the best, and I have questions regarding the first one:
Using Exchanger
I came up to something using an Exchanger (while I don't want to exchange only one object).
@Test
public void launchMyTest() {
    /**
     * An anonymous class to set some variables from a different thread
     */
    class ThreadTest extends Thread {
        //declare some various attributes that will be set
        //NOT DECLARED VOLATILE
        ...

        public final Exchanger<Integer> exchanger = new Exchanger<Integer>();

        @Override
        public void run() {
            try {
                //start of the synchronization
                int turn = 1;
                while (turn != 2) {
                    turn = this.exchanger.exchange(turn);
                }

                //do some work and set my various variables
                ...

                //main thread's turn
                turn = 1;
                this.exchanger.exchange(turn);
                //wait for this thread's turn
                while (turn != 2) {
                    turn = this.exchanger.exchange(turn);
                }

                //redo some other work and reset the various variables
                ...

                //main thread's turn
                turn = 1;
                this.exchanger.exchange(turn);

            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    try {
        //some work in the main thread
        ....

        //launch the job in the second thread
        ThreadTest test = new ThreadTest();
        test.start();
        //start of the synchronization
        int turn = 2;
        test.exchanger.exchange(turn);
        //wait for this thread's turn
        while (turn != 1) {
            turn = test.exchanger.exchange(turn);
        }

        //run some tests using the various variables of the anonymous class
        ....

        //now, relaunch following operations in the second thread
        turn = 2;
        test.exchanger.exchange(turn);
        //wait for this thread's turn
        while (turn != 1) {
            turn = test.exchanger.exchange(turn);
        }

        //do some other tests using the various variables of the anonymous class
        //...

    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}

Question:

*

*Am I correct that the exchange method performs memory synchronization, just as much as using a Lock?

Using Condition
Another solution using a Condition:
@Test
public void launchMyTest() {
    /**
     * An anonymous class to set some variables from a different thread
     */
    class ThreadTest extends Thread {
        //declare some various attributes that will be set
        //NOT DECLARED VOLATILE
        ...

        public final Lock lock = new ReentrantLock();
        public final Condition oneAtATime = lock.newCondition();
        public int turn = 1;

        @Override
        public void run() {
            this.lock.lock();
            try {
                //do some work and set my various variables
                ...

                //main thread's turn
                this.turn = 1;
                this.oneAtATime.signal();

                //wait for this thread's turn
                while (this.turn != 2) {
                    this.oneAtATime.await();
                }

                //redo some other work and reset the various variables
                ...

                //main thread's turn
                this.turn = 1;
                this.oneAtATime.signal();

            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                this.lock.unlock();
            }
        }
    }

    ThreadTest test = new ThreadTest();
    test.lock.lock();
    try {
        //some work in the main thread
        ....

        //launch the job in the second thread
        test.turn = 2;
        test.start();
        //wait for this thread's turn
        while (test.turn != 1) {
            test.oneAtATime.await();
        }

        //run some tests using the various variables of the anonymous class
        ....

        //now, relaunch following operations in the second thread
        test.turn = 2;
        test.oneAtATime.signal();
        //wait for this thread's turn
        while (test.turn != 1) {
            test.oneAtATime.await();
        }

        //do some other tests using the various variables of the anonymous class
        //...

    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    } finally {
        test.lock.unlock();
    }
}

It seems to me a bit more complicated.
Conclusion
What do you think is the best solution? Am I doing it right, or do I miss another obvious solution?
I didn't use a CountDownLatch as I want to run several operations alternatively, and the CountDownLatch cannot be reset. And I didn't find that the CyclicBarrier was making the code simpler... (actually I didn't totally understand how to use it, but it didn't look simpler than using Exchanger or Condition)
Thank you.
Update
@Clément MATHIEU provided different examples of how to achieve this, in comments of its accepted answer, see: https://gist.github.com/cykl/5131021
There are three examples, one using a CyclicBarrier, another one using an Exchanger, and a last one using 2 Semaphores. While he is right to say that the "more expressive is the semaphore based one", I chose to use an Exchanger for simplicity. My unit test became:
@Test
public void launchMyTest() {
    /**
     * An anonymous class to set some variables from a different thread
     */
    class ThreadTest extends Thread {
        //declare some various attributes that will be set
        //NOT DECLARED VOLATILE
        ...
        public final Exchanger<Integer> exchanger = new Exchanger<Integer>();

        @Override
        public void run() {
            try {
                //do some work and set my various variables
                ...

                //main thread's turn
                this.exchanger.exchange(null);
                //wait for this thread's turn
                this.exchanger.exchange(null);

                //redo some other work and reset the various variables
                ...

                //main thread's turn
                this.exchanger.exchange(null);

            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    try {
        //some work in the main thread
        ....

        //launch the job in the second thread
        ThreadTest test = new ThreadTest();
        test.start();
        //wait for this thread's turn
        test.exchanger.exchange(null);

        //run some tests using the various variables of the anonymous class
        ....

        //now, relaunch following operations in the second thread
        test.exchanger.exchange(null);
        //wait for this thread's turn
        test.exchanger.exchange(null);

        //do some other tests using the various variables of the anonymous class
        //...

    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}

A: exchanger looks right. After watching http://www.youtube.com/watch?v=WTVooKLLVT8 I think the variable should be volatile, says there is hardly any over head.

A:
Am I correct that the exchange method performs memory synchronization, just as much as using a Lock?

You are right. The javadoc specifies there is a happen-before relation:
"Memory consistency effects: For each pair of threads that successfully exchange objects via an Exchanger, actions prior to the exchange() in each thread happen-before those subsequent to a return from the corresponding exchange() in the other thread."

What do you think is the best solution?

Both are equivalent. You should target expressiveness. I find the synchronisation/Lock/Monitor based solution more expressive than the exchanged based one. But it does not really matter if you abstract this code in a dedicated class.

Am I doing it right, or do I miss another obvious solution?

AFAIK no If you don't want to re-implement the wheel.
Please note that your ReentrantLock based solution can also be written using plain old synchronisation or Monitor from Guava.
See: http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/util/concurrent/Monitor.html for a comparison.

And I didn't find that the CyclicBarrier was making the code simpler... (actually I didn't totally understand how to use it, but it didn't look simpler than using

CyclicBarrier does not fit your needs. It is not designed for mutual exclusion;  it allows a set of threads to define a common barrier. Threads will execute concurrently and wait for each other at some point before moving to the next step.

A: The locking mechanism is directly addressing the task you are performing here by focusing on the mutual exclusions of the locks so my recommendation is for that approach.

A: While I haven't used Exchanger yet, it looks like it's the simplest solution for what you want to achieve. Less code than the much more general Lock/Condition version. As for the memory consistency: That's what they promise here.


text:
Q: Android application communicate with other devices Wifi but not the Internet, through 3g -Fi Internet? Android application communicate with other devices Wifi but not the Internet, through 3g  Internet

A: I don't know exactly what are you asking for... But if you wanna connect two device over 3g you have to create server on public IP with one of port. For that you can use Socket.IO for example. It's really simply and have implementation for web browsers, Android, iOS and even Windows Phone.
Here you have some Demo.


text:
Q: LuaLanes and LuaSockets I'm working on a little Lua app (under Lua for Windows, if that matters) that uses sockets to communicate with the outside world. (LuaSocket)
And I'm trying to make several requests in parallel. So I thought LuaLanes was the way to go. (I'm open to alternatives, of course, if there's a better solution, but would prefer not to deal with coroutines for this.)
Something like this:
server = assert (socket.bind ('*', 1234))
client = server : accept ()
-- set id to some unique value
allClients [id] = client
theLane = lanes.gen ("", laneTest) ( id )
print (theLane [1])

Where the laneTest function is defined as follows:
function laneTest (id)
    local client = allClients [id]
    print ('peer: ', client:getpeername())
end

My problem is that inside the laneTest function, when run as a lane, I get this lovely error message:

attempt to index local 'client' (a userdata value)

(from the line client:getpeername())
So.. I'm not sure what's going on here? Is lanes incompatible with sockets, or am I doing something very wrong?
I guess it could be that the version of lanes that ships with Lua for Windows is ancient (luaforwindows) and doesn't work with sockets, but the latest version might? (Lanes 2.0.4 vs the more recent 3.xx)
I don't really know how to go about updating the version of Lanes I've got, else I would have tried that by now, so. I'd appreciate any advice if that's where I could be heading or there's something more obvious that I've done wrong.
Edit:
I went ahead and installed lanes via luarocks, and have the same problem using lanes 3.1.6-1 that's installed as a rock.
Edit 2:
Tried this (and still failed):
require ('socket')
require ('lanes')
local allClients = {}

function theLane (id)
    print ('the id:', id) -- correctly prints out the id passed to the function
    local SOCKET = require ('socket')
    local client = allClients [id]
    print ('peer:', client:getpeername())
    client : close ()
end

local server = assert (SOCKET.bind ('*', 1234))
local ip, port = server:getsockname ()
local laneFunc = lanes.gen('', theLane)
local client = server:accept ()
allClients [1] = client
local x = laneFunc (1)
print (x[1])

*

*This fails claiming: attempt to call global 'require' (a nil value)

*Removing the require ('socket') line inside the function and retrying also fails saying: attempt to index local 'client' (a userdata value)
I apologize in advance for missing the obvious, but... how do you get sockets to work with lanes?
Edit 3:
Well, I'm editing this in for future reference :)
As far as I can tell, there's no way of using Lanes with Sockets without patching luasockets. See discussion here for more about that; but in short (and as explained in Deco's answer): lanes does not work with userdata. luasocket does not provide any other way of accessing socket/socket info.
I have no desire to patch luasocket so as much as I would have rather used lanes, I'm going go ahead and stick with copas or couroutines.
Thanks all!

A: Programming Lua has example on non-preemptive multithreading (using coroutines), which you can probably use almost directly. In my opinion coroutines will be a better solution for your use case.
There is also copas library that describes itself as "a dispatcher based on coroutines that can be used by TCP/IP servers", but you can actually use it for sending requests asynchronously too (using a combination of addthread and step calls).

A: Lua Lanes creates an entirely new (but minimal) Lua state for each lane.
Any upvalues or arguments passed are copied, not referenced; this means your allClients table is being copied, along with the sockets it contains.
The error is occurring because the sockets are userdata, which Lua Lanes does not know how to copy without some advice from a C module. Unfortunately, LuaSocket offers no such advice.
(There are ways around this, but be cautious: LuaSocket is not thread-safe and synchronisation bugs are very difficult to track down.)
Although it will not solve your problem, you should note that you need to require LuaSocket in your spawned lane; it is not copied by default.
Solutions!
These are ordered from easy to hard (and mostly transcribed from my other answer here).
Single-threaded Polling
Repeatedly call polling functions in LuaSocket:

*

*Blocking: call socket.select with no time argument and wait for the socket to be readable.

*Non-blocking: call socket.select with a timeout argument of 0, and use sock:settimeout(0) on the socket you're reading from.

Simply call these repeatedly.
I would suggest using a coroutine scheduler for the non-blocking version, to allow other parts of the program to continue executing without causing too much delay.
(If you go for this solution, I suggest reviewing Paul's answer.)
Dual-threaded Polling
Your main thread does not deal with sockets at all. Instead, it spawns another lane which requires LuaSocket, handles all clients and communicates with the main thread via a linda.
This is probably the most viable option for you.
Multi-threaded Polling
Same as above, except each thread handles a subset of all the clients (1 to 1 is possible, but diminishing return will set in with large quantities of clients).
I've made a simple example of this, available here. It relies on Lua Lanes 3.4.0 (GitHub repo) and a patched LuaSocket 2.0.2 (source, patch, blog post re' patch)
The results are promising, though you should definitely refactor my example code if you derive from it.
LuaJIT + ENet
ENet is a great library. It provides the perfect mix between TCP and UDP: reliable when desired, unreliable otherwise. It also abstracts operating system specific details, much like LuaSocket does. You can use the Lua API to bind it, or directly access it via LuaJIT's FFI (recommended).


text:
Q: Download ONLY audio from a youtube video I know that there are a million ways to download a video from youtube and then convert it to audio or do further processing on it. But recently I was surprised to see an app called YoutubeToMp3 on mac actually showing "Skipping X mb of video" and supposedly only downloading the audio from the video, without the need to use bandwith to download the entire video and then convert it. I was wondering if this is actually correct and possible at all because I cant find any way to do that. Do you have any ideas ?
EDIT:
After some tests here is some additional information on the topic. The video which I tried to get the audio from is just a sample mp4 file from the internet:
http://download.wavetlan.com/SVV/Media/HTTP/MP4/ConvertedFiles/MediaCoder/MediaCoder_test6_1m9s_XVID_VBR_306kbps_320x240_25fps_MPEG1Layer3_CBR_320kbps_Stereo_44100Hz.mp4
I tried
ffmpeg -i "input" out.mp3
ffmpeg -i "input" -vn out.mp3
ffmpeg -i "input" -vn -ac 2 -ar 44100 -ab 320k -f mp3 output.mp3
ffmpeg -i "input" -vn -acodec copy output.mp3
Unfortunately non of these commands seems to be using less bandwith. They all download the entire video. Now that you have the video can you confirm if there is actually a command that downloads only the audio stream from it and lowers the bandwith usage? Thanks!

A: FFmpeg is capable of accepting an URL as input. If the URL is seekable, then FFmpeg could theoretically skip all the video frames, and thus it would need to download only the data for the audio stream.
Try using
ffmpeg -i http://myvideo.avi out.mp3

and see if it takes less bandwidth.

A: After a lot of research I found out that this is not possible and developed an alternative approach:

*

*Download the mp4 header

*Parse the header and get the locations of the audio bytes

*Download the audio bytes with http range requests and offsets

*Assemble the audio bytes and wrap them in a simple ADTS container to produce a playing m4a file

That way only bandwidth for the audio bytes is used. If you find a better approach of doing it please let me know.
For a sample Android APP and implementation check out:
https://github.com/feribg/audiogetter/blob/master/audiogetter/src/main/java/com/github/feribg/audiogetter/tasks/download/VideoTask.java


text:
Q: What was my boss talking about when he said stack? So my company works in ColdFusion, and it can be really frustrating to not have support on newer items unlike what you would get by using .NET or Java. I will be remaking a website for the company, from scratch.
I went up to my boss yesterday, and asked him if we could possibly change the language that we worked on, and I told him I'm most comfortable in C#.NET and could do it in MVC. What he said is that he'd be okay with me doing it in whatever language I wanted to, as long as there would be no problems with our "Stack". I asked him what he meant, and he said, the last he heard, our stack could use: Python, Java, Ruby, and a couple others, but that if it had changed, and could do .NET, then I could write the code in that.
So what does he mean by stack?

A: He means the hardware and software (in terms of operating system, database and web server) your company is running to power the website.
From the list he's given it's very unlikely you'll be able to use .NET - that requires a Microsoft based stack consisting of Windows Server, SQL Server and IIS. The technologies he lists are mainly open source, and while they will work on a Microsoft setup, they're far more commonly used on Linux-based systems.


text:
Q: In a web programming environment, what are the uses of a hashtable Vs other datastructures handling Key,Value pairs I have heard of people using them for keeping track of session variables, but I really want to know if there are many uses for them and under what conditions it would be beneficial to employ a hashtable vs any other data structure that can handle key value pairs, like a dictionary for example.
eg. I have heard of people putting session values in a hashtable then putting the hash table in the Session object.  I just wanted to know what benefit that was.
- Is it more performant?
- Does it protect against other developers putting same name variable into the session?
Edited.

A: A difficult question to answer, mainly because you're looking for a problem to match a solution rather than the other way around.  I'll throw in my two cents though.
Session variables essentially store information for the current user's session.  They're accessed by a key, so they really behave in the same way as a hashtable.  They may even be implemented under the covers (partly) as a hashtable - I don't know.
The important thing to note about session variables is that they are an abstraction from the fact that web applications are stateless.  What actually happens is that you save a value to session, and when you return the page, that value is saved somewhere (usually in memory or a database).  The next time a request comes from that person, the variable is reloaded.
Hashtables are useful mainly for fast access to a large number of objects or values using lookup keys.  Because web is stateless, and session is confined to a single user, I can't see much use for hashtables.  If you need to quickly get access to a piece of data in a large collection, storing an entire hashtable at the end of a request and reloading it at the start of a request just to get quick access to an item is unlikely to be an efficient use of resources.

A: Its like asking what is the use of hammer in construction of a house... if you want it simple then hashtable just key/value pair, its up to u where to place your nail :)

A: Depends what you mean by hash tables, for example the backend databases that drive most websites have multiple hash tables embedded into the tables (in the form of indices). Assigning data to user id's through session variables also comes to mind (or cookies for that matter). There's plenty of examples of hash table uses.

A: The framework I am currently developing will have a lot of socket requests, many a minute per client.
Each socket request will contain the client's identifier, which will be stored/looked up in the Hashtable.
The reason I have chosen to go down this route is the performance flexibility available through the Hashtable, which I will be able to leave for now - and tweak later on.
:)

A: Note that "dictionary" and "hash table" are at two different levels of abstraction. A dictionary is something that maps keys of arbitrary type to values. A hash table is one way to implement a dictionary.
Note that sometimes "hash[ table]" is used as a synonym of "dictionary", such as in Perl's %hashes.
You use a hash table when you want the performance characteristics of a hash table. Mostly you wouldn't care and would just leave it as an implementation detail of your programming language.
Note that you can implement a hash table to have (amortized randomized expected) O(1) worst case, but many implementations don't go through all the work and performance overhead to achieve that. You don't need to bother if your inputs are cryptographic hashes or outright random, as in your example of (good) session tokens, so a hash table could have less overhead as compared to a hash table implementing an arbitrary dictionary.

A: Try reading Wikipedia's definition of a hash table for ideas on how you might use them.
In essence, a hash table is a way of mapping a particular key to a particular value. So in the case of session variables, you might use the variable as a key and a user's ID as the value. This would allow you to map any actions taken on a particular session to a specific user (the one logged into that session) and attribute any actions to them. Again, Wikipedia has some more information on sessions.


text:
Q: df shows double the actual size on FreeBSD when run via cron I have written a bash script that collects data from a server
and sends it to a log file that is being monitored by a
splunkforwarder. The server runs FreeBSD and has a ZPool that
is shared via Samba. So of course one of the things I'd like
splunk to keep an eye on is how much space is used on said share.
To keep things readable, I have extracted the lines from my script that achieve this:
#!/usr/bin/env bash
while read disk used avail ; do
        # In reality I pass these values to a function
        # that adds some formatting, but let's keep it
        # simple for the moment
        echo $disk " " $used " " $avail
done < <(df | awk '/datapool\// {print $1, $3, $4}')

When I run these lines from the command line I get the correct
numbers (I have compared the output with zfs list).
But when I run this script via cron, the numbers I get are all
doubled.
Let's look at the exact output on my machine:
# Manually
datapool/myshare   4842023944   24758292883

# Via cron
datapool/myshare   9684047889   49516585766

This only happens on FreeBSD. I have another ZFS storage server
that runs on Debian and when I run the exact same script there,
I get correct numbers all of the time.
I have tried running the cron job as different users
(including root), but it's always the same result. I have also
set the PATH environment variable to the same value that I have
when I run this script manually (instead of the shortened
version that cron usually uses).
I have absolutely no clue regarding the cause of this problem
and I really don't know how to debug this problem. Plus I
couldn't find any information on the internet that is even
remotely related to this problem.
I really hope that you can help me out here and ANY hint is
greatly appreciated :)

A: df(1) uses the environment variable BLOCKSIZE to determine which units are used when reporting disk space.
By default, for historical reasons, a block size of 512 is used. It is usual to set this variable within the environment of one's login shell to a more convenient value. For example:
setenv  BLOCKSIZE  "K"

cron(8) runs with a different environment to the login shell. The symptoms you are seeing are consistent with BLOCKSIZE being undefined for cron's environment, and set to a value of k or 1024 for the environment of the login shell.


text:
Q: Import interface in Angular 2 In a Meteor app that uses Angular 2, I want to create a custom data type, something like this:
interface MyCustomType {
  index: number;
  value: string;
}

I then want to use this custom type in multiple files. I've tried creating a separate file named "mycustom.type.ts", with the following content:
export interface MyCustomType {
  index: number;
  value: string;
}

I then attempt to import this type so that it can be used in another file:
import MyCustomType from "./mycustom.type"

However, Atom reports the following error:
TS Error File '/.../mycustom.type.ts' is not a module ...

How should I be declaring and importing types, so that they can be used in multiple places?

A: You should rather import it like that :
import { MyCustomType } from './mycustom.type';

don't forget the { and }.

A: the problem is the path you are inside the component try change ./ with ../

A: I am adding this answer because the accepted one is incomplete. You have two issues:
One, you need to add export to your interface so that you can import it as a module:
export interface MyCustomType {
  index: number;
  value: string;
}
Second you need to add the curly brackets { } to the import statement:
import { MyCustomType } from './mycustom.type';

A: I tried all of top answers but still i get the same error then I understand moreover @edzillion issues one issue can be raise this error .

One, you need to add export to your interface so that you can import
  it as a module:
Second you need to add the curly brackets { } to the import statement:

Third: your interface name must be match your file name(file that interface exist in it).

A: I think, problem is in the path:
Kindly refer below example:
If your file in another folder then refer below:
import { IPosts } from "../interfaces/iposts.type";

iposts.type.ts :
export interface IPosts {
   userId: number;
   id: number;
   title: string;
   body: string;
}


text:
Q: Stoyan Stefanov: JavaScript Patterns - "The Default Pattern" In chapter 6 (Code Reuse Patterns) there is following example:
// the parent constructor
function Parent(name) {
    this.name = name || 'Adam';
}

// adding functionality to the prototype
Parent.prototype.say = function () {
    return this.name;
};

// empty child constructor
function Child(name) {}

// inheritance magic happens here
inherit(Child, Parent);

In section "Classical Pattern #1 — The Default Pattern" the implementation of the inherit() function is:
function inherit(C, P) {
    C.prototype = new P();
}

In the section "Drawbacks When Using Pattern #1" is the following example:
var s = new Child('Seth');
s.say(); // "Adam"

I don't understand the following author's explanation:

This is not what you'd expect. It's possible for the child to pass
  parameters to the parent's constructor, but then you have to do the
  inheritance every time you need a new child, which is inefficient,
  because you end up re-creating parent objects over and over.

How is it possible for the child to pass a parameter to the parent's constructor? And how is it possible to change the prototype of an child object after construction if not through the hidden prototype property? Could anyone please give me an example for that, what the author means?

A:
you have to do the inheritance every time you need a new child, which is inefficient, because you end up re-creating parent objects over and over.

It's not inefficient, not further objects are created if done properly. Indeed, you will have to do explicit inheritance every time for passing parameters and invoking parent constructors.
function Child(name) {
    Parent.call(this, name); // apply the parent constructor on new instance
                             // to set up instance variables like `name`
}

// inheritance stuff happens here
Child.prototype = Object.create(Parent.prototype);

… which is no magic when you understand how the prototype chain works and what Object.create does.

A: The proposed inheritance scheme is rotten.
The right way to inherit, even in the 'simple way' is :
// the parent constructor
function Parent(name) {
    this.name = name || 'Adam';
}

// adding functionality to the prototype
Parent.prototype.say = function () {
    return this.name;
};

// Child constructor
function Child(name) {
      Parent.apply(this, arguments);  // to call with exact same parameters.
     // or  .call(this, /* the parameters you want */ ) ;
}

Child.prototype = Object.create(Parent.prototype);

Child.prototype.otherMethod = function() { /*...*/} ;

Note that calling new P() instead of doing Object.create(P.prototype) is completely stupid, especially since the constructor might not accept no arguments. In this case, your application might throw an exception just for the inheritance, when Object.create cannot fail...
Forget about the other comments also... Talking about inefficiency for one object creation per class (not per instance) is just irrelevant.
(maybe forget about the book ? :-) )

A: As Bergi pointed out you should not create an instance of Parent to set up prototype part of Child.
To deal with constructor parameters or passing parameters to a function chain that is under construction (code you have to maintain and applications that need new features in the future are always under construction) you can use one object to be used when passing arguments.
This is also helpful when you use a mediator/publish subscribe object and never know what function will be called after another is finished.
For an example see here under "Passing (constructor) arguments"


text:
Q: OpenFileDialog: load files in the same order as the user selected them I have set Multiselect to true in order to be able to load several files at once. The problem is that it ignores the order in which the user selects the files, the list of FileNames  is always the same (if I select the same set of files in different order).
My question is: is it possible to achieve the desired behavior? (Store paths in the same order as selected).
   List<string> filePaths = new List<string>();
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
        dlg.Multiselect = true;
        dlg.DefaultExt = ".txt";
        // dlg.Filter = my filter //

        Nullable<bool> result = dlg.ShowDialog();
        if (result == true)
        {
                foreach (string file in dlg.FileNames)
            {

            }

       }

A: Is this help?
open file dialog multislection order problem


text:
Q: Extracting XML info using PHP I have a strange formatted XML file, I want to extract the <text xml:space="preserve" bytes="1099"> part and turn that info into its own array.
I assume I would have to find the | delimiter and split at that point, but not quite sure how to do that.
  <page>
    <title>Martial Ares</title>
    <ns>0</ns>
    <id>23026</id>
      <sha1>7imznp2a51dh3kslf5gtqnkpkidlvom</sha1>
    <revision>
      <id>79960</id>
      <timestamp>2014-02-25T07:24:27Z</timestamp>
      <contributor>
        <username>JScathach</username>
        <id>8024930</id>
      </contributor>
        <text xml:space="preserve" bytes="1017">{{Infobox card (2)
            |card name=[Martial] Ares
            |character name=Ares
            |release_date=May 1 2013
            |image 1=MartialAres5.jpg
            |rarity 1=Super Special Rare
            |pwr req 1=28
            |sale price 1=94200
            |max card lv 1=60
            |max mastery lv 1=40
            |quote 1=Ares prefers weapons that were used during the age of Greek myth: sword, axe, and spear.  But he can use any weapon expertly, and turn most ordinary objects into lethal weapons.
            |base atk 1=2440
            |base def 1=2650
            |max atk 1=7015
            |max def 1=7613
            |mastery bonus atk 1=915
            |mastery bonus def 1=993
            |image 2=MartialAres6.jpg
            |rarity 2=Ultimate Rare
            |sale price 2=188400
            |max mastery lv 2=200
            |quote 2=Next time I see Hercules, We're going to have a steel conversation. It's about time for him to answer for massacring my Stymphalian Birds.
            |max atk 2=9822
            |max def 2=10660
            |mastery bonus atk 2=1098
            |mastery bonus def 2=1192
            |alignment=Bruiser
            |ability=Warhawk
            |gender=Male
            |usage=Average
            |faction=Super Hero
            |effect=Significantly harden DEF of your Bruisers.
            |centretrait=None
            }}
            __NOWYSIWYG__
      </text>
    </revision>
  </page>

A: You can get the text this way:
$xml = simplexml_load_string($string);
$text = $xml->revision->text;

A:
I assume I would have to find the | delimiter and split at that point, but not quite sure how to do that.

PHP's libxml based libraries (this includes SimpleXMLElement and DOMDocument) with their default options do preserve the whitespace within the text element of your question, so on that end you should run into little problems.
For the format that is encoded into the text elements text-value, this is Mediawiki syntax and at the beginning for it's largest part an Infobox Template.
{{Infobox
 | title = Top level title
 | data1 = {{Infobox | decat = yes | child = yes
    | title = First subsection
    | label1= Label 1.1
    | data1 = Data 1.1
   }}
 | data2 = {{Infobox | decat = yes | child = yes
  |title = Second subsection
  | label1= Label 2.1
  | data1 = Data 2.1
  }}
 | belowstyle =
 | below = Below text
}}

Example of an infobox template with embedded use
The infobox template follows a general template syntax to name a template and provide (named or unnamed) parameters to it. You find this outlined in the Usage Syntax section of Help:Template. As Mediawiki itself is written in PHP, you can even find PHP code that is related to parsing these template codes within it's source. It shows how this data is meant to be parsed in a more strictly fahsion than the help page, however as it's source code in a little modular and structured manner, it's much more convoluted. Depending on your type of programmer, it might overwhelm you as it requires reading skills and knowledge about PCRE regular expressions.
From what I can see so far is that you need to extract (recursive) {{ ... }} blocks first. Within these you parse the title and optionally any number of (named or unnamed) parameters. The delimiting character to separate these fields is |. I can't say if any of these delimiters can be or if how they are escaped nor can I say whether or not multi-line values are possible for fields and names - next to the examples given that show a value can be another template which then can be multiline.


text:
Q: Update Asp.Net Core Role Claim How i can change role claim and apply it in terms of one request in Asp.Net Core?
I tried to use
_signInManager.RefreshSignInAsync(user);

But it only works after refreshing the page. Is there any way to update roles for user and change current principal in one request?

A: You could not change the Current ClaimsPrincipal directly.
To reflect the new claims, you could try _signInManager.CreateUserPrincipalAsync.
To check the new roles in the same request, you may try User.AddIdentity to explict add the new role claim to User.
                var roleName = Guid.NewGuid().ToString();
            var r1 = User.IsInRole(roleName);

            var user = await _userManager.GetUserAsync(User);
            var role = await _roleManager.CreateAsync(new IdentityRole { Name = roleName });
            await _userManager.AddToRoleAsync(user, roleName);

            var claimsPrincipal = await _signInManager.CreateUserPrincipalAsync(user);
            var claims = claimsPrincipal.Claims.ToList();

            User.AddIdentity(new ClaimsIdentity(new List<Claim>() { claims.FirstOrDefault(c => c.Value == roleName) }));

            var r3 = User.IsInRole(roleName);


text:
Q: Is Intel Server board sh3200 with xeon x3220 good for virtualization? I am wondering if the sh3200 and xeon x3220 will run virtualization well.
I have this server running and it's fine but I want to throw on some virtual servers.
My plan is to run linux/ubuntu with virtualbox.

A: VirtualBox has no special requirements. Although the right CPU helps speed things up, of course. That being said, your Xeon X3220, although relatively dated, supports Intel VT-x.


text:
Q: Bind on change and other actions to multiple ajax loaded elements inside div I have a form which has multiple inputs, selects and textareas.
On load jQuery finds every element, sets its data-attr to default value, binds an on change event to it and triggers a change.
Problem is, that some selects are being re-loaded with ajax based on other input values.
Is there a simple way to change this code, to work on ajax loaded elements?
It has to set the initial data-attr value, but only once per element (after it appears in dom), same with triggering the change.
This is the original code:
$main_form.find('input, select, textarea').each(function(){
    $(this).attr('data-empty', 'true').off('change').on('change', function(){
        if ($(this).hasClass('number')) validate_int($(this));
        update_progress($(this));
    }).trigger('change');
});

I know there is something like:
$main_form.on('change', 'input, select, textarea', function(){

});

But that would bind the data-attr on every change and it would also infinitely trigger the change. Also, the .off('change') is not really, needed there, I am just used to use it.
I do not want to copy this code and add it to ajax done function, as I am trying to prevent duplication of code, which would make maintaining and adjusting it harder than it already is. Or is that the only option?
.
If you have any questions, just comment and I will update my answer to be as precise as it possibly could.
Thanks for help.

A: If I understood correctly, you want to set an initial value for data-empty attribute and trigger a change event once for every loaded, and future loaded form element.
I would suggest that you use event delegation for the part of code that must be executed on every change event occurrence:
// This will affect all form element (including those loaded with ajax)
$main_form.on('change', 'input, select, textarea', function(){
    if ($(this).hasClass('number')) validate_int($(this));
    update_progress($(this));
});

Create a function that performs initial assignment of values:
/**
*  Set initial value and trigger change event
*  @param $elem {jQuery object} The target element
*/
function setInitialValue($elem) {
   $elem.attr('data-empty', 'true').trigger('change');
}

And set initial data attribute and trigger a change event on every ajax successful callback:
success: function(data) {
   var targetElement = $('select');
   targetElement .append(data);
   setInitialValue(targetElement);
}

Finally, you can trigger a change event for every initialy loaded element:
$(document).ready(function() {
    $main_form.find('input, select, textarea').each(function(){
        setInitialValue($(this));
    });
});


text:
Q: Applicative Functors and Left from Either I have been working through the great good book, but I am struggling slightly with Applicative Functors.
In the following example max is applied to the contents of the two Maybe functors and returns Just 6.
max <$> Just 3 <*> Just 6

Why in the following example is Left "Hello" returned instead of the contents of the Either functors: Left "Hello World"?
(++) <$> Left "Hello" <*> Left " World"

A: It's because the type parameter in the Functor instance (and Applicative etc.) is the second type parameter. In
Either a b

the a type, and the Left values are not affected by functorial or applicative operations, because they are considered failure cases or otherwise inaccessible.
instance Functor (Either a) where
    fmap _ (Left x)  = Left x
    fmap f (Right y) = Right (f y)

Use Right,
(++)  <$> Right "Hello" <*> Right " World"

to get concatenation.

A: To add to Daniel's excellent answer, there are a couple points I'd like to make:
First, here's the Applicative instance:
instance Applicative (Either e) where
    pure             =  Right
    Left  e  <*>  _  =  Left e
    Right f  <*>  r  =  fmap f r

You can see that this is 'short-circuiting' -- as soon as it hits a Left, it aborts and returns that Left.  You can check this with poor man's strictness analysis:
ghci> (++) <$> Left "Hello" <*> undefined
Left "Hello"                              -- <<== it's not undefined :) !!

ghci>  (++) <$> Right "Hello" <*> undefined
*** Exception: Prelude.undefined          -- <<== undefined ... :(

ghci> Left "oops" <*> undefined <*> undefined
Left "oops"                               -- <<== :)

ghci> Right (++) <*> undefined <*> undefined
*** Exception: Prelude.undefined          -- <<== :(

Second, your example is slightly tricky.  In general, the type of the function and the e in Either e are not related.  Here's <*>s type:
(<*>) :: Applicative f => f (a -> b) -> f a -> f b

If we make the substitution f -->> Either e, we get:
(<*>) :: Either e (a -> b) -> Either e a -> Either e b

Although in your example, e and a match, in general they won't, which means you can't polymorphically implement an Applicative instance for Either e which applies the function to a left-hand argument.


text:
Q: Identity morphism is unique I started reading Ravi Vakil's notes The Rising Sea - Foundations of Algebraic Geometry. On p. 26 he writes: 'If you wish, you may check that "identity morphisms are unique"'.
So I tried doing this and wonder whether I am correct.
Let $\text{id}_{A} : A \rightarrow A$ and $\bar{\text{id}}_{A} : A \rightarrow A$ be two identity morphisms. Then, $\text{id}_{A} \circ \bar{\text{id}}_{A} = \bar{\text{id}}_{A}$ and $\text{id}_{A} \circ \bar{\text{id}}_{A} = \text{id}_{A}$; since we know that if we left or right compose a morphism with the identity, we get the same morphism. Hence, $\text{id}_{A} = \bar{\text{id}}_{A}$.


text:
Q: NodeJS serialport Не могу работать с модулем serialport при дебаге выдаёт следующую ошибку

C:\Users\Guru\Desktop\step motor project\electron-quick-start\node_modules\bindings\bindings.js:121 Uncaught Error: The module '\?\C:\Users\Guru\Desktop\step motor project\electron-quick-start\node_modules@serialport\bindings\build\Release\bindings.node'
  was compiled against a different Node.js version using
  NODE_MODULE_VERSION 64. This version of Node.js requires
  NODE_MODULE_VERSION 69. Please try re-compiling or re-installing
  the module (for instance, using npm rebuild or npm install).

и т.д.

npm rebuild и npm install пробовал всё безрезультатно :(


text:
Q: Refcursors in Postgresql Good Morning,
I have a quick question on how to see the data that is fetched in an Output refcursor
I'm executing the below block, its successfully executed but I want to see the data fetched in Output RefCursor, by the way I'm using PGADMIN 4 tool to connect to Postgres Servers,
BEGIN;
SELECT prod_package_list ('G6028|G6026|G6025|G6024|G6022|G6021|G6020', NULL);
FETCH ALL IN vref_cur;
COMMIT;

I found online and according to them I should follow the below format,
BEGIN;
SELECT test_prod_package_list ('G6028|G6026|G6025|G6024|G6022|G6021|G6020', NULL, 'vref_cur');
FETCH ALL IN "vref_cur";
COMMIT;

But the above execution block throws an error
function prod_package_list(unknown, unknown, unknown) does not exist,
The function is as follows,
CREATE OR REPLACE FUNCTION ssp2_pcat.prod_package_list(
    prodlist text,
    billcodelist text,
    OUT vref_cur refcursor)
    RETURNS refcursor
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE
AS $BODY$

BEGIN
    vref_cur := 'vref_cur';

    IF prodlist IS NOT NULL THEN
        OPEN vref_cur FOR
        SELECT DISTINCT
            b.package_id, a.product_id, a.pdct_ctlg_id, a.product_name, a.billing_system, a.billing_code, a.fulfill_system, a.fulfill_code, a.speed_code, a.product_type, a.product_type_value, a.return_auth_applies, a.return_auth_term, a.nrc_waiver, a.nrc_waiver_product_id, a.linked_nrc_product_id, a.national_east_west, a.lata_list, a.state_list, a.product_info_url, a.isp_prov_flags, a.product_coefficient, a.last_updated, a.product_keywords, a.combo_product_list, a.additional_info, a.usoc_info, a.min_billing_days, a.data_nrf_product_id, a.video_nrf_product_id, a.account_line_level, a.web_desc, a.orderguicd, a.prod_startdate, a.prod_enddate, b.pdct_ctlg_id, b.package_name, b.billing_code, b.category_id, b.standalone_cpe, b.standalone_truckroll, b.btn_billed, b.emp_discount, b.package_type, b.last_updated, b.pkg_detail_descr, b.grandfathered AS pkg_grandfathered,
            CASE CONCAT_WS('', a.grandfathered, c.pkg_prod_grandfathered)
                WHEN 'YY' THEN 'Y'
                WHEN 'YN' THEN 'Y'
                WHEN 'NY' THEN 'Y'
                ELSE 'N'
            END AS grandfathered
            FROM ssp2_pcat.products AS a, ssp2_pcat.packages AS b, ssp2_pcat.package_products AS c
            WHERE strpos(prodlist, CONCAT_WS('', '|', a.product_id, '|')) > 0
            AND a.product_id = c.product_id AND c.package_id = b.package_id
            AND c.start_date <= LOCALTIMESTAMP AND c.end_date >= LOCALTIMESTAMP
            ORDER BY 1;

    ELSIF billcodelist IS NOT NULL THEN
        OPEN vref_cur FOR
        SELECT DISTINCT
            b.package_id, a.product_id, a.pdct_ctlg_id, a.product_name, a.billing_system, a.billing_code, a.fulfill_system, a.fulfill_code, a.speed_code, a.product_type, a.product_type_value, a.return_auth_applies, a.return_auth_term, a.nrc_waiver, a.nrc_waiver_product_id, a.linked_nrc_product_id, a.national_east_west, a.lata_list, a.state_list, a.product_info_url, a.isp_prov_flags, a.product_coefficient, a.last_updated, a.product_keywords, a.combo_product_list, a.additional_info, a.usoc_info, a.min_billing_days, a.data_nrf_product_id, a.video_nrf_product_id, a.account_line_level, a.web_desc, a.orderguicd, a.prod_startdate, a.prod_enddate, b.pdct_ctlg_id, b.package_name, b.billing_code, b.category_id, b.standalone_cpe, b.standalone_truckroll, b.btn_billed, b.emp_discount, b.package_type, b.last_updated, b.pkg_detail_descr, b.grandfathered AS pkg_grandfathered,
            CASE CONCAT_WS('', a.grandfathered, c.pkg_prod_grandfathered)
                WHEN 'YY' THEN 'Y'
                WHEN 'YN' THEN 'Y'
                WHEN 'NY' THEN 'Y'
                ELSE 'N'
            END AS grandfathered
            FROM ssp2_pcat.products AS a, ssp2_pcat.packages AS b, ssp2_pcat.package_products AS c
            WHERE strpos(billcodelist, CONCAT_WS('', '|', a.billing_code, '|')) > 0
            AND a.product_id = c.product_id AND c.package_id = b.package_id
            AND c.start_date <= LOCALTIMESTAMP AND c.end_date >= LOCALTIMESTAMP
            ORDER BY 1;

    ELSE
        RAISE USING hint = -20001, message = 'Product List and Billing Code Lists are empty.', detail = 'User-defined exception';
    END IF;

END;

$BODY$;

ALTER FUNCTION ssp2_pcat.prod_package_list(text, text)
    OWNER TO ssp2_pcat;

Please advise,

A: Use IN parameter to pass a cursor name. Do not forget to RETURN vref_cursor. Working example:
CREATE FUNCTION my_func(arg1 text, arg2 text, vref_cursor refcursor)
RETURNS refcursor AS $$
BEGIN
    OPEN vref_cursor FOR SELECT generate_series(1,3);
    RETURN vref_cursor;
END;
$$ LANGUAGE plpgsql;

BEGIN;
SELECT my_func('first arg', 'second arg', 'vref_cursor');
FETCH ALL IN vref_cursor;
COMMIT;


text:
Q: discord.py + PostgreSQL | 'NoneType' object has no attribute 'id' Я пробовал писать по-разному этот ансамбль из букв, вроде как суть самой проблемы я понимаю, но я все не могу понять, как ее тут исправить.
Базы данных создаются, вроде как, без проблем, пользователи сервера туда заносятся, и запуск происходит успешно. Но при использовании команды cash выдает ту самую неприятную для меня ошибку
async def on_ready():

    cur.execute("""CREATE TABLE IF NOT EXISTS users(
        name TEXT,
        id BIGINT NOT NULL,
        cash BIGINT,
        server_id BIGINT NOT NULL
    )""") # Создаем базу данных пользователей

    cur.execute("""CREATE TABLE IF NOT EXISTS shop(
        role_id BIGINT,
        id BIGINT,
        cost BIGINT
    )""") # Создаем базу данных магазина

    for guild in client.guilds:
        for member in guild.members:
            cur.execute(f"SELECT id FROM users WHERE id = {member.id}")
            row = cur.fetchone()
            if row is None: # Проверять пользователя на наличие в базе данных
                cur.execute(f"INSERT INTO users VALUES ('{member}', {member.id}, 0, {guild.id})") # Заносить пользователя в базу данных, если его нет
            else:
                pass # Пропустить пользователя
    con.commit()
    print("Активация прошла успешна") # Вывод в консоль готовности бота
    print('Подключение к базе данных прошло успешно')

@client.event
async def on_member_join(member):
    cur.execute(f"SELECT id FROM users WHERE id = {member.id}")
    row= cur.fetchone()
    if row is None: # Проверять пользователя на наличие в базе данных
        cur.execute(f"INSERT INTO users VALUES ('{member}', {member.id}, 0, {member.guild.id})") # Заносить пользователя в базу данных, если его нет
        con.commit()
    else:
        pass # Пропустить пользователя

# Баланс | Cash | Balance
@client.command(aliases = ['cash', 'balance'])
async def __cash(ctx, member: discord.Member = None):
    query = cur.execute("SELECT cash FROM users WHERE id = {}".format(member.id)[0])
    result = cur.fetchone(query)
    if member is None:
        await ctx.send(embed = discord.Embed(
            description = f"""Баланс пользователя **{ctx.author}** составляет **{result}** :small_red_triangle_down:"""
        ))
    else:
        await ctx.send(embed = discord.Embed(
            description = f"""Баланс пользователя **{member}** составляет **{result}** :small_red_triangle_down:"""
        ))

con.close()
client.run (settings['TOKEN']) # Запуск```

A: При создании команды вы добавили аргументу member стандартный параметр None, на тот случай, если при вызове команды !cash / !balance в чате дискорда, функции __cash не будет передан аргумент member.
Вы предусмотрели исключение этой ошибки при отправке результата, подставляя вместо member объект автора ctx.author на тот случай, если member is None, но забыли сделать это при выполнении запроса к базе данных.
Вам нужно точно также оформить запрос:
if member is None:
    query = cur.execute("SELECT cash FROM users WHERE id = {}".format(ctx.author.id))
else:
    query = cur.execute("SELECT cash FROM users WHERE id = {}".format(member.id))


text:
Q: Cannot find the input date into the textbox How can I search my date into the datagrid view? I have a sample code which I think is correct but why does it not search?

    private void textBox3_TextChanged(object sender, EventArgs e)
    {

        if (string.IsNullOrEmpty(textBox3.Text))
        {
            SqlDataAdapter sda = new SqlDataAdapter("Select * from STUDENT_RESEARCH_PROJECTS WHERE COURSE LIKE '" + comboBox2.Text + "%'", con);
            DataTable data = new DataTable();
            sda.Fill(data);
            dataGridView1.DataSource = data;
        }

        else
        {
            SqlDataAdapter sda = new SqlDataAdapter("SELECT ACCESSION_NO,TITLE_PROJECT,CATEGORY,YEAR,COURSE,DATE,Student_Name1,Student_Name2,Student_Name3,Student_Name4,Student_Name5,RELATED_TITLE1,RELATED_TITLE2,RELATED_TITLE3,RELATED_TITLE4,RELATED_TITLE5 FROM STUDENT_RESEARCH_PROJECTS WHERE DATE LIKE'" + textBox3.Text + "%'", con);
            DataTable data = new DataTable();
            sda.Fill(data);
            dataGridView1.DataSource = data;
        }
    }

A: You cannot use LIKE for date comparison unless your DATE field is a string
Also you need to check how is the date data saved into database
For example in my database I am using datetime which is being saved like 2018-03-20 07:25:58.557
So when you are querying you need to put a format of your date in order to be accepted

A: First be aware SQL injection.
you cannot use like operator on Date Column.
Your search TextBox value date format is 03/20/2018(mm/dd/yyyy) and database column contains something different which is usually 2018-03-20 00:00:00.000 to search with the date change the format when querying from database like this.
    private void textBox3_TextChanged(object sender, EventArgs e)
    {

        if (string.IsNullOrEmpty("textBox3.Text"))
        {
            string query = "Select * from STUDENT_RESEARCH_PROJECTS WHERE COURSE LIKE @COURSE";
            SqlCommand cmd = new SqlCommand(query, con);
            cmd.Parameters.AddWithValue("@COURSE", comboBox2.Text);

            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable data = new DataTable();
            sda.Fill(data);
            dataGridView1.DataSource = data;
        }

        else
        {
            string query = "SELECT ACCESSION_NO,TITLE_PROJECT,CATEGORY,YEAR,COURSE,DATE,Student_Name1,Student_Name2,Student_Name3,Student_Name4,Student_Name5,RELATED_TITLE1,RELATED_TITLE2,RELATED_TITLE3,RELATED_TITLE4,RELATED_TITLE5 FROM STUDENT_RESEARCH_PROJECTS WHERE CONVERT(varchar(10) ,DATE, 101)  = @DATE";
            SqlCommand cmd = new SqlCommand(query, con);
            cmd.Parameters.AddWithValue("@DATE", textBox3.Text);
            SqlDataAdapter sda = new SqlDataAdapter();
            DataTable data = new DataTable();
            sda.Fill(data);
            dataGridView1.DataSource = data;
        }
    }


text:
Q: Send multiples messages in one request (webhook) in Teams I'm trying to send multiple message card in same time
When I'm doing a request for only one message with postman, it works for example :
{
  "@type": "MessageCard",
  "@context": "http://schema.org/extensions",
  "summary": "Summary",
  "title": "Connector Card HTML formatting",
  "sections": [
    {
     "text": "This is some bold text"
    },
 }

And now, how can I create a another card message in same time?

A: Currently Webhook does not support sending multiple messages in one request. This is by  design.

A: *

*Only a single message card works for me.

*I really doubt we have an option to send multiple messages card.

*Unfortunately i failed to failed to see that in Microsoft
Documentation either.

*It looks like "by design" to me. It's confirmed
above too.


text:
Q: Selecting elements by name with wildcards Whats a good way to select elements by their name using wildcards?
The website has element names in the form of <a_1786439></a_1786439> which are likely auto-generated. This is doable by xpath, but is it doable using css selectors or jquery selectors which are faster?
This is clearly terrible-coding, but the website is not mine, and I'm writing a userscript for it.

A: This doesn't exist in CSS3, as the spec's section on type selectors only includes names and wildcards, but no combinations of them.

A: It's possible to create custom elements using the HTML DOM createElement method like this:
document.createElement('Funny_Element');

In the website code you are dealing with, they have created a custom element, or maybe extend the a element, but they didn't choose a significant name! a_1786439??? which is, I think, really bad.
Using CSS selectors or jQuery selectors depends essentially on what you want to do. Suppose you have to access children elements of a specific node, then jquery selectors would be more appropriate.
Hope it's useful!


text:
Q: Python calling DLL calling Python, "WindowsError: exception: access violation reading 0x00000004" I have an application written in Python.
The application calls some functions in the dll (using ctypes) that calls some functions from the python C API to load and run some functions in a (different) python module. This causes WindowsError: exception: access violation reading 0x00000004 Some cout debugging tells me that the access violation happens on a call to the Python C API.
I know the DLL successfully loads the python module, running to completion when I test it as a stand alone .exe but when it is run from the python application it gives this access violation error.
I first though that maybe I should use Py_NewInterpreter in the DLL to create a new separate space for these python module functions to run. This would seem convienent as there is no need for the application and the modules runs by the DLL to share any data.
http://docs.python.org/2/c-api/init.html#Py_NewInterpreter
However my initial tests with Py_NewInterpreter have proved unsuccessful simply making further errors and crashing.
So my question is how should I implement this/what do I need to do make the DLL load of the python modules work?

A: This looks like dereferencing a null pointer, i.e. a pointer to a structure/class is null and you are reading a subobject at offset 4. Sprinkle a few assert()s throughout your code to make sure you don't miss any null pointer. Note also that the Python C API regularly returns null in case of an exception.
That said, you have a Python program importing a DLL via ctypes. This DLL in turn embeds a Python interpreter via Python's C API. Right? If I'm not mistaken, that effectively gives you two interpreter instances in one process. The problem there is that any global objects are shared between the two and that this might not be coordinated.
What I would try is to write a proper Python (wrapper) module instead of using ctypes to import the DLL. However, there's another thing that I would do in parallel and that is to ask on the Python user mailinglist, whether this setup can work or not and why. There is also a news gateway in case you prefer that.


text:
Q: Maximizing with an assumption I want to maximize an expression assuming p is between zero and one. What should I do?
z = Re[N[Sqrt[p] Cos[θ1] Cos[θ] + Sqrt[1 - p] E^(I(ϕ + ϕ1)) (Sin[θ]) Sin[θ1]]];
λ = Maximize[z, {θ, p, θ1, ϕ1, ϕ}];

A: The code
z = Re[N[Sqrt[p] Cos[\[Theta]1] Cos[\[Theta]] +
Sqrt[1 -p] E^(I (\[Phi] + \[Phi]1)) (Sin[\[Theta]]) Sin[\[Theta]1]]];
\[Lambda] = Maximize[z,p >= 0 && p <= 1, {\[Theta], p, \[Theta]1, \[Phi]1, \[Phi]}]

does the job, producing

{1., {[Theta] -> -9.04986*10^-9,
    p -> 1., [Theta]1 -> -9.74328*10^-9, [Phi]1 ->
     0.430937, [Phi] -> -1.04225}}


text:
Q: Swift 3: How to change button's image to UIImageView's image Is there any way I can change UIButton's image to UIImageView's image?
The UIImageView's image is from database.
Any help is appreciated, thank you so much!

A: You can just set the button's image to imageView.image.
button.setImage(imageView.image, for: .normal)


text:
Q: Merging PHP Arrays for JSON output I'm having a difficult time trying to get back a single array, which I can then return as JSON.
The Model:
class CoverageLimit extends Eloquent {

    protected $table = 'webapp_limit_tbl';

    public static function index($code,$plan_type,$income_tier){
        $data =  CoverageLimit::where('limitcode', $code)
        ->where('plantypecode', $plan_type)
        ->where('incometiercode', $income_tier)
        ->get(array('limitcode','limit_desc'));
        return print_r($data->toArray());
    }

}

The Controller:
$limits = array();
    foreach($pieces as $coverage_limit) {
    $limits = array_merge($limits, coveragelimit::index($coverage_limit,$plan_type,$income_tier));
//this now works thanks to suggestion below
    }
return $limits;

Returns:
Array
(
    [0] => Array
        (
            [limitcode] => L0001
            [limit_desc] => $1M per claim / $2M annual aggregate
        )

)
Array
(
    [0] => Array
        (
            [limitcode] => L0002
            [limit_desc] => $2M per claim/ $2M annual aggregate
        )

)
[true,true]

The goal is to output the following JSON data via json_encode($limits):
[{"limitcode":"L0001","limit_desc":"$1M per claim / $2M annual aggregate"},{"limitcode":"L0002","limit_desc":"$2M per claim / $2M annual aggregate"}]
I think what I need is a single array like below in order to accomplish this, but I can't seem to make it happen.
Array
(
    [0] => Array
        (
            [limitcode] => L0001
            [limit_desc] => $1M per claim / $2M annual aggregate
        ),
    [1] => Array
        (
            [limitcode] => L0002
            [limit_desc] => $2M per claim/ $2M annual aggregate
        )

)

I would be grateful for any help on how I could merge this return into a single array for valid json output. Or if there is a way to return it from the foreach as one array. Thanks.

A: First, do not use return print_r($data->toArray());
That is incorrect. Just do return $data->toArray() and it should work just fine.
The problem is that print_r returns a boolean and outputs to stdout a text representation of your data structure. That is why you see that annoying [true, true] at the end of your output example. The array you are attempting to json_encode is actually just an array with two values of true returned from print_r.


text:
Q: How do you enable the Service Cloud Console in a developer org? I've seen a few pages online that talk about enabling the Service Cloud Console. They all seem to mention creating a new App and selecting "Service Cloud Console" but I don't have that as an option when I'm creating a new app in my dev org.
Here's an example of what I'm talking about: Creating A Service Cloud Console App
Is there something I need to do before I can create an app?

A: Is this an old developer edition?  The service cloud console hasn't been around for that long, so it may be that the template for your dev org didn't include it.  I have a similar org that doesn't have knowledge feature license.  If that is the case, you can either raise a case with support to have the feature enabled or just spin up a new dev org.  I usually choose the latter as its faster.

A: First go to your profile and activate "Service cloud User" option.
Then try again with service cloud console app :)

A: If you haven't already, make sure that you make the app (Sample Console) visible to your user profile. By default, no profiles can view the console.

A: Latest:
Go to your name--> my setting--> personal--service cloud user


text:
Q: increase by one a variable every time you push a button (PHP) I'd like that the variable $order is increase by 1 every time I push the submit button.
(The name of the page is study.php so every time I push the button the page is refreshed):
 <?php
 $order = $_GET['number'];

 echo "<form action='study.php' method='GET'>
   <input type='hidden' name='number' value='$order++' />
   <input class='big_b' type='submit'  value='next' />
 </form>";

 echo "$order";
 ?>

The first time 1 push the button $order is 1, the second 2, the third is 3 ... etc
Thanks for your help!
EDIT: SOLVED
 <?php
 session_start();
 if(empty($_SESSION['count'])) $_SESSION['count'] = 0;
 $order =  $_SESSION['count']+1;
 $_SESSION['count'] =  $order;

 echo "<form action='study.php' method='GET'>
        <input class='big_b' type='submit'  value='next' />
    </form>";

 echo "$order";
 ?>

A: How you currently have it, is that it will increment on each page refresh regardless whether button was clicked or not, do you need it only to increment if the button is pressed?
<?php
session_start();

// Reset to 1
if(isset($_POST['reset'])){unset($_SESSION['number']);}

// Set or increment session number only if button is clicked.
if(empty($_SESSION['number'])){
    $_SESSION['number']=1;
}elseif(isset($_POST['next'])){
    $_SESSION['number']++;
}

echo '
<form action="" method="POST">
   <input class="big_b" type="submit" name="next" value="Next" />
   <input type="submit" name="reset" value="Reset" />
</form>';

echo $_SESSION['number'];
?>

A: You need to put $order++ outside of the quotation marks to make an operation (incrementing by 1). Here's the code:
<?php
 $order = $_GET['number'];

 echo "<form action='study.php' method='GET'>
   <input type='hidden' name='number' value='".$order++."' />
   <input class='big_b' type='submit'  value='next' />
 </form>";

 echo "$order";
 ?>

A: <?php
session_start();
if(empty($_SESSION['order'])){

    $_SESSION['order'] = 1;
}

 echo "<form action='study.php' method='GET'>
   <input type='hidden' name='number' value='".$_SESSION['order']++."' />
   <input class='big_b' type='submit'  value='next' />
 </form>";

 echo $_SESSION['order'];

?>