text:
Q: Graphics header fails to compile? I downloaded the graphics.h and libbgi.a files and did exactly as the instructions provided and still it doesn't work! I've set linker parameters as well and I must say that this works in C++  mode , but not in C mode. I'm using Dev-C++ 4.9.9.2 as well. Here is what i get :

Can anyone illustrate the problem for me?
P.S : The header code is
// The winbgim library, Version 6.0, August 9, 2004
// Written by:
//      Grant Macklem (Grant.Macklem@colorado.edu)
//      Gregory Schmelter (Gregory.Schmelter@colorado.edu)
//      Alan Schmidt (Alan.Schmidt@colorado.edu)
//      Ivan Stashak (Ivan.Stashak@colorado.edu)
//      Michael Main (Michael.Main@colorado.edu)
// CSCI 4830/7818: API Programming
// University of Colorado at Boulder, Spring 2003

// ---------------------------------------------------------------------------
//                          Notes
// ---------------------------------------------------------------------------
// * This library is still under development.
// * Please see http://www.cs.colorado.edu/~main/bgi for information on
// * using this library with the mingw32 g++ compiler.
// * This library only works with Windows API level 4.0 and higher (Windows 95, NT 4.0 and newer)
// * This library may not be compatible with 64-bit versions of Windows
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
//                          Macro Guard and Include Directives
// ---------------------------------------------------------------------------
#ifndef WINBGI_H
#define WINBGI_H
#include <windows.h>        // Provides the mouse message types
#include <limits.h>         // Provides INT_MAX
#include <sstream>          // Provides std::ostringstream
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
//                          Definitions
// ---------------------------------------------------------------------------
// Definitions for the key pad extended keys are added here.  When one
// of these keys are pressed, getch will return a zero followed by one
// of these values. This is the same way that it works in conio for
// dos applications.
#define KEY_HOME        71
#define KEY_UP          72
#define KEY_PGUP        73
#define KEY_LEFT        75
#define KEY_CENTER      76
#define KEY_RIGHT       77
#define KEY_END         79
#define KEY_DOWN        80
#define KEY_PGDN        81
#define KEY_INSERT      82
#define KEY_DELETE      83
#define KEY_F1          59
#define KEY_F2          60
#define KEY_F3          61
#define KEY_F4          62
#define KEY_F5          63
#define KEY_F6          64
#define KEY_F7          65
#define KEY_F8          66
#define KEY_F9          67

// Line thickness settings
#define NORM_WIDTH      1
#define THICK_WIDTH     3

// Character Size and Direction
#define USER_CHAR_SIZE  0
#define HORIZ_DIR       0
#define VERT_DIR        1

// Constants for closegraph
#define CURRENT_WINDOW -1
#define ALL_WINDOWS -2
#define NO_CURRENT_WINDOW -3

// The standard Borland 16 colors
#define MAXCOLORS       15
enum colors { BLACK, BLUE, GREEN, CYAN, RED, MAGENTA, BROWN, LIGHTGRAY, DARKGRAY,
              LIGHTBLUE, LIGHTGREEN, LIGHTCYAN, LIGHTRED, LIGHTMAGENTA, YELLOW, WHITE };

// The standard line styles
enum line_styles { SOLID_LINE, DOTTED_LINE, CENTER_LINE, DASHED_LINE, USERBIT_LINE };

// The standard fill styles
enum fill_styles { EMPTY_FILL, SOLID_FILL, LINE_FILL, LTSLASH_FILL, SLASH_FILL,
                   BKSLASH_FILL, LTBKSLASH_FILL, HATCH_FILL, XHATCH_FILL, INTERLEAVE_FILL,
                   WIDE_DOT_FILL, CLOSE_DOT_FILL, USER_FILL };

// The various graphics drivers
enum graphics_drivers { DETECT, CGA, MCGA, EGA, EGA64, EGAMONO, IBM8514, HERCMONO,
                        ATT400, VGA, PC3270 };

// Various modes for each graphics driver
enum graphics_modes { CGAC0, CGAC1, CGAC2, CGAC3, CGAHI,
                      MCGAC0 = 0, MCGAC1, MCGAC2, MCGAC3, MCGAMED, MCGAHI,
                      EGALO = 0, EGAHI,
                      EGA64LO = 0, EGA64HI,
                      EGAMONOHI = 3,
                      HERCMONOHI = 0,
                      ATT400C0 = 0, ATT400C1, ATT400C2, ATT400C3, ATT400MED, ATT400HI,
                      VGALO = 0, VGAMED, VGAHI,
                      PC3270HI = 0,
                      IBM8514LO = 0, IBM8514HI };

// Borland error messages for the graphics window.
#define NO_CLICK        -1      // No mouse event of the current type in getmouseclick
enum graph_errors { grInvalidVersion = -18, grInvalidDeviceNum = -15, grInvalidFontNum,
                    grInvalidFont, grIOerror, grError, grInvalidMode, grNoFontMem,
                    grFontNotFound, grNoFloodMem, grNoScanMem, grNoLoadMem,
                    grInvalidDriver, grFileNotFound, grNotDetected, grNoInitGraph,
                    grOk };

// Write modes
enum putimage_ops{ COPY_PUT, XOR_PUT, OR_PUT, AND_PUT, NOT_PUT };

// Text Modes
enum horiz { LEFT_TEXT, CENTER_TEXT, RIGHT_TEXT };
enum vertical { BOTTOM_TEXT, VCENTER_TEXT, TOP_TEXT }; // middle not needed other than as seperator
enum font_names { DEFAULT_FONT, TRIPLEX_FONT, SMALL_FONT, SANS_SERIF_FONT,
             GOTHIC_FONT, SCRIPT_FONT, SIMPLEX_FONT, TRIPLEX_SCR_FONT,
             COMPLEX_FONT, EUROPEAN_FONT, BOLD_FONT };
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
//                              Structures
// ---------------------------------------------------------------------------
// This structure records information about the last call to arc.  It is used
// by getarccoords to get the location of the endpoints of the arc.
struct arccoordstype
{
    int x, y;                   // Center point of the arc
    int xstart, ystart;         // The starting position of the arc
    int xend, yend;             // The ending position of the arc.
};

// This structure defines the fill style for the current window.  Pattern is
// one of the system patterns such as SOLID_FILL.  Color is the color to
// fill with
struct fillsettingstype
{
    int pattern;                // Current fill pattern
    int color;                  // Current fill color
};

// This structure records information about the current line style.
// linestyle is one of the line styles such as SOLID_LINE, upattern is a
// 16-bit pattern for user defined lines, and thickness is the width of the
// line in pixels.
struct linesettingstype
{
    int linestyle;              // Current line style
    unsigned upattern;          // 16-bit user line pattern
    int thickness;              // Width of the line in pixels
};

// This structure records information about the text settings.
struct textsettingstype
{
    int font;                   // The font in use
    int direction;              // Text direction
    int charsize;               // Character size
    int horiz;                  // Horizontal text justification
    int vert;                   // Vertical text justification
};

// This structure records information about the viewport
struct viewporttype
{
    int left, top,              // Viewport bounding box
        right, bottom;
    int clip;                   // Whether to clip image to viewport
};

// This structure records information about the palette.
struct palettetype
{
    unsigned char size;
    signed char colors[MAXCOLORS + 1];
};
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
//                          API Entries
// ---------------------------------------------------------------------------
#ifdef __cplusplus
extern "C" {
#endif

// Drawing Functions
void arc( int x, int y, int stangle, int endangle, int radius );
void bar( int left, int top, int right, int bottom );
void bar3d( int left, int top, int right, int bottom, int depth, int topflag );
void circle( int x, int y, int radius );
void cleardevice( );
void clearviewport( );
void drawpoly(int n_points, int* points);
void ellipse( int x, int y, int stangle, int endangle, int xradius, int yradius );
void fillellipse( int x, int y, int xradius, int yradius );
void fillpoly(int n_points, int* points);
void floodfill( int x, int y, int border );
void line( int x1, int y1, int x2, int y2 );
void linerel( int dx, int dy );
void lineto( int x, int y );
void pieslice( int x, int y, int stangle, int endangle, int radius );
void putpixel( int x, int y, int color );
void rectangle( int left, int top, int right, int bottom );
void sector( int x, int y, int stangle, int endangle, int xradius, int yradius );

// Miscellaneous Functions
int getdisplaycolor( int color );
int converttorgb( int color );
void delay( int msec );
void getarccoords( arccoordstype *arccoords );
int getbkcolor( );
int getcolor( );
void getfillpattern( char *pattern );
void getfillsettings( fillsettingstype *fillinfo );
void getlinesettings( linesettingstype *lineinfo );
int getmaxcolor( );
int getmaxheight( );
int getmaxwidth( );
int getmaxx( );
int getmaxy( );
bool getrefreshingbgi( );
int getwindowheight( );
int getwindowwidth( );
int getpixel( int x, int y );
void getviewsettings( viewporttype *viewport );
int getx( );
int gety( );
void moverel( int dx, int dy );
void moveto( int x, int y );
void refreshbgi(int left, int top, int right, int bottom);
void refreshallbgi( );
void setbkcolor( int color );
void setcolor( int color );
void setfillpattern( char *upattern, int color );
void setfillstyle( int pattern, int color );
void setlinestyle( int linestyle, unsigned upattern, int thickness );
void setrefreshingbgi(bool value);
void setviewport( int left, int top, int right, int bottom, int clip );
void setwritemode( int mode );

// Window Creation / Graphics Manipulation
void closegraph( int wid=ALL_WINDOWS );
void detectgraph( int *graphdriver, int *graphmode );
void getaspectratio( int *xasp, int *yasp );
char *getdrivername( );
int getgraphmode( );
int getmaxmode( );
char *getmodename( int mode_number );
void getmoderange( int graphdriver, int *lomode, int *himode );
void graphdefaults( );
char *grapherrormsg( int errorcode );
int graphresult( );
void initgraph( int *graphdriver, int *graphmode, char *pathtodriver );
int initwindow
    ( int width, int height, const char* title="Windows BGI", int left=0, int top=0, bool dbflag=false, bool closeflag=true );
int installuserdriver( char *name, int *fp );    // Not available in WinBGI
int installuserfont( char *name );               // Not available in WinBGI
int registerbgidriver( void *driver );           // Not available in WinBGI
int registerbgifont( void *font );               // Not available in WinBGI
void restorecrtmode( );
void setaspectratio( int xasp, int yasp );
unsigned setgraphbufsize( unsigned bufsize );    // Not available in WinBGI
void setgraphmode( int mode );
void showerrorbox( const char *msg = NULL );

// User Interaction
int getch( );
int kbhit( );

// User-Controlled Window Functions (winbgi.cpp)
int getcurrentwindow( );
void setcurrentwindow( int window );

// Double buffering support (winbgi.cpp)
int getactivepage( );
int getvisualpage( );
void setactivepage( int page );
void setvisualpage( int page );
void swapbuffers( );

// Image Functions (drawing.cpp)
unsigned imagesize( int left, int top, int right, int bottom );
void getimage( int left, int top, int right, int bottom, void *bitmap );
void putimage( int left, int top, void *bitmap, int op );
void printimage(
    const char* title=NULL,
    double width_inches=7, double border_left_inches=0.75, double border_top_inches=0.75,
    int left=0, int right=0, int right=INT_MAX, int bottom=INT_MAX,
    bool active=true, HWND hwnd=NULL
    );
void readimagefile(
    const char* filename=NULL,
    int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX
    );
void writeimagefile(
    const char* filename=NULL,
    int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX,
    bool active=true, HWND hwnd=NULL
    );

// Text Functions (text.cpp)
void gettextsettings(struct textsettingstype *texttypeinfo);
void outtext(char *textstring);
void outtextxy(int x, int y, char *textstring);
void settextjustify(int horiz, int vert);
void settextstyle(int font, int direction, int charsize);
void setusercharsize(int multx, int divx, int multy, int divy);
int textheight(char *textstring);
int textwidth(char *textstring);
extern std::ostringstream bgiout;
void outstream(std::ostringstream& out=bgiout);
void outstreamxy(int x, int y, std::ostringstream& out=bgiout);

// Mouse Functions (mouse.cpp)
void clearmouseclick( int kind );
void clearresizeevent( );
void getmouseclick( int kind, int& x, int& y );
bool ismouseclick( int kind );
bool isresizeevent( );
int mousex( );
int mousey( );
void registermousehandler( int kind, void h( int, int ) );
void setmousequeuestatus( int kind, bool status=true );

// Palette Functions
palettetype *getdefaultpalette( );
void getpalette( palettetype *palette );
int getpalettesize( );
void setallpalette( palettetype *palette );
void setpalette( int colornum, int color );
void setrgbpalette( int colornum, int red, int green, int blue );

// Color Macros
#define IS_BGI_COLOR(v)     ( ((v) >= 0) && ((v) < 16) )
#define IS_RGB_COLOR(v)     ( (v) & 0x03000000 )
#define RED_VALUE(v)        int(GetRValue( converttorgb(v) ))
#define GREEN_VALUE(v)      int(GetGValue( converttorgb(v) ))
#define BLUE_VALUE(v)       int(GetBValue( converttorgb(v) ))
#undef COLOR
int COLOR(int r, int g, int b); // No longer a macro

#ifdef __cplusplus
}
#endif
// ---------------------------------------------------------------------------

#endif // WINBGI_H

A: If it works in C++ mode, but not in C mode, that tell me that it's probably a C++ library. The fact that you get syntax errors in C mode, but not in C++ mode, lends credence to this hypothesis.
Assuming this is what you're using (you should have specified that in your question), that's clearly C++ only, so no wonder you can't compile it as C code. You're hosed if you need to be able to use that library for C code. Still, you can write C-like code and just compile as C++ if you need. I just don't understand why you need to use a C++ library, but also need to compile as C and not C++.
Still, I'm only assuming that's the header file you're trying to include. Without further information on what you're trying to do, and exactly which library you're trying to use, I can only assume what the problem is.
EDIT: Based on the header you posted, it appears at first glance to be C compatible, except for including <sstream>. I have no idea if that's necessary or not. Someone with more experience might be a better resource to determine if that specific library would work in C.


text:
Q: A generalized ellipse We know that an ellipse is the locus of all point $z$ in the plane with $$|z-a|+|z-b|=\lambda$$
where $a,b$ are two given points in the plane and $\lambda$ is  a  constant.
Now we consider the following generalization:
For three given points $a,b,c \in \mathbb{R}^{2}$ define $$A_{\lambda}=\{z\in \mathbb{R}^{2} \;\text{with}\;\; |z-a|+|z-b|+|z-c|=\lambda\}$$

How is the geometric description of $A_{\lambda}$? Is it a closed curve, at least when $\lambda$ is very large?

More generally, assume that $G$ is  a compact topological group with Haar measure $\mu$. Assume that $G$ is topologically embedded in the plane. Define:
$$A_{\lambda}=\{z\in \mathbb{R}^{2} \;\text{with}\;\; \int_{G}  |z-g|d\mu=\lambda\}$$

Is the topology of $A_{\lambda}$ independent of choosing sufficiently large $\lambda$?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android-Notification: make ticker text stay longer I am working on JellyBean. The ticker text in notifications comes and goes away when the notification appears in the status bar.The notification icon stays there(in the status bar) until we clear the notification. Is it possible to keep the ticker text also in the status bar until the notification is cleared?

A: No, sorry -- the ticker text, like a Toast, is designed to be transient. After all, there are other things that go in the status bar that the ticker text replaces.


text:
Q: Using functions as applicative functors/cartesians I'm using the cats lib for this.
It's easy enough to combine two lists using their applicative functor instance (or Cartesian, to be precise):
import cats._
import cats.implicits._

(List(23, 4), List(55, 56)).mapN(_ + _)
>> List(78, 79, 59, 60)

However, I can't seem to be able to do the same with two functions:
val strLength: String => Int = _.length

(strLength, strLength).mapN(_ + _)
>> value mapN is not a member of (String => Int, String => Int)

It does work if I do some of the implicit conversions explicitly, and if I create a type alias to give the compiler a hand:
type F[A] = Function1[String, A]
val doubleStrLength = catsSyntaxTuple2Cartesian[F, Int, Int]((strLength, strLength)).mapN(_ + _)

doubleStrLength("hello")
>> 10

Is there an easier way to do this? Seems excessively verbose
Edit: I create a worksheet here if you wanna play with it: https://scastie.scala-lang.org/dcastro/QhnD8gwEQEyfnr14g34d9g/2

A: This only works if you have partial-unification enabled.
The easiest way to do so, is to add the sbt-partial-unification plugin.
If you're on Scala 2.11.9 or newer, you can also simply add the compiler flag:
scalacOptions += "-Ypartial-unification"


text:
Q: How do I open a WPF window in AddNew mode before any data has been loaded? I want to open a WPF4/EF4 form in AddNew mode so the user can start entering data in bound controls before any data has been selected from the database. I already have an "Add New Record" button but it only works with a populated DataContext (my CollectionViewSource). Here is the code so far:
private void btnAddNewRecord_Click(object sender, RoutedEventArgs e)
{
    LabSample newEntity = _labEntitiesContext.LabSamples.CreateObject<LabSample>();
    _labEntitiesContext.LabSamples.AddObject(newEntity);
    _labSamplesListCollectionView.AddNewItem(newEntity);
}

Background: This is a basic WPF app with bound controls. I started with an Entity Framework model that appears in my DataSources window. I dragged my LabSample entity from the DataSources window and let it create my CollectionViewSource (labSamplesViewSource) in the XAML's Windows.Resources section. The DataContext for all my controls is the labSamplesViewSource. I create a new LabEntities object called _labEntitiesContext as the window is instantiated. I use _labEntitiesContext to build my filtered ObjectQuery(of LabSample) and to SaveChanges, but I'm a little confused as to how this _labEntitiesContext is hooked up to my CollectionViewSource. If you could clarify this along with answering my question that would be helpful.  Note: I'm not ready to use MVVM.
When the window loads I use this.FindResource to grab a reference to the CollectionViewSource in a class level variable named _labSamplesCollectionViewSource. I allow the user to enter search fields to populate the screen with data. My LoadData routine looks something like this:
System.Data.Objects.ObjectQuery<LabSample> labSamplesObjectQuery = this.GetLabSamplesFiltered_Query(_labEntitiesContext, sampleID_LIKE, xxx_LIKE, yyy_LIKE);
System.Data.Objects.ObjectResult<LabSample> labSamplesObjectResult = labSamplesObjectQuery.Execute(System.Data.Objects.MergeOption.AppendOnly);
_labSamplesCollectionViewSource.Source = new System.Collections.ObjectModel.ObservableCollection<LabSample>(labSamplesObjectResult);
_labSamplesListCollectionView = (ListCollectionView)_labSamplesCollectionViewSource.View;

The _labSamplesListCollectionView class level variable set above is used in my btnAddNewRecord_Click code. Before LoadData is called the _labSamplesListCollectionView is null causing my AddNew code to fail with "Object reference not set to an instance of an object".
How can I make this work? I'm wondering if I should be making use of _labSamplesListCollectionView.AddNew instead of my current technique but I couldn't get that work either. Your help will be greatly appreciated.

A: I am writing an app that does something similar.  I am however using MVVM pattern, which allows me to do some neat things.  In mine, I am working with Shipments.  On the ShipmentsView, I can click an "Add New" button which fires off a bound command property which is housed in the associated ViewModel class.  That command methods looks like the following: Note: Views in this context are not CollectionView but refer to MVVM View classes.
Dim NewShipment = New Shipment()
_Context.AddToShipments(NewShipment)
Dim ShipVM = New ShipmentViewModel(NewShipment)
ShipmentVMCollection.Add(ShipVM)
Dim NewShipmentView as ShipmentView(ShipVM)

My ShipmentView handles it's placement and visiblility, and my Shipment object has it's property values initialized so that it does not immediately present errors via it's validation handlers.  This way the user can create a new shipment and if they get sidetracked they can save it and come back to it without having a bunch of mandatory fields.
When I use a CollectionViewSource, I populate it with an ObservableCollection of my entities, and then add the entities to that observable collection when I create them.  ObservableCollection implements INotifyPropertyChanged and INotifyCollectionChanged events and notifies the UI when something happens, and it all works through the CollectionViewSource.
You might take a look at the MVVM pattern which is really good for moving data and keeping it in the proper scope, and there are some good MVVM frameworks out there that will help you make a nice application with MVVM.
MVVM may be a bit of overkill for your app if it is small.  But if it gets over more than just a few Views it is going to get unwieldy and hard to move data back and forth and keep it current, and maintainable.
Wiki Article for MVVM - a pretty good place to start and get links
This is my Constructor for one of my ViewModels.  I realize you don't want to implement in MVVM right now, but a code behind would be similar.  In this instance, I am using a background worker to get my entity records, (the constructor call be for that and the View setting immediately afterward can be disregarded), then I link up my CVS, Populate it with my ObservableCollection, and set it's View to a field so I can filter on it later.
Public Sub New(ByRef MyView As NTMsView)
    Me.New(ViewManagerService.CreateInstance, ViewModelUIService.CreateInstance)
    NTMsBackgroundWorker.RunWorkerAsync()
    _View = MyView
    _NTMCollectionViewSource = _View.FindResource("NTMCollectionViewSource")
    _NTMCollectionViewSource.Source = NTMs
    _NTMCollectionView = _NTMCollectionViewSource.View
End Sub

This is an example of my AddRecord method.  Then I instance a new object, add it to the appropriate collection in the Context, Save it, execute a stored procedure, then refresh the context since the stored procedure did a few things to the record.  Then I add the object to my Observable.
Private Sub AddNTM()
    'Create an NTM Object.
    Dim NewNTM As New NTMShipment()
    'Add it to the context
    _context.AddToNTMShipments(NewNTM)
    _context.SaveChanges()
    _context.MakeNewSecurityID(NewNTM.NTMShipID)
    _context.Refresh(RefreshMode.StoreWins, NewNTM)
    'Wrap it in a ViewModel and Add it to the NTMs collection
    NTMs.Add(New NTMViewModel(NewNTM))
End Sub

As for creating a new entity before your CollectionViewSource is created, a couple of questions.  Is your edit forms datacontext related to the CVS?  In my forms, the CVS is only used in conjunction with ItemsControls since it is displaying a collection of items.  If your edit forms controls are dissociated from the CVS, you should not have much trouble populating them with a new entity and when it comes time to save, check to see if CVS is null and if so, create it then populate it.
If that is not a good answer, could you expand on how your application is structured?

A: Instead of opening the Window in AddNew mode I disable all data entry controls when the window loads or the when a search returns no records. When the "Add New Record" button is clicked I ALWAYS start over with a new data context that contains just one new entity. This means I have to prompt to save changes if any dirty (modified) records exist. The prompt allows the user to save changes, discard changes or continue editing (never entering AddNew mode). Here is the AddNew code:
MessageBoxResult response = PromptToSaveChanges(ReasonForPromptToSave.LoadingData);

if (response == MessageBoxResult.Cancel)  return;

LabSample newEntity = _labEntitiesContext.LabSamples.CreateObject<LabSample>();
_labEntitiesContext.LabSamples.AddObject(newEntity);

_labSamplesCollectionViewSource.Source = new ObservableCollection<LabSample>();
_labSamplesListCollectionView = (ListCollectionView)_labSamplesCollectionViewSource.View;

_labSamplesListCollectionView.AddNewItem(newEntity);
_labSamplesListCollectionView.CommitNew();
_labSamplesListCollectionView.Refresh();

Here are my steps to put the window in AddNew mode:
1) Prompt to save changes.
2) Create a new entity and add it to my data context.
3) Create a new ObservableCollection of my entity type and assign it to the .Source of my CollectionViewSource. Note the _labSamplesCollectionViewSource is a reference to the XAML's CollectionViewSource that was auto-generated by dragging a table from the data sources window.
4) Assign the .View of the CollectionViewSource to a class level ListCollectionView variable.
5) Add the new entity to the ListCollectionView that was just created.
6) Call CommitNew and Refresh on the ListCollectionView
I have answered my own question here, but keep in mind that the answer is the result of trial and error and may not be ideal. Regarding my confusion as to how the _labEntitiesContext is hooked up to the CollectionViewSource I believe the answer is in the line that reads _labSamplesListCollectionView.AddNewItem(newEntity), but I'd like to see an explanation of how all of the objects reference each other.
My final comment/question is that I'm disappointed at how hard it is to find a standard reference application or document that teaches non-MVVM WPF/Entity Framework databinding in detail. Microsoft promotes drag-and-drop binding but leaves us without a reference on how to build a complete application. I'll move on to MVVM soon, meanwhile if anyone can direct me to a GREAT resource or feature complete application that is WPF, non-MVVM and Entity Framework I would greatly appreciate it.


text:
Q: OLS with regression with a constant predictor Imagine for the sake of simplicity that I am regressing $Y$ on $X$  with the model
$Y = \beta_0 + \beta_1X + \epsilon$
Now imagine that observations on my $X$ are constant, e.g. take $Y = \{2, 7, 9\}$ and $X = \{3, 3, 3\}$. In this case, I am regressing $Y$ against a constant predictor. What is the statistical implication of this? Specifically, which of the assumptions of OLS am I breaking and Y does lm function in R produce NAs for the estimate of the coefficient $\beta_1$.

A: The estimated coefficient $\hat{\beta}_1$ is calculated as follows (using lm):
$$ \hat{\beta_1} = \frac{\sum_{i = 1}^n (x_i-\bar{x})(y_i-\bar{y})}{\sum_{i = 1}^n (x_i-\bar{x})^2}$$
You will get 0 in the denominator for constant x, and the fraction is not defined, so R gives you a NA output.


text:
Q: In ReactJS does my code have backing instances and therefore can use refs? I tend to write my ReactJS components by assembling bits of JSX together, example below.
I read this page https://facebook.github.io/react/docs/more-about-refs.html which says "Refs may not be attached to a stateless function, because the component does not have a backing instance"
What I am wondering is whether the code I am writing means I am writing stateless functions that do not have backing instances?
Or does my code have backing instances and therefore can use refs
I would like to be able to have refs to DOM elements, like:
    <input
      onChange={() = {console.log(e)}
      ref=**some ref callback function**
      value="rabbit"
    />

But I wonder if this is even possible given the coding approach I am taking.
example:
    import React, {Component, PropTypes} from 'react'

    export default class Blah extends React.Component {

      constructor(props) {
        super(props)
      }

      makeAnimal = () => {
        let animaltype = 'furry'
        if (animaltype === 'furry') {
          return (
            <input
              onChange={() = {console.log(e)}
              value="rabbit"
            />
          )
        } else {
          return (
            <input
              onChange={() = {console.log(e)}
              value="fish"
            />
          )
        }
      }

      makeForm = () => {
        let section = {}

        section.floob = (
            <input
              onChange={() = {console.log(e)}
              value="floob"
            />
        )

        section.flub = (
            <input
              onChange={() = {console.log(e)}
              value="flub"
            />
        )

        if (true) {
          return (

              {section.flub}

          )
        } else {
          return (

              {section.floob}
              {this.makeAnimal()}

          )
        }
      }

      render() {

        let section = {}

        section.extras = (

              The heading!

    )

    return (

        {section.extras}
        {this.makeForm()}

    )
  }
}

A: You're creating your components via classes therefore they are not stateless. A stateless component would look something like:
export default function Blah({ someProp, someOtherProp }) {
    return (

            {someProp}

    );
}

So in your code there keeping refs should work, however, the <input> component is stateless as it's not a react component, see wintvelt's answer below.


text:
Q: Should the DLQ on a Queue Manager *must* be a local queue on the QM? We are attempting to consolidate the DLQs across the board in our enterprise, into a single Q (an Enterprise_DLQ if you will...). We have a mix of QMs on various platforms - Mainframe, various Unix flavours - Linux,AIX,Solaris etc., Windows, AS/400....
The idea was to configure the DLQ on the QM (set the DEADQ attribute on the QM) to that of the ENTERPRISE_DLQ which is a Cluster Q. All the QMs in the Enterprise are members of the Cluster. This approach, however does not seem to work when we tested it.
I have tested this by setting up a simple Cluster with 4 QMs. On one of the QM, defined a QRemote to a non-existent QM and non-existent Q, but a valid xmitq and configure the requsite SDR chl between the QMs as follows:
QM_FR - Full_Repos
QM1, QM2, QM3 - members of the Cluster
QM_FR hosts ENTERPRISE_DLQ which is advertised to the Cluster
On QM3 setup the following:
QM3.QM1 - sdr to QM1, ql(QM1) with usage xmitq, qr(qr.not_exist) rqmname(not_exist) rname(not_exist) xmitq(qm1), setup QM1 to trigger-start QM3.QM1 when a msg arrives on QM1
On QM1:
QM3.QM1 - rcvr chl, ql(local_dlq), ql(qa.enterise_dlq), qr(qr.enterprise.dlq)
Test 1:
Set deadq on QM1 to ENTERPRISE_DLQ, write a msg to QR.NOT_EXIST on QM3
Result: Msg stays put on QM1, QM3.QM1 is RETRYING, QM1 error logs complain about not being able to MQOPEN the Q - ENTERPRISE_DLQ!!
ql(qm1) curdepth(1)
Test 2:
Set deadq on QM1 to qr.enterprise.dlq, write a msg to QR.NOT_EXIST on QM3
Result: Msg stays put on QM1, QM3.QM1 is RETRYING, QM1 error logs complain about not being able to MQOPEN the Q - qr.enterprise.dlq (all caps)!!
ql(qm1) curdepth(2)
Test 3:
Set deadq on QM1 to qa.enterise_dlq, write a msg to QR.NOT_EXIST on QM3
Result: Msg stays put on QM1, QM3.QM1 is RETRYING, QM1 error logs complain about not being able to MQOPEN the Q - qa.enterise_dlq (all caps)!!
ql(qm1) curdepth(3)
Test 4:
Set deadq on QM1 to local_dlq, write a msg to QR.NOT_EXIST on QM3
Result: Msg stays put on QM1, QM3.QM1 is RUNNING, all msgs on QM3 ql(QM1) make it to local_dlq on QM3.
ql(qm1) curdepth(0)
Now the question: Looks like the DLQ on a QM must be a local queue. Is this a correct conclusion? If not, how can I make all the DLQs msg go to a single Q - Enterprise_DLQ above?
One obvious solution is to define a trigger on local_dlq on QM3 (and do the same on others QMs) which will read the msg and write it to the Cluster Q - ENTERPRISE_DLQ. But this involves additional moving parts - trigger, trigger monitor on each QM. It is most desirable to be able to configure a Cluster Q/QRemote/QAlias to be a DLQ on the QM. Thoughts/ideas???
Thanks
-Ravi

A: Per the documentation here:

A dead-letter queue has no special requirements except that:

*

*It must be a local queue

*Its MAXMSGL (maximum message length) attribute must enable the queue to accommodate the largest messages that the queue manager has
  to handle plus the size of the dead-letter header (MQDLH)

The DLQ provides a means for a QMgr to handle messages that a channel was unable to deliver. If the DLQ were not local then the error handling for channels would itself be dependent on channels.  This would present something of an architectural design flaw.
The prescribed way to do what you require is to trigger a job to forward the messages to the remote queue.  This way whenever a message hits the DLQ, the triggered job fires up and forwards the messages.  If you didn't want to write such a program, you could easily use a bit of shell or Perl code and the Q program from SupportPac MA01.  It would be advisable that the channels used to send such messages off the QMgr would be set to not use the DLQ.  Ideally, these would exist in a dedicated cluster so that DLQ traffic did not mix with application traffic.
Also, be aware that one of the functions of the DLQ is to move messages out of the XMitQ if a conversion error prevents them from being sent.  Forwarding them to a central location would have the effect of putting them back onto the cluster XMitQ.  Similarly, if the destination filled up, these messages would also sit on the sending qMgr's cluster XMitQ.  If they built up there in sufficient numbers, a full cluster XMitQ would prevent all cluster channels from working. In that event you'd need some kind of tooling to let you selectively delete or move messages out of the cluster XMitQ which would be a bit challenging.
With all that in mind, the requirement would seem to present more challenges than it solves. Recommendation: error handling for channels is best handled without further use of channels - i.e. locally.


text:
Q: Ionic switch between tabs with parameters I have an app with tabs, where the first tab I show the latest post and an input search where a user can filter the results.
When user makes a search, I want to switch to the second tab, which will manage the search and display the results. I want to keep the first tab showing the latest post.
The code for switching to the second tab is:
    $scope.search_posts = function() {
        if ( !angular.isUndefined($scope.searchText) && $scope.searchText.length > 2 ) {
            $scope.searchText      = '';
            $scope.show_search_box = false;
            $ionicTabsDelegate.select($ionicTabsDelegate.selectedIndex() + 1);
        } else {
            $ionicLoading.show({ template: 'You must write at least 3 characters long.', noBackdrop: false, duration: 2000 });
        }
    }

...but I do not know how to send the 'searchText' as a parameter when switching.
How can I accomplish this?

A: you could use $rootScope to store shared data:
$scope.search_posts = function() {
    if ( !angular.isUndefined($scope.searchText) && $scope.searchText.length > 2 ) {
        $rootScope.searchTextFromTabOne = $scope.searchText;
        $scope.searchText = '';
        $scope.show_search_box = false;
        $ionicTabsDelegate.select($ionicTabsDelegate.selectedIndex() + 1);
    } else {
        $ionicLoading.show({ template: 'You must write at least 3 characters long.', noBackdrop: false, duration: 2000 });
    }
}

//in tab two's controller
$scope.searchText = $rootScope.searchTextFromTabOne;


text:
Q: Convert My MVC4 Web application to Android? I have a web application developed on .NET Framework using MVC4. So now I need to create a Android Application for it.

*

*Do I have to convert my entire C# code to Java (The code in
controllers in my MVC app)?

*Will it be better if I use Xamarin?

*Can I just create new Views for my application as I have controllers
and Models?

How do I approach this?

A: You won't be able to rip out your Models and Controllers directly from your MVC4 app and stuff it into an Xamarin.Android Application. However you will be able to reuse some of it. Especially the models.
At work I ported a Silverlight app to WP7/Android/iOS apps where a lot of the logic fetching data from servers, models and more were directly copy/pasted. However all the Views and logic for the Views had to be written from scratch as View Ports are different on a Computer monitor and a mobile device, and general UI is very different.
Also using the MVVM pattern helps separating the UI from the Model making the apps more testable and allows more code sharing. For this I use MvvmCross. There is also an MVC alternative called MonoCross. Both are free as in beer and as in speech. Both of these are for Xamarin.Android.
If you are only going to make an Android application and not going to be making it for other platforms as well and don't want to pay the price of the Xamarin products you should be able to make it in native Android. I don't see why this is possible. However you really need to find out what it is you want.
What does your Web App do? My guess is that it somehow manipulates some data in a database. So you would need to alter your Web App to expose that database in some kind of Web Service, maybe RESTful or otherwise.
You will need to layout your Android application such that the Views of the Web App you have fits into the smaller view ports of the mobile devices. A good too for this is to sketch your Android app out on paper and make arrows and annotations. You probably already know the model of your code in the Web App, it would be similar in your Android app. So get started coding the Views and then wire them up to the Web Service.
If you have read this far you might notice my answer is very vague. This is because your question is very vague.

A: I see more and more professional mobile app from different companies that are simply build upon the same companies' responsive Web Application (Website).
Either they use Cordova or some other technology, I can't say.
The architect is simple: 1- build a professional well-designed angularJs web application; 2- and then use Cordova to convert it to mobile apps (iOS, android, etc.).
Is it really that simple? hmmm.... maybe not! But theoretically it should work.
The good thing is Visual Studio still supports Cordova, even after Microsoft bought Xamarin.
https://www.visualstudio.com/vs/cordova/
You can start here:
https://taco.visualstudio.com/en-us/docs/get-started-first-mobile-app/
Happy Cross Platform Mobile Developing!


text:
Q: ValueError: Error when checking target: expected model_2 to have shape (None, 252, 252, 1) but got array with shape (300, 128, 128, 3) hi I am building a image classifier for one-class classification in which i've used autoencoder while running this model I am getting this error by this line (autoencoder_model.fit) (ValueError: Error when checking target: expected model_2 to have shape (None, 252, 252, 1) but got array with shape (300, 128, 128, 3).)
num_of_samples = img_data.shape[0]
labels = np.ones((num_of_samples,),dtype='int64')

labels[0:376]=0
names = ['cats']

input_shape=img_data[0].shape

X_train, X_test = train_test_split(img_data, test_size=0.2, random_state=2)

inputTensor = Input(input_shape)
x = Conv2D(16, (3, 3), activation='relu', padding='same')(inputTensor)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
encoded_data = MaxPooling2D((2, 2), padding='same')(x)

encoder_model = Model(inputTensor,encoded_data)

# at this point the representation is (4, 4, 8) i.e. 128-dimensional
encoded_input = Input((4,4,8))
x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded_input)
x = UpSampling2D((2, 2))(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Conv2D(16, (3, 3), activation='relu',padding='same')(x)
x = UpSampling2D((2, 2))(x)
decoded_data = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)

decoder_model = Model(encoded_input,decoded_data)

autoencoder_input = Input(input_shape)
encoded = encoder_model(autoencoder_input)
decoded = decoder_model(encoded)
autoencoder_model = Model(autoencoder_input, decoded)
autoencoder_model.compile(optimizer='adadelta',
 `enter code here`loss='binary_crossentropy')

autoencoder_model.fit(X_train, X_train,
            epochs=50,
            batch_size=32,
            validation_data=(X_test, X_test),
            callbacks=[TensorBoard(log_dir='/tmp/autoencoder')])

A: It's a simple incompatibility between the output shape of the decoder and the shape of your training data. (Target means output).
I see you've got 2 MaxPoolings (dividing your image size by 4), and three upsamplings (multiplying the decoder's input by 8).
The final output of the autoencoder is too big and doesn't match your data. You must simply work in the model to make the output shape match your training data.

A: You're using wrong API
autoencoder_model.fit(X_train, X_train,  <--- This one is wrong
        epochs=50,
        batch_size=32,
        validation_data=(X_test, X_test),
        callbacks=[TensorBoard(log_dir='/tmp/autoencoder')])

Take a look at .fit method source code
from https://github.com/keras-team/keras/blob/master/keras/models.py
def fit(self,
        x=None,
        y=None,
        batch_size=None,
        epochs=1,
        verbose=1,
        callbacks=None,
        validation_split=0.,
        validation_data=None,
        shuffle=True,
        class_weight=None,
        sample_weight=None,
        initial_epoch=0,
        steps_per_epoch=None,
        validation_steps=None,
        **kwargs):
    """Trains the model for a fixed number of epochs (iterations on a dataset).
    # Arguments
        x: Numpy array of training data.
            If the input layer in the model is named, you can also pass a
            dictionary mapping the input name to a Numpy array.
            `x` can be `None` (default) if feeding from
            framework-native tensors (e.g. TensorFlow data tensors).
        y: Numpy array of target (label) data.
            If the output layer in the model is named, you can also pass a
            dictionary mapping the output name to a Numpy array.
            `y` can be `None` (default) if feeding from
            framework-native tensors (e.g. TensorFlow data tensors).

So the x should be data, and the y should be label of the data.
Hope that help


text:
Q: Animated Ellipse Points I am using LineDDA to draw animated selection:
procedure TFormMain.DrawMarchingAnts;
begin
  AMarchingAntsCounter := AMarchingAntsCounterStart;
  // Use LineDDA to draw each of the 4 edges of the rectangle
  LineDDA(AMarchingAntsPointA.X, AMarchingAntsPointA.Y, AMarchingAntsPointB.X, AMarchingAntsPointA.Y,
    @MarchingAnts, LongInt(
    AMarchingAntsCanvas));
  LineDDA(AMarchingAntsPointB.X, AMarchingAntsPointA.Y, AMarchingAntsPointB.X, AMarchingAntsPointB.Y,
    @MarchingAnts, LongInt(
    AMarchingAntsCanvas));
  LineDDA(AMarchingAntsPointB.X, AMarchingAntsPointB.Y, AMarchingAntsPointA.X, AMarchingAntsPointB.Y,
    @MarchingAnts, LongInt(
    AMarchingAntsCanvas));
  LineDDA(AMarchingAntsPointA.X, AMarchingAntsPointB.Y, AMarchingAntsPointA.X, AMarchingAntsPointA.Y,
    @MarchingAnts, LongInt(
    AMarchingAntsCanvas));
  if AMarchingAntsPointB.X > AMarchingAntsPointA.X then
    ARubberbandVisible := True
  else
    ARubberbandVisible := False;
end;

Is there a function to add animated ellipses to the corners of the rect for grip points?

A: You want an animated "marching ants" circle? Then create a custom pen style. For example, as follows:
unit Unit1;

interface

uses
  Windows, Classes, Graphics, Controls, Forms, ExtCtrls, Math;

type
  TForm1 = class(TForm)
    Timer1: TTimer;
    procedure FormPaint(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    FMarkBrush: LOGBRUSH;
    FMarkPen: HPEN;
    FPenStyle: array[0..1] of Integer;
    FStartAngle: Single;
  end;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
  FPenStyle[0] := 4;
  FPenStyle[1] := 4;
  FMarkBrush.lbStyle := BS_SOLID;
  FMarkBrush.lbColor := ColorToRGB(clBlue);
  FMarkPen := ExtCreatePen(PS_GEOMETRIC or PS_USERSTYLE, 1, FMarkBrush, 2,
    @FPenStyle);
  Canvas.Pen.Handle := FMarkPen;
end;

procedure TForm1.FormPaint(Sender: TObject);
var
  X: Integer;
  Y: Integer;
begin
  Canvas.FillRect(Rect(0, 0, 50, 50));
  X := Round(25 * (1 + Cos(FStartAngle)));
  Y := Round(25 * (1 + Sin(FStartAngle)));
  Canvas.Arc(0, 0, 50, 50, X, Y, X, Y);
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  FStartAngle := FStartAngle + DegToRad(5);
  Invalidate;
end;

end.


text:
Q: error TS2339: Property '_ws' does not exist on type 'void' I've recently started with Angular2. After reading this articleI wanted to play around with websockets and reactive extensions. I used the websocket class from the article which compiled fine. The I wanted to call it from the ngOnInit method. I'm not entirely sure how to do this. So I created a new stance of the class and then initalised the wrapper method, but it didn't work. I'm just a little unsure of the syntax to init the method.
Thanks for the help.
let  message = 'test';
let ws = new WebSocketService();
let sock = ws.initializeWebSocket('www.google.com');

sock._ws.send();

sock._ws.close();

import { Injectable } from '@angular/core';
import {Observable}     from 'rxjs/Observable';
import 'rxjs/Rx';

@Injectable()
export class WebSocketService {
    private _wsObservable;
    private _ws;
    private _url  ='www.google.com';
    initializeWebSocket(_url) {
        this._wsObservable = Observable.create((observer) => {

            console.log('this._wsObservable');

            this._ws = new WebSocket(_url);

            this._ws.onopen = (e) => {
                console.log('onopen');

            };

            this._ws.onclose = (e) => {
                console.log('onclose');
                if (e.wasClean) {
                    observer.complete();
                } else {
                    observer.error(e);
                }
            };

            this._ws.onerror = (e) => {
                console.log('onopen');
                observer.error(e);
            };

            this._ws.onmessage = (e) => {
                console.log("this._wsObservable");
                observer.next(JSON.parse(e.data));
            };

            return () => {
                this._ws.close();
            };

        }).share();

    }

}

A: Try the following
@Injectable()
export class WebSocketService {
    private _wsObservable;
    private _ws;
    private self = this;
    private _url  ='www.google.com';
    initializeWebSocket(_url) {

and replace instances of this with self - you are getting this error as the annon function Observable.create is not bind this to the caller


text:
Q: Downgrade Safari Browser I have a MacBook Pro with OS X 10.8.5 and I have downloaded the wrong Safari browser, for OS X 10.10.
It says "You can't use this version of the application "Safari" with this version of OS X".
How to downgrade the incorrect version for OS X 10.10 and replace with the newest Safari for OS X 10.8.5?

A: From: Get the latest version of Safari for your Mac

You can keep Safari up to date by keeping macOS up to date.
Safari is included with your Mac. To get the latest version of Safari, install the latest macOS.
To keep Safari up to date for an earlier macOS, install the latest
  updates for that macOS.

Note: Updated to reflect changes in Apple Support HT204416 as of: Jun 15, 2017


text:
Q: Need a Simple Line Gradient Generator I need to write or find an application that will generate jpg line gradients, like the one below.

This application would probably be based on HTML5 or CSS3, which already have linear gradient generating commands, and would let the user chose the line width, line length, the colors and color positions, and will then generate a jpg that can be saved to a directory.  The application could be online or standalone.
Does anyone know of a application like this, or have some good ideas for writing one? Something in jQuery would be great!
Thanks

A: Here is a gradient stroke on canvas that can be saved as an image.

Example code:
<!doctype html>

<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />

    <button id="save">save</button>

    <canvas id="canvas" width=350 height=100></canvas>


text:
Q: How to import lwjgl_util I am trying to make a 3d lwjgl object, and have done so, but am getting an error telling me that I don't have the XPMFile. So I did some research, and have found that I need to load the XPMFile, but can't seem to find out how to do so. So I am wondering how to load the XPMFile for lwjgl_Util.
**EDIT**
Ok, I've decided to change the question to fit what I know now. The new Question is:
How do you import lwjgl_util, so that you don't get the XPMFile error???

A: have you put lwjgl_util.jar on the classpath? (i.e. the same place you put lwjgl.jar in eclipse).

A: This is the general package.
import org.lwjgl.util.*;


text:
Q: How to configure JBoss server in IntelliJ with server base dir and a settings.xml I'm trying to switch from Eclipse to IntelliJ Ultimate. But I have trouble configuring an application server.
What I have:

*

*IntelliJ IDEA Ultimate 2020.3

*a JavaEE application running on JBoss EAP 7.1

What I already achieved:

*

*Adding an application server in Settings -> Build, Execution, Deployment -> Application Servers: I added a JBoss Server and specified the JBoss home directory

*Adding a Run/Debug Configuration where I chose the JBoss server, added the artifacts which should be deployed, added some VM options, specified the JRE

Where I am stuck:
Here are the things I miss from the Eclipse configuration, and I can't find any documentation or help about that:

*

*In Eclipse, there is a "server runtime environment" which specifies a "server base directory" and a "configuration file" (settings.xml) in addition to the server home directory and JRE. Where can I find these settings in IntelliJ?

*Alternatively, there is the "launch configuration" in Eclipse, where you can define "program arguments" in addition to VM arguments. These also seem to set the server config and base dir.

Any help is highly appreciated. Thanks a lot!

A: There are instructions from IntelliJ site:
Application Servers
Application server run configurations
Update:
Basically you add your JBoss server
Settings->Application Servers- click + icon to add server
screenshot here
Then in run configurations you add and config  your JBoss server
screenshot here


text:
Q: Compiling the whole asp.net website on Mono at once i am compiling the asp.net web application page by page using "gmcs" command in Mono.
But i want to compile the whole asp.net website at once using Mono command.
For ex:
gmcs /t:library /out:bin/AJAX.dll -r:System.dll -r:System.Web.dll -r:bin/AjaxControlToolkit.dll  Default.aspx.cs Default.aspx.designer.cs
I do not want to do like the above one, instead i want to compile the whole folder containing files at once.
Plz let me know.thanks in advance

A: I used to run xbuild on projects created using Visual Studio as IDE. Worked perfectly! I'm not sure if MonoDevelop generates a .csproj file for your web application but that's the best way to compile ASP.NET, which, however, was supposed to be compiled automatically by xsp on the first request


text:
Q: Restoring Windows 7n Ultimate backup or system image to Windows 7 Ultimate I've been using Windows 7N via a key from a European friend for some time now, but have recently acquired a Windows 7 Ultimate (non-N) key:
I'd like to switch versions, partly for aesthetic reasons and partly because I've had impractically large issues with installing Microsoft's Feature Pack.
Is there any way I can backup to a system image/backup from the N version, perform a clean install of the non-N version and restore to it?


text:
Q: Flask socketio not receiving any message from javascript even after the connection is established I am trying to get response from javascript after the connection is established between the flask and javascript.The onconnect() function is working properly but onmessage() is not.
I tried broadcast along with the emit method in javascript too but it's not working.
This is my app.py
app=Flask(__name__)
bootstrap=Bootstrap(app)
socketio=SocketIO(app)

app.config['SECRET_KEY']="MY_KEY"

@app.route('/')
def login():
    return render_template('index.html')

@app.route('/home',methods=['GET','POST'])
def home():
    if(request.method=='POST'):
        data=request.form
        name=data['name']
        return render_template('message.html',name=name)
    else:
        return render_template('index.html')

@socketio.on('connect')
def onconnect():
    print("connect")

@socketio.on('message')
def onmessage(message):
    print('message')

if(__name__=='__main__'):
    socketio.run(app)

and this is my javascript file
const ws =io.connect(window.location.href)

ws.on('connect', function() {
  console.log("Connection estalished")
  ws.emit("adsd",broadcast=true)
});

EDIT:
There is a mistake in the javscript.
const ws =io()

This should be used for establishing the connection , not the previous method.
My Project is completed.
Link for the github project

A: First of all, only the server can broadcast, clients can only emit to the server.
Second, you are emitting an event named adsd, so you need to add a handler for that event in your server. For example:
@socketio.on('adsd')
def adsd_handler():
    print('got adsd!')


text:
Q: Having trouble incrementing runs by 100 for BirthdayParadox in Java I am writing a Birthday Paradox program in Java. I am having trouble using a for loop to increment a set by 100 so that it goes up to a maximum set of 10000. Each time the for loop is run it runs 1000 experiments in one set.
/**
* The class  BirthdayParadox is used to
* simulated the so-called Birthday paradox, and uses
* the class Statistics to store the results of
* the experiments.
*/

public class BirthdayParadox {

/**
    * Random generator
    */
private static java.util.Random generator = new java.util.Random();

/**
* Instance of the class Statistics
*/
private static Statistics stats;

/**
    * Runs the series of experiments, and stores the result into
    * a Statistics object
    *
    * @param range the size of the set from which random number are drawn
    * @param numberOfRuns the number of experiments to run
 *
 * @return a reference to a Statistics instance that holds the result
 * of the experiment
    */
public static Statistics runExperiments(int range, int numberOfRuns) {
     for (int i=0;i<numberOfRuns;i++) {
            stats.updateStatistics(oneRun(range));
     }
     return stats;
}

/**
    * Runs a single experiment.
    * The parameter range defines the size of the set from which
    * the experiment is drawn
    *
    * @param range the size of the set from which random number are drawn
    *
 * @return the number of random draw in the set that the method
 * used before drawing the same element for the second time
    */

private static int oneRun(int range){
     int counter=0;
     boolean foundTwice=false;
     int[] numberFound=new int[range];
     int number=0;
     while (foundTwice==false) {
            number=generator.nextInt(range);
            if (numberFound[number]==1) {
                foundTwice=true;
            }
            numberFound[number]++;
            counter++;
     }
     return counter;
}

/**
 * Main method. Runs the experiments numberOfRunstimes,
 * with increasingly large sets (increment in size:step).
 * Stop once the size reaches max.
 * plots the result.
 *
 * @param args if not empty, contains the runtime values for
 * step, max and numberOfRuns
 */

public static void main(String[] args) {
     if (args.length>1) {
            stats = new Statistics(Integer.parseInt(args[1]));
            stats = runExperiments(Integer.parseInt(args[0]), Integer.parseInt(args[1]));
            System.out.println(stats);
     }
     else {
        stats = new Statistics(10000);
        for (int i=100;i<10001;i+=100) {
            //stats = runExperiments(i,10000);
        }
            System.out.println(stats);
     }
}
}

I keep getting an ArrayIndexOutOfBoundsException of 10000.
This is my statistics class:
/**
 * The class  Statistics accumulates the results of
 * the experiments. It know ahead of time how many experiments
 * will be run, and provides at the end the min, the max, the
 * average and the standard deviation for the data.
 *
 * this class should not use classes such as Array,
 * Lists etc. to store the data, only prinitive types
 * and java arrays.
 */
public class Statistics {

    public static int numberOfRuns;
    public static int[] stats;
    public static int i=0;
    public static int tmp;
    public static int minimum=999999999;
    public static int maximum=0;

    /**
     * Constructor.
     *
     * @param numberOfRuns the number of experiments that will be run
     */
    public  Statistics(int numberOfRuns){
        this.numberOfRuns=numberOfRuns;
        stats=new int[numberOfRuns];
    }

    /**
     * Updates statistics after one experiment.
     * This method cannot be called more times than the
     * paramter that was passed in the constructor. If
     * it is, an error message should be printed and
     * no change should occur.
     *   @param value the result of the new experiment
     */
    public void updateStatistics(int value) {
        stats[i]=value;
        tmp=stats[i];
        if (tmp<minimum) {
            minimum=tmp;
        }
        if (tmp>maximum) {
            maximum=tmp;
        }
        i++;
    }

    /**
     *   @return the current average of the values passed
     * to the method updateStatistics
     */
    public double average(){
        double average=0.0;
        for (int i=0;i<numberOfRuns;i++) {
            average+=stats[i];
        }
        average/=numberOfRuns;
        average*=100;
        average=Math.round(average);
        average/=100;
        return average;
    }

    /**
     *   @return the current standard deviation of the values passed
     * to the method updateStatistic
     */
    public double standardDeviation(){
        double standardDeviation=0.0;
        double average=average();
        for (int i=0;i<numberOfRuns;i++) {
            standardDeviation+=Math.pow(stats[i]-average, 2);
        }
        standardDeviation/=numberOfRuns;
        standardDeviation=Math.sqrt(standardDeviation);
        standardDeviation*=100;
        standardDeviation=Math.round(standardDeviation);
        standardDeviation/=100;
        return standardDeviation;
    }

    /**
     *  @return Returns the complete statistics information:
     * current minimum, current maximim, current average and
     * current standard deviation. For the last two, only two
     * digits decimals are shown
     */
    public String toString(){

        return "We have run " + numberOfRuns + " experiments. \nThe minimum was: "+ minimum + "\nThe maximum was: " + maximum + "\nThe mean was: "+ average() + "\nThe standard deviation was: " + standardDeviation();
    }

}

A: stats = new Statistics(10000);  - is there are you create array for 10000 elements ? if yes - I guess you index them from 0 to 9999.
follow your for loop last element that will be processed is 10000, But you haven't such element.
Probably stats = new Statistics(10001); will solve problem
UPD:
if range is greater or equals than numberOfRuns (in runExperiments method) you can also get an exception, you may want to add validation/precondition here.
oneRun(10000) may return value 2..10001(inclusive) (!)
probably you wanted to break loop here:
if (numberFound[number]==1) {
  foundTwice=true;
  break;
}


text: Q: Advantage of setting window data on WM_CREATE According to Microsoft's docs, the way to set custom Window data is to pass it through the lpParam argument of CreateWindowEx, retrieve it within the window procedure on WM_CREATE, and then set it using SetWindowLongPtr.  I was wondering why you'd do that, instead of just setting it after calling CreateWindowEx, when you already have the window handle.  Thanks for any guidance, and sorry if this is a basic question.


text:
Q: Iterating the values of a submake I'm trying to automate some commands I use regularly in a Makefile, but I can't seem to figure out the right syntax for it.
Given the following targets:
.PHONY: params-list
params-list:
    @aws ssm get-parameters-by-path --path /${SERVICE}/${ENV} | jq -c -r '.Parameters[] | .Name'

.PHONY: params-get
params-get:
    @aws ssm get-parameter --name ${PARAM} --with-decryption | jq -c -r .Parameter.Value

I was attempting to call params-list and then feed the results into params-get. My best attempt was along the lines of:
.PHONY: params
params:
    for param in $(MAKE) params-list; do \
        $(MAKE) params-get PARAM=$${param}; \
    done

But obviously doesn't work. What's the right way of achieving this?

A: You could do a single (long) target/recipe as follows:
.PHONY: params-get
params-get:
    @for p in $$(aws ssm get-parameters-by-path --path /${SERVICE}/${ENV} | jq -c -r '.Parameters[] | .Name'); do \
        aws ssm get-parameter --name $$p --with-decryption | jq -c -r .Parameter.Value; \
     done

This assumes that your parameters don't have white spaces in them
------------  EDIT ---------------
To be able to access the parameters in another recipe, you can create a rule to create a file with the list of files in one recipe, and then access that file in another recipe as so:
# note that in this case .params-list is actually the name of a file,
# but it is declared as phony to force it to be rebuilt every time.
.PHONY: .params-list
.params-list:
    aws ssm get-parameters-by-path --path /${SERVICE}/${ENV} | jq -c -r '.Parameters[] | .Name' > $@

.PHONY: params-get
params-get: .params-list
    @for param in $$(cat .params-list); do \
       aws ssm get-parameter --name $${param} --with-decryption | jq -c -r .Parameter.Value; \
     done;

A: One hint is to eschew shell constructs for make ones. Going one step at a time here.
For the get operation, we encode one target for each param. So for param p1 (say), we invent a target params-get<p1>. We note that inside the recipe (i.e., the shell commands) that $@ will expand to params-get<p1>. Therefore ${@:params-get<%>=%} will expand to p1.
Writing this out in make syntax:
.PHONY: params-get<p1>
params-get<p1>:
      @aws ssm get-parameter --name ${@:params-get<%>=%} --with-decryption | jq -c -r .Parameter.Value

I note that with an intermediate variable we can have exactly the same recipe you used in your earlier incantation.
PARAM = ${@:params-get<%>=%}

.PHONY: params-get<p1>
params-get<p1>:
      @aws ssm get-parameter --name ${PARAM} --with-decryption | jq -c -r .Parameter.Value

If we have a second param pa (say), that's easy to add:
PARAM = ${@:params-get<%>=%}

.PHONY: params-get<p1> params-get<pa>
params-get<p1> params-get<pa>:
      @aws ssm get-parameter --name ${PARAM} …

I hope you can see some boiler plate appearing here.
Moving towards some more dynamically generated make, rather than hard-coding each param, let's put all the possible params in a list called $PARAMS
PARAMS := p1 pa another
get-targets := ${PARAMS:%=params-get<%>}

PARAM = ${@:params-get<%>=%}

.PHONY: ${get-targets}
${get-targets}:
      @aws ssm get-parameter --name ${PARAM} …

.PHONY: params-get
params-get: ${get-targets}
      echo $@ Done

I have added your original params-get target. Now all the work is done by dependencies.

*

*No shell loop in sight.

*The exit code of each aws ssm get-parameter is checked by make.

*The code is parallel safe: make -j9 will run 9 jobs in parallel until the work is exhausted. Nice if you have 8 CPUs. (If your make is not parallel safe then it is broken by the way.)

We are pretty close now. We just have to ensure $PARAMS is set to the output of ssm get-parameters-by-path.
Something like:
.PHONY: params-list
params-list:
    @aws ssm get-parameters-by-path --path /${SERVICE}/${ENV} | jq -c -r '.Parameters[] | .Name'

PARAMS := $(shell ${MAKE} params-list)
get-targets := ${PARAMS:%=params-get<%>}

PARAM = ${@:params-get<%>=%}

.PHONY: ${get-targets}
${get-targets}:
      @aws ssm get-parameter --name ${PARAM} --with-decryption | jq -c -r .Parameter.Value

.PHONY: params-get
params-get: ${get-targets}
      echo $@ Done

Definitely not a fan of using $(shell …), but this is just a sketch.


text:
Q: Qty Control in C# pstrjds, From the code you have provided I am trying to implement that code and the msdn link you provided couple of days ago. I am not sure how to put it together but I am see a message that "The variable name '@ID' has already been declared. Variable names must be unique within a query batch or stored procedurce." Do I need to create a stored procedurce? Can I assume I got the ID bit right as well, where you explained number of times?   Thank you.
           enter code here
        cs.Open();
        int remainingStock = 0;
        string Query = "SELECT StockA SET QTY = @QTY " + "WHERE ID = @ID;";
           SqlCommand cmd = new SqlCommand(Query, cs);
            cmd.Parameters.Add("@ID", SqlDbType.Int);
            cmd.Parameters["@ID"].Value = 1;
            cmd.Parameters.AddWithValue("@ID", Query);
            try
            {
                if (remainingStock == 1)
                {
                    lbqty.Text = "Not enough stocks.";
                }
                else
                {
                    cmd.CommandText = "UPDATE StockA SET QTY = QTY-1
                    WHERE ID=1";
                    int rowsUpdated = cmd.ExecuteNonQuery();
                    remainingStock--;
                    string remaining = "Remaining stocks: " +
                    remainingStock.ToString();
                    txQty.Text = remaining;
                    lbqty.Text = remaining;
                    DGA.Update(); //this is DataGridView
                }
                Int32 rowsAffected = cmd.ExecuteNonQuery();
                Console.WriteLine("RowsAffected: {0}", rowsAffected);

            }
            catch (Exception ex)
            {
               MessageBox.Show(ex.Message);
            }
            cs.Close();

    }

A: The problem is that you don't check for the case where ret == -1. Changing your second if-statement to if(ret < 1) should fix your issue.
Also, directly after the line cmd.ExecuteNonQuery(); add ret--; to sync the ret variable with the value that is now in the database.

A: I think this is your problem - you make ret - 1 while processing and then
txtQty.Text = "Remaining stocks: " + (ret - 1).ToString();
lbqty.Text = "Remaining stocks: " + (ret - 1).ToString();

that shows one less item. Try making it:
txtQty.Text = "Remaining stocks: " + ret.ToString();
lbqty.Text = "Remaining stocks: " + ret.ToString();

A: Your application flow should be as following;
protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection c = new SqlConnection("Data Source=.; Integrated Security=SSPI; Initial Catalog=FA");

        SqlCommand cmd = new SqlCommand();
        cmd.Connection = c;
        c.Open();

        // get remaining stocks
        cmd.CommandText = "SELECT Qty from TEST WHERE Id=1";
        int ret = Convert.ToInt32(cmd.ExecuteScalar().ToString());

        if (ret == 0)
        {
            Label1.Text = "Not enough stocks.";
        }
        else
        {
            cmd.CommandText = "UPDATE TEST SET Qty = Qty-1 WHERE Id=1";
            cmd.ExecuteNonQuery();

            if (ret == 2)
            {
                Label1.Text = "Re-order. Remaining stocks: 1";
            }
            else
            {
                Label1.Text = "Remaining stocks: " + (ret-1).ToString();
            }
        }

        c.Close();
    }

A: After reading your question again, I am more convinced that the comment I posted is actually the problem. You said in your question that your quantity is not going down. If you look at the return value from the line:
cmd.ExecuteNonQuery();

in your else statement I believe you will get a value of 0. This indicates that no records where updated. I believe the problem is exactly related to your query. If you connect to your database with a utility such as LINQPad or the Sql Management studio and run the query you have listed in your code I think you will find it is not updating anything. I highly suspect that your inventory is not being stored in a table called tblContacts. Which is why you can't select a quantity from it nor update a quantity in it.
Edit:
Meant to mention this initially and then got sidetracked and forgot to add it. I would put your SqlCommand in a using statement. The SqlCommand object is disposable and so it is good practice to place disposable objects in a using statement or in some sort of try/finally pattern where they can be cleaned up.
Additional edit - restructuring your code:
    cs.Open();
    int remainingStock = 0;
    string Query = "SELECT QTY from tblInventory WHERE ID=19";
    using(SqlCommand cmd = new SqlCommand(Query, cs))
    {
        var result = cmd.ExecuteScaler();
        if (result != null)
        {
            string str = result.ToString();
            if (!string.isNullOrWhiteSpace(str))
            {
                // NOTE: It would probably be safer to use int.TryParse here
                remainingStock = Convert.ToInt32(cmd);
            }

            if (remainingStock == 0)
            {
                lbqty.Text = "Not enough stocks.";
            }
            else
            {
                cmd.CommandText = "UPDATE tblInventory SET QTY = QTY-1 WHERE ID=19";
                int rowsUpdated = cmd.ExecuteNonQuery();
                remainingStock--;

                if (remainingStock == 1)
                {
                    lbqty.Text = "Re-order. Remaining stocks: 1";
                }
                else
                {
                    string remaining = "Remaining stocks: " + remainingCount.ToString();
                    txtQty.Text = remaining;
                    lbqty.Text = remaining;
                }
            }
        }
        else
            lbqty.Text = "No stock for contact";
        }

        dgUpdate();
    }
    cs.Close();

A: The fist thing i can see is that this in not right
 if (ret == 1)
        {
            lbqty.Text = "Re-order. Remaining stocks: 1";
            dgUpdate();
        }
        else

should be
 if (ret - 1  == 1)
        {
            lbqty.Text = "Re-order. Remaining stocks: 1";
            dgUpdate();
        }
        else

because when the value you read is 1 and you decrease it its 0.


text:
Q: SwiftUI doesn't refresh until button action finishes I want the view to be updated every time @State list gets updated.
But when I use Button to trigger a consecutive update, the list gets updated only after all the consecutive updates are finished.
This code updates the list 10 seconds after the button is pressed.
What should I do to make this code update every second?
@State var i_list: [Int] = []

var body: some View {
    VStack {
        Button(action: {
            for i in 0..<10 {
                i_list.append(i)
                do {
                    sleep(1)
                }
            }
        }) {
            Text(button_text)
        }

        List (i_list, id: \.self){ i in
            Text(String(i))
        }
    }
}

Solved:
I solved this problem by updating the list in a different thread.
let globalQueue = DispatchQueue.global()
globalQueue.async {
    for i in 0..<10 {
        DispatchQueue.main.async {
            i_list.append(i)
        }
        do {
            sleep(1)
        }
    }
}

A: If you want to see your view updates immediately, instead of using a for loop to update your array, use a publisher. Here I use a timer and add a onReceive(timer) on the List
struct ContentView : View {
    @State var i_list: [Int] = []
    @State var currentNumber = 0
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    var body: some View {
        VStack {
            List (i_list, id: \.self) { i in
                Text(String(i))
            }.onReceive(timer) { _ in
                guard currentNumber < 10 else {
                    return
                }
                i_list.append(currentNumber)
                currentNumber += 1
            }
        }
    }
}

Edit: changed currentNumber to @State


text:
Q: Unwanted permanent umount The problem
I've got a simple question: what's the difference between ejecting flash drive using GNOME Files (formerly known as Nautilus) button (see image below) and umount command?

Before you will read rest of this question I encourage you to think if you expect any difference between results of clicking eject button in GNOME Files and typing umount command? If yes, then what's the difference? If no, then read on...

1st try: GNOME Files eject
When I insert my flash drive to my computer's USB socket, Debian automatically mounts it, which is reflected both in GNOME Files:

and command line using e.g. df command:
me@host:~$ df -h
Filesystem      Size  Used Avail Use% Mounted on
(...)
/dev/sdf1       3,6G  3,6G     0 100% /media/me/Debian 9.1.0 amd64 1

or blkid command:
root@host:~# blkid
(...)
/dev/sdf1: UUID="XXXX-XX-XX-XX-XX-XX-XX" LABEL="Debian 9.1.0 amd64 1" TYPE="iso9660" PTUUID="XXXXXXXX" PTTYPE="dos" PARTUUID="XXXXXXXX-XX"
/dev/sdf2: SEC_TYPE="msdos" UUID="XXXX-XXXX" TYPE="vfat" PARTUUID="XXXXXXXX-XX"

When I click eject button marked with a red circle:

and I run those commands once again, there is no sdf string in commands' output (which is probably what I should expect after ejecting /dev/sdf1):
root@host:~# df -h | grep sdf
root@host:~# df -ah | grep sdf
root@host:~#

Note that I added -a (--all) flag to df command and I got the same (empty) result.
root@host:~# blkid | grep sdf
root@host:~#

Note that now I'm unable to remount /dev/sdf1 without reinserting my flash drive:
root@host:~# mkdir -p /mnt/test
root@host:~# mount /dev/sdf1 /mnt/test
mount: special device /dev/sdf1 does not exist

2nd try: umount command
Now repeat the hole procedure with only changing the way I unmount my flash drive. Instead of clicking eject button, I type:
umount /dev/sdf1

Here is the result of df:
root@host:~# df -h | grep sdf
root@host:~# df -ah | grep sdf
root@host:~#

df result is probably as expected because it's the same as above... but here comes the blkid:
root@host:~# blkid | grep sdf
/dev/sdf1: UUID="XXXX-XX-XX-XX-XX-XX-XX" LABEL="Debian 9.1.0 amd64 1" TYPE="iso9660" PTUUID="XXXXXXXX" PTTYPE="dos" PARTUUID="XXXXXXXX-XX"
/dev/sdf2: SEC_TYPE="msdos" UUID="XXXX-XXXX" TYPE="vfat" PARTUUID="XXXXXXXX-XX"

Note that remounting works fine in opposite to the previous try:
root@host:~# df -h | grep sdf
root@host:~# mkdir -p /mnt/test
root@host:~# ls /mnt/test | wc -l
0
root@host:~# mount /dev/sdf1 /mnt/test
mount: /dev/sdf1 is write-protected, mounting read-only
root@host:~# ls /mnt/test | wc -l
24

The question
Why is that?
What is the precise, underlying reason of above differences in blkid output? Does GNOME Files do something more than umount command? It seems to me that GNOME File eject button is kind of 'permanent' unmount. Why?


text:
Q: Secure API access with mobile apps in restricted environments In our current project, IT rules prohibit anything that is not PROD to be publicly accessible from the Internet. Access to development and review environments must be severely restricted. That said, the project also includes mobile apps that are developed together with the cloud-hosted API layer.
In very general terms, what are the common approaches to securing DEV / REVIEW-stage APIs with mobile apps? We've come up with the following ideas:

*

*IP whitelist on the ingress to the API (least secure, but easiest to use)

*VPN gateway to the hosting environment, with corresponding DEV / test devices configuration

*Mutual TLS authentication (most difficult to implement and operate)
There are multiple issues to address with each one of the approaches, but I'd like to understand the big picture before diving into any of that.

A: IP Whitelist

IP whitelist on the in the ingress to the API (least secure, but easiest to use)

I see it as least secure if you are whitelisting IPs that are not exclusive to your company office and/or the the IP is exclusive to your company but used by public WI-fis in your company.
Also in the case you need to whitelist access to remote developers and testers that may or not be in a public IP, this solution will be risky, because people always put convenience in front of security and they may ask to whitelist IPs that are from the coffee shop they like to work from, the shopping mall, the girl friend home, etc..
So I would discard this option, unless you are in a small office where you have the public WI-fi(the one for your clients to use) in a different IP from your main internet connection.
VPN Gateway

VPN gateway to the hosting environment, with corresponding DEV / test devices configuration

This approach seems to be the much wise to follow and only who have been granted access to the VPN will be able to use resources hidden behind it, and VPNs can be even used in public WI-fi.
Mutual TLS Authentication

Mutual TLS authentication (most difficult to implement and operate)

While is difficult to implement and operate they also suffer of the problem of certificate pinning be possible to bypass.
On this article about pinning in mobile apps we can read how easy it can be to implement certificate pinning:
// simplified android example

CertificatePinner certificatePinner = new CertificatePinner.Builder()
       .add("publicobject.com", "sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=")
       .add("bikewise.org", "sha256/x9SZw6TwIqfmvrLZ/kz1o0Ossjmn728BnBKpUFqGNVM=")
       .build();

OkHttpClient client = OkHttpClient.Builder()
         .certificatePinner(certificatePinner)
         .build();

In this same article we can also see how pinning can be a nightmare... as you said, difficult to operate!!!

The main difficulty with pinning is not technical but operational. By embedding fixed information about the server (the certificate) into the app you create a dependency between the two, as the term pinning implies. This means that whenever you (or your ops team) are planning to change the certificate on the server you must:

*

*Generate the certificate in advance

*Build, test and publish a new version of the app with both the new certificate and the old one.

*Wait for most (80%, 90%, 99% ?) of your users to upgrade to the new version

*Change the cert on the server

*Build, test and publish a new version of the app with the old certificate removed.

As if this was not enough, certificate pinning can be by passed by using introspection frameworks, as pointed on the same article I linked above:

Even if you successfully navigate the operational difficulties inherent in implementing pinning, there is still the giant pink elephant in the room that is unpinning. The development of hooking frameworks such as Xposed has reached such a level of sophistication that a rich ecosystem of modules exists to target various aspects of Android apps including the pinning functionality of HTTP libraries. Using them is very straightforward.

Another Approach - Going the extra mile

That said, the project also includes mobile apps that are developed together with the cloud-hosted API layer.

In the context of a mobile apps you can use a technique devised as Mobile App Attestation, that can be used across all environments to protect the API server, for the mobile apps, from responding to requests that are not originated from the genuine mobile app binary you released, signed and registered for that specific environment.
Mobile App Attestation
The role of a Mobile App Attestation service is to guarantee at run-time that your mobile app was not tampered or is not running in a rooted device. It consists of a SDK integrated in a your mobile app that runs in the background, without impacting the user experience, and  communicates with a service running in the cloud to attest the integrity of the mobile app and device is running on.
On successful attestation of the mobile app integrity a short time lived JWT token is issued and signed with a secret that only the API server and the Mobile App Attestation service in the cloud are aware. In the case of failure on the mobile app attestation the JWT token is signed with a secret that the API server does not know.
The mobile app must send the JWT token in the headers of the request for very API call it makes. This allows the API server to only serve requests when it can verify the signature and expiration time in the JWT token and refuse them when it fails the verification.
Anyone trying to verify at run-time if a JWT token issued by the Mobile App Attestation is a valid or invalid one will not succeed, because the only difference between them is the secret used to sign it, and this secret is only known at anytime by the Mobile App Attestation service and the API server. This means that even the mobile app is not in possession of the secret, thus is not aware if is sending a valid or invalid JWT token to the API server.
Conclusion
From your 3 solutions I would go with VPN approach and if you would want to go for the extra mile you should consider implement your own Mobile App Attestation service to guarantee that mobile APIs for any environment only communicate with mobile apps for that specific environment/stage and deny requests from any other source. This solution even allows for your mobile API to be hosted on the public domain without risking leaking any data, thus not needing a VPN on front of it.


text:
Q: Enable script tags with different type? Changing type attribute is not enought is possbile to run code that previosly were of an ignored content type. Example:
<script type="jquery">alert('WORKING!')</script>

Of course this tag will be ignored and not i would like to enable it. I tried with this:
$(document).ready(function() {
    $('script[type=jquery]').attr('type','text/javascript');
});

But nothing happens :/
Thanks for help!

A: Yes you can do it, but your only option is recreate new script tag and remove existing:

$(document).ready(function() {
    $('script[type=jquery]').each(function(){
        $(this).after(this.outerHTML.replace('jquery','text/javascript')).remove();
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script type="jquery">alert('WORKING!')</script>


text:
Q: How do I get a basic working example for django-user-account? I followed the installation instructions on  django-user-accounts.
When calling http://[mysite]/account/signup
I could see:{# This template intentionally left blank to satisfy test suites. Your project should always provide a site_base.html itself. #} (and I take it as a good sign, I'll add my base template later).
After that, i created an app: ./manage.py startapp myapp_account
...and filled it with the minimum code from the "Usage" page of the manual mentioned above as i want to get a basic working register/login/out.
Now i get an error when calling http://[mysite]/account/signup/:
Exception Value:     'module' object has no attribute 'views'
Exception Location:  /var/www/venv/django_1/django_1/urls.py in <module>, line 10
Python Executable:   /var/www/venv/bin/python3.4

my code:
urls.py (main project called django_1):
from django.conf.urls import patterns, include, url
import myapp_account

urlpatterns = patterns('',
    # this is line 10 in my case:
    url(r'^account/signup/$', myapp_account.views.SignupView(),name="account_signup"),
    url(r'^account/', include('account.urls')),
)

myapp_account/views.py:
import account.views
import account.forms
import myapp_account.forms

class SignupView(account.views.SignupView):

    form_class = myapp_account.forms.SignupForm

    def after_signup(self, form):
        self.create_profile(form)
        super(SignupView, self).after_signup(form)

    def create_profile(self, form):
        profile = self.created_user.get_profile()
        profile.birthdate = form.cleaned_data["birthdate"]
        profile.save()

class LoginView(account.views.LoginView):
    form_class = account.forms.LoginEmailForm

myapp_account/forms.py
from django import forms
from django.forms.extras.widgets import SelectDateWidget
import account.forms

class SignupForm(account.forms.SignupForm):
    birthdate = forms.DateField(widget=SelectDateWidget(years=range(1930, 2010)))

Is there a simpler way do get it working and be on the right track to extend the user accounts step by step?

A: As usual the answer was in the manual Django, Class-based views
:

*

*Import the class based view directly

*Call the class based view directly in the url

updated urls.py (main)
from django.conf.urls import patterns, include, url
from myapp_account.views import SignupView # <- import class based view

urlpatterns = patterns('',
    # call class based view directly:
    url(r'^account/signup/$', SignupView.as_view(), name="account_signup"),
    url(r'^account/', include('account.urls')),
)

Still i'd be happy if someone cloud point me to a well made example of django-user-accounts.


text:
Q: Extract appointments from pst file without loop I use Independentsoft.Pst to extract appointments from pst file but the problem is that a for loop is going over the entire appointments of the file, which is taking some time in very big files. Ill be very happy if someone could show me a way to do that with no loop or a way to convert the Independentsoft.Pst itemCollection to an array.
my code:
Public Function getAppointment(ByVal file As String) As List(Of String)
    Dim AppointmentDetails As New List(Of String)
    Dim App As New List(Of ItemCollection)
    Dim calendar As Folder
    Dim PSTfile = New PstFile(file)
    Dim delta As TimeSpan = MonthCalendar1.SelectionEnd - MonthCalendar1.SelectionStart
    Dim DelResult As Integer = delta.Duration.Days

    Using PSTfile
        calendar = PSTfile.MailboxRoot.GetFolder("calendar")
        If calendar IsNot Nothing Then
            Dim items As ItemCollection = calendar.GetItems()

            For m As Integer = 0 To items.Count - 1
                If TypeOf items(m) Is Appointment Then
                    Dim appointment As Appointment = DirectCast(items(m), Appointment)

                    AppointmentDetails.Add(appointment.Subject)
                    AppointmentDetails.Add(appointment.CreationTime)
                    AppointmentDetails.Add(appointment.CreationTime.Date)
                    AppointmentDetails.Add(appointment.Duration)
                End If
            Next
        End If
    End Using
    Return AppointmentDetails
End Function

A: Do you mean finding an appointment based on some particular value of one of its properties.
Here's some code using PIA.
Private Shared Function GetAppointmentsFolder() As Outlook.MAPIFolder

    Dim result As Outlook.MAPIFolder = Nothing

    If OutlookApp.ActiveExplorer.CurrentFolder.DefaultItemType = Outlook.OlItemType.olAppointmentItem Then
        result = OutlookApp.ActiveExplorer.CurrentFolder
    End If

    If result Is Nothing Then
        result = OutlookApp.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar)
    End If
    Return result

End Function

Public Function GetAppointment(billingInfo as string) As Outlook.AppointmentItem

Dim appointmentsFolder As Outlook.MAPIFolder = GetAppointmentsFolder()
    'Try to find an existing appointment (Using Find() Locates and returns an Outlook item object that satisfies the given Filter..)
    Dim outlookAppointmentItem As Outlook.AppointmentItem = CType(appointmentsFolder.Items.Find("BillingInformation]=""" & pstrAppointmentId & """"), Outlook.AppointmentItem)

    Return outlookAppointmentItem

End Function


text:
Q: Bypass openvpn for particular ip My desktop machine runs Trisquel GNU/Linux 6.0 (which is basically a libre version of Ubuntu 12.04), and I use OpenVPN to connect to a commercial VPN provider for internet access.
It currently routes all my traffic through the VPN, which is great, but I'm looking for a way to allow requests to one specific IP address to bypass the VPN. I'm sure there's a way but repeated web searching hasn't yet turned up anything (best I could find were instructions for doing this on the Cisco VPN client for Windows).
Can you help?
Thanks.

A: ip route add to $network/$mask via $gateway

A: Simply add a route for that IP to your local gateway.
You can do this in your openvpn client config like this.
route 10.99.77.55 255.255.255.255 net_gateway

In the config net_gateway is automatically replaced with the correct address.

A: route 10.99.77.55 255.255.255.255 net_gateway

I used this code line in ovpn config so it worked.
Now I want to bypass an IP range instead of single IP, How can I do it?
something like that:
route 10.99.77.55/22 255.255.255.255 net_gateway


text:
Q: Inheritance in entity framework - Table per concrete class? I have an existing database containing an article and a blog table. These have common columns such as title, author repeated in the two tables. I want to utilise entity framework to create a Content entity that pulls in the common properties so i can inherit the Content entity in the Article and Blog entity.
The idea being that I can say ok just get me all the content on the site in the last 10 days, i dont care whether its a blog or article. Then when i need to actually fetch an article ill go get the specific entity.
I have set up a content entity base and pulled in all the common blog and goal properties. Problem is what im trying to say in Contents. Ive got TWO mappings one to blog table  and one to article table and EF complains that it cant work out which one to goto. I was hoping to add conditions to do this but if i add a blog specific condition (thats not listed in my base class) it complains it cant find the mapping.
I spose my first question is am I looking at this totally backwards in order to make my Contents entity get data from article table and blog table?
Thanks
Phil
Edit : Adding model and db schemas

A: I'm not familiar with Entity but could you create a view in the database which contains all of the common data plus an extra key which identifies the record as either a blog or article.
You could then add the view to your Entity model, use that to fulfill your "get content from last 10 days" use case, and then when you need further detail, use the extra key you added to the view to determine whether you need to go to the blog or article entities. I know this isn't as clean and tidy as you want, but it may do the job.

A: As it's mentioned here there is no TPC inheritance support in EF ADO.NET Designer (but EF initially). So that must be either implemented manually in xml, or by Code First.


text:
Q: Sorting the lines in a CSV according to those containing numbers and those without I have a 4-column CSV file. I want to sort the lines, such that, the lines containing any number somewhere within the third column are pushed to the end of the document, lines without numbers in the third column are put to the beginning. How can I sort the file in this way?
Update:
To clarify, I need to move lines which contain any number (i.e. a match for [0-9]) somewhere within the letters of the third column (the third column of the line might contain other symbols). Spaces are not important. E.g.
dog, eats chicken, has 4 legs, does not like cats
cat, eats mice, has a tail, does not like water
mouse, eats bugs, has 4 legs, does not like cats
elephant, eats peanuts, has a trunk, does not like mice

Would be sorted to:
cat, eats mice, has a tail, does not like water
elephant, eats peanuts, has a trunk, does not like mice
dog, eats chicken, has 4 legs, does not like cats
mouse, eats bugs, has 4 legs, does not like cats

A: Something like this should work:
awk 'BEGIN {FS=","; OFS=","}; {print match($3,/[0-9]/), $0}' <file> | sort | cut -d, -f2-

The strategy is to

*

*use awk to insert at the beginning of each line the index in which a digit is found (or 0 if no digit is found)

*use sort to sort all the lines

*finally, use cut to remove the number that was prepended by awk.

A: This is a short 1-liner in awk that does not require calling other utilities such as sort
awk -F',' '$3 ~ /[[:digit:]]/{a[$0];next}1; END{for(i in a)print i}' ./infile

Explanation

*

*If the 3rd field contains a digit, store the current line as the key in array 'a' and process the next line

*Output all lines as-is if they don't match the rule above

*After all lines have been processed, output the lines that we stored in array 'a'

Output
$ awk -F',' '$3 ~ /[[:digit:]]/{a[$0];next}1; END{for(i in a)print i}' ./infile
cat, eats mice, has a tail, does not like water
elephant, eats peanuts, has a trunk, does not like mice
mouse, eats bugs, has 4 legs, does not like cats
dog, eats chicken, has 4 legs, does not like cats

A: This might work for you:
sed 'h;s/,/\n/2;s/.*\n/0/;s/,.*//;s/[^0-9]//g;G;s/\n/\t/' file |
sort -k1,1n -k2 |
cut -f2

Explanation:

*

*Generate a numeric key using numbers from the 3rd column (if none set the key to 0)

*Sort by the above key and then by the original file

*Remove the numeric key

A: This would work keeping the order in which lines were processed as well as no use of pipes and external commands.
awk -F, '
$3~/[0-9]+/{a[++i]=$0;x=i;next}1
END{for(i=1;i<=x;i++) print a[i]}' file

Input File:
[jaypal:~/Temp] cat file
dog, eats chicken, has 4 legs, does not like cats
cat, eats mice, has a tail, does not like water
mouse, eats bugs, has 4 legs, does not like cats
elephant, eats peanuts, has a trunk, does not like mice

Test:
[jaypal:~/Temp] awk -F, '
$3~/[0-9]+/{a[++i]=$0;x=i;next}1
END{for(i=1;i<=x;i++) print a[i]}' file
cat, eats mice, has a tail, does not like water
elephant, eats peanuts, has a trunk, does not like mice
dog, eats chicken, has 4 legs, does not like cats
mouse, eats bugs, has 4 legs, does not like cats


text:
Q: Convert to datetime - See all data raising exceptions Let's suppose that I am running the following lines in python and pandas:
# Load data
data = pd.read_csv('C:/Users/user/Desktop/data.txt',\
                   keep_default_na=True, sep='\t', na_values='?')

# Convert to datetime column
data['Date'] = pd.to_datetime(data['Date'], errors='raise', dayfirst=True)

However, I want to see all the data of this column raising exceptions in pandas.
For this reason I wrote this:
exceptions = []
for index, row in data.iterrows():

    try:
        row['PICKUP_DT'] = pd.to_datetime(row['PICKUP_DT'], errors='raise', dayfirst=True)

    except:
        exceptions.append(row['PICKUP_DT'])

dataframe = pd.DataFrame({'Exceptions': exceptions})

dataframe.to_csv('C:/Users/user/Desktop/EXCEPTIONS.csv', index=False, na_rep='NA')

Is there any better way to do this?
I actually thought that there would be an in-built pandas way to do this.

A: Use .loc to get all of the problematic rows checking .isnull() for the result with errors='coerce'. I exclude NaN as pd.to_datetime will not raise an error for null values.
Sample Data
import pandas as pd
import numpy a np
data = pd.DataFrame({'Date': [np.NaN, '12-03-2019', '001111231', '46-06-1988']})
#         Date
#0         NaN
#1  12-03-2019
#2   001111231
#3  46-06-1988

Code:
data.loc[pd.to_datetime(data.Date, errors='coerce', dayfirst=True).isnull()
         & data.Date.notnull(), 'Date']
#2     001111231
#3    46-06-1988
#Name: Date, dtype: object


text:
Q: How to Concatenate Integer Array to Single Integer in Ruby Given the array [1,2,3], is there a method (other than just iteration) to convert it to the integer 123?

A: Personally I would use
Integer([1,2,3].join, 10) #=> 123

since it has the nice side-effect of throwing an exception that you can deal with if you have non-numeric array elements:
>> Integer([1,2,'a'].join, 10) # ArgumentError: invalid value for Integer: "12a"

Compare this to to_i:
>> [1,2,'a'].join.to_i #=> 12

A: Just join the array and convert the resulted string to an integer:
[1,2,3].join.to_i

A: If you want to avoid converting to and from a String, you can use inject:
[1,2,3].inject{|a,i| a*10 + i}
#=> 123