text:
Q: How to skip some steps, and continue the running of a model from a later point, bases on a condition? I am building a Model in ArcGIS Desktop 10.8.
At some point in my model, I am dealing with Line feature classes. I turn them into Polygon feature classes, and then I merge them into one feature class.
The source of my problem is, that some of the inputs might be empty. If I run the Feature To Polygon tool with these inputs, it gives me the following error message:
Error executing function. The geometry is not M-aware Failed to execute
I tried to solve the problem, based on this thread: Geometry is not M-Aware?. It didn't help. I am working in a geodatabase, and the M-aware option is turned off in the environmental settings.
I thought that preconditioning would work, so I tried (as you can see in the 3rd and 4th row of the attached image). The problem here is that it won't run the Feature To Polygon tool indeed, but it won't run anything after this tool either. So it won't eventually merge the other, not empty feature classes either.
Is there a way to skip some steps, based on a condition, and continue the running from an other point?
In my case, can I skip the Feature To Polygon and the Calculate Field tools if my feature class is empty, but then run the Merge tool with the other, not empty feature classes?

A: I have just spoofed up this model to simulate what you are doing and it all works fine for me! I'm using ArcMap 10.6.1
The Merge takes 3 datasets, one with nothing in it and various M-aware levels, everything merges as expected.

This would indicate the source of the problem lies elsewhere. Modelbuilder often seems to hang on to old environment settings and in a few cases rebuilding a model from scratch seems to fix things.  I would try a new model with just a couple of outputs, one you know is creating an empty dataset and feed them into the merge tool. For me everything merged empty or not, M-aware or not....

A: Use Data Exists...Look at the following link!!
https://pro.arcgis.com/en/pro-app/latest/tool-reference/modelbuilder-toolbox/examples-of-using-logical-tools-in-modelbuilder.htm#GUID-C0E9F998-C1DE-4D52-9FCE-13543FBC0FCB


text:
Q: CNN predictions work from test set but not own images Im trying to do a CNN gender classifier and it works fine with images from the test set but when I input iamges from google its always classifying as male. I tried getting the answer from here but it didnt solve it.
data = pd.read_csv('/content/age_gender.csv')

## Converting pixels into numpy array
data['pixels']=data['pixels'].apply(lambda x:  np.array(x.split(), dtype="float32"))

classification = ['Male', 'Female']

X = np.array(data['pixels'].tolist())

## Converting pixels from 1D to 3D
X = X.reshape(X.shape[0],48,48,1)
X = X / 255.0

y = data['gender'].values

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.22, random_state=37)

model = Sequential.....   # create the CNN and compile it
history = model.fit.....          # fit the model and evaluate it gives me val_accuracy: 0.8902

Test loss: 0.24722696840763092
Test Accuracy: 0.8912960290908813
When I predict an image from the test set using the following code it works fine.
index = 5009
image = X_test[index]

pred = model.predict(image.reshape(1, 48, 48, 1), batch_size=1)

print(classification[pred.argmax()])

But when I try to predict images from google it always comes back as male.
file = "/content/female-2.jpeg"
image = cv.imread(file, cv.IMREAD_GRAYSCALE)

image = cv.resize(image, (48, 48))
image = image.reshape(1, 48, 48, 1)
image = image.astype('float32')
image = 255-image
image /= 255

pred = model.predict(image.reshape(1, 48, 48, 1), batch_size=1)
print(classification[pred.argmax()])

I have tried a whole bunch of different images that are females and it ALWAYS comes back as male. What am I missing here?

A: You preprocess the images from Google differently compared to when you train the model. The normalization of the pixel values is what causes the issue.
image = 255-image
image /= 255

This should instead be:
image /= 255.0

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to keep track of moving object (rectangle) in javafx? I found this code snippet in a video and I'm trying to integrate it in a ridesharing app. Basically, the rectangle will represent the driver moving on the map and I want to keep track of his location to see when he reaches his destination.
import javafx.animation.AnimationTimer;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.AnchorPane;
import javafx.scene.shape.Rectangle;

import java.net.URL;
import java.util.ResourceBundle;

public class MapController implements Initializable {

    private BooleanProperty wPressed = new SimpleBooleanProperty();
    private BooleanProperty aPressed = new SimpleBooleanProperty();
    private BooleanProperty sPressed = new SimpleBooleanProperty();
    private BooleanProperty dPressed = new SimpleBooleanProperty();

    private BooleanBinding keyPressed = wPressed.or(aPressed).or(sPressed).or(dPressed);

    private double movementVariable = 2;
    private int destinationX = 300, destinationY = 300;

    @FXML
    private Rectangle shape1;

    @FXML
    private AnchorPane scene;

    @FXML
    private Button buttonStartRide;

    @FXML
    void start(ActionEvent event) {
        shape1.setVisible(true);
        buttonStartRide.setOpacity(0);
        shape1.setLayoutY(200);
        shape1.setLayoutX(280);
    }

    AnimationTimer timer = new AnimationTimer() {
        @Override
        public void handle(long timestamp) {
            if(wPressed.get()) {
                shape1.setLayoutY(shape1.getLayoutY() - movementVariable);
            }

            if(sPressed.get()){
                shape1.setLayoutY(shape1.getLayoutY() + movementVariable);
            }

            if(aPressed.get()){
                shape1.setLayoutX(shape1.getLayoutX() - movementVariable);
            }

            if(dPressed.get()){
                shape1.setLayoutX(shape1.getLayoutX() + movementVariable);
            }
        }
    };

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        movementSetup();
        shape1.setVisible(false);

        keyPressed.addListener(((observableValue, aBoolean, t1) -> {
            if(!aBoolean){
                timer.start();
            } else {
                timer.stop();
            }
        }));
    }

    public void movementSetup(){
        scene.setOnKeyPressed(e -> {
            if(e.getCode() == KeyCode.W) {
                wPressed.set(true);
            }

            if(e.getCode() == KeyCode.A) {
                aPressed.set(true);
            }

            if(e.getCode() == KeyCode.S) {
                sPressed.set(true);
            }

            if(e.getCode() == KeyCode.D) {
                dPressed.set(true);
            }
        });

        scene.setOnKeyReleased(e ->{
            if(e.getCode() == KeyCode.W) {
                wPressed.set(false);
            }

            if(e.getCode() == KeyCode.A) {
                aPressed.set(false);
            }

            if(e.getCode() == KeyCode.S) {
                sPressed.set(false);
            }

            if(e.getCode() == KeyCode.D) {
                dPressed.set(false);
            }
        });
    }

    public boolean checkReachedDestination()
    {
        if((shape1.getLayoutX() == destinationX) && (shape1.getLayoutY() == destinationY))
        {
            return true;
        }
        return false;
    }
}

I thought that I could maybe do this with a Listener for shape1, however it seems like there is no Listener defined for the type Rectangle. Any thoughts?


text:
Q: R - convert BIG table into matrix by column names This is an extension to an existing question: Convert table into matrix by column names
I am using the final answer:  https://stackoverflow.com/a/2133898/1287275
The original CSV file matrix has about 1.5M rows with three columns ... row index, column index, and a value.  All numbers are long integers.  The underlying matrix is a sparse matrix about 220K x 220K in size with an average of about 7 values per row.
The original read.table works just fine.
  x <- read.table("/users/wallace/Hadoop_Local/reference/DiscoveryData6Mo.csv", header=TRUE);

My problem comes when I do the reshape command.
  reshape(x, idvar="page_id", timevar="reco", direction="wide")

The CPU hits 100% and there it sits forever.  The machine (a mac) has more memory than R is using.  I don't see why it should take so long to construct a sparse matrix.
I am using the default matrix package.  I haven't installed anything extra.  I just downloaded R a few days ago, so I should have the latest version.
Suggestions?
Thanks,
Wallace

A: I would use the sparseMatrix function from the Matrix package. The typical usage is sparseMatrix(i, j, x) where i, j, and x are three vectors of same length: respectively, the row indices, col indices, and values of the non-zero elements in the matrix. Here is an example where I have tried to match variable names and dimensions to your specifications:
num.pages <- 220000
num.recos <- 230000
N         <- 1500000

df <- data.frame(page_id = sample.int(num.pages, N, replace=TRUE),
                 reco    = sample.int(num.recos, N, replace=TRUE),
                 value   = runif(N))
head(df)
#   page_id   reco     value
# 1   33688  48648 0.3141030
# 2   78750 188489 0.5591290
# 3  158870  13157 0.2249552
# 4   38492  56856 0.1664589
# 5   70338 138006 0.7575681
# 6  160827  68844 0.8375410

library("Matrix")
mat <- sparseMatrix(i = df$page_id,
                    j = df$reco,
                    x = df$value,
                    dims = c(num.pages, num.recos))

A: The simplest way to do this in base R is with matrix indexing, like this:
# make up data
num.pages <- 100
num.recos <- 100
N <- 300
set.seed(5)
df <- data.frame(page_id = sample.int(num.pages, N, replace=TRUE),
                 reco    = sample.int(num.recos, N, replace=TRUE),
                 value   = runif(N))

# now get the desired matrix
out <- matrix(nrow=num.pages, ncol=num.recos)
out[cbind(df$page_id, df$reco)] <- df$value

However, in this case, your resulting matrix would be 220k*220k, which would take more memory than you have, so you need to use a package specifically for sparse matrices, as @flodel describes.


text:
Q: Open MPI/MPICH - What happens if a node terminates? I would like to know what happens if a node of a OpenMPI/MPICH2 cluster terminates? Is there some mechanism that is tolerant for this case and continues the execution?
Thanks for your answers
Heinrich

A: Note that a feature that has existed since MPI 1.x days is that you can set an error handler: eg,
http://www.mpi-forum.org/docs/mpi-11-html/node148.html
As Mark notes, most of us just use MPI_ERRORS_ARE_FATAL (which is the default) because our algorithms are very state-heavy and can't easily be recovered (except through checkpointing, which most of us do anyway).
But that need not be the case; you can have the MPI functions return the error messages and try to recover as best you can.
There are a few fault-tolerant MPI packages out there -- http://icl.cs.utk.edu/ftmpi/ (which is kind of old and only implements MPI 1.2 functionality).   More recently, http://osl.iu.edu/research/ft/cifts/ is one approach being put into OpenMPI as a separate project, and there is also an OS-level checkpoint/restart package, BLCR, which may be of interest.
The MPI-3 forum is discussing a standard fault-tolerance API in MPI, so the pace of such projects is accellerating.

A: Not really, MPI doesn't provide out-of-the-box fault tolerance.  You could write your programs to deal with the failure of a process, but most of us don't, we live with our programs crashing when the hardware dies.  This situation is changing with the emergence of supercomputers with hundreds of thousands of processors, and mean-time between failures of the order of seconds.


text:
Q: CIImage Convert to UIImage I have one UIImageView I want to add one CIImage to my UIImageView
Here is my code
@IBOutlet weak var imgimgurl: UIImageView!

imgurl.transform = CGAffineTransform(scaleX: CGFloat(slider.value), y: CGFloat(slider.value))

here is my convert code
imgurl.image = UIImage(CIImage: transformedImage)

but I received this error
Ambiguous use of 'init(CIImage:)'
1. Found this candidate (UIKit.UIImage)

A: you will call init for resolve this issue
imgurl.image = UIImage.init(ciImage: transformedImage)


text:
Q: How to reset region center when exited region in background using CoreLocation My idea is simple in theory, but am having a really hard time executing it.  I want to create a geofence at the user's location, and when the user exits that region, I want to recenter the region at the user's updated location.  Here is the flow:

*

*Retrieve user's currently location using standard [CLLocationManager startUpdatingLocation]

*On locationManager:didUpdateLocations:, create a geofence at the current location using startMonitoringForRegion, and on subsequent location updates, recenter that region

*On locationManager:didExitRegion:, which is usually called from the background to wake up the app, call [CLLocationManager startUpdatingLocation] to retrieve the user's current location to recenter the geofence (centered to the next updated location that is NOT the current region center coordinate).

Sometimes this all works, but more often than not, the geofence doesn't recenter correctly.  What's been happening is that the region is re-centered and locationManager:didExitRegion: is immediately called, which puts it into an infinite loop until the app is terminated again. Since it is terminated without a valid monitored region, the app then won't be woken up for location updates.
Is this incorrect usage of region monitoring?  I'm trying to play with different ways of tracking user location in a battery efficient way (and not constantly using the standard startUpdatingLocation).  Would a combination of signification location change tracking and visit monitoring be more effective?
Thanks!


text:
Q: do I need a new field for counting scores form another table? I have a Users Table
it has id, username, A, and B as my columns.
I also have a Votes Table.
a user can vote on A, and B.
it has id, user_id foreign key, A_id foreign key, and B_id foreign key.
I would like to do a query to Users and have the tally of votes for A and votes for B included.
so lets say I find a User with the id of 1,
How would I get something like
{
        "id": 1,
        "display_name": "test",
        "A" : 32,
        "B" : 132
}

Assuming there are 32 rows in the Votes table and 132 rows for B in the Votes table.

A: simplified table:
t=# select* from users;
 i | t
---+---
 1 | A
 1 | B
 1 | B
 2 | A
 2 | A
 2 | B
(6 rows)

query:
t=# select distinct
i
, sum(case when t='A' then count(1) filter (where t='A') else 0 end) over (partition by i) a
, sum(case when t='B' then count(1) filter (where t='B') else 0 end ) over (partition by i)b
from users
group by i,t
order by i;
 i | a | b
---+---+---
 1 | 1 | 2
 2 | 2 | 1
(2 rows)


text:
Q: is there a callback which runs just before the transaction begins in rails ActiveRecord? I just want to manipulate a model level object when it is newly created or it is updated.
For example, consider there is a test table with name attribute:
class Test < ActiveRecord::Base
  custom_callback :hi
  def hi
    name = "h"
  end
end
m = Test.new(:name => "hello")
m.save

I just want to write a custom callback which should get executed before_validation and should get executed whenever a save or save! is called.  Ideally, I want some callback in rails 2.3 which should get executed and hook into ActiveRecord::Base. is there any gem to do this or does anyone know how to write a callback which get executed before 'before_validation' callback?

A: You could override the save and save! methods to effectively inject the code. There's also the initialize method that might be appropriate depending on what you're trying to do. Also, before_validation runs before validate, so how much earlier do you need it to run exactly, and why?
Can you say more about why you want to do this? It sounds like you may have a design problem and you're trying to find a hack instead of addressing a more fundamental issue.

A: It seems you are looking for before_save, which runs after validation: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
Please refer to This answer


text:
Q: How to update a field in one table based off values in another table in oracle In Oracle, I'm trying to update a a field in one table based off calculations from fields in a second table and I can't seem to get any syntax to work.
For example,
Update item1 i1, item2 i2
Set i1.min_qty = i2.cases * i2.qty_per_case
Where i1.item_id = i2.item_id
And i1.flag1 = 'Y'

The relationship between i1.item_id and i2.item_id is one to one.
Any help would be greatly appreciated.

A: You would need to use a correlated subquery or merge statement:
update item1 i1
set    i1.min_qty = (select i2.cases * i2.qty_per_case
                     from   item2 i2
                     where  i1.item_id = i2.item_id)
where  i1.flag1 = 'Y';

merge into item1 tgt
using item2 src
  on (tgt.item_id = src.item_id)
when matched then
update set tgt.min_qty = src.cases * src.qty_per_case
where  tgt.flag1 = 'Y';

N.B. untested.


text:
Q: If a word is coined / popularized / used only or mainly by second-language speakers of English, is it still considered to be an English word? It seems that there are quite a few terms that look like English and are used in English spoken by non-fluent or fluent but nonnative speakers of English as a second language amongst themselves, but not by, or only very rarely by, native English speakers.
Here's a few that spring to mind before I look for a resource:

*

*advices [1] [2]

*campings

*drink shop (only used in Cambodia, they're actually like independent convenience stores)

*Handy (only used by German speakers)

*infos, informations [1], [2]

*KTV (only used by Chinese speakers)

*touristic
Also I know there is an English Wikipedia article on this phenomenon in which the preferred term is "Pseudo-anglicism". You'll find a lot more such terms there. Not only "incorrect" regular plurals of words that have no separate plural form that I was able to think up without peeking.
The most surprising thing for me was that many of these words and strange plural forms have English entries in the English edition of Wiktionary - mostly without any kind of note suggesting they are anything other than normal everyday words any English speaker might make!
I'm interested in both prescriptivist and descriptivist view on this topic. I'm also interested in both English native speakers view and non-native speakers.

A: My take on this (speaking as a native speaker of English who takes a generally descriptivist approach) is that these words are in the process of moving further and further away from mainstream English: they should really be regarded as loanwords imported from English into another language and adapted to the needs of the speakers of the other language.
(Such borrowing is a perfectly normal process in the development of most languages; what makes the pseudo-anglicisms noteworthy to us native speakers of English is that we are able to witness the beginnings of the transformation of words we know into novel entrants into another language, even though not all of us may realize what it is we are seeing. Additionally, as the Wikipedia entry notes, the borrowers of the term may also be unaware of the difference in their use of it compared with how it is normally used in the source language.)
As part of that transformation process, these words naturally begin to undergo changes in spelling, meaning, or both. Eventually, many of them will become changed to such a degree that their form will be unrecognizable, or only barely recognizable, to native speakers of the donor language, and their connotations will be known only to those native speakers of English to whom they have been explained. Once they have reached that point, they will be English words only in a historical sense.
(To pick up on one of the comments you made in your posting, I certainly think that the relevant Wikipedia entries need to point out the divergence from the usage of these words in Standard English.
I notice that you included touristic among your examples. This, to me, is a normal English word which I did not see in the Wikipedia list of pseudo-anglicisms. Can you point to a context in which the word is being used in a significantly different way to how a native speaker of English would use it?)

A: The current version of OED, not Wiktionary, is usually taken as being the authoritative decider of 'wordness'. It also seems far better at identifying the registers etc a word will be most suitable for.
Those people who adopt a Humpty-Dumpty approach to language ('A word means what I say it means' // A string is a word if [a few mates and] I say so / use it / have seen it on the internet) are not remaining true to its primary purpose, clarity of communication.

A: I think the answer is simple.  If the term is not understood by English speakers it is not an English word.  We borrow tons of words from other languages and sometimes we use them improperly.  People in other regions often don't use the words improperly to mimic what we do.
It isn't a word in English.  At best it is slang in the foreign language and then works itself into their vocabulary if adopted enough.


text:
Q: What are best practices for IPhone web development I need to know best practices for IPhone/IPAD HTML5 Web development.

A: Remember never to rely on "hover" states, because there is no hover on touch devices like the iPhone or the iPad.
Also, for the video tag, remember that you have to use video encoded in H264 (the only format supported by Apple) and that you'd better not use the poster attribute if you need it to work on iPhones without OS 4 (it was an old bug, now fixed). More info here: http://camendesign.com/code/video_for_everybody


text:
Q: cookie not working in popup on colorbox load I'm trying to get this simple cookie working in my simple colorbox but it isn't.
Could someone point me in the right direction because I'm not that handy with javascript. Thx
<script type="text/javascript">
$(document).ready(function () {

setTimeout(function() {
$.fn.colorbox({href:"{{ 'missroberta-international.jpg' | url_asset }}", open:true});
  }, 1000);

  setTimeout(function () { $.fn.colorbox.close(); }, 8000);

$(function() {
    if ($.cookie('test_status') != '1')
    {
        setTimeout(function()
        {
            alert('foo');
            jQuery.cookie('test_status', '1', { expires: 31});
        }, 1000);
    }
}
</script>

A: Both of your DOM ready functions are not properly closed. The first ins't closed at all, and the second needs }) not just }.
$(document).ready(function () {

setTimeout(function() {
$.fn.colorbox({href:"{{ 'missroberta-international.jpg' | url_asset }}", open:true});
  }, 1000);

  setTimeout(function () { $.fn.colorbox.close(); }, 8000);

}); // <-- here

$(function() {
    if ($.cookie('test_status') != '1')
    {
        setTimeout(function()
        {
            alert('foo');
            jQuery.cookie('test_status', '1', { expires: 31});
        }, 1000);
    }

}); // <-- here

Unless this code appears separately in the HTML, there is no point in using both $(function(){ ... }) and $(document).ready because the former is a shortcut to the latter, so combine the code into one if possible.


text:
Q: How to loop through files named in a text file? Windows Server 2012
*

*Windows Server 2012 cmd.exe box

*I need to make a batch file, call it get.bat, to process all directories listed in dlist.txt which is in the same dir as get.bat. Directory names are one per line in dlist.txt. dlist.txt was created with dir /b DIV_* > dlist.txt. These DIV_ files are actually subdirectories to the dir where my batch file is run.

*I cannot use a filespec in the FOR command because I need to edit dlist.txt by hand after creating it. I don't want to process all dirs like DIV_*, just some of them.

*Creating dlist.txt with dir /w DIV_* > dlist.txt means all directory names have [] around them and I cannot use that.

*There is one parameter to get.bat which is a base filename to contain all results form the fromxsf command. The .txt extension will be added by the batch file.

*I need to do multiple commands to each dir in dlist.txt, some of which are setting a temp filename called %tempoutfile% then used in fromxsf.

*I've read several pages I found on Google, including some from Superuser but the examples that might work for cmd.exe did not work for me. Maybe Windows 2012 Server is too old? I cannot change that, I have to work with what I've got.

*fromxsf that processes each directory in dlist.txt requires the directory as one parameter after the -cd and a temporary output file as another parameter which is %tempoutfile%.

*We don't appear to have powershell or at least there is no path set to it.

Here's what I've tried using a FOR loop:
set destdir=c:\tempdir
set outfile=%destdir%\%1.txt
FOR /F %%f in ('type dlist.txt') DO (
    echo "--------------------"

    echo Basedir=%%f should be directory
    set tempoutfile=../%%f.txt
    echo outfile=%destdir%\%outfile%
    echo tempoutfile=%tempoutfile%
    echo Processing dir %%f, to tempfile %tempfile%
    pause
    rem Below is the command to process the dir name in %%f to make a temp file in %tempoutfile%
    fromxsf %tempoutfile% -cd %%f +m -nbs -Rep -nofrills

    if exist "%destdir%" (
        echo " " >> %outfile%
        echo "{DIVNAME=%i}" >> %outfile%
        rem Append %tempoutfile% to %outfile%.
        type %tempoutfile% >> %outfile%
        del %tempoutfile%
    )
)

For the above the value of %%f is always the first line of dlist.txt. That is not what I want.
What I'm doing in the loop is outputting the processed contents of the directory into a temp file in %tempfile%, and then concatenating the contents of %tempfile% to %destdir%\%outfile%. mycommand requires the input directory %%f as a command line arg. I just can't redirect STDOUT and append the output to %destdir%\%outfile%.
Some alternate FOR loops I've tried:

*

*FOR %%f in (dlist.txt) DO (. For this case %%f is always the second dir name in dlist.txt and never changes.

Anyone know how to do this?
Thank you!

EDIT: Thanks. I figured it out using delayed expansion and another post I found using Google. The core of the loop is this, with filenames contained in the text file dlist.txt one filename per line. My problem was the missing "tokens=*" option. Also the !variable! notation must be used EVERY time in the loop. The loop below also has echo statements to show the values of variables.
setlocal EnableDelayedExpansion
set outfile=c:\temp\tempout.txt
del %outfile%
FOR /f "tokens=*" %%f in (dlist.txt) DO (
    echo.
    echo --------------------
    set indir=%%f
    echo Basediv indir=!indir!
    echo Processing division !indir!

    echo. >> %outfile%
    echo {DIVNAME=!indir!} >> %outfile%
    pause
    fromxsf %outfile% -cd !indir! +m -nbs -Rep -nofrills -a
)

Key issues in my loop

*

*Use the %%f variable only once per loop and assign it to indir. From thereafter use the !indir! variable.

*I removed the use of %tempoutfile% because the fromxsf command allows me to append output from itself (using -a) IF the file exists, which it does in this case.


text:
Q: Generate a PDF that automatically prints I have a ASP.NET Web application that generates a PDF. I am using iTextSharp. What happens is that you click a button and it downloads. My employer want to be able to click the button and have it open with the print dialog.

A: Another solution on this site... I use this solution and work great
I have a PDF Stream from Crystal report, and i add the openaction with pdfsharp
link : http://www.vo1dmain.info/pdfsharp-howto-inject-javascript-into-pdf-autoprinting-functionality#comments
public static MemoryStream AddAutoPrint(Stream pdfStream, bool ShowPrintDialog = true, int NumCopies = 1)
{
  PdfSharp.Pdf.PdfDocument doc = PdfSharp.Pdf.IO.PdfReader.Open(pdfStream, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Import);
  PdfSharp.Pdf.PdfDocument outputDocument = new PdfSharp.Pdf.PdfDocument();

  for (int idx = 0; idx < doc.PageCount; idx++)
  {
    PdfSharp.Pdf.PdfPage p = doc.Pages[idx];
    outputDocument.AddPage(p);
  }

  outputDocument.Info.Author = "author name";

  string JSScript = string.Empty;
  JSScript += "var pp = this.getPrintParams(); ";

  if(NumCopies > 0)
  {
    JSScript += "pp.NumCopies = " + NumCopies.ToString() + "; ";
  }

  if(!ShowPrintDialog)
  {
     JSScript += "pp.interactive = pp.constants.interactionLevel.automatic; ";
  }

  JSScript += "this.print({printParams: pp}); ";

  PdfSharp.Pdf.PdfDictionary dictJS = new PdfSharp.Pdf.PdfDictionary();
  dictJS.Elements["/S"] = new PdfSharp.Pdf.PdfName("/JavaScript");
  //dictJS.Elements["/JS"] = new PdfSharp.Pdf.PdfStringObject(outputDocument, "print(true);");
  //dictJS.Elements["/JS"] = new PdfSharp.Pdf.PdfStringObject(outputDocument, "this.print({bUI: false, bSilent: true, bShrinkToFit: true});");
  //dictJS.Elements["/JS"] = new PdfSharp.Pdf.PdfStringObject(outputDocument, "var pp = this.getPrintParams(); pp.NumCopies = 2; pp.interactive = pp.constants.interactionLevel.automatic; this.print({printParams: pp});");
  dictJS.Elements["/JS"] = new PdfSharp.Pdf.PdfStringObject(outputDocument, JSScript);

  outputDocument.Internals.AddObject(dictJS);

  PdfSharp.Pdf.PdfDictionary dict = new PdfSharp.Pdf.PdfDictionary();
  PdfSharp.Pdf.PdfArray a = new PdfSharp.Pdf.PdfArray();
  dict.Elements["/Names"] = a;
  a.Elements.Add(new PdfSharp.Pdf.PdfString("EmbeddedJS"));
  a.Elements.Add(PdfSharp.Pdf.Advanced.PdfInternals.GetReference(dictJS));

  outputDocument.Internals.AddObject(dict);

  PdfSharp.Pdf.PdfDictionary group = new PdfSharp.Pdf.PdfDictionary();
  group.Elements["/JavaScript"] = PdfSharp.Pdf.Advanced.PdfInternals.GetReference(dict);

  outputDocument.Internals.Catalog.Elements["/Names"] = group;

  MemoryStream ms = new MemoryStream();

  outputDocument.Save(ms, false);

  return ms;
}

A: As mentioned by yms, you can generate a PDF that has JavaScript or a "Named" PDF action that shows the Print dialog when the document is opened. We have demonstrated this using our product Gnostice PDFOne .NET in the article Create an Auto-Print PDF. You could do the same in iText I guess. If Adobe Reader is registered as PDF plugin in the browser, then both options will work.
HTML Javascript option seems to work only in IE.
DISCLAIMER: I work for Gnostice.

A: In iTextSharp do:
PdfDocument = pdfDoc = new Document(PageSize.LETTER);
// create and open the new pdf document for writing
FileStream fspdfDoc = new FileStream(pdfDocFileName, FileMode.Create,
FileAccess.ReadWrite);
PdfWriter pdfW = PdfWriter.GetInstance(pdfDoc, fspdfDoc);
pdfDoc.Open();
pdfW.AddJavaScript(PdfAction.JavaScript("this.print(true);\r", pdfW));

A: Method 1: Using embedded javascript inside your PDF files
You can try creating an iText PDFAction object with a javascript call this.print(false) (you can use new PdfAction(PdfAction.PRINTDIALOG) for this), and associate it with the OpenAction event of your pdf file.
The code in iText Java should look like this:
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("file.pdf"));
...
PdfAction action = new PdfAction(PdfAction.PRINTDIALOG);
writer.setOpenAction(action);
...

It should not be too diferent in C#.
As a side note, this is also possible with Amyuni PDF Creator .Net by setting the attribute "AutoPrint" to TRUE in the document class (usual disclaimer applies).
acPDFCreatorLib.Initialize();
acPDFCreatorLib.SetLicenseKey("Amyuni Tech.", "07EFCDA00...BC4FB9CFD");
Amyuni.PDFCreator.IacDocument document = pdfCreator1.Document;

// Open a PDF document from file
System.IO.FileStream file1 = new System.IO.FileStream("test_input.pdf", FileMode.Open, FileAccess.Read, FileShare.Read);

IacDocument document = new IacDocument(null);

if (document.Open(file1, ""))
{
    //Set AutoPrint
    document.Attribute("AutoPrint").Value = true;

    //Save the document
    System.IO.FileStream file2 = new System.IO.FileStream("test_output.pdf", System.IO.FileMode.Create, System.IO.FileAccess.Write);
    document.Save(file2, Amyuni.PDFCreator.IacFileSaveOption.acFileSaveView);
}

// Disposing the document before closing the stream clears out any data structures used by the Document object
document.Dispose();

file1.Close();

// terminate library to free resources
acPDFCreatorLib.Terminate();

This approach requires the PDF file to be opened in a reader that will take care of printing, and it has the drawback that if the file is saved locally, every time the file is opened later on it will show the print dialog.
Method 2: Using javascript from the browser to communicate with the reader that shows the file.
I found this other approach in this SO question that might worth trying:
<html>
<script language="javascript">
timerID = setTimeout("exPDF.print();", 1000);
</script>
<body>
<object id="exPDF" type="application/pdf" data="111.pdf" width="100%" height="500"/>
</body>
</html>

The idea is to use javascript in the browser to instruct the PDF reader to print the file. This approach will work on PDF files embedded in a HTML page.

A: HOW about good old fashion OLE?  It is still supported by most all document layers I am aware of... IN C# I normally do something like this.. where PDF, RTF, DOC, XLS... does not matter... they all print..
public void HandlePresentation(string fullFilePath, bool viewOnScreen, bool autoPrint)
{
    ProcessStartInfo info = new ProcessStartInfo(fullFilePath);
    if (autoPrint)
    {
        info.Verb = "Print";
        info.WindowStyle = ProcessWindowStyle.Hidden; // not normally required
        Process.Start(info);
        info.Verb = string.Empty;
    }

    if (viewOnScreen)
    {
        info.WindowStyle = ProcessWindowStyle.Normal;
        Process.Start(info);
    }
}


text:
Q: How to merge several Github users? I am newbie github users and mistakenly created two github user accounts. I'm wondering how can we merge two github users account into one, including their corresponding repositories? any idea?

A: A quick something search will give you this:

*

*Transfer any repositories from the account you want to delete to the account you want to keep. Issues, pull requests, and wikis are transferred as well. Verify the repositories exist on the account you want to keep.

*Update the remote URLs in any local clones of the repositories that were moved.

*Delete the account you no longer want to use.


text:
Q: Bash base64 has an additional character instead of an equals versus powershell If I do the following in powershell:
$b = [System.Text.Encoding]::UTF8.GetBytes("helloworld")
[System.Convert]::ToBase64String($b)
The output is:
aGVsbG93b3JsZA==
If I go into bash and do the same thing:
echo "helloworld" | base64 then the result is:
aGVsbG93b3JsZAo=
So in bash, instead of the first = its an o. Why is that?

A: In bash,
echo "helloworld" | base64

will add a newline character (\n or 0A in hex) to helloworld. Use
echo -n "helloworld" | base64

instead.


text:
Q: Indefinite article in a parallel (?) structure I'm confused as whether to use an article with the second noun in structures like this  (this is just an example, it's a person describing their profession):
"As a journalist and (a???) traveller...."
or,
"As a manager and (a???) teamplayer..."
There's no doubt I need the first 'a', what about the second one? Is there ANY context that doesn't suppose the usage of the second indefinite article in situations like this?
Thanks so much.


text:
Q: Is there an exact value of $\cos^{-1}(4/5)?$ This is about the $3,4,5$ Pythagorean triangle.
Question in the title. I think the answer is "no", but if not, then why not? What about the $5, 12, 13$ triangle, or even non-Pythagorean triangles like $1, 4,  \sqrt {17} $ ? Can you write the angles in these triangles in a "nice way"?


text:
Q: Sql server 2012 date comparison with format function not returning as expected Data from my database:

As you can see I have several rows with column NEWS_DPU populated.
I don't understand why this query:
select * from canews
where format(news_dpu, 'mm.dd.yyyy') <= format(convert(datetime, '12.01.2016'), 'mm.dd.yyyy')

is returning only this:

Only one row is returned from query, but there should be several of them with NEWS_DPU smaller or equal to december 1st 2016. Am I missing something?
SOLUTION:
As John pointed out, MM means month and mm means minutes.
I've just changed mm to MM and everything is fine.

A: First change your format to MM which is month while mm is minutes
But I really think you want
select * from canews
where news_dpu <= convert(datetime, '12.01.2016',103)


text:
Q: Powershell venv only use envirnmental variables python, not python in venv directory (Windows) I use vevn with python 3.6.8, pip 18.1.
I set powershell executionPolicy RemoteSigned,
create virtual environment with venv, refed to venv official site : (https://docs.python.org/3.6/library/venv.html)
and also activated according to powershell, used .<venv>\Scripts\activate.ps1
But when I execute 'pip list' command, it shows all packages installed in global, not in venv.
And when execute python - import sys - sys.prefix, to check python directory,
I can find, powershell venv uses environmental variables python.
Of course, run it on cmd in same way, it works correctly.
pip list shows
The pip list shows only packages installed in venv, and sys.prefix is python in venv directory.
Does anyone know why it works like this?
Powershell works correctly like cmd

A: Maybe you activated the "--system-site-packages" switch by accident when installing the virtual env. This switch makes all python packages in the global system available to the virtual env.
Also check that after activating the environment your powershell indicates that you are actually using the virtual env. This is indicated by (env_name) at the beginning of the new power shell line.


text:
Q: How do I analyse the data from my spaced repetition system As part of my MSc, I have recently developed a web application designed to assist toddlers with learning difficulties in the comprehension of spoken instruction.  The system shows a series of animations to convey an object and then tasks the child to pick out the correct object from a series of objects.  I then collect the data as to whether the child selected the correct object.
Then, through utilisation of a spaced repetition algorithm the cards are re-ordered and reshown at cutom intervals.
So I have have a load of data that basically looks like this:
Card Name - Correct/Incorrect(binary)
I have produced a line chart in Excel that plots the total number of questions posed vs the number of questions answered correctly over time.  The correct answer line looks quite straight, so I was hoping that I could show the children are learning the slope of the two lines are equal?  Would this signify the children are answering all the questions correctly all the time?
Are there any other deductions I could look to be making?  I'm not a stats person and quite new to all this.

A: Background:
I am a father of some very bright children, particularly my oldest daughter.  I proved to myself that my daughter had a primitive idea of number or symmetry by playing games with her while she was in the womb - I would find her hands pressing from the inside of the womb, I would push in gently and then she would respond back.  When I pushed in once, she would push back once.  When I pushed in twice, she would push back twice.  I taught her tongue-signs when she was a newborn and that was the only muscle she could control.  She could use them to ask for a bottle or binky before she could hold her own head up. She had an ~80 word vocabulary when she was ~9 months old.  My daughter independently invented very simple, but sufficient cases of, addition and multiplication, as a four year old.  Her bents are for animals and their parts, currently dinosaurs.  She can tell a gallimimus from a diplodocus by sight and would be delighted to explain the differences between theropods, sauropods, and pterosaurs.  Her birthday was in June, so she is a very early 5 year old.
I'm also the eldest of 6 children from a religious culture where many kids were a good thing.  I babysat for years in nursery, I took care of kids in sunday school and many activities.  I have some experience with children outside of my own offspring.
Training
It sounds like you are trying to show an animation or such to a kid to help them associate a sound with an action that you want from them.  So you are trying to have the spoken words "Pick up toy" associated in their minds with actually picking up the toy.  Is this the case?  Please correct me if I am wrong here.
Do you know how to teach little boys to use the toilet using the M&M candies as rewards?  (link) The subjects there (boys) often are resistant to change and don't want to use the toilet.  Animations would only be a single tool in the toolbox that combines both installing understanding, and installing motivation into the child.
Measurement
Without the ability to measure an error between the target and actual system, it is impossible to improve the alignment between the two.  This is axiomatic in control systems engineering.
You have a developed mind in action, in the mind of a child.  It gains advantage for the child when you think they don't understand.  I find in general that most kids understand far more than they want to let on, or are able to communicate.  This makes it essential that you give the child motive to answer correctly every time.
The will of the child confounds your data.
Questions:

*

*What is the input to the child?  Visual only?  Verbal?  Kinesthetic?

*What motivates the child to tell you the correct answer when they know it?

*How do you know that your mode of measuring the answer is appropriate to the child?

Presentation suggestion:
I would consider each correct answer a "1" and each incorrect a "0".  A sample set of data would be a sequence of ones and zeros.  If you have multiple choice then you can fractionally weight partially correct answers.  There is literature on doing this at a college level.  I think that engineering the wrong idea, when it characterizes typical misunderstandings or error modes, can be more informative than just knowing that the student selected the incorrect answer - because it can help to determine why the wrong answer was selected.

*

*A first simple test would be to plot both the running mean and running standard deviation as a function of time.  Think about Simple moving average and bollinger bands.

*I would also consider a variability plot by question of the answers.
This would indicate which of the types of ideas they get vs. which
they do not.

*You could do a variation on 1&2 where you track mean and stdev by category (or question) over time.

*you could make histogram of results (true vs. false) for first half and second half of samples.  This is equivalent to averaging over that window and making a histogram.  I like empirical CDF because I feel that it is more useful than a histogram, but many folks are addicted to having bin-widths.


text:
Q: Pop up box in Ruby on Rails I want  to display a popup windo on my rails application... Here is exactly what i want is  . I have the line called "My profile" (for link i used link_to). if user clicks the link the popup should come out and displays the user's profile details.... i tried with :popup => 'true' option but it creates new window. i want some Ajax kind of stuff... can any one help me on this.

A: This is not a ruby-on-rails question. What you need is some javascript library to do that. As mentioned by Salil, lightbox is one such library. Others include:

*

*colorbox

*jQuery UI dialog

*Fancybox

*shadowbox
I personally tried lightbox, thickbox (no longer supported), colorbox, and shadowbox, and found colorbox to best fit my needs.

A: use lightbox to achive it.Rails provide lightbox_helper plugin.

A: Here is the path I would follow: First, you "load" data from your application with the JQuery load function. For this you can use a normal controller action with a some basic view. Then, you want to put it in a fancy Jquery popup, e.g. explained here


text:
Q: Want NO ACTION on delete and NO ACTION on update on doctrine 2 ORM I created an entity as below:
namespace Application\Entity;

use Doctrine\ORM\Mapping as ORM;
/**
 * Application\Entity\Example
 *
 * @ORM\Table(name="example")
 * @ORM\Entity
 */

class Example {
     //...
     /**
      *
      * @var datetime
      * @ORM\Column(name="created_at", type="datetime", nullable=false)
      */
      private $createdAt;

     /**
      *
      * @var integer
      * @ORM\ManyToOne(targetEntity="User")
      * @ORM\JoinColumn(name="created_by", referencedColumnName="iduser", onDelete="NO ACTION")
      */
      private $createdBy;

   //.........

}

I tried to add annotation onDelete="NO ACTION" but it does not do anything.
I want to the NO ACTION for both on Update and On Delete on MySQL. Is there any way to do such or is it not supported by doctrine 2?

A: According to the documentation of Doctrine-ORM Documentation, the attributes of @JoinColumn are :

*

*name

*referencedColumnName

*unique

*nullable

*onDelete

*columnDefinition

So, the attribute you have used here onDelete="NO ACTION" should work here. But for 'on Update', there is not such attribute defined. By default, the (onUpdate) attribute of MySQL will use "Restrict" which is a synonym of "No Action" as described here.
As per my information, onUpdate attribute was removed from Doctrine 2. I don't know the actual reason behind it. But it's fine if you don't use onUpdate and get 'ON UPDATE = Restrict' by default instead of 'ON UPDATE = No Action' as you need in your question.

A: /**
  * @ORM\ManyToOne(targetEntity="User")
  * @ORM\JoinColumn(name="created_by", referencedColumnName="iduser",onDelete="NO ACTION")
**/

and then you need to execute the command
>php bin/console doctrine:schema:update --force


text:
Q: Auto click on button like in ifarme when page load If I wanted to auto-click a button element in ifarme how would I go about this working ?

function autoclick() {
document.getElementById('u_0_4').contentWindow.document.getElementById("u_0_5").click()
}

=====> if have any other way for do that please tell me :(

A: You cannot do that because otherwise people would just embed a 1x1 iframe and have every visitor "Like" whatever the author wanted. It's a security issue to let different origins have access to the contentWindow of iframes pointing to a different origin.
Imagine if you were able to do that. People could just start embedding gmail or your banking website in a 1x1 iframe and then trigger a few clicks and keyboard events to reset your password.


text:
Q: configure D-link Dir-300 I have a D-link DIR-300 router, but I am having problems configuring it on my network because I do not know what is my network type.
So in order to connect to my network through mac, I need to enter a manual IP address given by my ISP, and then go to the terminal and run an ssh command, with the command:
ssh user@server

which then asks me for the password of my account.
I have tried PPPoE configurations, but that did not work either, any ideas how to fix this ?


text:
Q: What are the best books for analytical geometry UG level? and substantially helpful for GMAT prep? I need a good book for studying analytical geometry which involves 2d geometry , conic sections, 3d geometry, quadroids, conicoids, locus etc at UG level and helpful for GMAT prep also.

A: There is no one such book but I will suggest you few books that will help you to learn and will help for GMAT.
1) Analytical Geometry: With the Properties of Conic Sections, and an Appendix, Constituting a Tract On Descriptive Geometry by John Narrien (2010 – Nabu Press)
2) Calculus with Analytical Geometry for the Technologies (Prentice Hall Series in Technical Mathematics) by Lawrence M. Clar and James A. Hart (1980 – Prentice Hall)
3) Analytical Geometry: Two and Three Dimensions by D. Chatterjee (2009 – Alpha Science International Limited)


text:
Q: how to sort query results with nested relation column field in laravel? $props = Property::with(['rentalUnit','rentalUnit.floor'])->get()->toArray();

I want to sort rentalunit collection with field of floor table field floor_name
Any help would be appreciated

A: Add this to your Property model
public function rentalUnitOrderByFloorName()
{
    return $this->rentalUnit()->select('rental_units.*', 'floors.name')->leftJoin('floors', 'floors.rental_unit_id', '=', 'rental_units.id')->orderBy('floors.name');
}

Then
$props = Property::with(['rentalUnitOrderByFloorName','rentalUnitOrderByFloorName.floor'])->get()->toArray();


text:
Q: Smooth animation with SceneKit on OS X I am trying to simulate the orientation of a body using accelerometer data and am having difficulty getting a smooth animation.
I have a large file of accelerometer data and want to animate the orientation using the pitch and roll values calculated from the accelerometer data.  The data is sampled at constant time intervals and I figured I could approximate that by setting the duration = to the sample time which could vary between 80ms and 640ms.
The code below does not seem to work and changing the duration seems to have no effect on the time taken to animate the transition to the new orientation.
What would the correct way be to animate the orientation changes of the body and also be able to adjust the simulation speed such that it approximates the actual time or some multiple thereof?
func animate(scan: ScanData) {

    if let accel = scan.next() {
        let orientation = accel.orientation
        let start = scan.startTimeString
        let time = StringFromDate(scan.dateFromTime(orientation.ms)!)

        let pitch = Double(DegreesToRadians(0.0))
        let yaw = Double(DegreesToRadians(CGFloat(orientation.roll)))
        let roll = Double(DegreesToRadians(CGFloat(orientation.pitch)))

        CATransaction.begin()
            CATransaction.setCompletionBlock({
                animate(scan)
            })

            bodyNode.eulerAngles = SCNVector3(pitch, yaw, roll)

            CATransaction.setAnimationDuration(0.16)
        CATransaction.commit()

    } else {
        print("No more data")
        return
    }
}

A: For SceneKit implicit animations use SCNTransaction (not CATransaction).


text:
Q: Download/Install Android App from Non-Market Web Server: How? I'm trying to do a test-download of my first app from a non-Market web server (mine).  I placed a signed APK on the server, browsed to it from my Nexus-S browser and clicked.  I get a brief message about downloading, but then zilcho, no install, no nothing.  And yes, I enabled "Unknown Sources" in the settings.  Each time I try this, a small red circle appears at the top-left of my screen with an incrementing number.
Should this work? Am I doing something wrong?
Note: I don't want to use ADB or an App installer program if avoidable (I want to let unsophisticated beta testers install it).
Thanks,
John

A: I believe this is done by the manufacturer. I've seen it on a few phones.
Try using a different ROM (like cyanogen) if you're rooted.

A: Well, I figured it out myself (Duh), it was operator error.
The answer is that I didn't understand how download-install works.  After downloading APK, I had to go to "Downloads" on my phone and select the file to install.  It's all good now.
-John


text:
Q: Singularity container: can we make a container out of an environment from within this environment? I have an ambitious demand.
I am connected to a distant server through SSH, and I have a conda environment installed on it.
Is it possible using Singularity to create a container that "copy" this distant server and the conda env that goes with it ?
Thank

A: If I understand correctly, you want to copy a folder (in this case, a conda env) into your singularity container.
You can leverage the %setup section if you have ssh keys set up with this remote host. Reference for %setup: https://apptainer.org/docs/user/main/definition_files.html#sections
Something like the following:
%setup
  scp remote_user@remote_host:/full/path/to/remote/conda/env ${APPTAINER_ROOTFS}/full/path/to/container/conda/env

Alternatively, you could create a tmpdir on your local system and scp the file into the tmpdir within %setup then use the %files to copy the files over to the container.


text:
Q: How prevalent is branch prediction on current CPUs? Due to the huge impact on performance, I never wonder if my current day desktop CPU has branch prediction. Of course it does. But how about the various ARM offerings? Does iPhone or android phones have branch prediction? The older Nintendo DS? How about PowerPC based Wii? PS 3?
Whether they have a complex prediction unit is not so important, but if they have at least some dynamic prediction, and whether they do some execution of instructions following an expected branch.
What is the cutoff for CPUs with branch prediction? A hand held calculator from decades ago obviously doesn't have one, while my desktop does. But can anyone more clearly outline where one can expect dynamic branch prediction?
If it is unclear, I am talking about the kind of prediction where the condition is changing, varying the expected path during runtime.

A: Branch prediction is getting more important and emphasized while ARM is getting more complicated.
For example new 64-bit ARM architecture called ARMv8 drops most use of conditional execution (mainly due to instruction encoding space restrictions with increased number of registers) and relies on branch prediction to keep performance at acceptable levels.
Even for newer ARMv7-a devices you can check terrible cases like unsorted data question on SO, which branch prediction improvement is around 3x.

A: Any CPU with a pipeline beyond a few stages requires at least some primitive branch prediction, otherwise it can stall waiting on computation results in order to decide which way to go.  The Intel Atom is an in-order core, but with a fairly deep pipeline, and it therefore requires a pretty decent branch predictor.
Old ARM 7 designs were only three stages.  Combine that with things like branch delay slots (required on MIPS, optional on SPARC), and branch prediction isn't so useful.
Incidentally, when MIPS decided to get more performance by going beyond 4 pipeline stages, the branch delay slot became an annoyance.  In the original design, it was necessary, because there was no branch predictor.  Therefore, you had to sequence your branch instruction prior to the last instruction to be executed before the branch.  With the longer pipeline, they needed a branch predictor, obviating the need for a branch delay slot, but they had to emulate it anyway in order to run older code.
The problem with a branch delay slot is that it can only be filled with a useful instruction about 50% of the time.  The rest of the time, you either fill it with an instruction whose result is likely to be thrown away, or you use a NO-OP.

A: Modern high end superscalar CPUs with long pipelines (which means almost all CPUs commonly found in desktops and servers) have quite sophisticated branch prediction these days.
Most ARM CPUs do not have branch prediction, which saves silicon and power consumption, but ARM CPUs generally have relatively short pipelines. Also the support for conditional execution of most instructions in the ARM ISA helps to reduce the number of branches required (and hence mitigates the cost of branch misprediction stalls).

A: Not so much for the ARM Cortex-A8 (though it does have some branch prediction), but I believe the Cortex-A9 is out-of-order super-scalar, with complex branch prediction.

A: You can expect Dynamic Branch predictor in any out of order processor, those processors not only rely on pipelining but also fetch multiple instructions at the time, and they have multiple execution units(Floating point units, ALU), more registers; to increase the instruction execution, you have multiple instructions on the fly on any given moment, of course branches are a problem if you want to keep all that machinery utilization high so this kind of processors, rely on dynamic branch prediction in order to keep throughput and utilization very high.
You can expect any server to have dynamic branch prediction, also desktops, in the past embedded systems like the ARM chips in current smartphones did not have branch predictions since they had smaller pipelines, and they did not have out of order execution, but as Moore's law give us more transistor per area, you will start seeing more and more processors increasing their architecture. So to answer your question, besides the obvious looking for the CPU specs, you can expect to have branch prediction on chips of 32 Bits, bigger pipelines, out of order exection. The most recent chips from ARM are moving in some level to this directions.


text:
Q: Can a positive operator acting on $C_{b}(X)$ be extended to a positive operator acting on $C(\beta X)$? Let $X$ be a normal or completely regular topological space, $C_{b}(X)$ the set of all real bounded continuous functions on $X$ and $T:C_{b}(X)\to C_{b}(X)$ a positive linear operator. I would like to know wether $T$ can be extended to a positive linear operator $\bar{T}:C(\beta X) \to C(\beta X)$, where $\beta X$ is the Stone-Cech compactification of $X$.

A: This is completely trivial, since $C_b(X)$ and $C(\beta X)$ are the same thing so there's no "extending" to do at all.  More precisely, the map $r:C(\beta X)\to C_b(X)$ taking a function on $\beta X$ to its restriction to $X$ is an isomorphism (of Banach lattices, or of pretty much any natural structure you might care about).  The fact that $r$ is a bijection is immediate from the definition of $\beta X$ (by definition, every bounded continuous function on $X$ extends uniquely to $\beta X$).  Clearly $r$ is linear, and the fact that it preserves the norm and the order follows from the fact that $X$ is dense in $\beta X$ and so if $f\in C(\beta X)$, the image of $f$ is just the closure of the image of the restriction $r(f)$.
(Note that none of this even requires $X$ to be completely regular; you just have to interpret "restrict from $\beta X$ to $X$" to mean "compose with the canonical map $X\to\beta X$", since that map may not be injective.)

A: If we also assume that $X$ is Hausdorff, then we can consider $X \subseteq \beta X$. Define $$\overline T : C(\beta X) \to C(\beta X): f \mapsto \beta(Tf|_X)$$
Linearity of $\overline T$ follows from the universality of $\beta$: $a\overline T(f) + b\overline T(g)$ is an extension of $T((af + bg)|_X) = aT(f|_X) + bT(g|_X)$ to all of $\beta X$, and thus must be the unique extension $\beta(T(af + bg)|_X) = \overline T(af + bg)$.
And if $f \ge 0$, then $T(f|_X) \ge 0$ by the positivity of $T$. Hence $ T(f|_X) \subseteq [0, b]$ for some $b$, and so $\overline T(f) = \beta T(f|_X) \subseteq [0, b]$ as well (by definition, the $\beta$ lifting does not change the compact codomain of the function). Thus $\overline T(f) \ge 0$.
If we don't have that $X$ is Hausdorff, then I'm not sure that it holds.


text:
Q: Connection from Express App to MongoDB container refused with Docker-Compose When trying to connect my express app to a mongo container with docker-compose the connection is refused. I am able to connect to the db container with robo3T using localhost:27017 and the l/p  setup with the dbSetup.js, but when express tries to connect I get an error:
{ MongoNetworkError: failed to connect to server [mongo:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 172.19.0.2:27017]
// mongoose
const options = {
  autoIndex: true, // Don't build indexes
  reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
  reconnectInterval: 500, // Reconnect every 500ms
  poolSize: 10, // Maintain up to 10 socket connections
  // If not connected, return errors immediately rather than waiting for reconnect
  bufferMaxEntries: 0
};
console.log(options);
mongoose.connect('mongodb://blogUser:blogUserPassword@mongo/blog', options).then(
  () => { console.log("connected !!!"); },
  err => { console.log(err);  }
);

The Docker-Compose
version: '3'

services:
  mongo:
    container_name: mongo
    image: mongo
    environment:
      - MONGO_INITDB_ROOT_USERNAME=${MONGO_INITDB_ROOT_USERNAME}
      - MONGO_INITDB_ROOT_PASSWORD=${MONGO_INITDB_ROOT_PASSWORD}
    volumes:
      - ./dbSetup.js:/docker-entrypoint-initdb.d/dbSetup.js
      - /data/db:/data/db
    ports:
      - "27017:27017"

  blog_api:
    container_name: blog_api
    build: ../blog.com/api
    restart: always
    expose:
      - 3000
    ports:
      - "3000:3000"
    links:
      - mongo
    depends_on:
      - mongo

A: If you can run the app after the mongo service is running, it means mongo is taking longer to start up and be connection-ready than when your app tries to connect. If your app doesn't ever connect it may not be restarting properly - you probably want it to exit if it doesn't connect and then make sure you have your Docker restart policy set accordingly ("always", "on-failure", etc.) see docs. Assuming mongo eventually starts up, your app will eventually connect.
You can also look into using healthchecks in which case you could see if the database is actually connecting rather than starting up. The depends_on flag will only check to see that the container is up, it doesn't check to see if the apps in the container are running much less if they are working properly.


text:
Q: reboot on kernel panic and drac Does anyone know if it is possible to have a DRAC5 make a screenshot of the console when Linux reboots (automatically) due to a kernel panic?
Our current system doesn't reboot automatically when it panics, so we can manually make a screenshot using the DRAC when it crashes.
However, I'd like to configure it so it will reboot automatically when a panic happens, but still be able to log the cause of the crash.

A: I'm not certain about the Drac 5, but the iDrac 6 Enterprise version records every boot, and keeps the last 3 in memory so you can replay them. The express version does not though. Also, it records only the boot, so if you're looking for information that would be before that (which is, I assume, where you would see the kernel panic), I think you're out of luck.
In Windows, I can tell it not to automatically reboot, this way I can see the screen before I reboot it manually. Is there some equivalent in Linux?


text:
Q: Probability for finding a double-as-likely event Repeating an experiment with $n$ possible outcomes $t$ times independently, where all but one outcomes have probability $\frac{1}{n+1}$ and the other outcome has the double probability $\frac{2}{n+1}$, is there a good approximate formula for the probability that the outcome with the higher probability happens more often than any other one?
For me, $n$ is typically some hundreds, and $t$ is chosen depending on $n$ such that the probability that the most likely outcome occurs most often is between 10% and 99.999%.
In the moment I use a small program that calculates a crude approximation by assuming that the counts for how often each outcome shows up in $t$ trials are independent and approximate the counts using the Poisson distribution. How can I improve on this?
EDIT: I'd strongly appreciate comments/votes on the two (maybe soon more) answers given.
EDIT 2: As none of the two answers is convincing me, but as I don't want to let the 100 points bounty to vanish (and as nobody voted for/against one of the two answers), I'll just pick one of the answers. I'd still appreciate other answers.

A: Partition the outcomes by the frequency of occurrences $x$ of the "double outcome", $0 \le x \le t$.  Conditional on this number, the distribution of the remaining $t-x$ outcomes is multinomial across $n-1$ equiprobable bins.  Let $p(t-x, n-1, x)$ be the chance that no bin out of $n-1$ equally likely ones receives more than $x$ outcomes.  The sought-for probability therefore equals
$$\sum_{x=0}^{t} \binom{t}{x}\left(\frac{2}{n+1}\right)^x \left(\frac{n-1}{n+1}\right)^{t-x} p(t-x,n-1,x).$$
In Exact Tail Probabilities and Percentiles of the Multinomial Maximum, Anirban DasGupta points out (after correcting typographical errors) that $p(n,K,x)K^n/n!$ equals the coefficient of $\lambda^n$ in the expansion of $\left(\sum_{j=0}^{x}\lambda^j/j!\right)^K$ (using his notation).  For the values of $t$ and $n$ involved here, this coefficient can be computed in at most a few seconds (making sure to discard all $O(\lambda^{n+1})$ terms while performing the successive convolutions needed to obtain the $K^{\text{th}}$ power).  (I checked the timing and corrected the typos by reproducing DasGupta's Table 4, which displays the complementary probabilities $1 - p(n,K,x)$, and extending it to values where $n$ and $K$ are both in the hundreds.)
Quoting a theorem of Kolchin et al., DasGupta provides an approximation for the computationally intensive case where $t$ is substantially larger than $n$.  Between the exact computation and the approximation, it looks like all possibilities are covered.

A: I agree with some comments, in that the Poisson approximation sounds nice here (not a 'crude' approximation). It should be asympotically exact, and it seems the most reasonable thing to do, as an exact analytic solutions seems difficult.
As an intermediate alternative, (if you really need it) I suggest I fisrt order correction to the Poisson approximation, in the following way (I've done something similar some time ago, and it worked).
As suggested by a comment, your model is (not approximately but exactly) Poisson if we condition on the sum. That is:
Let $X_t$ ($t$ is a parameter here) be a vector of $n$ independent Poisson variables, the first one with $\lambda = 2t/(n+1)$, the others with $\lambda = t/(n+1)$. Let $s=\sum x$, so $E(s)=t$. It is clear that $X_t$ is not equivalent to other model (because our model is restricted to $s=t$), but it is a good approximation. Further, the distribution of $X_t | s$ is equivalent to our model. Indeed, we can write
$ \displaystyle P(X_t) = \sum_s P(X_t | s) P(s)$
This can also be writen for the event in consideration (that $x_1 $ is the maximum).
We know to compute the LHS, and $P(s)$, but we are interested in the other term. Our first order Poisson approximation comes from assuming that $P(s)$ concentrates about the mean so that it can be assimilated to a delta, and then $ P(X_t) \approx  P(X_t | s=t) $
To refine the aprroximation, we can see the above as a convolution of two functions: our unknown $P(X_t | s)$, which we assume smooth around $s=t$, and a quasi delta function, say a gaussian with small variance. Now, we have our first order approximation (for continuous variables) :
$h(x) = g(x)  * N(x_0,\sigma^2)$ (convolution)
$h(x_0) \approx g(x_0)  + g(x_0)''\sigma^2/2$
$g(x_0) \approx h(x_0)  - h''(x_0)''\sigma^2/2$
Applying this to the previous equation can lead to a refined approximation to our desired probability.

A: Just a word of explanation: Part out of curiosity, part for lack of a better more theoretical method, i approached the problem in a completely empirical/inductive way. I'm aware that there is the risk of getting stuck in a dead end without gaining much insight, but i thought, i'll just present what i got so far anyway, in case it is useful to someone.
Starting by computing the exact probabilities for $n,t\in\{1,...,8\}$ we get

Due to the underlying multinomial distribution, multiplying the entries in the table by $(n+1)^t$ leaves us with a purely integer table:

Now we find that there is a polynomial in $n$ for every column which acts as the sequence function for that column:

Dividing the sequence functions by $(n+1)^t$ gives us sequence functions for the original probabilities for the first $t$'s. These rational polynomials can be simplified by decomposing them into partial fractions and substituting $x$ for $1/(n+1)$, leaving us with:

or as coefficient table

Starting with the $x^2$ column there are sequence functions for these coefficients again:

That's how far i got. There are definitely exploitable patterns here that allow sequence functions to occur, but i'm not sure if there is a nice closed form solution for these sequence functions.


text:
Q: django.db.utils.IntegrityError: NOT NULL contraint failed: appname_modelName.id I am creating a client management system in django.
I have two models called 'Client' and 'Installment'. my 'models.py' file is given below:
models.py

from django.db import models
from django.utils import timezone
from django.urls import reverse
# Create your models here.

class Client(models.Model):
    name = models.CharField(max_length = 100)
    dob = models.SlugField(max_length = 100)
    CNIC = models.SlugField(max_length = 100)
    property_type = models.CharField(max_length = 100)
    down_payment = models.IntegerField()
    date_posted = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('client_details',kwargs={ 'pk' : self.pk})

class Installment(models.Model):
    client = models.ForeignKey(Client, blank=True, on_delete=models.CASCADE)
    installment_month = models.CharField(max_length = 100)
    installment_amount = models.IntegerField()
    installment_date = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.installment_month

    def get_absolute_url(self):
        return reverse('installment_confirmation')

I am using ForeignKey in the installment model to link the Client model to it, because one client can have multiple installments.
When I RUN the following two commands
python manage.py makemigrations
python manage.py migrate

I didn't get any error.
Then I RUN the server using:
python manage.py runserver

and it runs successfully.
Then I add a new client in My app that uses client model.
But when I want to add installment to the client, is takes input from the user in the fields (installment_month and installment_month), and when I click 'add installment', it gives the following error:
IntegrityError at /1/Add-Installment
NOT NULL constraint failed: property_details_installment.client_id
Request Method: POST
Request URL:    http://127.0.0.1:8000/1/Add-Installment
Django Version: 2.1.3
Exception Type: IntegrityError
Exception Value:
NOT NULL constraint failed: property_details_installment.client_id
Exception Location: /anaconda3/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 296
Python Executable:  /anaconda3/bin/python3
Python Version: 3.6.5
Python Path:
['/Users/razajaved/Documents/installment_plan',
 '/anaconda3/lib/python36.zip',
 '/anaconda3/lib/python3.6',
 '/anaconda3/lib/python3.6/lib-dynload',
 '/anaconda3/lib/python3.6/site-packages',
 '/anaconda3/lib/python3.6/site-packages/aeosa']
Server time:    Sun, 28 Mar 2021 13:55:36 +0000

What I tried next is that I removed the 'blank=True' parameter from the ForeignKey line in the installment model. and then it adds the installment successfully.
But, to check that the added installment is correctly corresponds to the added client. I went into the shell using the following command:
python manage.py shell

Once in the shell i did the following:
from property_details.models import Client
from property_details.models import Installment

Then I tried to check the client I added using the following command:
client1 = Client.objects.filter('clientName')

It works.
I can also check the added installment using the above command.
But when I RUN
client1.id

it gives the following error:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-abd51507c2e0> in <module>()
----> 1 client1.id

AttributeError: 'QuerySet' object has no attribute 'id'

But when I RUN
installment.id

it returns the id of the added installment.
It looks like, there is some problem with the ForeignKey I used in the installment model, and there is no id assigned to the client. I have tried different solution like putting 'blank=True' OR 'null=True' parameters. But it didn't work for me.
Does anyone has an idea how to solve this problem?

A: one error what I can see is this:
client1 = Client.objects.filter('clientName')

it should be like this:
client1 = Client.objects.filter('clientName').first()

filter() returns QuerySet you have to get the model instance either by first() or slicing then only you can access the fields like client1.id


text:
Q: SharedArray Deadlock and raise Conditions I'm trying to stimulate the scenario of deadlocks in the shared array using Reentrant Locks.
class SharedArray {
    private int ff[];
    private Lock keys[];

    public SharedArray(int n){
        ff = new int[n];
        keys = new ReentrantLock[n];
        for(int j = 0; j < n; j++){
            ff[j] = (int)(Math.random()*100);
            keys[j] = new ReentrantLock();
        }
    }

    void swap(int j, int k) {
        keys[j].lock(); keys[k].lock();
        int t = ff[j]; ff[j] = ff[k]; ff[k] = t;
        keys[j].unlock(); keys[k].unlock();
    }
}

Here the swap method is deadlock prone which I have achieved. for example if Thread 1 is swap(7,4) and at the same time Thread 2 is swap(4,7) this will raised the deadlock.
How do I prevent it from deadlock. What sort of refactoring is required. I have tried to used synchronized but I'm looking for possibly a reliable way to solve that.
synchronized void swap(int j, int k) {
    keys[j].lock(); keys[k].lock();
    int t = ff[j]; ff[j] = ff[k]; ff[k] = t;
    keys[j].unlock(); keys[k].unlock();
}

A:
How do I prevent it from deadlock?

One way to prevent deadlock would be to ensure that any threads that acquire the same two locks always will acquire them in the same order.
void swap(int j, int k) {
    int first = Math.min(j, k);
    int second = Math.max(j, k);
    keys[first].lock(); keys[second].lock();
    int t = ff[j]; ff[j] = ff[k]; ff[k] = t;
    keys[second].unlock(); keys[first].unlock();
}

A: You want to employ lock ordering. If you lock each time in a predictable order you can prevent dead locking.
Found in Java Concurrency In Practice, you can see an example of how to achieve this:
public void transferMoney(final Account fromAcct, final Account toAcct, final DollarAmount amount)
        throws InsufficientFundsException {
    class Helper {
        public void transfer() throws InsufficientFundsException {
            if (fromAcct.getBalance().compareTo(amount) < 0)
                throw new InsufficientFundsException();
            else {
                fromAcct.debit(amount);
                toAcct.credit(amount);
            }
        }
    }
    int fromHash = System.identityHashCode(fromAcct);
    int toHash = System.identityHashCode(toAcct);
    if (fromHash < toHash) {
        synchronized (fromAcct) {
            synchronized (toAcct) {
                new Helper().transfer();
            }
        }
    } else if (fromHash > toHash) {
        synchronized (toAcct) {
            synchronized (fromAcct) {
                new Helper().transfer();
            }
        }
    } else {
        synchronized (tieLock) {
            synchronized (fromAcct) {
                synchronized (toAcct) {
                    new Helper().transfer();
                }
            }
        }
    }
}

https://pdfs.semanticscholar.org/3650/4bc31d3b2c5c00e5bfee28ffc5d403cc8edd.pdf, search for Listing 10.3. Inducing a Lock Ordering to Avoid Deadlock.


text:
Q: Logging data to database with EnterpriseLibrary Hi I am trying to integrate EnterprisLibrary Logging block into my application using a database as storage.Here is what I have so far:
I have runed the scripts for the database and have created a database called e-shop.Logging
that has 3 tables Category , CategoryLog and Log.
I have created this configuration on my web config:

In my code I have this configuration class:
public static class LoggerBootstrapper
{
    public static void Start()
    {
        DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory());

        Logger.SetLogWriter(new LogWriterFactory().Create());
    }
}

This is called in Global.asax in my WebApi project.
And this is the class that I use in my entire application:
[InjectorRegistration(typeof(IExceptionLogger))]
public class ExceptionLogger : IExceptionLogger
{
    public void LogServerException(Exception exception)
    {
        string logger = LoggerCategories.ServerLogger.ToString();
        Logger.Write(exception, LoggerCategories.ServerLogger.ToString());
    }

    public void LogClientException(Exception exception)
    {
        Logger.Write(exception, LoggerCategories.ClientLogger.ToString());
    }
}
 public enum LoggerCategories
{
    ServerLogger,
    ClientLogger
}

When I call the LogServerException or LogClientException , the data get's stored in the Log table but nothing get's stored in the Category and CategoryLog tables.
I first asummed that I had to add the categories myself so I added this two categories:
ServerLogger
ClientLogger
Of course it did not work.I have seen this configured that when you add a category it automaticly get's added to the Category table and when an exception get's added the mapping beetween Category and Log is automaticly done threw CategoryLog.
Does anyone know what I am doing wrong here?
Why when I am adding an exception data get's added only in  the log table and the other two table are not updated?

A: After going threw the XML I realized that the stored procedure ressposible for adding the category was not set right.I had it set to ServerLogger an the actual stored procedure name was AddCateogry.


text:
Q: django uploadify 302 error with @user_passes_test decorator Hi I'm using Uploadify in one of my django applications. It works fine. But when I use the @user_passes_test decorator, uploadify is getting a Http 302 error. Only logged in users with a specific permission should be allowed to use the fileupload.
my view looks like this:
@user_passes_test(lambda u: u.has_perm('cylebrations.can_multiupload'))
def myFileHandler(request):
    if request.method == 'POST':
        for field_name in request.FILES:
            image=Image(gallery_id=gallery.id, image=request.FILES[field_name])
            image.save()
            return HttpResponse("ok", mimetype="text/plain")
    return render_to_response('gallery_upload.html', context_instance=RequestContext(request))

when I use something like following in the view instead of the decorator, I also get a 302 error.
if not request.user.has_perm('cylebrations.can_multiupload'):
    return HttpResponse("You can't upload.")

It looks like the view doesn't get the userinformation.
Is there any way to pass the neccessary user information through uploadifys postData setting? How can I use uploadify with django permissions?

A: Here is a forum entry, that shows how it can be done:
http://www.uploadify.com/forum/#/discussion/7195/uploadify-3-0-beta-with-django/p1
It contains a link to another stackoverflow question which might be helpful too.


text:
Q: How to conform UIImage to Codable? Swift 4 has Codable and it's awesome. But UIImage does not conform to it by default. How can we do that?
I tried with singleValueContainer and unkeyedContainer
extension UIImage: Codable {
  // 'required' initializer must be declared directly in class 'UIImage' (not in an extension)
  public required init(from decoder: Decoder) throws {
    let container = try decoder.singleValueContainer()
    let data = try container.decode(Data.self)
    guard let image = UIImage(data: data) else {
      throw MyError.decodingFailed
    }

    // A non-failable initializer cannot delegate to failable initializer 'init(data:)' written with 'init?'
    self.init(data: data)
  }

  public func encode(to encoder: Encoder) throws {
    var container = encoder.singleValueContainer()
    guard let data = UIImagePNGRepresentation(self) else {
      return
    }

    try container.encode(data)
  }
}

I get 2 errors

*

*'required' initializer must be declared directly in class 'UIImage' (not in an extension)

*A non-failable initializer cannot delegate to failable initializer 'init(data:)' written with 'init?'

A workaround is to use wrapper. But are there any other ways?

A: One way to pass an UIImage is to convert it to something that conforms to Codable, like String.
To convert the UIImage to String inside func encode(to encoder: Encoder) throws:
let imageData: Data = UIImagePNGRepresentation(image)!
let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
try container.encode(strBase64, forKey: .image)

To convert the String back to UIImage inside required init(from decoder: Decoder) throws:
let strBase64: String = try values.decode(String.self, forKey: .image)
let dataDecoded: Data = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters)!
image = UIImage(data: dataDecoded)

A: The existing answers all appear to be incorrect. If you compare the deserialized image with the original, you will find they may well not be equal in any sense. This is because the answers are all throwing away the scale information.
You have to encode the image scale as well as its pngData(). Then when you decode the UIImage, combine the data with the scale by calling init(data:scale:).

A: The best solution is to use a custom property wrapper

*

*the property remains mutable

*no code alternations needed, just add the @CodableImage prefix

Usage
class MyClass: Codable {

    @CodableImage var backgroundImage1: UIImage?
    @CodableImage var backgroundImage2: UIImage?
    @CodableImage var backgroundImage3: UIImage?

Add this code to project:
@propertyWrapper
public struct CodableImage: Codable {

    var image: UIImage?

    public enum CodingKeys: String, CodingKey {
        case image
    }

    public init(image: UIImage?) {
        self.image = image
    }

    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        if let b = try? container.decodeNil(forKey: CodingKeys.image), b {

            self.image = nil

        } else {

            let data = try container.decode(Data.self, forKey: CodingKeys.image)

            guard let image = UIImage(data: data) else {
                throw DecodingError.dataCorruptedError(forKey: CodingKeys.image, in: container, debugDescription: "Decoding image failed")
            }

            self.image = image

        }

    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        if let data = image?.pngData() {
            try container.encode(data, forKey: CodingKeys.image)
        } else {
            try container.encodeNil(forKey: CodingKeys.image)
        }
    }

    public init(wrappedValue: UIImage?) {
        self.init(image: wrappedValue)
    }

    public var wrappedValue: UIImage? {
        get { image }
        set {
            image = newValue
        }
    }

}

A: Properly the easiest way is to just make the property Data instead of UIImage like this:
public struct SomeImage: Codable {

    public let photo: Data

    public init(photo: UIImage) {
        self.photo = photo.pngData()!
    }
}

Deserialize the image:
UIImage(data: instanceOfSomeImage.photo)!

A: A solution: roll your own wrapper class conforming to Codable.
One solution, since extensions to UIImage are out, is to wrap the image in a new class you own. Otherwise, your attempt is basically straight on. I saw this done beautifully in a caching framework by Hyper Interactive called, well, Cache.
Though you'll need to visit the library to drill down into the dependencies, you can get the idea from looking at their ImageWrapper class, which is built to be used like so:
let wrapper = ImageWrapper(image: starIconImage)
try? theCache.setObject(wrapper, forKey: "star")

let iconWrapper = try? theCache.object(ofType: ImageWrapper.self, forKey: "star")
let icon = iconWrapper.image

Here is their wrapper class:
// Swift 4.0
public struct ImageWrapper: Codable {
  public let image: Image

  public enum CodingKeys: String, CodingKey {
    case image
  }

  // Image is a standard UI/NSImage conditional typealias
  public init(image: Image) {
    self.image = image
  }

  public init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    let data = try container.decode(Data.self, forKey: CodingKeys.image)
    guard let image = Image(data: data) else {
      throw StorageError.decodingFailed
    }

    self.image = image
  }

  // cache_toData() wraps UIImagePNG/JPEGRepresentation around some conditional logic with some whipped cream and sprinkles.
  public func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    guard let data = image.cache_toData() else {
        throw StorageError.encodingFailed
    }

    try container.encode(data, forKey: CodingKeys.image)
  }
}

I'd love to hear what you end up using.
UPDATE: It turns out the OP wrote the code that I referenced (the Swift 4.0 update to Cache) to solve the problem. The code deserves to be up here, of course, but I'll also leave my words unedited for the dramatic irony of it all. :)

A: You can use very elegant solution using extension for KeyedDecodingContainer and KeyedEncodingContainer classes:
enum ImageEncodingQuality {
  case png
  case jpeg(quality: CGFloat)
}

extension KeyedEncodingContainer {
  mutating func encode(
    _ value: UIImage,
    forKey key: KeyedEncodingContainer.Key,
    quality: ImageEncodingQuality = .png
  ) throws {
    let imageData: Data?
    switch quality {
    case .png:
      imageData = value.pngData()
    case .jpeg(let quality):
      imageData = value.jpegData(compressionQuality: quality)
    }
    guard let data = imageData else {
      throw EncodingError.invalidValue(
        value,
        EncodingError.Context(codingPath: [key], debugDescription: "Failed convert UIImage to data")
      )
    }
    try encode(data, forKey: key)
  }
}

extension KeyedDecodingContainer {
  func decode(
    _ type: UIImage.Type,
    forKey key: KeyedDecodingContainer.Key
  ) throws -> UIImage {
    let imageData = try decode(Data.self, forKey: key)
    if let image = UIImage(data: imageData) {
      return image
    } else {
      throw DecodingError.dataCorrupted(
        DecodingError.Context(codingPath: [key], debugDescription: "Failed load UIImage from decoded data")
      )
    }
  }
}

PS: You can use such way to adopt Codable to any class type

A: There's also a simple solution using lazy var on the image:
var mainImageData: Data {
    didSet { _ = mainImage }
}
lazy var mainImage: UIImage = {
    UIImage(data: mainImageData)!
}()

This way, during object initialization and assignment to mainImageData, its didSet will kick in which will then initiate the initialization of the UIImage.
Since UIImage initialization is resource heavy, we couple them together.
Just pay attention that the entire initialization will be on the background thread.

A: Swift 5.4
// MARK: - ImageWrapper

public struct ImageWrapper: Codable {

    // Enums

    public enum CodingKeys: String, CodingKey {
        case image
    }

    // Properties

    public let image: UIImage

    // Inits

    public init(image: UIImage) {
        self.image = image
    }

    // Methods

    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let data = try container.decode(Data.self, forKey: CodingKeys.image)
        if let image = UIImage(data: data) {
            self.image = image
        } else {
            // Error Decode
        }
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        if let imageData: Data = image.pngData() {
            try container.encode(imageData, forKey: .image)
        } else {
            // Error Encode
        }
    }
}


text:
Q: Disable autorotate while animation show Can I disable autorotation if my views animated in this moment? And then if orientation changed, after end of animation - change orientation manual

A: try setting a flag when animation begins and based on that flag return NO from orientation delegates and once animation is completed reset the flag.


text:
Q: How to move to the bottom of Facebook permission dialog? In my app, I request permission: [publish_stream,offline_access] and the permission dialog show as
I want the dialog show the allow button directly, just as following without scroll

Could you give me a hand?

A: This is a bug. File a bug @ https://developers.facebook.com/bugs and it will get reviewed.


text:
Q: Structuring SQL query Help structuring SQL query:
Select Distinct ilc.itemnum, id.itemname, statename, realname
From hsi.itemlc ilc
INNER JOIN hsi.itemdata id ON
id.itemnum = ilc.itemnum
INNER JOIN hsi.lcstate lcs ON
lcs.statenum = ilc.statenum
INNER JOIN hsi.useraccount ua ON
ua.usernum = id.usernum
INNER JOIN hsi.wftransactionlog wft ON
id.itemnum = wft.itemnum

Where ilc.statenum not in ('143','144')
and ilc.lcnum in ('101','252')
and ilc.status <> 16

On my last join to hsi.wftransactionlog I only want to pull the max wft.logdate when id.itemnum = wft.itemnum.   What is the best way to accomplish this?  There are several "itemnum's" in  hsi.wftransactionlog but I only want to grab the matches in the table on the latest wft.logdate.
Please let me know if this doesn't make sense.

A: You can use a CROSS APPLY with a sub query:
SELECT DISTINCT ilc.itemnum, id.itemname, statename, realname
From hsi.itemlc ilc
INNER JOIN hsi.itemdata id ON
id.itemnum = ilc.itemnum
INNER JOIN hsi.lcstate lcs ON
lcs.statenum = ilc.statenum
INNER JOIN hsi.useraccount ua ON
ua.usernum = id.usernum
CROSS APPLY ( SELECT MAX(logdate) AS logdate
              FROM hsi.wftransactionlog wft
              WHERE id.itemnum = wft.itemnum
            ) wft1

A: Bit of a shot in the dark without any example data to test on, but using a subquery might work for you.
Select Distinct ilc.itemnum, id.itemname, statename, realname,
        ( select max(wft.logdate)
            hsi.wftransactionlog wft
            where wft.itemnum = id.itemnum
        ) as logdate
    From hsi.itemlc ilc
    INNER JOIN hsi.itemdata id ON id.itemnum = ilc.itemnum
    INNER JOIN hsi.lcstate lcs ON lcs.statenum = ilc.statenum
    INNER JOIN hsi.useraccount ua ON ua.usernum = id.usernum
    Where ilc.statenum not in ('143','144')
        and ilc.lcnum in ('101','252')
        and ilc.status <> 16


text:
Q: OSX: "last" command and utmpx We have a bunch of OSX Yosemite machines.  I can go to any of them and issue the last command and see possibly a year of records.  I know that OSX went to using utmpx years ago but I don't think last uses that facility under the hood.  I can see the utmpx file for a given machine in /var/run (/private/var/run/) but each one is tiny.
I have a simple C program that reads the local utmpx file (getutxent) but only see a couple of records, justifying the small size of the file.  I think I know that the utmpx system is not "started" until the utmpx file exists so it is possible that my exploration created the now tiny files.
What resource is the OSX last command reading from?
What is the current state of the art for getting machine usage data off of Macs?

A: Since Mac OS X 10.6 (Snow Leopard) Apple has replaced the utmp/wtmp mechanism with the Apple logging system. See man 5 utmpx for details.  Here is a pertinent excerpt:
Traditionally, separate files would be used to store the running log of the logins
and logouts (wtmpx), and the last login of each user (lastlogx).  With the avail-
ability of the Apple system log facility asl(3), these separate files can be
replace with log entries, which are automatically generated when utmpx entries are
written.  The API to access the logins and logouts is described in
endutxent_wtmp(3) while the last login info is accessible with getlastlogx(3).

See man asl for the programatic interface to the log system.  Apple Syslog saves all its utmp/wtmp/lastlog-like information in /var/log/asl/*.


text:
Q: Populate dataTable with knockout observable array I want to populate my dataTable with knockoutjs objervable array.
here is my javascript code:
function AppViewModel()
{
var self = this;
self.tableData = ko.observableArray();

 $.ajax({
    type: "GET",
    url: "<?php echo $this->config->base_url('api/categoryList')?>",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
            console.log(result);
            self.tableData(result);
        },

    error: function (err) {
            alert("err");
        }
      });// you have missed this bracket

}

var vm = new AppViewModel();
ko.applyBindings(vm);

here is my HTML:
The json objest that I am getting from ajax request is:
{
    "aaData": [
        {
            "client_Id": "",
            "categoryId": "1",
            "categoryName": "Individual",
            "categoryDescription": "",
            "lastUpdatedBy": ""
        },
        {
            "client_Id": "",
            "categoryId": "2",
            "categoryName": "Firm",
            "categoryDescription": "",
            "lastUpdatedBy": ""
        },
        {
            "client_Id": "",
            "categoryId": "3",
            "categoryName": "Private Limited Company",
            "categoryDescription": "",
            "lastUpdatedBy": ""
        },
        {
            "client_Id": "",
            "categoryId": "5",
            "categoryName": "company",
            "categoryDescription": "",
            "lastUpdatedBy": ""
        }
    ]
}

I am getting object is not a function error in javascript and DataTable cannot be reinitialize alert.

Please help with this.
Thank you.

A: You are populating the observableArray with a object that is not an array:
success: function (result) {
    console.log(result);
    self.tableData(result);

and you say that
result = {
    "aaData": [
        {"client_Id":"","categoryId":"1","categoryName":"Individual","categoryDescription":"","lastUpdatedBy":""},
        {"client_Id":"","categoryId":"2","categoryName":"Firm","categoryDescription":"","lastUpdatedBy":""},
        {"client_Id":"","categoryId":"3","categoryName":"Private Limited Company","categoryDescription":"","lastUpdatedBy":""},
        {"client_Id":"","categoryId":"5","categoryName":"company","categoryDescription":"","lastUpdatedBy":""}
    ]
}

so you need to fill the observableArray with result.aaData:
success: function (result) {
    console.log(result);
    self.tableData(result.aaData);

Edit:
Seeing the source of datatbles bindingHandler you're using (Knockout.js DataTable bindings), your binding options are incorrect. You should replate aaData with data here:
<table class="table table-bordered"
    data-bind="
        dataTable: {
            data: tableData,  // <-- Here!
            options: {
                ...

A: Try this out! This is what I did to integrate knockout with datatables but I had to add a couple of custom events to knockout's code...
I hope they add the events to knockout source...
NOTE:  The link for this fiddle does not work
[JSFiddle]


text:
Q: Django App incorporated with Multiprocessing using Gevent library facing race condition or may be some thing else I use a global dictionary variable as a cache to keep track of tokens issued for a user on day to day basis. The tokens are getting duplicated. Code logic is given below. I use Django 1.8 with Nginx server spawning multiple Gunicorn threads using Gevent library

--------------config.py----------------

    global DOCTOR_TOKEN_CACHE
    DOCTOR_TOKEN_CACHE = {}

---------------------------------------

    if consultant_code in config.DOCTOR_TOKEN_CACHE:
        config.DOCTOR_TOKEN_CACHE[consultant_code] += 1
    else:
        last_encounter = models.Encounter.objects.filter(
                consultation_date=encounter.consultation_date
            ).exclude(token_no=None).order_by('token_no').last()

        if last_encounter:
           tkn = (last_encounter.token_no+1) if last_encounter.token_no else 1
        else:
           tkn = 1
        config.DOCTOR_TOKEN_CACHE[consultant_code] = tkn

Here even if the cache gets empty there is logic to set the cache back but in spite of all this the tokens are getting duplicated which I'am not able to figure out. Kindly help me out


text:
Q: How to react to end of dragging in a custom component I noticed that it is not guaranteed that a components pointerReleased method is called after its pointerPressed method has been called.
With a Conponent derivate - one that handles pointer events - what would be the recommended way to get notified of a pointer released event under all circumstances?
Say my custom component is supposed to be green and gets red when tapped. How would I warrant that it becomes green again when the pointer is no longer pressed?

New example - Component derivate with isStickyDrag() returning true - pointer events are logged - when the component is pressed and then dragged vertically the surrounding Container instance scrolls - no pointerReleased then:
    Form hi = new Form("Hi World", BoxLayout.y());
    hi.setScrollableY(true);
    Component component = new Component() {
        @Override
        protected Dimension calcPreferredSize() {
            return new Dimension(120, 120);
        }
        @Override
        public void paint(Graphics aGraphics) {
            aGraphics.setColor(0x000000);
            aGraphics.drawRoundRect(getX(), getY(), getWidth() - 1, getHeight() - 1, 20, 20);
        }
        @Override
        protected boolean isStickyDrag() {
            return true;
        }
        protected int getDragRegionStatus(int x, int y) {
            return Component.DRAG_REGION_IMMEDIATELY_DRAG_XY;
        };
        @Override
        public void pointerPressed(int x, int y) {
            super.pointerPressed(x, y);
            Log.p("pointerPressed(" + x + ", " + y + ")");
        }
        @Override
        public void pointerReleased(int x, int y) {
            super.pointerReleased(x, y);
            Log.p("pointerReleased(" + x + ", " + y + ")");
        }
    };
    hi.add(component);
    hi.show();

A: It should override the isStickyDrag method as such:
protected boolean isStickyDrag() {
    return true;
}

It already defines it and in this case should always receive pointer released events.