text:
Q: Remove the number behind the chapter on the ToC For example, using \chapter{INTRODUCTION} will be printed as
1 INTRODUCTION...............x

I want to remove the number 1 behind the chapter, so the output on the ToC would be:
INTRODUCTION................x

Note: x is a page number.
My MWE is :
\documentclass{a4paper, 12pt, oneside, openany}{book}
\usepackage[a4paper, inner=4cm, outer=3cm, top=4cm, bottom=3cm]{geometry}
\usepackage{blindtext}

\begin{document}

\tableofcontents

\chapter{Chapter 1. INTRODUCTION}
\section{Section Name}
\blindtext
\section{Section Name}
\blindtext
\chapter{Chapter 2. BACKGROUND}
\section{Section Name}
\blindtext
\section{Section Name}
\blindtext

\end{document}

A: You can influence the appearance of the titles in the table of contents with the titletoc package. This allows you to remove the number.
The command for this is \titlecontents. See the comments in the code below for a description of the arguments of this command. See also the package documentation.
MWE (note that I removed the manual 'Chapter n.' parts of the \chapter commands):
\documentclass[a4paper, 12pt, oneside, openany]{book}
\usepackage[a4paper, inner=4cm, outer=3cm, top=4cm, bottom=3cm]{geometry}
\usepackage{blindtext}
\usepackage{titletoc}
\titlecontents{chapter}% redefine chapter toc appearance
[1.5em]% left margin
{}% code before starting the title, here empty
{\hspace*{-2.3em}\bfseries}% format: shift a bit left and boldface, no number
{\hspace*{-2.3em}\bfseries}% format for \chapter*, not really needed for the MWE but added for completeness
{\titlerule*[1pc]{.}\contentspage}% dotted line and page number

\begin{document}

\tableofcontents

\chapter{INTRODUCTION}
\section{Section Name}
\blindtext
\section{Section Name}
\blindtext
\chapter{BACKGROUND}
\section{Section Name}
\blindtext
\section{Section Name}
\blindtext

\end{document}

Result in TOC:

In the document:

If you also want to change the appearance in the document then you can use the titlesec package which is closely related to titletoc with very similar syntax. The command for changing the title in the document is \titleformat. See the comments in the code below for a description of the arguments of this command.
\documentclass[a4paper, 12pt, oneside, openany]{book}
\usepackage[a4paper, inner=4cm, outer=3cm, top=4cm, bottom=3cm]{geometry}
\usepackage{blindtext}
\usepackage{titlesec}
\usepackage{titletoc}
\titlecontents{chapter}% redefine chapter toc appearance
[1.5em]% left margin
{}% code before starting the title, here empty
{\hspace*{-2.3em}\bfseries}% format: shift a bit left and boldface, no number
{\hspace*{-2.3em}\bfseries}% format for \chapter*, not really needed for the MWE but added for completeness
{\titlerule*[1pc]{.}\contentspage}% dotted line and page number

\titleformat{\chapter}% change format of chapter in the document
{\huge\bfseries}% huge font and bold
{Chapter \thechapter}% the word Chapter followed by the chapter number
{1em}%horizontal space between 'Chapter n' and the chapter title
{}% code after the title, here empty

\begin{document}

\tableofcontents

\chapter{INTRODUCTION}
\section{Section Name}
\blindtext
\section{Section Name}
\blindtext
\chapter{BACKGROUND}
\section{Section Name}
\blindtext
\section{Section Name}
\blindtext

\end{document}

The TOC is the same, but in the document a chapter is now as follows:


text:
Q: Using Lucee from java Currently trying to create a way for my java project to call ColdFusion methods. I have stumbled upon Lucee but I'm having trouble getting the imports to work properly within a maven java project. It just does not find the javax.* dependencies. Also the Cookie is giving me the Abstract error, and I don't really want to implement about 20+  methods.
import java.util.HashMap;
import java.util.Map;
import lucee.loader.engine.CFMLEngine;
import lucee.loader.engine.CFMLEngineFactory;
import lucee.runtime.PageContext;
import lucee.runtime.type.scope.Cookie;

public class Controller{

  public static void main(String[] args) {
        CFMLEngine engine = CFMLEngineFactory.getInstance();
        javax.servlet.http.Cookie[] cookies = new Cookie[]{new Cookie("myCookie","myCookieValue")};
        Map<String, Object> headers=new HashMap();
        headers.put("accept","text/html");
        Map<String, String> parameters=new HashMap();
        Map<String, Object> attributes=new HashMap();
        PageContext pc = engine.createPageContext(
                "localhost"
                ,"/index.cfm"
                ,"test=1"
                ,cookies
                ,headers
                ,parameters
                ,attributes
                ,System.out
                ,50000
                ,true
                );
        try{
            }
        finally{
            engine.releasePageContext(pc, true/* unregister the pc from the thread*/);
        }
  }
}

This was taken directly from the Lucee docs, so I'm pretty sure the code is correct. Sadly it doesn't seem to explain the correct imports to use. So I'm currently at a confused state and figuring this out.
Is my import correct? or have I derped and used the wrong ones?
Edit 1: I tried downloading and adding the Javax.jar but that alters the parameters that Pagecontext wants. As I'm still new to Lucee, I'm not too comfortable altering too much of the given code (nor do I feel like I should need to).

redpajama_set_name: RedPajamaStackExchange


text:
Q: What happens if two ObjC categories override the same method? I know of a couple of rules regarding Objective-C categories:

*

*Category methods should not override existing methods (class or instance)

*Two different categories implementing the same method for the same class will result in undefined behavior

I would like to know what happens when I override one of my own category methods in the same category. For example:
@interface NSView (MyExtensions)
- (void)foo; // NSView category implementation
@end

@interface MyClass : NSView
{ }
@end

@interface MyClass (MyExtensions)
- (void)foo; // MyClass category implementation
@end

With these interfaces defined, which method will be executed when I run the following code?
MyClass * instance = [[MyClass alloc] initWith...];
[instance foo];
[instance release];

Note: With my compiler, the MyClass implementation takes precedence, but I'm not sure if that is guaranteed to occur, or simply one specific flavor of undefined behavior.

A: To extend on drawnonward answer:
It's matter of hierarchy. Categories are really just a means of organizing source files. When compiled, all the methods of a class, including the ones defined in any category, end up in the same file.
Anything you could do in a regular class interface you can do in a category and anything you shouldn't do in a regular class interface you shouldn't do in a category.
So:

Category methods should not override
  existing methods (class or instance)

You can use methods defined in the regular class interface to override inherited methods so you can override inherited methods in a category.
However, you would never try to have to two identical method definitions in the same ordinary interface so you should never have a method in a category that has the same name as a method in either the ordinary interface or another category on the same class. Since all the method definitions end up in the same compiled file, they would obviously collide.

Two different categories implementing
  the same method results in undefined
  behavior

That should be rewritten to say "Two different categories implementing the same method for the same class results in undefined behavior." Again, because all the methods for any one class end up in the same file, having two methods in the same class would obviously cause weirdness.
You can use categories to provide methods that override superclass methods because a class and its superclass are two distinct classes.
If your ever confused about whether a category will cause problem just ask yourself this: "Would the methods in the category work if I copied and pasted them all into the class' .h/.m files?" If the answer is "yes" then you're in the clear. If "no", then you've got problems.

A: Each method of each class has an implementation.  A category adds or replaces a method for a specific class.  That means the behavior you are seeing, where MyClass has one foo and NSView has another foo, is well defined.  Any instance of MyClass will have a different foo than any instance of NSView that is not a MyClass, just as if foo had been defined in the main implementation and not a category.  You should even be able to call [super foo] from MyClass to access the foo defined for NSView.


text:
Q: Golang Mongodb Filter Queries as a string I try to write queries for mongodb collection in Golang. However to use db.Collection.find() method we need to add filter in an interface{} type. I can use bson.D and bson.M to create filters. However, The user will send as a string these filters to backend side. For example:
In Golang:
filter := `bson.D{ // a string variable sent by UI
   {"$and",
      bson.A{
         bson.D{{"rating", bson.D{{"$gt", 7}}}},
         bson.D{{"rating", bson.D{{"$lte", 10}}}},
      },
   },
}`

How can I convert dynamic string filter to interface{} type for accepting by find() method.

A: I think one workaround for parse query string could be the query string from UI could be raw json like {"$and": [{"rating": {"$gt": 7}}, {"rating": {"$lte", 10}]}, then you could parse it through bson.UnmarshalExtJSON
Sample codes
filterStr := `{"$and": [{"rating": {"$gt": 7}}, {"rating": {"$lte", 10}]}`
var filter interface{}
err := bson.UnmarshalExtJSON([]byte(filterStr), true, &filter)

// the filter could be passed to Find() method


text:
Q: Google Maps Directions - Which API? I'm trying to get the directions from the user's current location to a user defined location in the app that I'm building. This seems like it should be a relatively easy thing to do but I'm getting stuck on which API to use.
Right now I've managed to hook up to the google directions API but the JSON it's returning is very strange (they've added a \n everywhere to make it human readable) which suggests to me that this API isn't the correct one for mobile.
I've also seen the google places API being recommended for this purpose but I can't seem to find out how to use it from the documentation.
Any help is greatly appreciated since I'm just a titch confused
EDIT: Just to clarify the questions is which API I should be using to get directions for maps?

A: I do not remember where I get it but this classes help me a lot, it includes if you want to draw the route.
GoogleParser.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.maps.GeoPoint;
import com.monumentos.log.Logger;

public class GoogleParser extends XMLParser implements Parser {
    /** Distance covered. **/
    private int distance;

    public GoogleParser(String feedUrl) {
            super(feedUrl);
    }

    /**
     * Parses a url pointing to a Google JSON object to a Route object.
     * @return a Route object based on the JSON object.
     */

    public Route parse() {
            // turn the stream into a string
            final String result = convertStreamToString(this.getInputStream());
            //Create an empty route
            final Route route = new Route();
            //Create an empty segment
            final Segment segment = new Segment();
            try {
                    //Tranform the string into a json object
                    final JSONObject json = new JSONObject(result);
                    //Get the route object
                    final JSONObject jsonRoute = json.getJSONArray("routes").getJSONObject(0);
                    //Get the leg, only one leg as we don't support waypoints
                    final JSONObject leg = jsonRoute.getJSONArray("legs").getJSONObject(0);
                    //Get the steps for this leg
                    final JSONArray steps = leg.getJSONArray("steps");
                    //Number of steps for use in for loop
                    final int numSteps = steps.length();
                    //Set the name of this route using the start & end addresses
                    route.setName(leg.getString("start_address") + " to " + leg.getString("end_address"));
                    //Get google's copyright notice (tos requirement)
                    route.setCopyright(jsonRoute.getString("copyrights"));
                    //Get the total length of the route.
                    route.setLength(leg.getJSONObject("distance").getInt("value"));
                    //Get any warnings provided (tos requirement)
                    if (!jsonRoute.getJSONArray("warnings").isNull(0)) {
                            route.setWarning(jsonRoute.getJSONArray("warnings").getString(0));
                    }
                    /* Loop through the steps, creating a segment for each one and
                     * decoding any polylines found as we go to add to the route object's
                     * map array. Using an explicit for loop because it is faster!
                     */
                    for (int i = 0; i < numSteps; i++) {
                            //Get the individual step
                            final JSONObject step = steps.getJSONObject(i);
                            //Get the start position for this step and set it on the segment
                            final JSONObject start = step.getJSONObject("start_location");
                            final GeoPoint position = new GeoPoint((int) (start.getDouble("lat")*1E6),
                                    (int) (start.getDouble("lng")*1E6));
                            segment.setPoint(position);
                            //Set the length of this segment in metres
                            final int length = step.getJSONObject("distance").getInt("value");
                            distance += length;
                            segment.setLength(length);
                            segment.setDistance(distance/1000);
                            //Strip html from google directions and set as turn instruction
                            segment.setInstruction(step.getString("html_instructions").replaceAll("<(.*?)*>", ""));
                            //Retrieve & decode this segment's polyline and add it to the route.
                            route.addPoints(decodePolyLine(step.getJSONObject("polyline").getString("points")));
                            //Push a copy of the segment to the route
                            route.addSegment(segment.copy());
                    }
            } catch (JSONException e) {

                    Logger.appendLog( "Google JSON Parser - " + feedUrl);
            }
            return route;
    }

    /**
     * Convert an inputstream to a string.
     * @param input inputstream to convert.
     * @return a String of the inputstream.
     */

    private static String convertStreamToString(final InputStream input) {
    final BufferedReader reader = new BufferedReader(new InputStreamReader(input));
    final StringBuilder sBuf = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sBuf.append(line);
        }
    } catch (IOException e) {
            Logger.appendLog( "Google parser, stream2string");
    } finally {
        try {
            input.close();
        } catch (IOException e) {
            Logger.appendLog( "Google parser, stream2string");
        }
    }
    return sBuf.toString();
}

    /**
     * Decode a polyline string into a list of GeoPoints.
     * @param poly polyline encoded string to decode.
     * @return the list of GeoPoints represented by this polystring.
     */

    private List<GeoPoint> decodePolyLine(final String poly) {
            int len = poly.length();
            int index = 0;
            List<GeoPoint> decoded = new ArrayList<GeoPoint>();
            int lat = 0;
            int lng = 0;

            while (index < len) {
            int b;
            int shift = 0;
            int result = 0;
            do {
                    b = poly.charAt(index++) - 63;
                    result |= (b & 0x1f) << shift;
                    shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                    b = poly.charAt(index++) - 63;
                    result |= (b & 0x1f) << shift;
                    shift += 5;
            } while (b >= 0x20);
                    int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
                    lng += dlng;

            decoded.add(new GeoPoint(
                    (int) (lat*1E6 / 1E5), (int) (lng*1E6 / 1E5)));
            }

            return decoded;
            }
}

Parser.java
public interface Parser {
    public Route parse();
}

Route.java
import java.util.ArrayList;
import java.util.List;

import com.google.android.maps.GeoPoint;

public class Route {
    private String name;
    private final List<GeoPoint> points;
    private List<Segment> segments;
    private String copyright;
    private String warning;
    private String country;
    private int length;
    private String polyline;

    public Route() {
            points = new ArrayList<GeoPoint>();
            segments = new ArrayList<Segment>();
    }

    public void addPoint(final GeoPoint p) {
            points.add(p);
    }

    public void addPoints(final List<GeoPoint> points) {
            this.points.addAll(points);
    }

    public List<GeoPoint> getPoints() {
            return points;
    }

    public void addSegment(final Segment s) {
            segments.add(s);
    }

    public List<Segment> getSegments() {
            return segments;
    }

    /**
     * @param name the name to set
     */
    public void setName(final String name) {
            this.name = name;
    }

    /**
     * @return the name
     */
    public String getName() {
            return name;
    }

    /**
     * @param copyright the copyright to set
     */
    public void setCopyright(String copyright) {
            this.copyright = copyright;
    }

    /**
     * @return the copyright
     */
    public String getCopyright() {
            return copyright;
    }

    /**
     * @param warning the warning to set
     */
    public void setWarning(String warning) {
            this.warning = warning;
    }

    /**
     * @return the warning
     */
    public String getWarning() {
            return warning;
    }

    /**
     * @param country the country to set
     */
    public void setCountry(String country) {
            this.country = country;
    }

    /**
     * @return the country
     */
    public String getCountry() {
            return country;
    }

    /**
     * @param length the length to set
     */
    public void setLength(int length) {
            this.length = length;
    }

    /**
     * @return the length
     */
    public int getLength() {
            return length;
    }

    /**
     * @param polyline the polyline to set
     */
    public void setPolyline(String polyline) {
            this.polyline = polyline;
    }

    /**
     * @return the polyline
     */
    public String getPolyline() {
            return polyline;
    }

}

RouteOverlay.java

public class RouteOverlay extends Overlay {
/** GeoPoints representing this routePoints. **/
private final List<GeoPoint> routePoints;
/** Colour to paint routePoints. **/
private int colour;
/** Alpha setting for route overlay. **/
private static final int ALPHA = 200;
/** Stroke width. **/
private static final float STROKE = 4.5f;
/** Route path. **/
private final Path path;
/** Point to draw with. **/
private final Point p;
/** Paint for path. **/
private final Paint paint;

/**
 * Public constructor.
 *
 * @param route Route object representing the route.
 * @param defaultColour default colour to draw route in.
 */

public RouteOverlay(final Route route, final int defaultColour) {
        super();
        routePoints = route.getPoints();
        colour = defaultColour;
        path = new Path();
        p = new Point();
        paint = new Paint();
}

@Override
public final void draw(final Canvas c, final MapView mv,
                final boolean shadow) {
        super.draw(c, mv, shadow);

        paint.setColor(colour);
        paint.setAlpha(ALPHA);
        paint.setAntiAlias(true);
        paint.setStrokeWidth(STROKE);
        paint.setStyle(Paint.Style.STROKE);

        redrawPath(mv);
        c.drawPath(path, paint);
}

/**
 * Set the colour to draw this route's overlay with.
 *
 * @param c  Int representing colour.
 */
public final void setColour(final int c) {
        colour = c;
}

/**
 * Clear the route overlay.
 */
public final void clear() {
        routePoints.clear();
}

/**
 * Recalculate the path accounting for changes to
 * the projection and routePoints.
 * @param mv MapView the path is drawn to.
 */

private void redrawPath(final MapView mv) {
        final Projection prj = mv.getProjection();
        path.rewind();
        final Iterator<GeoPoint> it = routePoints.iterator();
        prj.toPixels(it.next(), p);
        path.moveTo(p.x, p.y);
        while (it.hasNext()) {
                prj.toPixels(it.next(), p);
                path.lineTo(p.x, p.y);
        }
        path.setLastPoint(p.x, p.y);
}

}
Segment.java
    import com.google.android.maps.GeoPoint;

public class Segment {
    /** Points in this segment. **/
    private GeoPoint start;
    /** Turn instruction to reach next segment. **/
    private String instruction;
    /** Length of segment. **/
    private int length;
    /** Distance covered. **/
    private double distance;

    /**
     * Create an empty segment.
     */

    public Segment() {
    }

    /**
     * Set the turn instruction.
     * @param turn Turn instruction string.
     */

    public void setInstruction(final String turn) {
            this.instruction = turn;
    }

    /**
     * Get the turn instruction to reach next segment.
     * @return a String of the turn instruction.
     */

    public String getInstruction() {
            return instruction;
    }

    /**
     * Add a point to this segment.
     * @param point GeoPoint to add.
     */

    public void setPoint(final GeoPoint point) {
            start = point;
    }

    /** Get the starting point of this
     * segment.
     * @return a GeoPoint
     */

    public GeoPoint startPoint() {
            return start;
    }

    /** Creates a segment which is a copy of this one.
     * @return a Segment that is a copy of this one.
     */

    public Segment copy() {
            final Segment copy = new Segment();
            copy.start = start;
            copy.instruction = instruction;
            copy.length = length;
            copy.distance = distance;
            return copy;
    }

    /**
     * @param length the length to set
     */
    public void setLength(final int length) {
            this.length = length;
    }

    /**
     * @return the length
     */
    public int getLength() {
            return length;
    }

    /**
     * @param distance the distance to set
     */
    public void setDistance(double distance) {
            this.distance = distance;
    }

    /**
     * @return the distance
     */
    public double getDistance() {
            return distance;
    }

}

XMLParser.java
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import com.monumentos.log.Logger;

public class XMLParser {
    // names of the XML tags
    protected static final String MARKERS = "markers";
    protected static final String MARKER = "marker";

    protected URL feedUrl;

    protected XMLParser(final String feedUrl) {
            try {
                    this.feedUrl = new URL(feedUrl);
            } catch (MalformedURLException e) {
                Logger.appendLog( "XML parser - " + feedUrl);
            }
    }

    protected InputStream getInputStream() {
            try {
                    return feedUrl.openConnection().getInputStream();
            } catch (IOException e) {
                Logger.appendLog(  "XML parser - " + feedUrl);
                    return null;
            }
    }
}

Hope it will helps you.
Calling api example:
        Parser parser;

        String jsonURL = "http://maps.googleapis.com/maps/api/directions/json?";
        final StringBuffer sBuf = new StringBuffer(jsonURL);
        sBuf.append("origin=");
        sBuf.append( points.get(0).getLatitudeE6()/1E6);
        sBuf.append(',');
        sBuf.append(points.get(0).getLongitudeE6()/1E6);
        sBuf.append("&destination=");
        sBuf.append(points.get(points.size()-1).getLatitudeE6()/1E6);
        sBuf.append(',');
        sBuf.append(points.get(points.size()-1).getLongitudeE6()/1E6);

        sBuf.append("&sensor=true&mode="+routeMode);

        Logger.appendLog(sBuf.toString());

        parser = new GoogleParser(sBuf.toString());

        Route r =  parser.parse();

A: You can parsing them using google http java client. Try this example


text:
Q: How do I access the sound device with modern libraries? It used to be that if you wanted to test your sound you could simply cat any file to /dev/snd, but that doesn't appear to work on any of the systems (Debian/Ubuntu/Mint, Arch) that I've tried.
From what I've read, this can be any kind of file - text, pdf, whatever. And if it's a .wav file then it will actually play music.
So how can you do the same thing on modern systems (e.g. ones using pulse audio & other drivers)

A: From my testing, aplay works:
aplay <filename>

When I did
aplay test.html   # a simple html file

I got hissy static.
aplay something.wav

Played the music in the wav file. And in a bizarre twist, a file containing this:
Fri Jan 13 08:20:01 CST 2012
Fri Jan 13 08:21:01 CST 2012
Fri Jan 13 08:22:01 CST 2012
Fri Jan 13 08:23:01 CST 2012
Fri Jan 13 08:24:01 CST 2012
Fri Jan 13 08:25:01 CST 2012
Fri Jan 13 08:26:01 CST 2012
Fri Jan 13 08:27:01 CST 2012
Fri Jan 13 08:28:01 CST 2012
Fri Jan 13 08:29:01 CST 2012
Fri Jan 13 08:30:01 CST 2012
Fri Jan 13 08:31:01 CST 2012
Fri Jan 13 08:32:01 CST 2012
Fri Jan 13 08:33:01 CST 2012

Makes a gentle "beep"

A: If your goal is specifically to pipe arbitrary data from a file to your sound card then your solution is solid.
If your goal is simply to test that your sound works then I would recommend the command speaker-test. It plays static over a single channel by default. On Debian based systems it comes from the alsa-utils package.


text:
Q: Implementing IErrorHandler in a WCF Service Application or a WCF Service Library When implementing the IErrorHandler interfaces and adding it to the dispatcher in a WCF Service Application I'm experiencing some strange behavior.
Only the HandleError method is fired, not the ProvideFault method.
When using the same code and configuration in a WCF Service Library both methods are fired upon an Exception in the code.
Example:
public class ErrorHandler : IErrorHandler, IServiceBehavior
{
    public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
    {
        // Provide the fault
    }

    public bool HandleError(Exception error)
    {
        // If handled return true, otherwise false
    }

    // Validate
    // AddBindingParameters
    // ApplyDispatchBehavior
}

public class ErrorHandlerBehavior : BehaviorExtensionElement
{
    public override Type BehaviorType
    {
        get { return typeof(ErrorHandler); }
    }

    protected override object CreateBehavior()
    {
        return new ErrorHandler();
    }
}

And in the Web.config:
    <extensions>
      <behaviorExtensions>
        <add name="ErrorLogging" type="Service.ErrorHandlerBehavior, Service, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
      </behaviorExtensions>
    </extensions>
...
      <serviceBehaviors>
        <behavior>
          <ErrorLogging />
        </behavior>
      </serviceBehaviors>

The code and configuration is the same (although the configuration is in Web.config in the Service Application and i App.config in the Service Library).
By inserting breakpoints in the ProvideFault and HandleError I can see that ProvideFault is only invoked for the Service Library - how can this be? Am I missing something?
EDIT
It seems that ProvideFault is not invoked when the signature of the service operation being called is has a return type other then a primitive type, eg:
public IEnumerable<MyType> GetMyType(string s1)
{
    throw new Exception("Testing...");
}

...will not trigger the ProvideFault.
But:
public bool DoStuff(string s1, string s2)
{
    throw new Exception("Testing...");
}

...does trigger the ProvideFault.

A: NicklasJepsen, you were close to the right answer.
I've just had the same problem with IEnumerable, but managed to solve it, not changing the return type.
In my case the problem reason was that the method was using the yield return statement. As you probably know, the method that returns IEnumerable and uses yield return to return the elements, is compiled into a "state machine". In fact it returns the IEnumerable instance, which returns the iterator, which methods implement that state machine. This great feature lies in the core of LINQ, and it allows deferred execution - the state machine works only when you need another element.
In case of WCF, I guess I know what happens.
WCF acts kinda like this:

*

*It calls the method.

*If the method fails, WCF passes the exception to your ErrorHandler methods (both of them).

*If the method succeeds, WCF prepares the response. It serializes the object returned by the method in accordance with the response format.

*If serialization fails (what is less expected than the method failure), WCF passes the exception to your ErrorHandler, but only to method HandleError. For some reason ProvideFault is not called at this stage.

*If serialization succeeds, the serialized object is sent to the client.
Now consider these 2 examples:
public bool DoStuff();
public IEnumerable<bool> DoALotOfStuff();

DoStuff certainly fails at step 2. But DoALotOfStuff does not! Remember, it's a state machine, which execution is deferred till the moment you query the first element. So, the method does not fail, it only returns the IEnumerable instance, which is ready to give you the enumerator once you need the elements.
Consequently, WCF is happy with what is returned by the method, so it proceeds to serialization. And that's where it gets your insidious exception!
Now, the solution is quite simple - just do not defer execution. Return a "real" enumerable instance like List instead of the "state machine".
public IEnumerable<bool> DoALotOfStuff()
{
    return _DoALotOfStuff().ToList();
}

protected IEnumerable<bool> _DoALotOfStuff()
{
    yield return true;
    yield return false;
    throw new Exception( "Testing..." );
}

Now if the method fails, it fails in the right place, so you have your ProvideFault called.


text:
Q: not able to fetch data from subscribed topic from test.mosquitto.org here is my lua script ,running on esp8266 with nodemcu firmware,I am keeping a function check_wifi() to check that my esp module is connected ,then I am publishing topic "on" , and setting two event handler for "connect" and for "message",but my handler for
  function check_wifi()
     local ip = wifi.sta.getip()
     if(ip==nil) then
       print("Connecting...")
     else
      tmr.stop(0)
      print("Connected to AP!")
      print(ip)

      m:connect("test.mosquitto.org", 1883, 0, function(conn) print("connected") end)
      m:publish("on","1",0,0,0)
      m:on("connect",function(m)

        m:subscribe("on",0,function(m) print(m);print("subcribed") end)

        end )
       m:on("message", function(conn, topic, data)
    print("in on")
      print(topic .. ":" )
      if data ~= nil then
        print(data)
      end
    end)
    end
    end

    local SSID = "Crystalrock2"
    local SSID_PASSWORD = "nest2abc123"

    gpio.mode(4,gpio.OUTPUT)
    gpio.write(4,gpio.LOW)

    -- configure ESP as a station
    wifi.setmode(wifi.STATION)
    wifi.sta.config(SSID,SSID_PASSWORD)
    wifi.sta.connect()

    m = mqtt.Client("dee15", 120, "test", "password")

    m:on("message", function(conn, topic, data)
    print("in on")
      print(topic .. ":" )
      if data ~= nil then
        print(data)
      end
    end)

    m:on("connect",function(m)

        m:subscribe("on",0,function(m) print(m);print("subcribed") end)

        end )
    m:connect("test.mosquitto.org", 1883, 0, function(conn) print("connected") end)

    tmr.alarm(0,2000,1,check_wifi)

here what I am getting:
output:Connecting...
Connecting...
Connected to AP!
192.168.0.100
userdata: 3fff8678
subcribed
why m:on("message" ..)is not triggering and printing message received


text:
Q: Query Works in phpmyadmin but not on the page I have tried all kinds of things and spent hours doing this and would really like it if someone can tell me what I'm doing.
This is my SQL query:
SELECT * FROM txp_file WHERE filename LIKE '%Fast®%' OR description LIKE '%Fast®%'
In phpmyadmin, this brings back the results I want. On the page, the query apparently works but gets no result. I have tried to use substring to omit the special trademark symbol, I have tried a million different variations but I get no result. Here is my php code:
$sql = "SELECT * FROM txp_file WHERE filename LIKE '%$querytitle%' OR description LIKE '%$querytitle%'";
$query = mysql_query($sql) or die(mysql_error());
$result = mysql_fetch_array($query);
if ($result){
    echo "$querytitle";
}
else
    echo 'nil';

The connection to the database is already there so I don't need to do it again in this case. Can anyone find anything wrong with this code?
P.S. $querytitle is a global variable. I have echoed it and it comes up just the way it should.

A: You probably haven't set the character set for the connection. Use the command:
SET NAMES utf8;

or whatever character set you are using. To find the default character set of the database and the connection you can execute this command:
USE yourdb;
SHOW VARIABLES LIKE "%coll%";

It will show you a list of collations for the server, the database and the connection.


text:
Q: Twenty Ten Theme: Replace the Logo by a picture without moving the code I would like to replace the twenty ten's theme logo (text) by a picture, Is there any plugin allowing me to do that.
I know how to do it, but every time wordpress gets updated (often) the code comes back to how it was before I changed it.
Thanks in advance.

A: Your best bet is to make a child theme and simply add in the twentyten header.php with a link to your image.
How to make child theme, http://codex.wordpress.org/Child_Themes
It would be something like this ( under the branding div.)

<img src="<?php bloginfo( 'template_url' ); ?>/images/YourImage.png" alt=""/>


text:
Q: How to get if statement in php to work if there´re more conditions inside if I have 2 variable sent from ajax to php user and email
if ($key=="user"){
    //and sql will check if user name is exist or not

    if($stmt->rowCount() >0); //if user is exist
   echo"user is already exist";

    if(!preg_match('/^[0-9A-Za-z!@#$%][0-9A-Za-z!@#$% ]+[0-9A-Za-z!@#$%]$/',$user));

    echo"bad user name";

}

How to get it work ? I might have more if statement inside the big if (maybe)

A: Use curly braces and add more conditions like so:
if ($key=="user")
{
    //and sql will check if user name is exist or not
    if($stmt->rowCount() >0)
    {
    //if user is exist
    echo"user is already exist";

        if(!preg_match('/^[0-9A-Za-z!@#$%][0-9A-Za-z!@#$% ]+[0-9A-Za-z!@#$%]$/',$user))
        {
        echo"bad user name";
        }

        if(condition2)
        {
        //code
        }

        if(condition3)
        {
        //code
        }
    }
}

Also, you don't need a semicolon at the end of an if statement. Refer to the PHP manual for more information.


text:
Q: OnActivityResult Doesn't work with activityGroup im my App i use TabHost. and ActivityGroup to load activities under the tab. on my 2nd tab i open activityGroup "TabGroupActivity"... and from here i open a child activity "childActivity2". from the "childActivity2" i want to open an normal activity which has a theme dialog. and when i return from my normal activity i want to run the onActivityResult() in my childActivity2.
But the onActivityResult() in ChildActivity2 is not working.
the code where in childActivity2 to start the normal activity is
data.putInt("doctorId", doctor_id);
                Intent createSchedule = new Intent(ScheduleWeekly.this, CreateSchedule.class).putExtras(data);

                startActivityForResult(createSchedule, 1);

this is my onActivityResult()
 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode==Activity.RESULT_OK)
        {   Log.e("get","result");
            .................
                         ......
        }

    }

A: Your problem is same as mine. The problem is that the onActivityResult function won't directly trigger from a child activity in activity group, even your intent is from that child activity.
The solution is divided in three steps.
First, you have to let your parent activity, that is your ActiviyGroup class to call the startActivityForResult function in the position you need to jump out the current activity. In your child activity, when you need to lunch your normal activity, instead call:
startActivityForResult(intent, 0);

You should call:
getParent().startActivityForResult(intent,0);

This will let the ActivityGroup to take care of the call back. In your case, since your have three level nested, you may have to try whether the parent or grandparent should take care of the call back and make proper modification about getParent() part.
Second, after you make the parent class of current activity start the intent, you will need to add onAcivityResult() function into BOTH parent class and the current child class. In current class you just write normal call back handle message as you do now. But in parent class, the onActivityResult() function will catch the call back from the normal activity and deliver the intent to the current class.
Third, This step is for the parent onActivityResult class, in that class, your need:
public void onActivityResult(int requestCode, int resultcode, Intent data)
{
    super.onActivityResult(requestCode, resultcode, data);
    switch (resultcode)
    {
    case RESULT_OK:
         MyChildActivity CA = (MyChildActivity) getLocalActivityManager().getCurrentActivity();
         CA.onActivityResult(requestCode, resultcode, data);
    }
}

As you can see, the onActivityResult function in parent ActivityGroup class is just catch the call back, get the child activity you which needs to jump to another activity, and transfer the data to it. You may not need exactly onActivityResult function in your child activity as state in Step 2, but I think this is a better way to do it.
Hope this help!


text:
Q: Does a Windows service have to be its own exe? In short, what I'm trying to do is include Windows Services that run when ASP.NET MVC application starts and which are defined inside that MVC solution.
I have a class
public class PageRetriever : ServiceBase
{
    // ...
}

that I defined in
MyMvcProject/Services/PageRetriever.cs

and I have try to start the service in my app start like
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        ServiceBase.Run(new PageRetriever());
    }

but when I build-and-run I get the error

Why's that, and what should I be doing instead?


text:
Q: After Updating Dart in VS code its showing "Configuration 'Flutter (Pixel_3a_API_33_x86_64)' is missing in 'launch.json'." When i opened VS code and it said "Try to Update to newest Version of Dart 3. something. but after that, i can't run my Android Studio emulator in VS code it gives me error,

i try to Run>add Configuration in launchJson, its didn't work for my Android Studio Emulator, It just Work for my Default Chrome Emulator in VS code.
What should i do ? I want My Android Studio Emulator Back.


text:
Q: Mostrar un formulario y JTable en un JInternalFrame estoy intentando agregar un Formulario (3 JTextFiel y 2 JButtons) y 1 JTable en el mismo JInternalFrame.. Sin embargo solo puedo mostrar el Formulario o la Tabla (incompleta).
He intentado agregarla con 2 Panels, uno para el formulario y otro para la tabla, el resultado es el siguiente:
String[] columnStudents = {
      "Nombre", "Curso", "Calificacion",
    };
    Object[][] dataStudents = {
      {"Juanito", "Español", "6"},
      {"Pepito", "Ciecias", "7"},
      {"Albterto", "Historia", "8"},
    };
    JTable tableStudent = new JTable(dataStudents, columnStudents);
    printDataStudent(tableStudent);

    JScrollPane scrollPane_student = new JScrollPane();
    JInternalFrame_student.add(scrollPane_student, BorderLayout.NORTH);

    JPanel JPanel_student = new JPanel();
    JPanel_student.add(labelName);
    JPanel_student.add(textfieldName);
    JPanel_student.add(labelCourse);
    JPanel_student.add(textfieldCourse);
    JPanel_student.add(labelScore);
    JPanel_student.add(textfieldScore);
    JPanel_student.add(btnAddStudent);
    JPanel_student.add(btnDeleteStudent);

    JPanel JPanel_tableStudent = new JPanel();
    JPanel_tableStudent.add(tableStudent, BorderLayout.CENTER);

    JInternalFrame_student.add(JPanel_student);
    JInternalFrame_student.add(JPanel_tableStudent);

Y esto es lo que me muestra:

Después, intente usar el mismo scrollPane para agregar ahi la tabla sin embargo, obtengo este resultado:
Codigo
JTable tableStudent = new JTable(dataStudents, columnStudents);
    tableStudent.setPreferredScrollableViewportSize(new Dimension(500,70));
    tableStudent.setFillsViewportHeight(true);
    printDataStudent(tableStudent);
    JScrollPane scrollPane_student = new JScrollPane(tableStudent);

    JInternalFrame_student.add(scrollPane_student, BorderLayout.CENTER);

    JPanel JPanel_student = new JPanel();
    JPanel_student.add(labelName);
    JPanel_student.add(textfieldName);
    JPanel_student.add(labelCourse);
    JPanel_student.add(textfieldCourse);
    JPanel_student.add(labelScore);
    JPanel_student.add(textfieldScore);
    JPanel_student.add(btnAddStudent);
    JPanel_student.add(btnDeleteStudent);

    JInternalFrame_student.add(JPanel_student);

¿Alguna idea de porque no puede mostrarse ambos en el InternalFrame?

A: BorderLayout tiene 5 áreas, y cada área no puede tener mas de un componente.  Cuando usas el método add() sin restricciones (segundo argumento) el componente (primer argumento) se irá al área central, la cual tenderá a ocupar el máximo espacio posible ya que es donde va el componente preponderante.
De tal manera que cuando haces el segundo add a JInternalFrame_student estas sustituyendo el componente existente, y ocupa todo el espacio.
Prueba lo siguiente:
    JTable tableStudent = new JTable(dataStudents, columnStudents);
    printDataStudent(tableStudent);

    JScrollPane scrollPane_student = new JScrollPane(tableStudent);

    JPanel JPanel_student = new JPanel();
    ...

    JInternalFrame_student.add(scrollPane_student, BorderLayout.CENTER);
    JInternalFrame_student.add(JPanel_student, BorderLayout.PAGE_END);


text:
Q: What's the cheapest way to get a Visual Studio 2008 Standard Edition license? I know I can purchase it for $299.00, but my primary reason for upgrading from the Express version is I want to be able to use ReSharper, which is an additional expense. Are there any ways I can get a VS copy for less than off-the-shelf price? Any special programs I can join, or is there a special "developer" version :) (kind of redundant, I know)

A: The Microsoft currently has time limited action where it is possible to buy the Visual Studio 2008 (both Standard and Pro) at upgrade price ($199 for standard) even when upgrading from the Express editions or even free tools such as Eclipse. See the section "Before you buy" on this page. However it is possible that this is limited to some regions.

A: You can get all the MS dev tools and lots of other goodies for about that much if you join their empower program or free with bizspark

A: https://downloads.channel8.msdn.com/ - Free MS Dev stuff for students.

A: Is there a .NET User Group in your community? If so, contact them. Often they can get things at a discount. MS User Group Support Services provides plenty of freebies for user groups, perhaps they have a copy you can have.

A: No idea if you qualify, but if you're a student, I believe you can get it for free.  If you're not, get your company to pony up :)
Edit: Here's the DreamSpark site, for students.

A: Just something out of left field here...Why not also look at SharpDevelop, it's surprisingly good, it's free and you have access to the source code for it. I'm not sure if ReSharper supports it, probably not, but there is already some good refactoring stuff in there, plus of course you can extend it yourself. IMO its worth a look at least.
http://www.icsharpcode.net/OpenSource/SD/Features.aspx

A: My university had an MSDNAA subscription for CompSci majors which gave me student licenses to practically every Microsoft product on the market... but it wasn't really advertised. I'm not sure how you'd go about finding if your school does the same.

A: Got to any one of the dozens Microsoft conferences held all the time. The fumble over themselves to give you free copies of stuff - including Visual Studio.


text:
Q: How to use Button as a control in Manipulate I am trying to use Button as a controller in Manipulate.
I have done some thing like this:
Manipulate[
  p = Column[{Plot[Sin[x - n], {x, 0, 12.4}, ImageSize -> 500]}],
  {n, 0, 1},
  Button["Export", Export["test.jpg", p]]]

Is there any better way to do this?
I am thinking of making something like this:
Manipulate[
  Column[{p = Plot[Sin[x - n], {x, 0, 12.4}, ImageSize -> 500],
  If[x, Export["test.jpg", p]]}],
  {n, 0, 1},
  {x, {False, True}}]

in which the controller x is represented by Button instead of a Checkbox.
How can I do that?

A: Personally, I would stay with your first example, but if you insist on a more loose coupling between the button and the Export expression, maybe something like the following:
filePath = FileNameJoin[{HomeDirectory[], "DeskTop", "test.jpg"}];
Manipulate[
  p = Plot[Sin[x - n], {x, 0, 4 Pi}, ImageSize -> 300];
  If[export, Export[filePath, p]; export = False];
  p,
  {n, 0, 2 Pi, Appearance -> "Labeled"},
  {{export, False}, None},
  Button["Export", export = True]]


text:
Q: NGINX + PHP7 + FastCGI Not Executing PHP Files and Downloading PHP file to client The title says it all... follows are my config files.
There have to be many others looking for an updated solution to the FastCGI configuration woes.
Merci!
I enabled log_level debug for php-fpm and follows is the output.
[29-Mar-2017 09:29:45.978844] DEBUG: pid 18992, fpm_pctl_perform_idle_server_maintenance(), line 379: [pool www] currently 0 active children, 2 spare children, 2 running children. Spawning rate 1
[29-Mar-2017 09:29:46.979937] DEBUG: pid 18992, fpm_pctl_perform_idle_server_maintenance(), line 379: [pool www] currently 0 active children, 2 spare children, 2 running children. Spawning rate 1
[29-Mar-2017 09:29:47.981031] DEBUG: pid 18992, fpm_pctl_perform_idle_server_maintenance(), line 379: [pool www] currently 0 active children, 2 spare children, 2 running children. Spawning rate 1
[29-Mar-2017 09:29:48.443352] DEBUG: pid 18992, fpm_got_signal(), line 85: received SIGTERM
[29-Mar-2017 09:29:48.443381] NOTICE: pid 18992, fpm_got_signal(), line 86: Terminating ...
[29-Mar-2017 09:29:48.443404] DEBUG: pid 18992, fpm_pctl(), line 231: switching to 'terminating' state
[29-Mar-2017 09:29:48.443414] DEBUG: pid 18992, fpm_pctl_kill_all(), line 159: [pool www] sending signal 15 SIGTERM to child 18994
[29-Mar-2017 09:29:48.443421] DEBUG: pid 18992, fpm_pctl_kill_all(), line 159: [pool www] sending signal 15 SIGTERM to child 18993
[29-Mar-2017 09:29:48.443425] DEBUG: pid 18992, fpm_pctl_kill_all(), line 168: 2 child(ren) still alive
[29-Mar-2017 09:29:48.443433] DEBUG: pid 18992, fpm_event_loop(), line 419: event module triggered 1 events
[29-Mar-2017 09:29:48.443440] DEBUG: pid 18992, fpm_pctl_kill_all(), line 159: [pool www] sending signal 9 SIGKILL to child 18994
[29-Mar-2017 09:29:48.443445] DEBUG: pid 18992, fpm_pctl_kill_all(), line 159: [pool www] sending signal 9 SIGKILL to child 18993
[29-Mar-2017 09:29:48.443450] DEBUG: pid 18992, fpm_pctl_kill_all(), line 168: 2 child(ren) still alive
[29-Mar-2017 09:29:48.444010] DEBUG: pid 18992, fpm_got_signal(), line 76: received SIGCHLD
[29-Mar-2017 09:29:48.444034] DEBUG: pid 18992, fpm_children_bury(), line 252: [pool www] child 18993 exited on signal 15 (SIGTERM) after 198.667599 seconds from start
[29-Mar-2017 09:29:48.444051] DEBUG: pid 18992, fpm_children_bury(), line 252: [pool www] child 18994 exited on signal 15 (SIGTERM) after 198.667194 seconds from start
[29-Mar-2017 09:29:48.444058] NOTICE: pid 18992, fpm_pctl_exit(), line 70: exiting, bye-bye!
[29-Mar-2017 09:29:48.501376] DEBUG: pid 19048, fpm_scoreboard_init_main(), line 40: got clock tick '100'
[29-Mar-2017 09:29:48.501543] DEBUG: pid 19048, fpm_event_init_main(), line 337: event module is epoll and 1 fds have been reserved
[29-Mar-2017 09:29:48.501597] NOTICE: pid 19048, fpm_init(), line 85: fpm is running, pid 19048
[29-Mar-2017 09:29:48.502089] DEBUG: pid 19048, fpm_children_make(), line 421: [pool www] child 19049 started
[29-Mar-2017 09:29:48.502530] DEBUG: pid 19048, fpm_children_make(), line 421: [pool www] child 19050 started
[29-Mar-2017 09:29:48.502556] DEBUG: pid 19048, fpm_event_loop(), line 366: 6000 bytes have been reserved in SHM
[29-Mar-2017 09:29:48.502562] NOTICE: pid 19048, fpm_event_loop(), line 367: ready to handle connections
[29-Mar-2017 09:29:48.502614] DEBUG: pid 19048, fpm_systemd_heartbeat(), line 68: have notify start to systemd
[29-Mar-2017 09:29:48.502631] NOTICE: pid 19048, fpm_systemd_heartbeat(), line 75: systemd monitor interval set to 10000ms
[29-Mar-2017 09:29:49.503709] DEBUG: pid 19048, fpm_pctl_perform_idle_server_maintenance(), line 379: [pool www] currently 0 active children, 2 spare children, 2 running children. Spawning rate 1
[29-Mar-2017 09:29:50.504808] DEBUG: pid 19048, fpm_pctl_perform_idle_server_maintenance(), line 379: [pool www] currently 0 active children, 2 spare children, 2 running children. Spawning rate 1
[29-Mar-2017 09:29:51.505900] DEBUG: pid 19048, fpm_pctl_perform_idle_server_maintenance(), line 379: [pool www] currently 0 active children, 2 spare children, 2 running children. Spawning rate 1
[29-Mar-2017 09:29:52.506994] DEBUG: pid 19048, fpm_pctl_perform_idle_server_maintenance(), line 379: [pool www] currently 0 active children, 2 spare children, 2 running children. Spawning rate 1
[29-Mar-2017 09:29:53.508089] DEBUG: pid 19048, fpm_pctl_perform_idle_server_maintenance(), line 379: [pool www] currently 0 active children, 2 spare children, 2 running children. Spawning rate 1
[29-Mar-2017 09:29:54.509183] DEBUG: pid 19048, fpm_pctl_perform_idle_server_maintenance(), line 379: [pool www] currently 0 active children, 2 spare children, 2 running children. Spawning rate 1

curl -i http://ipaddress
HTTP/1.1 200 OK
Server: nginx/1.10.2
Date: Tue, 28 Mar 2017 21:18:20 GMT
Content-Type: application/octet-stream
Content-Length: 1780
Last-Modified: Thu, 15 Dec 2016 15:20:08 GMT
Connection: keep-alive
ETag: "5852b4a8-6f4"
Accept-Ranges: bytes

nginx/php-fpm generated no errors in logs
nginx access log generated the following.
192.88.135.5 - - [28/Mar/2017:13:18:38 -0400] "GET / HTTP/1.1" 200 1780 "-""Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36 OPR/43.0.2442.1144"

The files that show in the .sock path are:
-rw-r--r--. 1 root  root  5 Mar 28 18:45 php-fpm.pid
srw-rw-rw-. 1 nginx nginx 0 Mar 28 18:45 website.com.sock

nginx version: nginx/1.10.2
PHP 7.0.16 (fpm-fcgi) (built: Feb 18 2017 10:26:54)
nginx.conf
user  nginx nginx;
worker_processes  4;

error_log  /var/log/nginx/error.log;
error_log  /var/log/nginx/error.log  notice;
error_log  /var/log/nginx/error.log  info;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
     keepalive_timeout  65;

    upstream php {
    server unix:/var/run/php-fpm/website.com.sock;
    }

    server {
    include /etc/nginx/conf.d/default.conf;
    include /etc/nginx/sites-available/*.conf;
    }
}

default.conf
include /etc/nginx/security;
#expires max;

#Uploads configuration
client_max_body_size 32m;

site-available/site.conf
listen [::]:80;
server_name *.website.com;
root /some/directory/website/;

access_log  /var/log/nginx/www.access.log;
error_log  /var/log/nginx/www.error.log notice;

#fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;

#Index targets
index index.php index.html index.htm;

location / {

    # redirect admin/auth
    #rewrite ^/(admin|auth)(.*) https://$host$request_uri?;

    # try_files $uri =404;
    # #fastcgi_split_path_info ^(.+\.php)(/.+)$;
    try_files $uri $uri/ /index.php$is_args$args;

}

# if the file being requested ends in ".php", it's something
#    that PHP-FPM should process, so hand it to upstream server

location ~ \.php$ {
    fastcgi_pass php;
}

php-fpm/www.conf
; Start a new pool named 'www'.
[www]

ping./var/run/php-fpm/website.com.sock = /ping
listen = /var/run/php-fpm/website.com.sock;
pm = dynamic
pm.status_/var/run/php-fpm/website.com.sock = /status

user = nginx
group = nginx

listen.owner = nginx
listen.group = nginx
listen.mode = 0666

pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3

fastcgi.conf
fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

#  To use NGINX + Virtual Host + PHP you should ommit the SCRIPT_NAME     variable in order for
#   PHP to choose the correct DOCUMENT_ROOT.
#fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
#

fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  REQUEST_SCHEME     $scheme;
fastcgi_param  HTTPS              $https if_not_empty;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

A: Your PHP socket has permissions of root:root and 644. Nginx is running as nginx. It's likely that PHP can't access the socket to run PHP, as Nginx won't be a member of the root group.
I would change permissions of the socket. This is one way, but you might decide to do it differently based on the multitude of tutorials that no doubt exist online and can be found via Google.
chown nginx:nginx /var/run/php-fpm/website.sock

NB: old answer was regarding socket path, but this didn't turn out to be the answer as the question was inaccurate.

A: The problem turned out to be PHP 5.4.16 was installed on server as opposed to PHP7.1 on local instance.  The application requires PHP 5.5+ to successfully run requests through kernel.  This is why I was not generating any errors for NGINX with my configuration.  I discovered the solution by installing and configuring Apache as the server instead of NGINX only to receive the white screen on client.  Thanks for all comments and eyeballs contributed!


text:
Q: QgsRasterCalculator fails in standalone Python application I am trying to write a simple Python program which shall be a wrapper for QgsRasterCalculator() function, to use it in some batch processes. In both QGIS 2.14 (on Linux) and QGIS 3.10 (on Windows 10) I have problems to find an expression that works.
Copying a raster, when the expression holds just the band reference works. But including an operator or a second band will fail.
E.g.:
layer = QgsRasterLayer(path_to_dted_tile, 'n45_dt1')
entries = []
band = QgsRasterCalculatorEntry()
band.ref = layer.name() + '@1'
band.raster = layer
band.bandNumber = 1
entries.append(band)

expression = '"n45_dt1@1"'

context = QgsCoordinateTransformContext()  # QGIS 3.10 only
calc = QgsRasterCalculator(expression,
                           path_to_output_file,
                           'GTiff',
                           layer.extent(),
                           layer.width(),
                           layer.height(),
                           entries,
                           context)   # QGIS 3.10 only
result = calc.processCalculation()

works as expected. When I use: expression = '"n45_dt1@1" + 1.0'
QgsRasterCalculator crashes with the following output on the console:

Process finished with exit code -1073740940 (0xC0000374)

If the expression is wrong, how should it look like and, if not, what may cause this failure?

A: I think the problem is not your expression. I checked this out using the Raster calculator from the Processing Toolbox and observed the same issue in QGIS 3.10.0. The same thing works in QGIS 3.4.14 LTR as you can see in Screenshot:

I bet that your python code with the '"raster@1" + 1.0' expression will work in the current LTR too.
Just opened an issue for this: https://github.com/qgis/QGIS/issues/32477

A: The solution for Raster Calculator issue in Qgis 3.10 is:
1. Goto the Qgis 'Setting',
2. Option,
3. Acceleration,
4. Then, check the box 'Enable OpenCL acceleration'
This will work sure.


text:
Q: Aggregate CSV data based on unique ID using command-line tools I would like to aggregate data from one CSV file into another, using command-line tools such as bash, sed, awk etc. Each row in each file begins with a unique ID in column 1, and if a row in the destination matches this ID, the line should be replaced, otherwise it should be appended. The input data is not sorted, but the sort order of the result doesn't matter so files can be sorted as part of the script if it helps.
For example, given the current state of aggregate.csv:
1,olddata
3,olddata
2,olddata

And the file new.csv:
4,newdata
2,changeddata
3,changeddata

I would like aggregate.csv to come out as follows (in any sort order):
1,olddata
2,changeddata
3,changeddata
4,newdata

The lines may contain a large number of columns so replacing one cell at a time is not ideal. The CSVs are guaranteed not to contain quoted newlines, so a line-by-line search and replacing a whole line at a time is a valid approach.
Apologies if this is a duplicate but I can't find another question that exactly uses this CSV merging approach.
I have tried adapting the answers to this question but it required first generating the "template file" of all IDs by parsing both files line-by-line, sorting, removing duplicates, and saving - I hoped that a simpler method was possible.
This question has answers in sed and awk that I also replicated, and managed the regex-replacement part but not a method to append a new line to the file if a match did not exist.
Thanks!

A: Assumptions:

*

*replace entire lines

*total file size is ~8-10 MB (so likely won't have any out-of-memory issues)

*field #1 is unique within each file

*no sorting requirements for output

*input not guaranteed to be sorted

One awk solution:
awk -F"," '                      # input delimiter is comma ","

FNR==NR { a[$1]=$0 ; next }      # first file: store contents in array a[], using field #1 as index

        { if ( $1 in a )         # second file: if field #1 is an index in array a[] then
             { print a[$1]       # print the contents of said array entry and
               delete a[$1]      # remove entry from array
             }
          else                   # field #1 is not an index in array a[] so
             print $0            # print current line
        }

END     { for ( i in a )         # anything still in array a[] was not in second file so
              print a[i]         # print these entries
        }
' new.csv aggregate.csv          # order of input files is important !!!

This geneates:
1,olddata
3,changeddata
2,changeddata
4,newdata

NOTE: While the output appears to be ordered by field #1, this is merely a coincidence based on the ordering of the input data; there's nothing in this awk code that explicitly generated this 'ordered' output.
This will not overwrite the aggregate.csv file. While it's possible to use the GNU awk -i inplace option to overwrite aggregate.csv, this would require a change in processing to keep from overwriting new.csv. The easiest solution will likely be to direct this output to a new file and then OP can decide if said new file should be used to overwrite aggregate.csv.

A: With any awk:
$ awk -F, '!seen[$1]++' new agg
4,newdata
2,changeddata
3,changeddata
1,olddata

or with GNU sort for -s:
$ sort -ust, -k1,1 new agg
1,olddata
2,changeddata
3,changeddata
4,newdata


text:
Q: Hide/Unhide an image using jquery on hover I have 3  tags in my html and they each contain 2 images. Only the grescale images are displayed and the other ones are set to none.
I want to hide the greyscale image when I hover the mouse over the grescale image and display the colored one. And when I un-hover I want the colored image to be hidden again. How can I do that using jquery?

.color-image
{
    display:none
}

A: Why use jQuery and not pure CSS?
You can use :hover and toggle the display of the images.
a.mylink:hover .color-image,
a.mylink .greyscale-image {
   display: inline;
}

a.mylink .color-image,
a.mylink:hover .greyscale-image {
   display: none;
}

In jQuery it is just
function swap(evt) {
    var isOver = evt.type === "mouseenter";
    link.find(".color-image").toggle(isOver);
    link.find(".greyscale-image").toggle(!isOver);
}

$("a.mylink").hover(swap, swap);

A: NO Jquery needed. Use the :hover css pseudo on the .myLink anchor, like:
.color-image {
    display:none;
}

a.myLink:hover .color-image {
    display: block;
}

a.myLink:hover .greyscale-image {
    display: none;
}

A: My way :p
a[class="mylink"]:not(:hover) img[class*="greyscale"],
a[class="mylink"]:hover img[class*="color"] {
    display: inline-block;
}
a[class="mylink"]:not(:hover) img[class*="color"],
a[class="mylink"]:hover img[class*="greyscale"] {
    display: none;
}

Here is a demo JSFiddle
http://jsfiddle.net/agaex70r/
Here is another JSFiddle with a transition.
http://jsfiddle.net/agaex70r/2/

A: You could do this with css:hover. Hover on gray scale image, display:none and the reverse for the colored image. This has the benefit of working when JS is disabled. Otherwise, you could look into Jquery UI


text:
Q: FastAPI Custom Websocket Object I want to be able to create a custom WebSocket object rather than using Starlette's so that I can add some more things in the constructor and add some more methods. In FastAPI, you're able to subclass the APIRoute and pass in your own Request object. How would I do the same for the WebSocket router?

A: As you say, there doesn't seem to be an easy way to set the websocket route class (short of a lot of subclassing and rewriting). I think the simplest way to do this would be to define your own wrapper class around the websocket, taking whatever extra data you want, and then define the methods you need. Then you can inject that as a dependency, either with a separate function, or use the class itself as a dependency, see the documentation for details, which is what I'm doing below.
I've put together a minimal example, where the URL parameter name is passed to the wrapper class:
# main.py
from fastapi import Depends, FastAPI, WebSocket

app = FastAPI()

class WsWrapper:
    def __init__(self, websocket: WebSocket, name: str) -> None:
        self.name = name
        self.websocket = websocket

    # You can define all your custom logic here, I'm just adding a print
    async def receive_json(self, mode: str = "text"):
        print(f"Hello from {self.name}", flush=True)
        return await self.websocket.receive_json(mode)

@app.websocket("/{name}")
async def websocket(ws: WsWrapper = Depends()):
    await ws.websocket.accept()
    while True:
        data = await ws.receive_json()
        print(data, flush=True)

You can test it by running uvicorn main:app and connecting to ws://localhost:8000/test, and it should print "Hello from test" when receiving JSON.

A: Ended up just monkeypatching the modules. Track this PR for when monkeypatching isn't necessary: https://github.com/tiangolo/fastapi/pull/4968
from typing import Callable

from fastapi import routing as fastapi_routing
from starlette._utils import is_async_callable
from starlette.concurrency import run_in_threadpool
from starlette.requests import Request as StarletteRequest
from starlette.websockets import WebSocket as StarletteWebSocket
from starlette.types import ASGIApp, Receive, Scope, Send

class Request(StarletteRequest):
    pass

class WebSocket(StarletteWebSocket):
    pass

def request_response(func: Callable) -> ASGIApp:
    """
    Takes a function or coroutine `func(request) -> response`,
    and returns an ASGI application.
    """
    is_coroutine = is_async_callable(func)

    async def app(scope: Scope, receive: Receive, send: Send) -> None:
        request = Request(scope, receive=receive, send=send)
        # Force all views to be a coroutine
        response = await func(request)
        if is_coroutine:
            response = await func(request)
        else:
            response = await run_in_threadpool(func, request)
        await response(scope, receive, send)

    return app

fastapi_routing.request_response = request_response

def websocket_session(func: Callable) -> ASGIApp:
    """
    Takes a coroutine `func(session)`, and returns an ASGI application.
    """
    # assert asyncio.iscoroutinefunction(func), "WebSocket endpoints must be async"

    async def app(scope: Scope, receive: Receive, send: Send) -> None:
        session = WebSocket(scope, receive=receive, send=send)
        await func(session)

    return app

fastapi_routing.websocket_session = websocket_session


text:
Q: Button is disabled until I reopen the Activity I have my main Activity with two Buttons on it. When I start the application, you can click on one Button and it will take you to the right Activity, but I can click the second Button a hundred times and nothing happens. It looks just like the first Button and changes to the usual blue color when I press it, BUT if I go the the first button's Activity, then go BACK to the first Activity, the second Button works. I don't understand what's going on here.
Main Activity:(Note, SignUp is the button that doesn't work):
public class GameNetActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.first);
    getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

                Button SignIn = (Button) findViewById(R.id.button1);
    SignIn.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    Intent myIntent = new Intent(view.getContext(), Welcome.class);
                    startActivityForResult(myIntent, 0);

            Button SignUp = (Button) findViewById(R.id.button2);
    SignUp.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent myIntent = new Intent(view.getContext(), Signup.class);
            startActivityForResult(myIntent, 0);
                }

            });
        }
    });
  }
}

A: You have registered for the onClickListener for SignUp button within the onClickListener of SignIn button. Take that out and put it separately in the onCreate().
public void onCreate(Bundle savedInstanceState) {
...
....
    Button SignIn = (Button) findViewById(R.id.button1);
    SignIn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent myIntent = new Intent(view.getContext(), Welcome.class);
            startActivityForResult(myIntent, 0);
        }
    });

    Button SignUp = (Button) findViewById(R.id.button2);
    SignUp.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent myIntent = new Intent(view.getContext(), Signup.class);
            startActivityForResult(myIntent, 0);
        }
    });
...
...}

Hope this helps!!


text:
Q: Finding a row in a 2d array in python if the value of the column is known I have a matrix in an excel sheet I am reading into my script using Pandas. I convert it to an np matrix like so and come out with this as a result.
df = pd.read_excel(r'C:\Users\PycharmProjects\OLS_Script\ols1.xlsx')
matrix = np.matrix(matrix)
print(matrix)

Now my question is regarding if some mechanics in python exist that I am not familiar with as I come from C++. Essentially what I am trying to do with this matrix is for each column, acquire the entire row that the column has values in, as well as the row corresponding to that.
For instance, looking at column 0, I would need the entire row 0, as well as row 1 since it is the only other row with a 1 in column 0.
So I would need the indices [1,2,3] in row 0, and [4,5,6,7] in row 1, excluding anything in column 0.
Column 1 has a 1 in row 0 as well as row 2, so I would need to get those two rows and the corresponding column indices in each of those rows with a population in it.
[0,2,3] in row 0, [4,8,9,10,11] in row 2, excluding anything in column 1, and so on for the following columns.
My original idea was the have a for loop go through each column, then another for loop inside to go through each row at the same column index to find where the next corresponding row is. I am not too familiar with python and the various "shortcuts" it has compared to something like C++ since I have seen a lot of functionality in python beforehand that might make something like what I need to do with as few lines of code as possible, so if there is a shorter way to accomplish what I need, please let me know.

A: With an excerpt of your matrix as an example:
import pandas as pd

matrix = [
    [1, 1, 1, 1, pd.NA, pd.NA, pd.NA, pd.NA, pd.NA, pd.NA, pd.NA, pd.NA,],
    [1, pd.NA, pd.NA, pd.NA, 1, 1, 1, 1, pd.NA, pd.NA, pd.NA, pd.NA,],
    [pd.NA, 1, pd.NA, pd.NA, 1, pd.NA, pd.NA, pd.NA, 1, 1, 1, 1],
]

df = pd.DataFrame(matrix)

     0     1     2     3     4     5     6     7     8     9     10    11
0     1     1     1     1  <NA>  <NA>  <NA>  <NA>  <NA>  <NA>  <NA>  <NA>
1     1  <NA>  <NA>  <NA>     1     1     1     1  <NA>  <NA>  <NA>  <NA>
2  <NA>     1  <NA>  <NA>     1  <NA>  <NA>  <NA>     1     1     1     1

Here is one way to do it:
results = {
    i: df.dropna(subset=i).dropna(how="all", axis=1).drop(columns=i).columns.to_list()
    for i in range(df.shape[1])
}

print(results)
# Output
{
    0: [1, 2, 3, 4, 5, 6, 7],
    1: [0, 2, 3, 4, 8, 9, 10, 11],
    2: [0, 1, 3],
    3: [0, 1, 2],
    4: [0, 1, 5, 6, 7, 8, 9, 10, 11],
    5: [0, 4, 6, 7],
    6: [0, 4, 5, 7],
    7: [0, 4, 5, 6],
    8: [1, 4, 9, 10, 11],
    9: [1, 4, 8, 10, 11],
    10: [1, 4, 8, 9, 11],
    11: [1, 4, 8, 9, 10],
}


text:
Q: How to save multiple dictionaries to hdf5 and combine information for common keys from different dictionaries? Briefly, I'm interested is there any efficient way to save multiple dictionaries with common keys into hdf5 file.
Perhaps I have N dictionaries with the following structure (I will use 2 dicts in the below example):
sample_1 = {'gene1_gene1': 1,
            'gene1_gene2': -0.385,
            'gene1_gene3': 0.25,
            'gene2_gene2': 1,
            'gene2_gene3': 0.004,
            'gene3_gene3': 1
           }
sample_2 = {'gene1_gene1': 1,
            'gene1_gene2': -0.0035,
            'gene1_gene4': 0.0421,
            'gene2_gene2': 1,
            'gene2_gene4': -0.0783,
            'gene4_gene4': 1
           }

Each dictionary contains M keys. Some keys are common for multiple dictionaries (like gene1_gene2), some keys are unique (like both gene2_gene3 and gene2_gene4).
I want to save each dictionary to the one hdf5 file with the structure like this one:
{
    'gene1_gene2': {
         'sample_1': -0.385,
         'sample_2': -0.0035,
         ....
    }
    ....
}

So the file must contain both values for each key and the corresponding sample names.
After that, I want to extract both sample names and values from hdf5 file using target geneX_geneY pairs.
To do it, I write this code:
with h5py.File("out_file.hdf5", 'a') as f:
    for gene_pair, cor_val in sample_N.items():
        try:
            grp = f.create_group(gene_pair)
            grp.create_dataset('data', (0,), maxshape=(None,), dtype=h5py.string_dtype(encoding='ascii'),
                               compression="gzip", compression_opts=9)
            grp.create_dataset('cor', (0,), maxshape=(None,), dtype='f4', compression="gzip", compression_opts=9)
            data = f[gene_pair]['data']
            cor = f[gene_pair]['cor']
            cor.resize(cor.shape[0] + 1, axis=0)
            cor[-1] = cor_val
            data.resize(data.shape[0] + 1, axis=0)
            data[-1] = 'sample_N'
        except:
            data = f[gene_pair]['data']
            cor = f[gene_pair]['cor']
            cor.resize(cor.shape[0] + 1, axis=0)
            cor[-1] = cor_val
            data.resize(data.shape[0] + 1, axis=0)
            data[-1] = 'sample_N'

Briefly, code creates groups corresponding to geneX_geneY key and save both the value (f[gene_pair]['cor']) and the dataset name (f[gene_pair]['data']) to corresponding datasets with numpy arrays.
I'm interested, is there any efficient way to do it?

A: As noted in the comments, HDF5/h5py uses NumPy array structures and doesn't support dictionaries. Frankly, I think arrays are far superior to dictionaries for managing this kind of data. (Personally, I would NOT store the gene_pair data in dictionaries...way to messy to load and unload...but that's just me.)
There is no need to create a gene_pair group with separate datasets for cor and data. In fact, your method complicates the schema, requiring access to 2 different datasets to get cor and data. You can do it all in a single dataset/table for each gene_pair (equivalent to a NumPy record array). There are a lot of ways to do this. If you can change the gene_pair data structure upstream of this process, I would highly recommend a NumPy record array. It has a natural mapping to HDF5/h5py datasets, and creating them is a one step process. If you can't (or don't want) to do that, I have 3 suggestions.
Note: Code to create the sample_N dictionary is the same for all methods and provided at the end.
Also, I followed your example and created each dataset/table as an expandable dataset with zero rows initially, adding one row at a time. This is OK for small data samples, but reallocating large datasets will become slow if you have millions of rows. If you plan to add a lot of data, I suggest a different approach. Allocate an initial large row block (10e4?), then keep track of the current row, and expand as needed with additional large blocks. This method is only "slightly" more complicated. :-)
Method 1:
This is the table format that matches your request. It creates a dataset (table) for each gene_pair name. The dataset name is the name of the gene_pair, and it has 3 fields: Sample_ID (text), ID (extracted integer), and the test value associated to this sample.
with h5py.File("SO_61351577_1.h5", 'w') as h5f:
  for sample_N in sample_dict:
    for gene_pair, cor_val in sample_dict.get(sample_N).items():
        gene_dt = np.dtype ([ ('Sample', 'S20'), ('ID', int), ('Value', float) ])
        if gene_pair not in h5f.keys() :
            gene_pair_ds = h5f.create_dataset(gene_pair, (1,), maxshape=(None,), dtype=gene_dt,
                           compression="gzip", compression_opts=9)
        else:
            gene_pair_ds = h5f[gene_pair]
            gene_pair_ds.resize(gene_pair_ds.shape[0] + 1, axis=0)
        gene_pair_ds[-1,'Sample'] = sample_N
        gene_pair_ds[-1,'ID'] = int(sample_N[7:] )
        gene_pair_ds[-1,'Value']  = cor_val

Method 2:
This uses a different table format. It has one row of data for each sample, and test values under the matching column/field. It's just a suggestion for your consideration. It would not make sense if the number of pairs is big (say >100). Also, the table has 0.0 for values that weren't entered, so that could be a problem.
How the process works: First I get the gene_pair names from the sample_N dictionaries, and build a list of unique names. I use this list to create a NumPy dtype to hold all the data. Then I loop on the sample_N dictionaries, and write all gene_pair values for that sample on the same row. Mapping to field/column is done with the gene_pair name.
#Create a list of unique dictionary keys:
gene_list = []
for sample_N in sample_dict:
    for gene_pair in sample_dict.get(sample_N):
        if gene_pair not in gene_list:
            gene_list.append(gene_pair)
gene_list.sort()
# Create dictionary of names and formats to use for dtype
# Then use as NumPy dtype to create the dataset
dt_genetable = {'names':['Sample','ID'], 'formats':['S20', int] }
for gene_name in gene_list:
     dt_genetable['names'].append(gene_name)
     dt_genetable['formats'].append(float)

with h5py.File("SO_61351577_2.h5", 'w') as h5f:
    genetable_ds = h5f.create_dataset('GeneTable', (0,), maxshape=(None,),
                        dtype=dt_genetable, compression="gzip", compression_opts=9)

    for sample_N in sample_dict:
        genetable_ds.resize(genetable_ds.shape[0] + 1, axis=0)
        genetable_ds[-1,'Sample'] = sample_N
        genetable_ds[-1,'ID'] = int(sample_N[7:] )
        for gene_pair, cor_val in sample_dict.get(sample_N).items():
            print (sample_N, ':', gene_pair, ':', cor_val)
            genetable_ds[-1,gene_pair]  = cor_val

Method 3:
I created this example because this dataset/table format most closely mimics your original dictionary format. It is similar to Method 2 with slightly different dtype and table. Like Method 2, it has one row of data for each sample, with 12 additional fields for the gene_pair name and cor_val values. (I assumed you always have 6 pairs.)
# Create dictionary of names and formats to use for dtype
# Then use as NumPy dtype to create dataset
sample_table_dt = {'names':['Sample','ID'], 'formats':['S20', int] }
for cnt in range(1,7,1):
     sample_table_dt['names'].append('gene_name_'+str(cnt))
     sample_table_dt['formats'].append('S20')
     sample_table_dt['names'].append('cor_val_'+str(cnt))
     sample_table_dt['formats'].append(float)

with h5py.File("SO_61351577_3.h5", 'w') as h5f:
    sample_table_ds = h5f.create_dataset('SampleTable', (0,), maxshape=(None,),
                        dtype=sample_table_dt, compression="gzip", compression_opts=9)

    for sample_N in sample_dict:
        sample_table_ds.resize(sample_table_ds.shape[0] + 1, axis=0)
        sample_table_ds[-1,'Sample'] = sample_N
        sample_table_ds[-1,'ID'] = int(sample_N[7:] )
        gcnt = 1
        for gene_pair, cor_val in sample_dict.get(sample_N).items():
            sample_table_ds[-1,'gene_name_'+str(gcnt)]  = gene_pair
            sample_table_ds[-1,'cor_val_'+str(gcnt)]  = cor_val
            gcnt += 1

Code to create the sample_N dictionary:
sample_1 = {'gene1_gene1': 1,
            'gene1_gene2': -0.385,
            'gene1_gene3': 0.25,
            'gene2_gene2': 1,
            'gene2_gene3': 0.004,
            'gene3_gene3': 1
           }
sample_2 = {'gene1_gene1': 1,
            'gene1_gene2': -0.0035,
            'gene1_gene4': 0.0421,
            'gene2_gene2': 1,
            'gene2_gene4': -0.0783,
            'gene4_gene4': 1
           }
sample_3 = {'gene1_gene1': 1,
            'gene1_gene2': -0.065,
            'gene1_gene4': 0.0567,
            'gene2_gene2': 1,
            'gene2_gene3': -0.0378,
            'gene4_gene4': 1
           }

sample_dict = dict( sample_1=sample_1,
                    sample_2=sample_2,
                    sample_3=sample_3 )


text:
Q: play audio only when button is pressed otherwise not in android I want to make an entertainment app which will produce sound only when the play button is pressed, but it is not working properly .
My code is
final MediaPlayer mp = new MediaPlayer();
play.setOnClickListener(new OnClickListener() {
    public void onClick(View arg0) {
        try{
            AssetFileDescriptor descriptor = getAssets().openFd("3dpolicesi_mAYkXAbm.mp3");
                long start = descriptor.getStartOffset();
                long end = descriptor.getLength();

                mp.setDataSource(descriptor.getFileDescriptor(), start, end);
                mp.prepare();
                mp.start();

                mp.stop();

        }catch(Exception e){e.printStackTrace();}
    }
} );

A: It is because mp.stop() is called directly after mp.start(). It won't get a chance to play.

A: First delete this 3 line of your code:
mp.prepare();
mp.start();
mp.stop();

Write this outside of onClick:
int x = 0;

Then write this inside of onClick:
if(x == 0){
  mp.start();
  x = 1;
}else if(x == 1){
  mp.stop();
  x = 0;
}

At first time x is 0 so when you click on button player will be start and x will be replace with 1. next time when you click on button x is 1 so player will be stop.I hope it help.


text: Q: AWS amplify auth - google opens a separate window on currentCredentials either currentAuthenticatedUser retrieve Recently I got an legacy code to work with and the amplify version was really low, upgraded it to the most recent version and trying to get rid of one unwanted behaviour. We use google auth. When I want to get currentCredentials or currentAuthenticatedUser it opens an separate window. Could you just tell me what should I search for?


text:
Q: FAT32 file write speed to removable drive I am trying to write many files to USB flash removable drive FAT32 formatted.
I am not expert in Windows internal things so I asking for your experience and advices.
While big files write speed is limited by USB and the USB device, the small files write speed is ridiculously slow.
Using DiskMon I can see what Win7 is writing to USB drive sectors per file.
Some facts:
Writes to Directory is done by 8x 512 bytes sectors blocks equal 4KB with 4KB boundary.
Writes to FAT is done by 1-8x 512 bytes sectors blocks up to 4KB with 4KB boundary.
Writes FAT sectors amount is depending on file size, cluster size, sector size and crossing of FAT sector boundary.
Some equations:
filetotalclusters= (filesize+clustersize-1)/clustersize
clusterspersector=sectorsize/4
fileFATsectors=filetotalclusters/clusterpersector and optionally +1 sector when FAT sector border crossed.
So for 32KB cluster and 512 bytes sector, 1 FAT sector covers 4MB of file size, 8 sectors (4KB) covers 32MB file.
not big file single block write (<32MB and FAT chain doesnt cross sector boundary):
create(),write(),close()  6 writes per file
1) create() write dir 4KB  (name of file, default attributes and current times)
2) write()  write file data
3)          write dir 4KB  (first cluster of chain)
4)          write FAT1 up to 4KB (chain of clusters)
5)          write FAT2 up to 4KB (chain of clusters)
6) close()  write dir 4KB (I guess it writes new file size)

bigger file or cross of FAT sector boundary and single block write:
create(),write(),close()  4+2x(ceiling of filesize/32MB) writes per file
1) create() write dir 4KB  (name of file, default attributes and current times)
2) write()  write file data
3)          write dir 4KB  (first cluster of chain)
4)          write FAT1 up to 4KB (chain of clusters)
5)          write FAT2 up to 4KB (chain of clusters)
6)          write FAT1 up to 4KB (continue chain of clusters)
7)          write FAT2 up to 4KB (continue chain of clusters)
8) close()  write dir 4KB (I guess it writes new file size)
So for long files added 2x(filesize/32MB) writes to the FAT.

with file times set
create(),setfiletime(),write(),close()  7 writes per file
1) create() write dir 4KB (name of file, default attributes and current times)
2) setfiletime() write dir 4KB  (new file times: creation,lastaccess,lastwrite)
3) write()  write file data
4)          write dir 4KB  (first cluster of chain)
5)          write FAT1 up to 4KB (chain of clusters)
6)          write FAT2 up to 4KB (chain of clusters)
7) close()  write dir 4KB (I guess it writes new file size)

with file length set before write to avoid fragmentation.
create(),setfiletime(),setlength(),write(),close()  7 writes per file
1) create() write dir 4KB (name of file, default attributes and current times)
2) setfiletime() write dir 4KB  (new file times: creation,lastaccess,lastwrite)
3) setlength() write dir 4KB (first cluster of chain and file size)
4)          write FAT1 up to 4KB (chain of clusters)
5)          write FAT2 up to 4KB (chain of clusters)
6) write()  write file data
7) close()  write dir 4KB  (I dont know what it writes as file times, file length and cluster already set)

if multiple block writes, 13 writes for 2 blocks write (<32MB and no FAT sector crossed) and more.
create(),setfiletime(),setlength(),write1(),write2(),writeX(),close()
1) create() write dir 4KB (name of file, default attributes and current times)
2) setfiletime() write dir 4KB  (new file times: creation,lastaccess,lastwrite)
3) setlength() write dir 4KB (first cluster of chain)
4)          write FAT1 up to 4KB (chain of clusters)
5)          write FAT2 up to 4KB (chain of clusters)
6) write1() write file data block1
7) write2() write file data block2 (and it triggers write of buffered FAT and Dir sectors)
8-9..)      write multiple FAT1 and FAT2 depending on file size which should be already written on step 4 and 5.
10)         write dir 4KB which should be already written on step 3.
11) writeX() write file data blockX (and it triggers write of buffered FAT and Dir sectors)
12)         write dir 4KB which should be already written on step 3.
13-14..)    write multiple FAT1 and FAT2 depending on file size which should be already written on step 4 and 5
15) close()  write dir 4KB  (I dont know what it writes as file times, file length and cluster already set)
16-17..)    write multiple FAT1 and FAT2 depending on file size which should be already written on step 4 and 5

I guess write file in multiple blocks somehow makes Dir and FAT sectors dirty in Windows Cache.
So it rewrites them again and again regardless of its contents didnt change.
How to avoid such behavior?
So to reduce amount of writes per file seems need to use:
1) cluster size as big as possible, 32KB or 64KB, but small files will eat much space.
2) write file in single data block write or as less amount of blocks as possible to reduce triggering of excessive FAT and Dir writes.
But it is hard to allocate big contiguos block of memory so might be 64MB is upper limit.
If I write files in multiple threads I see amount of writes to FAT and Dir is twice less.
Seems Windows Cache allows to modify FAT and Dir buffers twice before it rushes to flush on disk.
Only two modifications regardless of amount of parallel threads.
I dont know if it possible to increase that flush time for USB removable drive.
So slowness of writing of many small files is related to many duplicate writes to FAT and Dir.
If files are 1KB size, 1 FAT 4KB block shared by 1024 files and 1 Dir 4KB block shared by 128 files.
And if per file OS writes Dir and FAT multiple times you can see how it waste resources: time and flash life.
I can enforce write cache on USB removable drive, it really speed up write of first files but total time is even worse.
I dont know yet a reason for it, might be multiple writes also "poisons" FAT and Dir cached sectors so they start writes again and again mixing with data.


text:
Q: Compare two csv entries in powershell I'm just learning powershell, but have run up on this error that has me stumped. The objective is to take a csv file and ascertain how many groups there are in the file. There will be multiple entries under each group. The end result would be to split the file into different arrays/dictionaries/whathaveyou (i started with powershell 3hrs ago..) based on the groups, keeping the TaxonIDs intact, then export those to separate files. But for now, I'm just at the comparison step.
My practice data look like
Group,TaxonID
AA,1
AA,2
BB,3
BB,4

and true data look like:
Group,TaxonID
Bilateria_Ropsin,Mus_musculus_Rhabdomeric_MEL
Bilateria_Ropsin,ROp_OG3TodaroP

To do this, I tried to compare the group in one row with the group in the next row. if they differ, then I add one to a variable for later use. Here's what i've got to do the comparison:
Set-Variable -name book -value C:\Users\XXX\Documents\Book1.csv
$work = Import-Csv $book
$numgroups = 0
$i=0
foreach ($Group in $work) {
    $Ogroup = $work[$i] | select-object{$_.Group}
    $nextGroup = $work[$i+1] | select-object{$_.Group}
    $compare = $Ogroup.Equals($nextGroup)
    $compare
    $i++
}

When i print out $Ogroup and $nextGroup, they give me the proper pairs (AA AA, AA BB, BB BB), but $compare always prints out false. Using Compare-Object gives me an error about $nextGroup being null..so I opted for using .Equals(). CompareTo() throws an error about it not being a valid method.
I'm stumped and need help.

A: You shoud use Group-Object CmdLet
Set-Variable -name book -value C:\Users\XXX\Documents\Book1.csv
$work = Import-Csv $book

$groups = $work | Group-Object -Property Group
$groups.count
$groups[0].name
$groups[0].Group[0]
for ($i=0 ; $i -lt $groups.count ; $i++) { $groups[$i].name}

for ($i = 0 ; $i -lt $groups.count ; $i++)
{
  $groups[$i].name;
  for ($j=0 ; $j -lt $groups[$i].count;$j++)
  {
    $groups[$i].group[$j]
  }
}

A: Comparing isn't needed. Split the groups out first:
$book = "$env:USERPROFILE\Documents\Book1.csv"
$work = Import-CSV $book
$Groups = $work | Group-Object Group
ForEach($Group in $Groups){
    "Group Name: "+$Group.name
    "Taxon IDs: "
    $Group.group.TaxonID
}

If you want to save each group to a file, within that ForEach loop you can do $Group|export-csv "c:\path\$($Group.name).csv" -notypeinfo
Edit: Sorry, was working on an answer when security called me over the intercom and said a water main burst under my truck and they needed me to go move my vehicle. Figured not losing my vehicle to a sinkhole was more important than this.


text:
Q: How can I put all value in list into same line new=None
for i in range (0,11):
  behave = ['Siberian Husky','Shiba Inu','Shiba Inu','Golden Retriever','Golden Retriever',
            'Golden Retriever','Golden Retriever','Golden Retriever',
            'Siberian Husky','Siberian Husky','Golden Retriever','Golden Retriever',
            'Golden Retriever','Shiba Inu','Shiba Inu','Shiba Inu','Shiba Inu',
            'Labrador Retriever','Labrador Retriever','Shiba Inu','Siberian Husky']
  test = [1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,0,1,1]
  #print(len(test))
  if test[i]==1:
    new=behave[i]
    #print(new)

    all_new = [ x for x in new.split(',') ]
    print(all_new)

I want all new show like this:
['Siberian Husky','Shiba Inu','Shiba Inu','Golden Retriever','Golden Retriever','Golden Retriever',
'Golden Retriever','Golden Retriever','Siberian Husky']

A: The list comprehension shouldn't be in the loop, it should be instead of the loop.
all_new = [behave[i] for i in range(11) if test[i] == 1]
print(all_new)

A: This is what you are looking for
behave = ['Siberian Husky','Shiba Inu','Shiba Inu','Golden Retriever','Golden Retriever', 'Golden Retriever','Golden Retriever','Golden Retriever', 'Siberian Husky','Siberian Husky','Golden Retriever','Golden Retriever', 'Golden Retriever','Shiba Inu','Shiba Inu','Shiba Inu','Shiba Inu', 'Labrador Retriever','Labrador Retriever','Shiba Inu','Siberian Husky']
test = [1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,0,1,1]
all_new = []
for i in range(0,11):
   if test[i]:
      all_new.append(behave[i])
print(all_new)


text:
Q: supremum and infimum of a bounded and decreasing sequence Is there supremum and infimum of a bounded sequence? I have a bounded and decreasing sequence. Why does this sequence have infimum?

A: The Axiom of Completeness states that every bounded set of real numbers has a least upper bound, a supremum. Notice the word axiom. Notice further that the AOC says nothing about the existence of infima. Why? Because we can prove the existence of an infimum using the AOC.


text:
Q: Can't find Python executable "python3.10.6", you can set the PYTHON env variable with NPM install I am trying to npm install on a module but it always errors out. I think this has something to do with npm not finding my python3 executable. I get this error
gyp ERR! stack Error: Can't find Python executable "python3.10.6", you can set the PYTHON env variable.
How do I go about setting the env. I've already updated my .bash_profile to this
export PATH=$PATH:/opt/homebrew/bin/python3
Is there anything that I am missing?


text:
Q: Show only one child product (of grouped product) to have a quantity of 1 in WooCommerce By default, all child products under a grouped product show a quantity of "0" on the single listing page as shown here.
There's a way to change ALL the quantities from "0" to "1" but can we only choose the first child product to have a quantity of 1?


text:
Q: retrieving e-mail from user after submission through Direct Url OAuth Dialog? I am using the Link
`https://www.facebook.com/dialog/oauth/?
scope=email,user_birthday&
client_id=289912184369824&
redirect_uri=http://takeinsocialmedia.com&
response_type=token`

To request the user e-mail and birthday on our landing page. this link will be connected to a normal html button to accept user information quicker then then typing it in. How do i access the e-mail information and birthday information?
please understand that I am not a coder and do not have full knowledge of how to use API.

A: Once you have the access token a call to /me/?fields=birthday,email will return the two fields you want.
if you're not using any of the SDKs for some reason, you can manually go to https://graph.facebook.com/me?fields=birthday,email&access_token={YOUR_ACCESS_TOKEN} to get the values


text:
Q: Why is there a delay in my VHDL combinational logic within a process? I'm creating a testbench for combinational logic, where a, b, cin are inputs in to an instantiated unit under test.  All that appears to be working fine.
However, I'm deriving a test_s signal through addition within my test bench process, and that seems to be strangely delayed.  It doesn't matter the duration of my 'wait' statements, I can change the units from ps to ns and the symptoms are the same.  What seems to be happening is that a and b set up properly, but test_s doesn't change until a and b change their values.  When this happens, test_s actually updates to the previous values of a and b.  So at first when a and b become 0, test_s becomes XXXXXXX.  Then, when a becomes 1, test_s becomes 0000000 when it should actually be 00000001.

-- Instantiate the Unit Under Test (UUT)
   uut: FastCarry8 PORT MAP (
      a => a,
      b => b,
      cin => cinVec(0),
      cout => cout
    );

   signal a : std_logic_vector(7 downto 0) := (others => '0');
   signal b : std_logic_vector(7 downto 0) := (others => '0');
   signal cinVec : std_logic_vector(1 downto 0);
   signal test_s : std_logic_vector(8 downto 0);

  -- Stimulus process
  stim_proc: process
  begin
  -- hold reset state
  wait for 10 ps;

    carry_gen: for carry in 0 to 1 loop
        cinVec <= std_logic_vector(to_unsigned(carry, 2));

        b_gen: for j in 0 to 255 loop
            a_gen: for i in 0 to 255 loop

                a <= std_logic_vector(to_unsigned(i, 8));
                b <= std_logic_vector(to_unsigned(j, 8));
                test_s <= std_logic_vector(resize(unsigned(a), test_s'length) +
                    unsigned(b) + unsigned(cinVec));

                wait for 5ps;

                ASSERT (test_s(8) = cout)
                    REPORT "Carry out failed for cin = 0!";

                wait for 5ps;

            end loop a_gen;
        end loop b_gen;
    end loop carry_gen;

A: Had to put a wait between assignment of a,b and the assignment of test_s since test_s is depending on those signal values.. this was answered privately


text:
Q: Pointers in AVL Tree Rotation I have trouble understanding why the below tree rotation code works. If T2 points to y.left and y.left points to x, doesn't this make the last assignment x.right = T2 equal to x.right = x? Shouldn't the pointer point to the initial T2?
Node leftRotate(Node x) {
    Node y = x.right;
    Node T2 = y.left;

    // Perform rotation
    y.left = x;
    x.right = T2;

    //  Update heights
    x.height = max(height(x.left), height(x.right)) + 1;
    y.height = max(height(y.left), height(y.right)) + 1;

    // Return new root
    return y;
}

A: The best way to reason with this is to draw it out and go through it a step at a time:
At the beginning of the function we have Node x:
   x
  /  \
 L    R
     /   \
    l1    r1

Now we say y = R.
  R
 /  \
L1   R1

Node T2 = R.Left which is l2
Then the rotation:
y.left (R1.Left) = x
     R
   /   \
  x      R1
 / \
l   R
   /  \
  l1    r1

x.right = T2 (l1)
    R
   /  \
  x    r1
 / \
l   l1

A great resource I found for all things tries (albeit in C) is eternally confuzzled

A: Node T2 = y.left;

This line makes T2 point to the same place y.left pointed at the time that line was run.  If y.left is updated to point to a different object -- x, in this case -- that change is not reflected in T2.
Mind you, if someone changed a property of that object, that change would be reflected.  E.g. the code
Node T2 = y.left;
y.left.foo = bar;

then T2.foo would reflect the change to bar.  It's changes to what y.left is referencing that aren't reflected.  This is a pretty universal thing in Java, related to the whole "references are passed by value" thing.