text:
Q: How do I save an SVG file to clipboard using processing/java? I am creating a program using processing(java) that outputs an SVG file for me to add it to PowerPoint and other programs.
I figured it would be a lot more convenient for the program to directly copy the generated file to my system clipboard, instead of having to copy the file from the output directory.
The trouble is that I can't find a way to set the contents of the clipboard to an SVG file. I've found ways that work with images, but not SVG. To clarify, I want the pasted file to be an SVG too because I want to edit the shapes and lines in PowerPoint afterward.
I am also open to javascript solutions which may work on the web. The goal is to be able to paste an editable collection of shapes, lines, and texts into PowerPoint.
All help is appreciated, thanks in advance!
Edit: Here is the code that works for images:
import java.awt.image.*;
import java.awt.*;
import java.awt.datatransfer.*;
import javax.imageio.*;

void setup() {
  size(200, 200);
  background(0);
  Image img=null;
  try {
    img = ImageIO.read(new File("path/to/file.jpg"));//path to image file
  }
  catch (IOException e) {
    print(e);
  }

  ImageSelection imageSelection = new ImageSelection(img);
  Toolkit toolkit = Toolkit.getDefaultToolkit();
  toolkit.getSystemClipboard().setContents(imageSelection, null);
}
void draw() {
}
public class ImageSelection implements Transferable {
  private Image image;

  public ImageSelection(Image image) {
    this.image = image;//added on
  }

  public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
    if (flavor.equals(DataFlavor.imageFlavor) == false) {
      throw new UnsupportedFlavorException(flavor);//usually with transferable
    }
    return image;
  }

  public boolean isDataFlavorSupported(DataFlavor flavor) {
    return flavor.equals(DataFlavor.imageFlavor);//usually with transferable
  }

  public DataFlavor[] getTransferDataFlavors() {
    return new DataFlavor[] {
      DataFlavor.imageFlavor//usually with transferable
    };
  }
}

A: There is a bit of confusion with the code you posted: so far it looks like for some reason you want to load an image and copy that to the clipboard, not an SVG.
If you want to copy an SVG to the clipboard for PowerPoint there are a few hoops to jump through:

*

*Use the PShapeSVG source code to understand to get the SVG markup

*Use the right MIME type: I simply tried this solution
Putting it together:
import processing.svg.*;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.SystemFlavorMap;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Writer;

import java.nio.charset.StandardCharsets;

import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.batik.svggen.SVGGraphics2DIOException;

void setup(){

  PGraphicsSVG svg = (PGraphicsSVG)createGraphics(300,300,SVG);
  svg.beginDraw();

  svg.background(#4db748);
  svg.noFill();
  svg.strokeWeight(27);
  int a = 80;
  int b = 220;
  svg.line(a,a,b,b);
  svg.line(a,b,b,a);
  svg.line(a,a,b,a);
  svg.line(a,b,b,b);
  svg.ellipse(150, 150, 250, 250);

  copyToClipboard(svg);

  // normally you would call endDraw, but this will obviously throw an error if you didn't specify a filename in createGraphics()
  //svg.endDraw();

  println("svg copied to clipboard");
  exit();
}

String getSVGString(PGraphicsSVG svg){
  // make a binary output stream
  ByteArrayOutputStream output = new ByteArrayOutputStream();
  // make a writer for it
  Writer writer = PApplet.createWriter(output);
  // same way the library writes to disk we write to the byte array stream
  try{
    ((SVGGraphics2D) svg.g2).stream(writer, false);
  } catch (SVGGraphics2DIOException e) {
      e.printStackTrace();
  }
  // convert bytes to an UTF-8 encoded string
  return new String( output.toByteArray(), StandardCharsets.UTF_8 );
}

void copyToClipboard(PGraphicsSVG svg){
  // get the SVG markup as a string
  String svgString = getSVGString(svg);
  println(svgString);
  // access the system clipboard
  Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
  // get an binary clipboard with the correct SVG MIME type
  SvgClip strSVG = new SvgClip(svgString);
  // commit the clipboard encoded SVG to clipboard
  clip.setContents(strSVG, null);
}

// blatant copy/adapation of https://stackoverflow.com/questions/33726321/how-to-transfer-svg-image-to-other-programs-with-dragndrop-in-java
class SvgClip implements Transferable{

    String svgString;

    DataFlavor svgFlavor = new DataFlavor("image/svg+xml; class=java.io.InputStream","Scalable Vector Graphic");

    DataFlavor [] supportedFlavors = {svgFlavor};

    SvgClip(String svgString){
        this.svgString = svgString;

        SystemFlavorMap systemFlavorMap = (SystemFlavorMap) SystemFlavorMap.getDefaultFlavorMap();
        systemFlavorMap.addUnencodedNativeForFlavor(svgFlavor, "image/svg+xml");
    }

    @Override public DataFlavor[] getTransferDataFlavors(){
          return this.supportedFlavors;
    }

    @Override public boolean isDataFlavorSupported(DataFlavor flavor){
       return true;
    }

    @Override public Object getTransferData(DataFlavor flavor)
            throws UnsupportedFlavorException, IOException{
        return new ByteArrayInputStream(svgString.getBytes(StandardCharsets.UTF_8));
    }

}

Note Call copyToClipboard(svg) after your last drawing command, but before PGraphicsSVG's endDraw() call (otherwise it will return an empty SVG document)
The result in PowerPoint:


text:
Q: automate rules in makefile from two variables at the same time I have some search patterns that fits poorly as part of a file name for the result. I therefore split the regular expression and the corresponding file name part into two different variables like below. How can I automate the following so that I do not have to manually list files for ALL and also do not have to manually enter the rules running grep?
SEARCH_RE   = test  a/b/c  a.*b
SEARCH_FILE = test  abc    ab

ALL = result.test result.abc result.ab

all: $(ALL)

result.test:
        grep test  inputfile > result.test

result.abc:
        grep a/b/c inputfile > result.abc

result.ab
        grep a.*b  inputfile > result.ab

A: I don't know how to create the rules, but the ALL target is easy enough:
ALL = $(patsubst %,result.%,$(SEARCH_FILE))

A: I recommend

ALL = $(addprefix result.,$(SEARCH_FILE))

As for writing the rules, the kind of lookup I think you want can be done in Make, but really shouldn't be-- it would be a horrible kludge. I'd suggest doing it this way:

result.test: TARG = test
result.abc: TARG = a/b/c
result.ab: TARG = a.*b

$(ALL):
    grep $(TARG) inputfile > $@

redpajama_set_name: RedPajamaStackExchange


text:
Q: Running google analytics on intranet pages I have two sites internally,
one with apps: http://myapps.mycompany.com, the url internally is just http://myapps
But it logs even if the user uses the shortcut.
But that is not the case with the other one which is a mediawiki (with ldap).
http://mywiki.mycomapny.com where the shortcut is http://mywiki . It only logs if the users uses the extended url (which no one does). What may be the issue here?
I am using this media wiki extension: http://www.mediawiki.org/wiki/Extension:Google_Analytics_Integration


text:
Q: PHP oci_execute for Multiple Statements I'm trying to issue multiple INSERT statements within a single oci_execute() call on PHP. The problem is that I get this error:
ORA-00911: invalid character

I'm guessing it's the ; after each statement.
So now, my question is how do I make multiple INSERT statements that would work within oci_execute()?
Here's my query so far:
INSERT INTO tbl (id, name) VALUES(1, 'John');
INSERT INTO tbl (id, name) VALUES(2, 'Martha');
INSERT INTO tbl (id, name) VALUES(3, 'Richard')

EDIT:
Note that there is no ; at the end of my query because I'm using SQL statements.

A: Just wrap all statement into anonymous PL/SQL block:
BEGIN
    INSERT INTO tbl (id, name) VALUES(1, 'John');
    INSERT INTO tbl (id, name) VALUES(2, 'Martha');
    INSERT INTO tbl (id, name) VALUES(3, 'Richard');
END;

Oracle doesn't support batch of commands. Anonymous PL/SQL block is executed as single command.


text:
Q: How to get the environment variables in the hook script of the golang-buildpack in Heroku? I have met a very odd issue, when I was building the script of the automation for the DB migration. I followed the official document:

Pre/Post Compile Hooks
If the file bin/go-pre-compile or bin/go-post-compile exists and is executable then it will be executed either before compilation (go-pre-compile) of the repo, or after compilation (go-post-compile).
Because the buildpack installs compiled executables to bin, the go-post-compile hook can be written in go if it's installed by the specified  (see above).

Then I crafted the go-post-compile script below:
var (
    appURI := os.Getenv("APP_URI")
    databaseURL := os.Getenv("DATABASE_URL")
)

func main() {
    fmt.Printf("app_uri: %s\n", appURI)
    fmt.Printf("database_url: %s\n", databaseURL)
    sourcePath := fmt.Sprintf("file://%s/db/migrations", appURI)
    m, err := migrate.New(sourcePath, databaseURL)
    if err != nil {
        logger.Error("Failed to establish the connection of the migration.", err)
    }
    err = m.Up()
    if err != nil && err.Error() == "no change" {
        fmt.Println("  > NOTE: There is no change related to the operation of the migration.")
        return
    } else if err != nil {
        logger.Error("Failed to establish the connection of the migration.", err)
    }
    fmt.Println("  > Done.")
}

When I pushed the code to the heroku, I got the following error:
remote: -----> Running bin/go-post-compile hook
remote: app_uri:
remote: database_url: ?sslmode=require
remote: panic: runtime error: invalid memory address or nil pointer dereference
remote: [signal SIGSEGV: segmentation violation code=0x1 addr=0x58 pc=0x503b06]
remote:

It seems that the process could not get the environment variables when it run the go-post-compile script.
The process works well with the config vars after the buildpack compiles the application.
So do you have any ideas?

A: After some researches, I found the solution about running the automation of the DB migration. Developers should run these kinds of commands in the release phase in Heroku. You can check the official document: https://devcenter.heroku.com/articles/release-phase


text:
Q: What's the difference between :out-of-range and :invalid? Example
input[type="number"] {
    background: white;
    color: black;
}
input[type="number"]:in-range {
    background: green;
    color: white;
}
input[type="number"]:out-of-range {
    background: red;
    color: white;
}

<input c type="number" min="1" max="100">

What's the difference between :out-of-range and :invalid?

A: The out-of-range selector applies the specified style only if the value of the input element is "out of range". The out-of-range selector only works for elements with range limitations, such as input elements with min and max attributes.
Eg: Max number of characters that could be entered into an input field is 50. But when the user tries entering more than that, the input field can change color depending on the style specified here(like a red highlight or so).
The invalid selector applies the specified style only if the value of the input element is "invalid". This only works for form elements with limitations, such as input elements with min and max attributes, email fields without a legal email, or number fields without a numeric value, etc. So when the input value entered by the user is rendered to be false or invalid the specified style is applied to the input field.
Eg:
When an input email is detected as invalid, the input field can be disabled while a notification/instruction is being displayed to the user.

A: The :out-of-range selector selects elements that have a value that is outside the set min and max values of the input
<input type="number" min="5" max="10" value="17"> <!-- Gets selected with :out-of-range -->
<input type="number" min="5" max="10" value="8"> <!-- Does not get selected with :out-of-range -->

The :invalid selector selects elements that are invalid according to what type the input is.
<input type="email" value="abc@gmail.com"> <!-- Is a valid e-mail address and does not get selected with :invalid -->
<input type="email" value="foo"> <!-- Is not a valid e-mail address and gets selected with :invalid -->

JSFiddle

A: It's simple, but remember that some browsers does not support these features.
:out-of-range
<input type="date" name="dateCheck" min="2000-01-01" max="2016-07-06">
<!-- in this case if you enter date after 2016-07-06 input:out-of-range will match -->

The :out-of-range selector selects all elements with a value that is outside a specified range.
Note: The :out-of-range selector only works for elements with range limitations, such as input elements with min and max attributes.
Tip: Use the :in-range selector to select all elements with a value that is within a specified range.

source: http://www.w3schools.com/cssref/sel_out-of-range.asp
:in-range is also reversed version of :out-of-range
:invalid
<input type="date" name="dateCheckInvalid" min="2016-07-06">
<!-- in this case if u enter date before 2016-07-06 input:invalid will match -->

The :invalid selector selects form elements with a value that does not validate according to the element's settings.
Note: The :invalid selector only works for form elements with limitations, such as input elements with min and max attributes, email fields without a legal email, or number fields without a numeric value, etc.
Tip: Use the :valid selector to select form elements with a value that validates according to the element's settings.

source: http://www.w3schools.com/cssref/sel_invalid.asp
See simple demo: https://jsfiddle.net/bytdubk4/


text:
Q: Help me decide whether to use ASP.NET default membership/roles providers or write custom providers I spent a good part of yesterday reading up on the subject and still feel like I am uncertain which way to go.  I come from a "roll your own" background when it comes to authentication and authorization.  We never used Forms authentication, let alone the Membership API.  Looking at our old code we would use session variables to capture/control whether a user is logged in etc.  With this new project I am about to undertake I want to put us back on track with what we should have done to begin with, which is use the tools provided by the framework.
I already have a database schema that I'll be working with, however it's not set in stone; I am able to make changes to it if necessary.  In this schema there is already a Users table, utilizing an integer as the primary key.  This table also has other information such as First and Last names.  I  also have foreign keys based on the UserId to other tables such as Phone and Address.  Below I outline some of the pros/cons that come to mind.
Default Provider
Pros

*

*Less code.

*Ability to utilize all of the associated server controls such as Login, ChangePassword.

Cons

*

*Some controls might not be usedful to me out of the box.  For example the CreateUserWizard, I will need to possibly capture other information during user creation such as phone and address information to associated tables.  Not sure if this renders this control useless to me.

*I'll have to create foreign keys in my associated tables (Phone, Address) to the UserId which is a GUID in the default provider.

*If I do create these foreign key constrains and not utilize cascade delete; I will need to also delete associated rows in foreign key tables.  Potentially having to utilize something like a TransactionScope object to make sure all of this is an atomic operation.

Custom Provider
Pros

*

*Ability to utilize existing schema tables.

*Easier to extract authentication/authorization into a service down the line.

Cons

*

*Have to provide implementation to most/everything myself.

*To use any of the controls, I'll have to provide their required implementation in the provider.

There might be other things I have not yet considered, being that I never used this before which makes me a little uncomfortable as well.
Thank you.

A: I recently had to make the same choice and decided to go with creating a custom provider.
My biggest reason to do this came down to the default db schema.  All of the default db objects are created in the dbo schema and are prefixed with 'aspnet_' or 'vw_aspnet', etc.  For me it was a real turnoff.  If you haven't seen them yet, run aspnet_regsql.exe to create them.
In addition, Steven Sanderson says this in Pro ASP.NET MVC 2 Framework:

...SqlProfileProvider uses an especially disgusting database schema, in which profile entries are stored as colon-separated name/value pairs, so it's basically impossible to query.
Overall, it's worth following the API because of the clear separation of concerns, reuse across projects, and integration with the rest of ASP.NET, but you'll only want to use the built-in SQL storage providers for small or throwaway projects.

I haven't gone through the entire process of creating the custom providers yet (I did do a partial implementation when I was playing with Azure Table storage), but I plan to use these providers over multiple projects in the future, so I feel the effort will be well worth it.

A: If you are building a new application I would not hesitate to use the asp.net default provider. you can always decide not to use the default controls and programatically create your own. you can also save a lot of time by using any opensource pre created user management tool. At the same time you can always extend the information contained into the default tables.

A: Personally, I use the SqlMembershipProvider as a standalone entity while the rest of my database is in Oracle.  I never look at the database, so the names and GUIDs don't bother me (out of sight, out of mind).  It just works out of the box, which is great!
In my scenario, I've got a user table in the Oracle database that I insert/delete when membership users are created/deleted (no GUIDs).   I consider the membership database to be the "master" record and the Oracle table to be there basically for referential integrity of supporting tables.  It's not really done in an official transaction, but I use try/catch to keep them synchronized well enough.
The Role Provider is really limited and if you want any sort of hierarchical or dynamic roles, you're toasted.  But it's a separate system completely isolated from membership and you don't have to use it.
The controls aren't bad.  A lot of them support templates, so that you can add your own controls to them, and have plenty of events to hook into them.  Don't be afraid to roll your own controls, but give the default controls a chance first. The ease of use of the Membership API really facilitate creating those controls.

A: Personally, I'd go with what the framework provides.  There's no reason to roll your own authentication in this case.
In the past, you might have wanted to do things on your own, but nowadays there is no reason to.
I think if you tried to write this on your own, you'd be re-creating the wheel and it would take way too much time and resources to get it right.  Especially, when dealing with security.


text:
Q: Segment violation on attempt to initialize a memory mapped file The following is code I've used to create a memory mapped file:
fid = open(filename, O_CREAT | O_RDWR, 0660);

if ( 0 > fid )
{
    throw error;
}

/* mapped offset pointer to data file */
offset_table_p = (ubyte_2 *) shmat(fid, 0, SHM_MAP);

/* Initialize table */
memset(offset_table_p, 0x00, (table_size + 1) * 2);

say table_size is around 2XXXXXXXX bytes.
During debug, I've noticed it fails while attempt to initializing the 'offset table pointer',
Can anyone provide me some inputs on why it's failing during intilalization?
is there any possibilities that my memory map file was not created with required table size?

A: As far as I can tell from reading documentation, you are doing it completely wrong.
Either use open() and mmap() or use shmget() and shmat().
If you use open() you will need to make the file long enough first.  Use ftruncate() for that.

A: First things first:
Examine the file both before and after the open() call.  If on Linux, you can use the code:
char paxbuff[1000];                            // at start of function
sprintf (paxbuff,"ls -al %s",filename);
system (paxbuff);
fid = open(filename, O_CREAT | O_RDWR, 0660);  // this line already exists.
system (paxbuff);

Then, after you call shmat(), check the return values and size thus:
offset_table_p = (ubyte_2 *) shmat(fid, 0, SHM_MAP);  // already exists.
printf ("ret = %p, errno = %d\n",offset_table_p,errno);
printf ("sz = %d\n",table_size);

That should be enough to work out the problem.


text:
Q: Python equivalent to C#'s using statement
Possible Duplicate:
What is the equivalent of the C# "using" block in IronPython?

I'm writing some IronPython using some disposable .NET objects, and wondering whether there is a nice "pythonic" way of doing this. Currently I have a bunch of finally statements (and I suppose there should be checks for None in each of them too - or will the variable not even exist if the constructor fails?)
def Save(self):
    filename = "record.txt"
    data = "{0}:{1}".format(self.Level,self.Name)
    isf = IsolatedStorageFile.GetUserStoreForApplication()
    try:
        isfs = IsolatedStorageFileStream(filename, FileMode.Create, isf)
        try:
            sw = StreamWriter(isfs)
            try:
                sw.Write(data)
            finally:
                sw.Dispose()
        finally:
            isfs.Dispose()
    finally:
        isf.Dispose()

A: Python 2.6 introduced the with statement, which provides for automatic clean up of objects when they leave the with statement.  I don't know if the IronPython libraries support it, but it would be a natural fit.
Dup question with authoritative answer: What is the equivalent of the C# "using" block in IronPython?

A: I think you are looking for the with statement. More info here.

A: If I understand correctly, it looks like the equivalent is the with statement. If your classes define context managers, they will be called automatically after the with block.

A: Your code with some comments :
def Save(self):
    filename = "record.txt"
    data = "{0}:{1}".format(self.Level,self.Name)
    isf = IsolatedStorageFile.GetUserStoreForApplication()
    try:
        isfs = IsolatedStorageFileStream(filename, FileMode.Create, isf)

        try: # These try is useless....
            sw = StreamWriter(isfs)
            try:
                sw.Write(data)
            finally:
                sw.Dispose()
        finally: # Because next finally statement (isfs.Dispose) will be always executed
            isfs.Dispose()
    finally:
        isf.Dispose()

For StreamWrite, you can use a with statment (if your object as __enter__ and _exit__ methods) then your code will looks like :
def Save(self):
    filename = "record.txt"
    data = "{0}:{1}".format(self.Level,self.Name)
    isf = IsolatedStorageFile.GetUserStoreForApplication()
    try:
        isfs = IsolatedStorageFileStream(filename, FileMode.Create, isf)
        with StreamWriter(isfs) as sw:
            sw.Write(data)
    finally:
        isf.Dispose()

and StreamWriter in his __exit__ method has
sw.Dispose()


text:
Q: How do I fix my computer via BusyBox? 3DSlicer froze my computer importing a CT set, and not finding any way to fix it, I held the power button 'til it shut off.
Booting up, after selecting 'Ubuntu' from the boot menu, I am met with a black screen saying:

lvmetad is not active yet, using direct activation during sysinit
  /dev/mapper/ubuntu--vg-root contains a file system with errors, check
  forced. Inodes that were part of a corrupted orphan linked list found.
/dev/mapper/ubuntu--vg-root: UNEXPECTED INCONSISTENCY; RUN fsck
  MANUALLY. (i.e., without -a or -p options) fsck exited with status
  code 4 The root filesystem on /dev/mapper/ubuntu--vg-root requires a
  manual fsck
BusyBox v1.22.1 (Ubuntu 1:1.22.0-15ubuntu1) built-in shell (ash) Enter
  'help' for a list of built-in commands.
(initramfs)

Typing 'help', 'fsck' is not one of the listed built-in commands. Typing 'exit' repeats the message and brings me back to the (initramfs) prompt. Typing 'fsck' returns fsck from util-linux 2.27.1 and returns me to the (initramfs) prompt.
How do I fix the installation?

A: Execute fsck /dev/mapper/ubuntu--vg-root from that prompt, press y to say yes each time to fix everything found wrong, and then execute exit from that same prompt to return to the normal login screen.


text:
Q: Return specified field using findById | Mongoose MongoDB When using the Model.findOne() method, I can choose to include a string that limits my return value to just those field, but when I try to do so with the findById method, it appears to not work out.
The example below is a contrived example. I'm using a real _id and it works when using the first example, but I just want to use the findById method because a tiny voice in the back of my mind is telling me that's faster (maybe).
Example:
let Joe = new PersonModel({
  _id: ObjectId("12345")
  name: 'Joe',
  age: 30,
  password: 'GreatPW'
}).save();

Now find Joe, and return only his name and age. This works!
PersonModel.findOne({_id: Joe._id}, 'name age')
  .then(person => console.log(person))

Now do the same thing, but using findById(). This isn't working for me.
PersonModel.findById(Joe._id, 'name age')
  .then(person => console.log(person))

A: Turn on logging in Mongoose. you'll see that the only difference between those two calls is an extra function call from findById to findOne.
Source code reference: findById (provided by MikaS)

A: I'm not sure but I think you need to write {}, on query and in the projection:
This:
PersonModel.findById(Joe._id, 'name age')

Should be this:
PersonModel.findById({idValueToFind}, {name:1, age:1, _id:0})


text:
Q: value of asp.net textbox is null inside jquery popover I have a jQuery popover that contains an asp.net textbox and button. I have it submitting but the textboxes value is not coming thru. I had to add UseSubmitBehavior = false to get the button to fire.
Script
   //

$('.popover-markup>.trigger').popover({
    html: true,
    title: function () {
        return $(this).parent().find('.head').html();

    },
    content: function () {
        return $(this).parent().find('.content').html();

    },

    open: function () {

        $(this).parent().appendTo("form");
    }

});

$("#popover-markup").parent().appendTo($("form:first"));
//]]>

Markup
enter code

Save Report

      <asp:TextBox runat="server" ID="txtReportName"  CssClass="form-control" Width="150px" placeholder="Report Name" data-dismiss="popover" />

    <asp:Button CssClass="btn btn-lg btn-info btn-block" ID="btnSaveLayout" runat="server" Text="Save" OnClick="btnSaveLayout_Click" UseSubmitBehavior="false" data-dismiss="popover"/>

Button Click Event
 Protected Sub btnSaveLayout_Click(sender As Object, e As EventArgs)

    ReportingDAL.ExecuteNonQuery(ReportingDAL.GetConnection(), "InsertReportGridState", New SqlParameter("@StateString", Session("layout")), New SqlParameter("@ReportName", txtReportName.Text))

    lbLayouts.DataBind()

End Sub


text:
Q: Implicit conversion from data type nvarchar to varbinary(max) is not allowed I am getting the following error from the code below:

Implicit conversion from data type nvarchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.

 protected void btnOKImageUpload_Click(object sender, EventArgs e)
 {
     try
    {
        string filePath = "";
        string fileName = "";

        int UserId = Convert.ToInt32(hdnUserId.Value);
        if (fileImage.HasFile)
        {
            if (CheckFileType(fileImage.FileName))
            {
                filePath = Server.MapPath(Application["UploadFolder"].ToString());
                if (UserId > -1)
                {
                    fileName = "Image_" + UserId.ToString() + Path.GetExtension(fileImage.FileName);
                }
                else
                {
                    fileName = Path.GetFileName(fileImage.FileName);
                }
                string virFileName = Application["UploadFolder"].ToString() + "/" + fileName;
                string tmpFileName = Path.Combine(filePath, fileName);
                fileImage.SaveAs(tmpFileName);
                SessionData.LocationFloorPlanFile = tmpFileName;

                DataAccess.SaveEmployeeImage(UserId, fileName);

                hdnImageFileName.Value = fileName;
                txtImageUpload.Text = virFileName;
                //btnFloorPlanView.HRef = hdnFloorPlan.Value;
                btnImageUpload.Disabled = true;
                btnImageDelete.Enabled = true;
                hdnPostbackAction.Value = "UPLOAD";
            }
        }
   }
     catch (Exception ex)
     {
         hdnErrMsg.Value = ex.Message;
         //"An error has occurred while processing your request. Please contact support for further assistance.";
     }
}
public static void SaveEmployeeImage(int userId, string imageFilePath)
{
    ArrayList paramaters = getParamArray();
    paramaters.Add(getParam("@userId", DbType.Int32, userId));
    paramaters.Add(getParam("@imageFilePath", DbType.AnsiString, imageFilePath));

    executeNonQuery("xp_SaveEmployeeImage", paramaters);
}

My procedure takes userId and image, to insert into the table.
What data type do I need to change?

A: Well, you're passing that image as an AnsiString datatype, which is where the problem is occurring.
I think you need DbType.Binary.
But then, your parameter name is imageFilePath, so presumably you should actually be giving it a path to a file as a string?  This could mean your xp is actually wrong.


text:
Q: Adaptive Optics Capability in the Visible Range Telescopes with adaptive optics (AO) have been in use for several decades. To my knowledge, the lowest wavelengths utilized are in the near-infrared. It's known that Fried parameters are smaller for visible versus infrared ranges.

Are there any earth-based observatories utlizing AO in the visible range? What are the technical issues to achieve acceptable AO Strehl ratios in the visible range?

A: As per my knowledge in visible range making workable AO compensation system is very difficult and no earth based observation telescope exits. If we assume that acceptable S=0.8, at the near-IR wavelength range (say, 1.5 um), then the strehl ratio at visible (say, 0.5 um) is 1/3*0.8. Because the S is proportional to (wavelength)^6/5.

A: They are rare because the size of the patch of atmosphere that can be corrected by a given guide star is so much smaller at shorter wavelengths and changes faster - so you are either limited to where you can observe (near a bright guide star), or you need complex and expensive laser guide star systems.
If you are purely imaging (rather than trying to use AO to feed a spectrograph) there is a common alternative. You image the object continually but only use those images where the atmosphere happened to be still enough to briefly give a good image. You can do this either by reading out the CCD in short exposures or using a separate shutter.
You can combine this with a simpler AO system to make a "good" atmosphere into an "very good" one - eg the Magellan telescope has a visible AO system
The other big driver against a visible AO system purely for imaging is that you can always use the Space telescope instead.


text:
Q: Why don't a child's vertical margins expand their parent container? I have come across a case where I need a child's margin to expand a parent container. I found that the space outside of the parent is allocated, but the parent itself is not expanded. I then found that by adding overflow: hidden to the parent I could fix this issue.
Can anyone shed any light on why this is the case?
I have found that adding any padding or border value to the parent also fixes this.

section {
    background: black;
    //overflow: hidden; /* toggle this */
    //padding: 1px; /* or toggle this */
    //border: solid 1px green; /* or toggle this */
}

div {
   margin: 10px;
   background: red;
}

        SOME CONTENT

JSFiddle Example

A: I think collapsing margins is the reason : http://www.w3.org/TR/CSS2/box.html#collapsing-margins

A: A small update as of July 2018. Mozilla has a great article on this matter which is due to margin collapse.
Summary: Margins of the parent and the first child may collapse. They end up as if the parent had the resulting margin.

Parent and first/last child
If there is no border, padding, inline part, block formatting context created, or clearance to separate the margin-top of a block from the margin-top of its first child block; or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block from the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.

A: The answer to "why" is described well and succinctly here. There are certain properties that establish a "block formatting context". Namely:

Floats, absolutely [and fixed] positioned elements, block containers (such as
inline-blocks, table-cells, and table-captions) that are not block
boxes, and block boxes with 'overflow' other than 'visible' (except
when that value has been propagated to the viewport) establish new
block formatting contexts for their contents.

It is this change of block formatting context that is the reason why such solutions as given above in the comments work for how margin (and in the case of a preceding float, padding of following inflow elements) operates.


text:
Q: ObjectDatasource Update Method - with Generic object parameter which contains sub object is not working Entities
public class Calculation
{
    public int UniqueID { get; set; }
    public int Value1 { get; set; }
    public int Value2 { get; set; }
    public int Result { get; set; }
    public Operation Operation { get; set; }
    public DateTime EntryDateTime { get; set; }
}

 public class Operation
{
    public int OperationID { get; set; }
    public string OperationName { get; set; }
}

Business Logic Layer
public bool UpdateCalculation(Calculation calcObject)
    {
        bool returnVal = false;
        try
        {
            if (GetCalculationByID(calcObject) != null)
            {
                returnVal = calcDAL.UpdateCalculation(calcObject);
                if (returnVal)
                    return returnVal;
                else
                    throw new ApplicationException(ResourceHelper.GetErrorResourceValue("MSG003"));
            }
            else
                throw new ApplicationException(ResourceHelper.GetErrorResourceValue("MSG006"));
        }
        catch (Exception exp)
        {
            LoggingHelper.WriteLog(exp, MethodBase.GetCurrentMethod(), TraceEventType.Error);
            throw exp;
        }
    }

Data Access Layer:
public bool UpdateCalculation(Calculation calcObject)
    {
        try
        {
            object[] parameters = new object[5];
            parameters.SetValue(calcObject.UniqueID, 0);
            parameters.SetValue(calcObject.Value1, 1);
            parameters.SetValue(calcObject.Value2, 2);
            parameters.SetValue(calcObject.Result, 3);
            parameters.SetValue(calcObject.Operation.OperationID, 4);
            int returnVal = _db.ExecuteNonQuery(ResourceHelper.GetSpResourceValue("UPD_CALC"), parameters);
            if (returnVal > 0)
                return true;
            else
                return false;
        }
        catch (Exception exp)
        {
            Utilities.LoggingHelper.WriteLog(exp, MethodBase.GetCurrentMethod(), TraceEventType.Error);
            throw exp;
        }
    }

I am using the Enterprise Library 5.0 to perform the DB operation from DAL.
The below code shows how the objects are binded to the HTML in Web project.
Website
 <asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="3" AutoGenerateColumns="False"
        DataSourceID="CalculationDS" AllowSorting="True" OnRowDeleted="GridView1_RowDeleted"
        OnRowUpdated="GridView1_RowUpdated" OnSorting="GridView1_Sorting"
        onrowupdating="GridView1_RowUpdating" DataKeyNames="UniqueID">
        <Columns>
            <asp:CommandField ShowEditButton="True" />
            <asp:BoundField DataField="UniqueID" HeaderText="UniqueID"
                SortExpression="UniqueID" />
            <asp:BoundField DataField="Value1" HeaderText="Value1"
                SortExpression="Value1" />
            <asp:BoundField DataField="Value2" HeaderText="Value2"
                SortExpression="Value2" />
            <asp:BoundField DataField="Result" HeaderText="Result"
                SortExpression="Result" />
            <asp:TemplateField HeaderText="Operation"
                SortExpression="OperationName">
                <EditItemTemplate>
                    <asp:DropDownList ID="drpOperations" runat="server" DataSourceID="OperationDS"
                        DataTextField="OperationName" DataValueField="OperationID"
                        SelectedValue='<%# Eval("Operation.OperationID") %>'>
                    </asp:DropDownList>
                    <asp:ObjectDataSource ID="OperationDS" runat="server"
                        SelectMethod="GetAllOperations" TypeName="SampleBLL.OperationBLL">
                        <SelectParameters>
                            <asp:Parameter DefaultValue="OperationName" Name="sortExpression"
                                Type="String" />
                            <asp:Parameter DefaultValue="Ascending" Name="sortDirection" Type="String" />
                        </SelectParameters>
                    </asp:ObjectDataSource>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server"
                        Text='<%# Eval("Operation.OperationName") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="EntryDateTime" HeaderText="EntryDateTime"
                SortExpression="EntryDateTime" />
        </Columns>
    </asp:GridView>
    <asp:ObjectDataSource ID="CalculationDS" runat="server" DataObjectTypeName="SampleEntities.Calculation"
        DeleteMethod="DeleteCalculation" InsertMethod="InsertCalculation" SelectMethod="GetAllCalculations"
        TypeName="SampleBLL.CalculationBLL" UpdateMethod="UpdateCalculation" OnSelecting="CalculationDS_Selecting"
        OnUpdating="CalculationDS_Updating">
        <SelectParameters>
            <asp:ControlParameter ControlID="GridView1" DefaultValue="UniqueID" Name="sortExpression"
                PropertyName="SortExpression" Type="String" />
            <asp:ControlParameter ControlID="GridView1" Name="sortDirection" PropertyName="SortDirection"
                Type="String" />
        </SelectParameters>
    </asp:ObjectDataSource>

When i try to edit the row and submit, the OPERATION column in the CALCULATION object is NULL in the DAL when i read the calculation object Operation ID its NULL.
I have tried to read the value from the CalculationDs (ObjectDatasource) Updating event
and GridView Updating event but no use.
The OPERATION object column is not automatically mapped to the GridView column.
Thanks in advance. if you got solution for this update to work.. !!:(


text:
Q: Find line (one only) based on first string in line using C++ Objective:
Find the correct line in the datafile to make adjustment on by searching for email address
Problem:
I can find the line when I use string::find as per the current code below, but when I search for rick@fakedomain.tld I get two hits, the frederick@ and rick@ lines. As the email address is first field I cant include a leading space (delimiter) to overcome the problem.
Sample input datafile (called datafile):
alan@fakedomain.tld q7gPGAdb0zGKHlQd./ Alan Smith
frederick@fakedomain.tld cyHSYctfJpOq7gPGAd Frederick Smith
david@fakedomain.tld nz0hz1uevogQgNxqQA David Smith
rick@fakedomain.tld 4bExd5J3tU7Pi9o/My Rick Smith
john@fakedomain.tld q7gPGAdb0zGKHlQd./0 John Smith

Current c++ code:
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(int argc, char *argv[]) {
    // Are there the right number of command line arguments
    if (argc < 2) { // expecting 2, the command and email address
        cout << "test [emailaddress]" << endl;
        return 1;
    }
    if (argc > 2) {
        cout << "test: to many arguments" << endl;
        return 1;
    }

    // put the command line arguments into string variables
    string cmd = argv[0];
    string email = argv[1];

    // display the command line for testing - remove secton for production
    string space = " ";
    string cmdline = cmd + space + email + space + oldPW + space + oldPW;
    cout << cmdline << endl;

    // Open the files
    ifstream filein("datafile"); //File to read from
    if(!filein)
    {
        cout << "Error opening file!" << endl;
        return 1;
    }

    string strLine;
    while(getline(filein, strLine))
    {
        // the test to see if this is the line to work with
        size_t found = strLine.find(email);
        if (found != string::npos) {
            // this is the string so add code here to work with it
            cout << strLine << endl;
        }
    }
    return 0;
}

Question:
How do I only return the line with an exact match of the needle?
If it's not asking to much, hoping for an answer that teaches me, not just some un-commented code that works, but will take the latter if it's all I can get.
Optional: if there is a better way to do other parts of the code you see, feel free to suggest in your answer or comment. Always keen to learn better ways.
Desired output
./test rick@fakedomain.tld
alan@fakedomain.tld q7gPGAdb0zGKHlQd./ Alan Smith
 - - no match
frederick@fakedomain.tld cyHSYctfJpOq7gPGAd Frederick Smith
 - - no match
david@fakedomain.tld nz0hz1uevogQgNxqQA David Smith
 - - no match
rick@fakedomain.tld 4bExd5J3tU7Pi9o/My Rick Smith
 |=|=| MATCH
john@fakedomain.tld q7gPGAdb0zGKHlQd./0 John Smith
 - - no match

Output I'm getting
./test rick@fakedomain.tld
alan@fakedomain.tld q7gPGAdb0zGKHlQd./ Alan Smith
 - - no match
frederick@fakedomain.tld cyHSYctfJpOq7gPGAd Frederick Smith
 |=|=| MATCH
david@fakedomain.tld nz0hz1uevogQgNxqQA David Smith
 - - no match
rick@fakedomain.tld 4bExd5J3tU7Pi9o/My Rick Smith
 |=|=| MATCH
john@fakedomain.tld q7gPGAdb0zGKHlQd./0 John Smith
 - - no match

NB: No compile errors or warnings using g++ test.c -o test

A: If you want to make sure the the found email is at the start of the string then just check to make sure found is zero.
if (found == 0)
    cout << strLine << endl;

Another option is to use std::string::substr on the line from the file and do a direct comparison with operator ==
if (email == strLine.substr(0, email.size()))
    cout << strLine << endl;


text:
Q: SIMD Dot using doubles and .NET Framework 4.8 I would like to speed up the following calculation using SIMD:
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static double Dot(double x1, double x2, double y1, double y2)
{
    return x1 * y1 + x2 * y2;
}

I saw that there is Vector2.Dot but this is only for floats and not for doubles.
I cannot switch to .NET Core and therefor I cannot use Vector128 Create (double e0, double e1).
The above Dot method is used in the following code which computes a union of two sorted list (id arrays):
static void ChainRule(int x_n, int[] x_id, double[] x_jacobi, double x_diff,
                      int y_n, int[] y_id, double[] y_jacobi, double y_diff,
                      out int z_n, out int[] z_id, out double[] z_jacobi)
{
    int n = x_n + y_n;
    z_id = new int[n];
    z_jacobi = new double[n];
    int i = 0, ix = 0, iy = 0;
    while (ix < x_n && iy < y_n)
    {
        if (x_id[ix] < y_id[iy])
        {
            z_id[i] = x_id[ix];
            z_jacobi[i++] = x_diff * x_jacobi[ix++];
        }
        else if (y_id[iy] < x_id[ix])
        {
            z_id[i] = y_id[iy];
            z_jacobi[i++] = y_diff * y_jacobi[iy++];
        }
        else
        {
            z_id[i] = x_id[ix];
            z_jacobi[i++] = Dot(x_diff, y_diff, x_jacobi[ix++],  y_jacobi[iy++]);
        }
    }
    while (ix < x_n)
    {
        z_id[i] = x_id[ix];
        z_jacobi[i++] = x_diff * x_jacobi[ix++];
    }
    while (iy < y_n)
    {
        z_id[i] = y_id[iy];
        z_jacobi[i++] = y_diff * y_jacobi[iy++];
    }
    z_n = i;
}

I tried as well to precompute the product of x_diff and x_jacobi and the product of y_diff and y_jacobi with the following code:
    double[] x_diff_jacobi = new double[x_n];
    for (int i0 = 0; i0 < x_n; i0++)
        x_diff_jacobi[i0] = x_diff * x_jacobi[i0];
    double[] y_diff_jacobi = new double[y_n];
    for (int i0 = 0; i0 < y_n; i0++)
        y_diff_jacobi[i0] = y_diff * y_jacobi[i0];

This will simplify the calculation of z_jacobi, e.g.: z_jacobi[i++] = x_diff_jacobi[ix++] + y_diff_jacobi[iy++]. But this code is running slower than the one above. I think the problem is the initialization of the additional arrays x_diff_jacobi and y_diff_jacobi.
Any other ideas to speed up this code?


text:
Q: no suitable method for read(java.lang.String) Hello I'm trying to display an image I have displayed in my pictures on a Java application.
If someone could help me figure this out I would greatly appreciate it. This is the code I used when I got this error:
import java.awt.Image;
import javax.imageio.ImageIO;

public class JPipesCard
{
    Image img = null;

    {
        try {
            img = ImageIO.read("J Pipe's Card.png");
        } catch (IOException e) {
        }
    }
}

A: You need to pass a java.util.File as stated in ImageIO#read documentation:
img = ImageIO.read(new File("J Pipe's Card.png"));

A: ImageIO does not have a read method that accepts a String. As the file is local, you need to use the one that accepts a File object:
img = ImageIO.read(new File("J Pipe's Card.png"));

*

*ImageIO


text:
Q: How do I set up my model associations for an conference registration app? I've been playing around with writing a RoR 4.2 app that will allow the following behaviors:

*

*Admin users to create a list of conference courses that will include topic, description, etc

*Conference attendees can register with the website and then select the conference courses they'd like to attend.

*Conference attendees should not be able to create conference courses, only to select from a list of courses listed in the database and to select them to attend. The must be a way to associate many users with the same course.

*When a user selects a course, the seating capacity for that course should be decremented (the details of this aspect of the solution are a secondary requirement at the time)

For the sake of discussion, let's say I am using Devise with user roles all figured out and configured. So I have one user.rb model/table.
I also created a model/table called course.rb.
I created a join model/table called course_selection.rb.
I configured these tables using the has_many through associations with the join table belonging to each like so:
class User < ActiveRecord::Base
  has_many :course_selections
  has_many :courses, :through => :course_selections
end

class Course < ActiveRecord::Base
  has_many :course_selections
  has_many :users, :through => :course_selections
end

class CourseSelection < ActiveRecord::Base
  belongs_to :user
  belongs_to :course
end

I have this set up and am able to create new users, but the users with non-admin roles are able to create courses (but I haven't set up any kind of role based exclusions for these users to prevent them from creating courses). When I call a RESTful route such as
http://localhost:3000/users/3/courses
I am expecting to see only a list of courses associated with this particular user. Instead I am seeing ALL the courses listed in the database.
My questions are:

*

*Can the model associations strategy I've selected be used to accomplish the behavioral goals I've specified?

*How would the controllers be set up so that a user's course selection is established, but that they are not using the new/create methods to actually create the course?

*How would the forms be set up (I'm using simple_form) to allow the user to select from the list of existing courses?

Thanks for your help. I haven't found any tutorials that seem to address this challenge.

A:
Can the model associations strategy I've selected be used to accomplish the behavioral goals I've specified?

Yes, those models are a fine start.

How would the controllers be set up so that a user's course selection is established, but that they are not using the new/create methods to actually create the course?

The typical Rails REST-like way is to have a controller CourseSelectionsController that manages the association.
Suppose you have a view page where a user can select a course. The view would submit the data to the CourseSelectionsController, with params user_id and course_id. The controller then creates the CourseSelection model, which associates the user and course.
The CourseSelectionsController would have typical actions for "create", "read", "delete". If the course selection also has other data, such as a price, or time slot, etc. then there can be an action for "update".
By the way, in your kind of application, the middle model is often called Enrollment instead of CourseSelection, and the REST controller is called EnrollmentsController.

How would the forms be set up (I'm using simple_form) to allow the user to select from the list of existing courses?

Typically in app/views/course_selections. The form is based on CourseSelections (not Users, and not Courses). The form shows a list of courses. When the user submits the form, it does a PUT (or POST) to CourseSelectionsController.
If you want the form to be able to handle multiple courses, one way is to use AJAX as each course is selected or unselected. Another way is to use multiple select fields, and make a controller method that can iterate on all the selected/unselected courses.


text:
Q: Maintaining exact aspect ratio when scaling videos using ffmpeg I have a mkv video, which is a mix of multiple resolution recordings, e.g. I have the first few seconds of widescreen 16:9 (1024x576) resolution, and the rest of the video if 4:3 (768x576) resolution. I want to scale this video down 3 times, while copying all the other attributes (audio codec, subtitles etc.). I use ffmpeg -i <input_mkv> -vf scale=iw/2:-1 -acodec copy <output_mp4>. Also, VLC detects it's resolution as 720x576.
The problem is that after the scaling, the resolution constantly becomes 4:3 (360x288). How can I maintain the dynamic aspect ratio of the input video file i.e. the 16:9 parts to scale to 16:9, while the 4:3 parts scale to 4:3?
update
The player size actually changes, atleast in mplayer, when the resolution is switched. I figured out the main problem. It seems each frame is tagged with a Sample Aspect Ratio (SAR), so when the player plays it, it can find the display aspect ratio. This SAR value isn't getting copied over when encoding to MKV. When encoding to MPG, it does get copied over and I get an exact copy, with the player switching sizes, but not with MKV.
Output of ffprobe -show_streams filename:
ffprobe version 0.10.3 Copyright (c) 2007-2012 the FFmpeg developers
  built on May  9 2012 17:51:07 with gcc 4.7.0 20120505 (prerelease)
  configuration: --prefix=/usr --enable-libmp3lame --enable-libvorbis --enable-libxvid --enable-libx264 --enable-libvpx --enable-libtheora --enable-libgsm --enable-libspeex --enable-postproc --enable-shared --enable-x11grab --enable-libopencore_amrnb --enable-libopencore_amrwb --enable-libschroedinger --enable-libopenjpeg --enable-librtmp --enable-libpulse --enable-gpl --enable-version3 --enable-runtime-cpudetect --disable-debug --disable-static
  libavutil      51. 35.100 / 51. 35.100
  libavcodec     53. 61.100 / 53. 61.100
  libavformat    53. 32.100 / 53. 32.100
  libavdevice    53.  4.100 / 53.  4.100
  libavfilter     2. 61.100 /  2. 61.100
  libswscale      2.  1.100 /  2.  1.100
  libswresample   0.  6.100 /  0.  6.100
  libpostproc    52.  0.100 / 52.  0.100
Input #0, matroska,webm, from 'sample.mkv':
  Metadata:
    title           : Pan prstenu. Dve veze
  Duration: 00:00:29.80, start: 0.000000, bitrate: 3124 kb/s
    Stream #0:0(eng): Video: mpeg2video (Main), yuv420p, 720x576 [SAR 64:45 DAR 16:9], 15000 kb/s, 25 fps, 25 tbr, 1k tbn, 50 tbc (default)
    Stream #0:1(cze): Audio: mp2, 48000 Hz, stereo, s16, 128 kb/s (default)
[STREAM]
index=0
codec_name=mpeg2video
codec_long_name=MPEG-2 video
codec_type=video
codec_time_base=1/50
codec_tag_string=[0][0][0][0]
codec_tag=0x0000
width=720
height=576
has_b_frames=1
sample_aspect_ratio=64:45
display_aspect_ratio=16:9
pix_fmt=yuv420p
level=8
timecode=16:35:19:10
id=N/A
r_frame_rate=25/1
avg_frame_rate=25/1
time_base=1/1000
start_time=0.000000
duration=N/A
nb_frames=N/A
TAG:language=eng
[/STREAM]
[STREAM]
index=1
codec_name=mp2
codec_long_name=MP2 (MPEG audio layer 2)
codec_type=audio
codec_time_base=1/48000
codec_tag_string=[0][0][0][0]
codec_tag=0x0000
sample_fmt=s16
sample_rate=48000
channels=2
bits_per_sample=0
id=N/A
r_frame_rate=0/0
avg_frame_rate=125/3
time_base=1/1000
start_time=0.000000
duration=N/A
nb_frames=N/A
TAG:language=cze
[/STREAM]

A: FFmpeg video filters have a surprisingly rich set of logical functions for building complex filters and you should be able to use those to preserve the changing SAR in your file.  Try something like this:
ffmpeg ... -vf scale='if(gt(dar\, 4/3)\, 512) + ifnot(gt(dar\, 4/3)\, 384):-1' ...

Replacing 512 and 384 with appropriate values as necessary.  That said, I don't have a multi-SAR video to test with, so YMMV.
You might also look into the showinfo filter to get excruciatingly detailed information about each frame, and potentially the setsar filter, though the lack of frame-specific variables would suggest difficulty in changing it midstream.


text:
Q: trouble stopping a file read process I'm trying to quit a loop, reading the file contents in to a list, when I hit a the line of text that says "stop". Here is my code:
let f_in = "file.text"
let lines = ref [];;

  let chan = open_in f_in in
  try
    while true do

      let line = input_line chan in
      if line = "stop" then raise End_of_file;
      lines := input_line chan :: !lines

    done
  with End_of_file -> close_in chan

The problem is that it's reading 1 extra line, and it wont read lines that have the word "stop" within the text. An example would be this kind of file:
aaa
bbb stop
ccc stop
ddd
eee
stop
fff

Now my code should print all those lines, and stop reading at the line that has the word "stop" alone. Can someone fix this? Thanks.

A: Replacing the second input_line with line yields the result you want.
let f_in = "file.text"
let lines = ref [];;

let chan = open_in f_in in
  try
    while true do

      let line = input_line chan in
      if line = "stop" then raise End_of_file;
      lines := !lines @ [ line ]

    done
  with End_of_file -> close_in can

The result stored in lines is:
["aaa"; "bbb stop"; "ccc stop"; "ddd"; "eee"]


text: Q: Entity Framework 6 Model From Database - Disable Automatic Association Creation I have an EF model with all associations / table relationships deleted, but every time I "update model from database" all of the associations return.  I would like a flat model, with no relationships, and don't want to have to delete the associations each time I refresh the model.  When you first create the model from the DB, you can choose to ignore FK relationships, but regardless of this setting, future updates of the model bring the associations back.


text:
Q: Is it valid to calculate standard deviation for n=2? My colleagues and I are having discussion whether it's valid to calculate standard deviation for $n=2$ or not? I think it's valid since I can calculate based on the equation, but higher N will give more power in the analysis. Can anyone comment? Thank you!

A: Standard deviation is a measure of spread from the mean, so it is defined even when $N=1$ (although in that case it will always be 0). Certainly when $N=2$, it is a meaningful statistic.
And you are right -- if $N$ is larger, the statistic will be more powerful.

A: It depends on how many "degrees of freedom" you have, or how much data you have left after estimating the other parameters you need before getting to the variance.  If you have a single univariate sample and just want to estimate a variance, you can since this only requires an estimate of the mean.  If on the other hand you have a simple linear regression and have fit an intercept and slope, then you have no degrees of freedom left and can't estimate the variance of the error term.


text:
Q: Facebook SDK 4.0.1 Swift Errors xcode 6.2 iOS 8.2 Here in this change-log(facebook change-log) it is stated that there is no need for objective-c bridging headers for swift.
But when I import FBSDKCoreKit in AppDelegate.swift these errors occur:
FBSDKAppLinkResolver.h

/Users/[username]/Documents/FacebookSDK/FBSDKCoreKit.framework/Headers/FBSDKAppLinkResolver.h:21:9:
Include of non-modular header inside framework module
'FBSDKCoreKit.FBSDKAppLinkResolver'

AppDelegate.swift

/Users/ashrafkholeif/Projects/xcode/TabbedApplicationTemplate/TabbedApplicationTemplate/TabbedApplicationTemplate/AppDelegate.swift:10:8:
Could not build Objective-C module 'FBSDKCoreKit'

edit: I even set the allow non-modular header inside framework modules to YES.

A: I had the exact same issue, the solution suggested on https://stackoverflow.com/a/29457503/425682 for an Objective-C project worked straight away on my Swift project:
Write a new file in the Facebook SDK folder under Bolts.framework/Modules/module.modulemap with the following content:
framework module Bolts {
umbrella header "Bolts.h"

export *
module * { export * }

explicit module BFAppLinkResolver {
    header "BFAppLinkResolver.h"
    link "BFAppLinkResolver"
    export *
}}

This works without bridging headers (not needed anymore in version 4.0.1 of the SDK as mentioned by the OP), and without changes to the build settings.
EDIT: this bug is now fixed as of version 4.1 of the Facebook SDK, the library works without having to do any change.

A: This is a bug and Facebook is currently "assigning this to the appropriate team".
To get updates to this issue follow this link:
https://developers.facebook.com/bugs/362995353893156/
and hit subscribe.
Hopefully it doesn't take them too long to fix.
Also here is a related question recently posted on SO:
issue using FBSDK in swift iOS application
And some people have found success using the answers on this link (none have worked for me):
Facebook iOS8 SDK build module error for FBSDKCoreKit

A: The fix that worked for me:
rm -r ~/Documents/FacebookSDK/FBSDKCoreKit.framework/Modules/

Repeat with other frameworks.
Source: https://developers.facebook.com/docs/ios/troubleshooting#xcode_link

A: Create a new header file and import any objective-c code you are using, something like this..
#ifndef RJv1_RJBridge_h
#define RJv1_RJBridge_h
#import "NSMutableString+Obfuscated.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#endif

Then go to your Build Settings, look for Install Objective-C Compability Header, and make sure is set to Yes, then add a relative path to your header file in the field Objective-C Bridging Header.
Hope it works!


text:
Q: Tensorflow, Keras: In a multi-class classification, accuracy is high, but precision, recall, and f1-score is zero for most classes General Explanation:
My codes work fine, but the results are wired. I don't know the problem is with

*

*the network structure,

*or the way I feed the data to the network,

*or anything else.

I am struggling with this error several weeks and so far I have changed the loss function, optimizer, data generator, etc., but I could not solve it. I appreciate any help.
If the following information is not enough, let me know, please.
Field of study:
I am using tensorflow, keras for multiclass classification. The dataset has 36 binary human attributes. I have used resnet50, then for each part of the body (head, upper body, lower body, shoes, accessories), I have added a separated branch to the network. The network has 1 input image with 36 labels and 36 output nodes (36 denes layers with sigmoid activation).
Problem:
The problem is that the accuracy that keras is reporting is high, but f1-score is very low or zero for most of the outputs (even when I use f1-score as a metric when compiling the network, the f1-socre for validation is very bad).
aAfter train, when I use the network in prediction mode, it returns always one/zero for some classes. It means that the network is not able to learn (even when I use weighted loss function or focal loss function.)
Why it is weird? Because, state-of-the-art methods report heigh f1 score even after the first epoch (e.g. https://github.com/chufengt/iccv19_attribute, that I have run it in my PC and got good results after one epoch).
Parts of the Codes:
        print("setup model ...")
        input_image = KL.Input(args.img_input_shape, name= "input_1")
        C1, C2, C3, C4, C5 = resnet_graph(input_image, architecture="resnet50", stage5=False, train_bn=True)
        output_layers = merged_model (input_features=C4)
        model = Model(inputs=input_image, outputs=output_layers, name='SoftBiometrics_Model')

...

        print("model compiling ...")
        OPTIM = optimizers.Adadelta(lr=args.learning_rate, rho=0.95)
        model.compile(optimizer=OPTIM, loss=binary_focal_loss(alpha=.25, gamma=2), metrics=['acc',get_f1])
        plot_model(model, to_file='model.png')

...

        img_datagen = ImageDataGenerator(rotation_range=6, width_shift_range=0.03, height_shift_range=0.03, brightness_range=[0.85,1.15], shear_range=0.06, zoom_range=0.09, horizontal_flip=True, preprocessing_function=preprocess_input_resnet, rescale=1/255.)
        img_datagen_test = ImageDataGenerator(preprocessing_function=preprocess_input_resnet, rescale=1/255.)

        def multiple_outputs(generator, dataframe, batch_size, x_col):
          Gen = generator.flow_from_dataframe(dataframe=dataframe,
                                               directory=None,
                                               x_col = x_col,
                                               y_col = args.Categories,
                                               target_size = (args.img_input_shape[0],args.img_input_shape[1]),
                                               class_mode = "multi_output",
                                               classes=None,
                                               batch_size = batch_size,
                                               shuffle = True)
          while True:
            gnext = Gen.next()
            # return image batch and 36 sets of lables
            labels = gnext[1]
            output_dict = {"{}_output".format(Category): np.array(labels[index]) for index, Category in enumerate(args.Categories)}
            yield {'input_1':gnext[0]}, output_dict

    trainGen = multiple_outputs (generator = img_datagen, dataframe=Train_df_img, batch_size=args.BATCH_SIZE, x_col="Train_Filenames")
    testGen = multiple_outputs (generator = img_datagen_test, dataframe=Test_df_img, batch_size=args.BATCH_SIZE, x_col="Test_Filenames")

    STEP_SIZE_TRAIN = len(Train_df_img["Train_Filenames"]) // args.BATCH_SIZE
    STEP_SIZE_VALID = len(Test_df_img["Test_Filenames"]) // args.BATCH_SIZE

    ...

    print("Fitting the model to the data ...")
            history = model.fit_generator(generator=trainGen,
                                         epochs=args.Number_of_epochs,
                                         steps_per_epoch=STEP_SIZE_TRAIN,
                                         validation_data=testGen,
                                         validation_steps=STEP_SIZE_VALID,
                                         callbacks= [chekpont],
                                         verbose=1)

A: There is a possibility that you are passing binary f1-score to compile function. This should fix the problem -
pip install tensorflow-addons

...

import tensorflow_addons as tfa

f1 = tfa.metrics.F1Score(36,'micro' or 'macro')

model.compile(...,metrics=[f1])

You can read more about how f1-micro and f1-macro is calculated and which can be useful here.

A: Somehow, the predict_generator() of Keras' model does not work as expected. I would rather loop through all test images one-by-one and get the prediction for each image in each iteration. I am using Plaid-ML Keras as my backend and to get prediction I am using the following code.
import os
from PIL import Image
import keras
import numpy

print("Prediction result:")
dir = "/path/to/test/images"
files = os.listdir(dir)
correct = 0
total = 0
#dictionary to label all traffic signs class.
classes = {
    0:'This is Cat',
    1:'This is Dog',
}
for file_name in files:
    total += 1
    image = Image.open(dir + "/" + file_name).convert('RGB')
    image = image.resize((100,100))
    image = numpy.expand_dims(image, axis=0)
    image = numpy.array(image)
    image = image/255
    pred = model.predict_classes([image])[0]
    sign = classes[pred]
    if ("cat" in file_name) and ("cat" in sign):
        print(correct,". ", file_name, sign)
        correct+=1
    elif ("dog" in file_name) and ("dog" in sign):
        print(correct,". ", file_name, sign)
        correct+=1
print("accuracy: ", (correct/total))


text:
Q: Django/Python: Tried to update field with a model instance. Use a value compatible with CharField I have created a Django project in which type-1 users can create a Post and type-2 users can bid on a post. Finally, post_owner can accept a bid. In my Post model there is a CharField 'bidder' which sets to '0' as default. After accepting I wanted to  update this field with bidder_id as in accepted bid. I written an updated view for this field in my Auction view.
But it raising an error : Tried to update field MyApp1.Post.bidder with a model instance, . Use a value compatible with CharField. I would appreciate helping me solve this.
Models.py:
class Post(models.Model):

    item = models.CharField(max_length=20)
    post_owner = models.OneToOneField(settings.AUTH_USER_MODEL, default=1)
    bidder = models.CharField(max_length=20, default=0)

class Bid(models.Model):

    post = models.ForeignKey(Post, related_name = bids)
    amount = models.IntegerField(max_length = 20)
    bidder = models.ForeingKey(settings.AUTH_USER_MODEL)

class Auction(models.Model):

    post = models.ForeignKey(Post, related_name='auctions')
    post_owner = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
    bid = models.OneToOneField('truck.Bid', related_name='auctions')

forms.py:
class AcceptedForm(forms.ModelForm):
    bidder = forms.CharField(required=False, widget=forms.HiddenInput())
    class Meta:
        model = Post
        fields = ('bidder', )

Views.py:
def live_bids(request):

    if request.method=='POST':
        instance_post = Post.objects.get( id = request.POST['post_id'])
        form = AcceptedForm(request.POST,  instance = instance_post)

        post = Post.objects.get( id = request.POST['post_id'] )
        bid = Bid.objects.get(id = request.POST['bid_id'])
        if form.is_valid():
        accepted = form.save(commit=False)
        accepted.bidder = bid.bidder
        accepted.save()
        form.save()

    else:
        form = AcceptedForm()

    return render(request, 'live_bids.html', 'form':form)

live_bids.html:
<form class="nomargin" method='POST' action='' enctype='multipart/form-data'>{% csrf_token %}
{{form.bidder}}
<input type='hidden' name='post_id' value='{{post.id}}'/>
<input type='hidden' name='bid_id' value='{{bid.id}}'/>
<input type='submit' value='Accept'/>

Traceback:
File "C:\python34\lib\site-packages\django\core\handlers\base.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

File "C:\python34\lib\site-packages\django\core\handlers\base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\python34\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "C:\python34\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "C:\Users\sumanth\Desktop\django-custom-user-master\search field\Project\mysite\personal\views.py" in live_bids
  323.      if form.is_valid() :

File "C:\python34\lib\site-packages\django\forms\forms.py" in is_valid
  161.         return self.is_bound and not self.errors

File "C:\python34\lib\site-packages\django\forms\forms.py" in errors
  153.             self.full_clean()

File "C:\python34\lib\site-packages\django\forms\forms.py" in full_clean
  364.         self._post_clean()

File "C:\python34\lib\site-packages\django\forms\models.py" in _post_clean
  380.             self.instance = construct_instance(self, self.instance, opts.fields, exclude)

File "C:\python34\lib\site-packages\django\forms\models.py" in construct_instance
  60.             f.save_form_data(instance, cleaned_data[f.name])

File "C:\python34\lib\site-packages\django\db\models\fields\__init__.py" in save_form_data
  865.         setattr(instance, self.name, data)

File "C:\python34\lib\site-packages\django\db\models\fields\related_descriptors.py" in __set__
  207.                     self.field.remote_field.model._meta.object_name,

Exception Type: ValueError at /live_bids/
Exception Value: Cannot assign "''": "Post.bidder" must be a "EmailUser" instance.

A: The problem is in view. You cant do this:
 bid = Bid.objects.get(id = request.POST['bid_id'])
        if form.is_valid():
            accepted = form.save(commit=False)
            accepted.bidder = bid.bidder

because accepted.bidder is CharField and bid.bidder is UserModel
so you can do either:
bid = Bid.objects.get(id = request.POST['bid_id'])
    if form.is_valid():
        accepted = form.save(commit=False)
        accepted.bidder = str(bid.bidder_id) # add User.id as string

OR I think better solution is make little changes
class AcceptedForm(forms.Form):
    bidder = forms.InteferField(required=False, widget=forms.HiddenInput())
    post_id = forms.InteferField(required=False, widget=forms.HiddenInput())
    bid_id = forms.InteferField(required=False, widget=forms.HiddenInput())
    class Meta:
        fields = ('bidder', 'post_id', 'bid_id')

and view:
if request.method=='POST':
    form = AcceptedForm(request.POST)
    if form.is_valid():
        post = Post.objects.get( id = form.cleaned_data['post_id'] )
        bid = Bid.objects.get(id = form.cleaned_data['bid_id'])
        post.bidder = bid.bidder # You set post.bidder instance so you have to change model
        post.save()
else:
    form = AcceptedForm()

and models:
class Post(models.Model):
   item = models.CharField(max_length=20)
   post_owner = models.OneToOneField(settings.AUTH_USER_MODEL, default=1)
   # Bidder should be User Foreign Key, but you have to set related_name, because you already have one User FK in model
   bidder = models.ForeingKey(settings.AUTH_USER_MODEL, null=True, blank=True, related_name='posts_bidded')

and template:
<form class="nomargin" method='POST' action='' enctype='multipart/form-data'>{% csrf_token %}
{{form}}
<input type='submit' value='Accept'/>

But I dont know purpose of bidder field, even in your code you override the field bidder anyway.


text:
Q: Milnor's definition of the Stiefel Whitney number In Milnor's characteristic class, he defines the Stiefel-Whitney class as follows:
Let $M$ be a closed possibly disconnected smoooth $n$-manifold. Using mod $2$ coefficients there is a unique fundamental homology class $\mu_M\in H_n(M;\mathbb{Z}/2)$. Hence for any cohomology class $v\in H^n(M,\mathbb{Z}/2)$, the Kronecker index $v(\mu_M)\in\mathbb{Z}_2$.
My question is, what is the meaning of $v(\mu_M)$? In Hatcher, $v$ needs to act on $n$-dimensional chains with $\mathbb{Z}$ coefficients, it seems that Milnor defines cohomology with coefficients differently. My question is: is there anyway to do this using Hatcher's definition? Or did I miss anything? Thanks in advance!

A: This is the cap product $v \frown \mu_M \in H_0(M;\Bbb Z/2)$, composed with the point-counting map $c: H_0(M;\Bbb Z/2) \to \Bbb Z/2$. (Rephrased: take $v \frown \mu_M$ in each connected component and add up the results.)
But note that it is also true that $$\text{Hom}_{\Bbb Z}(C_*(X;\Bbb Z), \Bbb Z/2) \cong \text{Hom}_{\Bbb Z/2}(C_*(X;\Bbb Z/2), \Bbb Z/2),$$ so that your concerns about pairing against integer homology classes are unnecessary: this canonical isomorphism shows that you can think of $\Bbb Z/2$-cochains as functions on $\Bbb Z/2$-chains.


text:
Q: What is a rock solid and lightweight file manager to use with ubuntu 16.04 and Awesome WM? I have been using Awesome with Ubuntu and other Linux flavors as well for quite some time, it is all fine, nothing to complain, but tasks related to files sometimes can be managed faster using a file manager, I wonder what is the best file manager to use with Awesome, also it need to be rock solid (I mean no buggy!!) and lightweight as I stated in the title, just to say I do not like KDE, gnome it is okay, but to heavy for my machine. It is a low resources machine.
If it helps, I have installed Openbox Desktop (would be nice to call only the Openbox file manager in Awesome, but not sure how to do that), and sometimes I use it, but I prefer Awesome for many reasons.
I also found here some -> https://awesomewm.org/wiki/File_Managers (out of date I think) but I would like to go with Openbox if possible and avoid to install another package.

A: I don't like two-pane window managers or any window managers that have the word commander in their name. All the other file managers at File Managers - awesome are either too heavy or else look ugly except for Rox-Filer and PCManFM.
Maybe Rox is more "rock solid" than PCManFM, but PCManFM wins the beauty contest. If Rox starts to behave like the asteroid belt, I'd say go with PCManFM.


text:
Q: How to get weight on each layers I'm trying to get the input weight on each layer, including the lstm 1, lstm 2, and weight after the attention layer, and want to display them using a heatmap. But when I run the code, the following error appears. What happened? Because the layer exists.
Here is the code:
model.add(LSTM(32, input_shape=(n_timesteps,n_features), return_sequences=True))
#print weights
print(model.get_layer(LSTM).get_weights()[0])
model.add(LSTM(32, input_shape=(n_timesteps,n_features), return_sequences=True))
model.add(Dropout(0.1))
model.add(attention(return_sequences=False)) # receive 3D and output 2D
model.add(Dense(n_outputs, activation='softmax'))
model.summary()
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# fit network
model.fit(trainX, trainy, epochs=epochs, batch_size=batch_size, verbose=verbose)
# evaluate model
_, accuracy = model.evaluate(testX, testy, batch_size=batch_size, verbose=0)

Attention layer:
class attention(Layer):
def __init__(self, return_sequences=True):
    self.return_sequences = return_sequences
    super(attention,self).__init__()
def build(self, input_shape):
    self.W=self.add_weight(name="att_weight", shape=(input_shape[-1],1),
                           initializer="normal")
    self.b=self.add_weight(name="att_bias", shape=(input_shape[1],1),
                           initializer="zeros")
    super(attention,self).build(input_shape)
def call(self, x):
    e = K.tanh(K.dot(x,self.W)+self.b)
    a = K.softmax(e, axis=1)
    output = x*a
    if self.return_sequences:
        return output
    return K.sum(output, axis=1)

And this is the error that appears:
ValueError: No such layer: <class 'keras.layers.recurrent_v2.LSTM'>. Existing layers are [<keras.layers.recurrent_v2.LSTM object at 0x7f7b5c215910>].

A: You can get certain layer weights using model.layers after defining your whole model:
import tensorflow as tf
import seaborn as sb
import matplotlib.pyplot as plt

class attention(tf.keras.layers.Layer):
  def __init__(self, return_sequences=True):
      self.return_sequences = return_sequences
      super(attention,self).__init__()
  def build(self, input_shape):
      self.W=self.add_weight(name="att_weight", shape=(input_shape[-1],1),
                            initializer="normal")
      self.b=self.add_weight(name="att_bias", shape=(input_shape[1],1),
                            initializer="zeros")
      super(attention,self).build(input_shape)
  def call(self, x):
      e = tf.keras.backend.tanh(tf.keras.backend.dot(x,self.W)+self.b)
      a = tf.keras.backend.softmax(e, axis=1)
      output = x*a
      if self.return_sequences:
          return output
      return tf.keras.backend.sum(output, axis=1)

model = tf.keras.Sequential()
model.add(tf.keras.layers.LSTM(32, input_shape=(5,10), return_sequences=True))
model.add(tf.keras.layers.LSTM(32, return_sequences=True))
model.add(tf.keras.layers.Dropout(0.1))
model.add(attention(return_sequences=False)) # receive 3D and output 2D
model.add(tf.keras.layers.Dense(3, activation='softmax'))
model.summary()
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

trainx = tf.random.normal((25, 5, 10))
trainy = tf.random.uniform((25, 3), maxval=3)
model.fit(trainx, trainy, epochs=5, batch_size=4)

lstm1_weights = model.layers[0].get_weights()[0]
lstm2_weights = model.layers[1].get_weights()[0]
attention_weights = model.layers[3].get_weights()[0]

heat_map = sb.heatmap(lstm1_weights)
plt.show()

Model: "sequential_16"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 lstm_24 (LSTM)              (None, 5, 32)             5504

 lstm_25 (LSTM)              (None, 5, 32)             8320

 dropout_12 (Dropout)        (None, 5, 32)             0

 attention_12 (attention)    (None, 32)                37

 dense_12 (Dense)            (None, 3)                 99

=================================================================
Total params: 13,960
Trainable params: 13,960
Non-trainable params: 0
_________________________________________________________________
Epoch 1/5
7/7 [==============================] - 4s 10ms/step - loss: 5.5033 - accuracy: 0.4400
Epoch 2/5
7/7 [==============================] - 0s 8ms/step - loss: 5.4899 - accuracy: 0.5200
Epoch 3/5
7/7 [==============================] - 0s 9ms/step - loss: 5.4771 - accuracy: 0.4800
Epoch 4/5
7/7 [==============================] - 0s 9ms/step - loss: 5.4701 - accuracy: 0.5200
Epoch 5/5
7/7 [==============================] - 0s 8ms/step - loss: 5.4569 - accuracy: 0.5200

If you want to see how the weights of your layers change during training, you should define a callback as shown in this post.


text:
Q: GNU Parallel - global variables and function I have this script:
GLOBAL_VAR="some global value"

function test
{
  echo $1
  echo ${GLOBAL_VAR}
}

export -f test
parallel --jobs 5 --linebuffer test ::: "${files[@]}"

How can I have $GLOBAL_VAR visible from parallel?

A: Shell variables are not visible to child processes unless they are exported so you'll need to say
export GLOBAL_VAR

somewhere before the child process is launched; in modern shells the export can be combined with the assignment
export GLOBAL_VAR="some global value"

A: "Shell variables are not visible to child processes unless they are exported" - and even so they are still not visible if you run a command remotely. That is unless you use env_parallel which is a frontend for GNU Parallel that copies the environment:
   . `which env_parallel.bash`

   aliases
             alias myecho='echo aliases'
             env_parallel myecho ::: work
             env_parallel -S server myecho ::: work
             env_parallel --env myecho myecho ::: work
             env_parallel --env myecho -S server myecho ::: work

   functions
             myfunc() { echo functions $*; }
             env_parallel myfunc ::: work
             env_parallel -S server myfunc ::: work
             env_parallel --env myfunc myfunc ::: work
             env_parallel --env myfunc -S server myfunc ::: work

   variables
             myvar=variables
             env_parallel echo '$myvar' ::: work
             env_parallel -S server echo '$myvar' ::: work
             env_parallel --env myvar echo '$myvar' ::: work
             env_parallel --env myvar -S server echo '$myvar' ::: work

   arrays
             myarray=(arrays work, too)
             env_parallel -k echo '${myarray[{}]}' ::: 0 1 2
             env_parallel -k -S server echo '${myarray[{}]}' ::: 0 1 2
             env_parallel -k --env myarray echo '${myarray[{}]}' ::: 0 1 2
             env_parallel -k --env myarray -S server echo '${myarray[{}]}' ::: 0 1 2


text:
Q: how to remove xmlnode within a foreach loop? At the following code i use foreach loop to check each node in nodelist and remove some of them.
after i remove one node the foreach loop throw the following error:
"The element list has changed. The enumeration operation failed to continue".
How can i avoid it?
public static XmlNodeList Scan(XmlNodeList nodeList)
        {
            string elementValue = null;
            foreach (XmlNode xmlElement in nodeList)
            {
                elementValue = xmlElement.InnerText;
                if (elementValue.Length >= 6 && elementValue.Substring(0, 3) == "999")
                {
                    continue;
                }
                else
                {
                    XmlNode node = xmlElement.ParentNode;
                    node.RemoveChild(xmlElement);
                }
            }

            return nodeList;
        }

A: The answer, sadly, is to not use foreach, but to fallback on the very bulletproof "for()".
for(int i = collection.Count - 1; i >= 0; i--)
{
    object myObject = collection[i];
    collection.Remove(myObject);
}

In this case, I loop backward in the collection, and remove one object at a time. That way, I can never have an invalid index.

A: As you're not simply removing items from the collection you're looping over, I'm not sure if "use a for loop" will work.
The following takes two steps:

*

*Create a regular list of all the elements you want to detach from their parents.

*Detatch those elements from their parents - by iterating over the regular list, which isn't affected by the detachings.

public static XmlNodeList Scan(XmlNodeList nodeList)
{
    List<XmlNode> toRemove = new List<XmlNode>();

    foreach (XmlNode xmlElement in nodeList)
    {
        string elementValue = xmlElement.InnerText;
        if (elementValue.Length < 6 || elementValue.Substring(0, 3) != "999")
        {
            toRemove.Add(xmlElement);
        }
    }

    foreach(XmlNode xmlElement in toRemove)
    {
        XmlNode node = xmlElement.ParentNode;
        node.RemoveChild(xmlElement);
    }

    return nodeList;
}

A: Use for loop instead from
for(I=length-1;I>=0;I--)

For each is used for enumerating and you cannot delete while enumerating the list. Also the loop must start from the last element to avoid any shift when you delete an element.

A: I found an alterative: Convert xmlnodelist to list<>
XmlNodeList has a method Cast and can be used as follows:
var listOfNodes = new List<XmlNode>(xmlNodeList.Cast<XmlNode>());

A: You are not allowed to change a collection used during a foreach iteration. You can use For..loop instead
for(int i=0; i<nodeList.Length; i++)
{
   //remove nodeList[i];
}


text:
Q: Equation Solving: Solution in terms of predefined functions Is there a way that I can have Mathematica give me the solution of a problem it has solved in terms of functions that I have predefined?
The specific problem I'm trying to solve is:
s = alp^2 (E0*mu1 + N01);
k = 1 - E^(-Pmax/s^2) + Sqrt[π*Pmax]/(2*s)*Erfc[Sqrt[Pmax]/s];

E1 = s^2 (1 - E^(-Pmax/s^2));

epsd = E1 - (s*k)^2;

A = 1 + epsd/((k*alp)^2 N01);

c = E1/(N01*(k*alp)^2);

SIG1 = (E0*mu1)/N01; SIG2 = (E1*mu2)/N02;

D[1 - 2 E^(-((A SNRth)/SIG1)) Sqrt[(c SNRth)/(SIG1 SIG2)]
     BesselK[1, 2 Sqrt[(c SNRth)/(SIG1 SIG2)]], {alp}]

The solution given by Mathematica is extremely lengthy. However, by observation it can be seen that many of the functions that I have defined above the differentiation operator are contained within the solution.


text:
Q: Upload existing java WAR file to AWS Elastic Beanstalk I have a working maven java web project on an EC2 instance running a Jetty server (I dropped the .WAR file for that project in the jetty webapps/ folder). However, when I try to upload this same .WAR file to an Elastic Beanstalk environment through the AWS console it doesn't work at all. What changes do I need to make to my web project to get it to work on Elastic Beanstalk?

A: To deploy a WAR as application version in Elastic Beanstalk you need to use the Java Tomcat platform.
You other option with java in Elastic Beanstalk is the Java SE platform. But you need to upload a zip file as an application version in this case, not a WAR. So your better chance of working with jetty and Java SE ELB platform is to embed jetty within you application and build a fat runnable jar.


text:
Q: Can Minecraft PS4 edition connect to local LAN servers without PlayStation Network? Some context
I have a home LAN where I connect

*

*Wifi Router

*Playstation 4

*Playstation 3

*Desktop with Windows 10

*Laptop with Windows 10

*Android Tablet

*Android Phones

I have bought Minecraft for my PS4. My son loves it. We play in multiplayer in the same screen. I don't pay playstation network and would like to avoid it.
I am thinking on creating a dedicated Minecraft Server in my desktop PC so I am planning to run a dedicated server there to be able to have the same server for all devices and install mods.
Then I plan to have Minecraft clients in the devices listed above.
My questions are

*

*Does Minecraft ps4 edition allow you to play in your local LAN?

*Are clients from different platforms able to play in the same server (PS4, PC, PS3, Android Tablet, etc.)

A: Answer to #1
You can play on a LAN game on PS4, but you will need PS Plus.
Answer to #2
The clients can play on the same server if they are all of Bedrock Edition. Bedrock Edition is Pocket (Mobile), Xbox One, Playstation 4, Nintendo Switch, and Windows 10 Edition. With that said, if you are setting up a LAN game on your PC you must run the Windows 10 Edition, not the Java Edition.

*

*You have Windows 10 Edition if you bought the game from the Windows Store

*You have Java Edition if you bought the game from minecraft.net.

Java edition cannot play a LAN game with PlayStation 4. Windows 10 edition can play a LAN game with PlayStation 4.

A: Unfortunately, it appears (according to some Reddit threads #1, #2, #3, #4), two distinct concepts jump out:

*

*Minecraft on the PlayStation 4 doesn't directly support LAN games. They are considered "cross-play" games.

*As such, what you describe would be considered an "online" game, and therefore you'd need an active PlayStation Plus subscription to join one from a PlayStation 4 console.

A "bug report" in Mojang's Jira bug tracker was filed in December 2019 to have developers address this point exactly, but went un-responded to because of a lack of required information on the reporter's part.


text:
Q: CloudFront Top Referrers Report - ALL referrer URLs In AWS I can find under:
Cloudfront >> Reports & Analytics >> Top Referrers (CloudFront Top Referrers Report)
There I get the top25 items. How can I get ALL of them?
I have turned on logging in my bucket, but it seems that the referrer is not part of the log-file. Any idea how amazon collects its top25 and how I can according to that get the whole list?
Thanks for your help, in advance.

A: Amazon's built in analytics are, as you've noticed, rather basic.  The data you're looking for all lives in the logfiles that you can set cloudfront up to export (in the cs(Referer) field).  If you know what you're looking for, you can set up a little pipeline to download logs, pull out the numbers you care about and generate reports.
Amazon also makes it easy[1] to set up Athena or Redshift to look directly at Cloudfront or S3 logfiles in their target bucket.  After a one-time setup, you could query them directly for the numbers you need.
There are also paid services built to fill in the holes in Amazon's default reports.  S3stat (https://www.s3stat.com/), for example, will give you a Top 200 Referrer list in its reports, with the ability to export complete lists.
[1] "easy", using Amazon's definition of the word, meaning really really hard.


text:
Q: Join unrelated tables(A,B) with some condition on basis of table A for postgresql I am trying to join two unrelated tables, both table has a common column, a foreign key of third table, If suppose first table is Notification table, and second table is Photos table. A device takes photo on basis of several criteria on timely basis, if any movements, and also on basis of notifications. Need to pick both notifications and only one photo after that notification.
Notification Table
+-----+----------------------------+----------+----------------+
| id1 |  Notification timestamp    |   data1  |    deviceID    |
+-----+----------------------------+----------+----------------+
| 11  |  2020-10-26 22:31:33.602   | 2038.75  |        6       |
| 12  |  2020-10-26 22:31:34.001   | 2043.5   |        2       |
| 13  |  2020-10-26 22:51:47.178   | 1778.75  |        8       |
| 14  |  2020-10-26 23:12:07.761   | 2015.75  |        3       |
| 15  |  2020-10-26 23:12:09.611   | 2005.75  |        2       |
| 16  |  2020-10-26 23:12:09.122   | 1963.25  |        7       |
| 17  |  2020-10-26 23:12:11.930   | 694.75   |        2       |
+-----+----------------------------+----------+----------------+

Photo Table
+-----+---------------------------+----------+----------------+
| id2 |    Photo timestamp        |   data2  |    deviceID    |
+-----+---------------------------+----------+----------------+
| 21  |  2020-10-26 22:31:34.016  |     5    |        2       |
| 22  |  2020-10-26 22:31:34.102  |    75    |        6       |
| 23  |  2020-10-26 22:31:34.022  |    20    |        3       |
| 24  |  2020-10-26 22:51:47.97   |    55    |        2       |
| 25  |  2020-10-26 22:51:47.975  |    63    |        7       |
| 26  |  2020-10-26 22:51:47.977  |    19    |        4       |
| 27  |  2020-10-26 22:51:47.978  |    77    |        8       |
| 28  |  2020-10-26 23:12:07.613  |    44    |        6       |
| 29  |  2020-10-26 23:12:08.61   |    11    |        3       |
| 30  |  2020-10-26 23:12:09.625  |    51    |        2       |
| 31  |  2020-10-26 23:12:09.628  |    63    |        7       |
| 32  |  2020-10-26 23:12:10.635  |    19    |        4       |
| 33  |  2020-10-26 23:12:11.635  |    77    |        8       |
| 34  |  2020-10-26 23:12:12.235  |    44    |        6       |
| 35  |  2020-10-26 23:12:12.435  |    11    |        3       |
| 36  |  2020-10-26 23:12:12.650  |    51    |        2       |
+-----+---------------------------+----------+----------------+

Resultant Table
+---------------------------+----------+---------------------------+----------+----------------+
|  Notification timestamp   |   data1  |    Photo timestamp        |   data   |    deviceID    |
+---------------------------+----------+---------------------------+----------+----------------+
| 2020-10-26 22:31:33.602   | 2038.75  |  2020-10-26 22:31:34.102  |    75    |        6       |
| 2020-10-26 22:31:34.001   | 2043.5   |  2020-10-26 22:31:34.016  |     5    |        2       |
| 2020-10-26 22:51:47.178   | 1778.75  |  2020-10-26 22:51:47.978  |    77    |        8       |
| 2020-10-26 23:12:07.761   | 2015.75  |  2020-10-26 23:12:08.61   |    11    |        3       |
| 2020-10-26 23:12:09.611   | 2005.75  |  2020-10-26 23:12:09.625  |    51    |        2       |
| 2020-10-26 23:12:09.122   | 1963.25  |  2020-10-26 23:12:09.628  |    63    |        7       |
| 2020-10-26 23:12:11.930   | 694.75   |  2020-10-26 23:12:12.650  |    51    |        2       |
+---------------------------+----------+---------------------------+----------+----------------+

Tried with joining sub-queries. Definitely not a correct way to do though
select "notification".*, "filter_data".* FROM public.notification
  left JOIN
    ( select "photo"."time", "photo"."data2", "photo"."deviceid", "notification"."id" as "eid", "notification"."time" as "etime"
      from public."photo" inner join  public."notification" on "notification"."deviceid" = "photo"."deviceid" where
      "photo"."time" >= "notification"."time" order by "photo"."time" ASC
      limit 1
    )
  filter_data on "filter_data"."did" = "notification"."deviceid"
  where "notification"."time" > date '2021-10-28 01:37:20.305+00' - interval '7 days'
  order by "notification"."device" ASC, "notification"."time" DESC limit 100;

Kindly suggest. I am aware my solution is not right

A: try this :
WITH list AS
(
SELECT n.Notification, n.data1, n.deviceID, first_value(p.Photo) OVER (ORDER BY p.Photo ASC) AS Photo
     , p.data2, p.deviceID
  FROM Notification AS n
 INNER JOIN Photo AS p
    ON p.deviceID = n.deviceID
   AND p.Photo >= n.Notification
 GROUP BY n.Notification, n.data1, n.deviceID
)
SELECT l.Notification, l.data1, l.Photo, p.data2 AS data, l.deviceID
  FROM list AS l
 INNER JOIN Photo AS p
    ON l.deviceID = p.deviceID
   AND l.Photo = p.Photo

A: You can use the distinct on to get just a single Notification+Photo. The problem being that id1 in Notification is not unique (typo?). Note that sorting the age function gives the minimum time between the Notification and the Photo. (See demo)
select distinct on (n.id1,n.deviceid)
       n.ts       "Notification Time"
     , n.data1    "Notification Data"
     , p.ts       "Photo Time"
     , p.data2    "Photo Data"
     , n.deviceid "Device Id"
  from notifications  n
  left join photos    p
         on (     p.deviceid = n.deviceid
              and p.ts > n.ts
            )
 order by n.id1,n.deviceid,age(p.ts,n.ts);


text:
Q: Does writing JSON in a single line create any problem? I have used json.dump() without indent
with open (JSONfilename, 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False)
f.close()

This saves all of JSON data in a single line. I have done this because I noticed that using indent=4 for formatting JSON file increases it size. Is saving big JSON file in single line ok or will I encounter any problem in future?
Edit: Does it effect on saving, loading or parsing time?

A: Well, people will have trouble reading it, if you consider that a problem.
The JSON parser ignores whitespace outside of quotation marks.

A: The format of .json file will be okay.
I want to add one 'Important@ thing. While reading the same file, json.load module only can read till 226538 column length in one line. If you data is much larger, It will cause this extra data problem in one line.


text:
Q: Threading works in simulator but not on iPhone I'm trying to display a UIActivityIndicatorView while background processing takes place.
The below simplified code works when I try it in the simulator(the alert is displayed)..but when I download it to my phone from Xcode, the background thread does not seem to get called at all. (the alert never gets displayed)
Any ideas?
 -(void)viewDidLoad {
    [self performSelectorInBackground:@selector(runInAnotherThread) withObject:nil];

}

-(void) runInAnotherThread {
    NSAutoreleasePool *pool = [ [ NSAutoreleasePool alloc ] init ];
  int i;
    for(i=0;i < 1000 ;i ++){
        NSLog(@"INDEX = %d", i);
    }

    [self performSelectorOnMainThread : @ selector(backToMainThread ) withObject:nil waitUntilDone:NO];
    [ pool release ];
}

-(void) backToMainThread {

    UIAlertView *completeAlert = [[UIAlertView alloc]
                     initWithTitle:@"Back to main "
                message: @"Success"
                delegate:nil
                cancelButtonTitle:@"OK"
                otherButtonTitles:nil];
    [completeAlert show];
    [completeAlert release];
}

A: Have you you tried cleaning your build? I just ran your code on my device and simulator and it works as expected in both cases

A: Use NSOperation instead of raw thread manipulation. It abstracts all sorts of stuff for you (priority, autoreleasepools etc...). ? You can simply add some kind of delegate to your NSOperation subclass to get a callback when you need.

A: Thanks for replying so quickly!
It turned out that the issue was not in this code fragment at all. I was executing this code dependent on a value in the keychain. While my simulator's keychain has that value, my test iphone did not have this value.
Feel so silly for troubling all of you. But following up on the reply from nduplessis helped me narrow down the issue.


text:
Q: Hexo (and other static-site-generators) front-end dependency-management workflow Are there any recommended workflows for managing front-end dependencies? I've been reading a lot of articles that recommend moving away from Bower, and on to an npm-only solution like Webpack, but Webpack is a whole new paradigm (loading js, scss, fonts, etc through a single js file) that by default, requires js to be running in the browser for css to load. Part of the reason I want a static site is so that js isn't mandatory for an end-user. However, I'm really tired of bower-installing things, and then having to either host everything in bower_components, targeting specific filenames (js, css, img) to include in output, or move their css/img dependencies into my own repo. Not to mention that relying on two registries is less than ideal.
Does Hexo have a recommended way, or does anyone have an opinion on how to do this? Running a Hexo server in a separate terminal from a webpack-dev-server seems painful and awkward, and possibly create some confusion as to which library should be handling which files.
Are other tools more suited for dependency management in a static site generator's dev/build process?