text:
Q: Expression for the (relativistic) mass of the photon I started learning a bit ahead from an old physics book, and they were discussing the photoelectric effect and after that Planck's hypotheses and energy quantas.
The book said that the mass of a microscopic oscillator (what is that?) is not continuous, but discrete and the difference between states is an energy quanta:
$ \varepsilon = h\nu = E_k - E_i $
And since
$ E = mc^2 $ then the (relativistic) mass of the photon is
$ m = \frac{h\nu}{c^2} $
How did they deduce that?

A: This is probably related to the derivation of de-Broglie wavelength... Since photon has wave-particle duality,
We could equate Planck's quantum theory (wave nature) which gives the expression for energy of a wave of frequency $\nu$, ($E=h\nu$) with Einstein's mass-energy equivalence (particle nature) which gives relativistic energy for photon ($E=mc^2$)
$$mc^2=h\nu$$
The resultant mass gives the relativistic mass for a moving photon (since photon has zero rest mass)


text:
Q: make a javascript HMAC token I am trying to emulate the following .NET code in javascript using the Crypto.js library.
var hashInput = "public=ID1000000001::routetype=POST::route=personsearch::key1=ID1000000001::key2=1043"
byte[] inputBytes = new byte[hashInput.Length * sizeof(char)];
System.Buffer.BlockCopy(hashInput.ToCharArray(), 0, inputBytes,0,inputBytes.Length);

byte[] keyBytes = HexadecimalStringToByteArray("A_HEX_STRING_GOES_HERE");

var hmac = HMACSHA256.Create();
hmac.Key = keyBytes;
var clientHash = hmac.ComputeHash(inputBytes);

This gives me a ByteArray which is used as part of POST to a WebAPI in the form of
[41,197,254,91,244,87.....] etc.
I want to make the same exact byte array in a javascript client but i am having diffculty getting this. I have tried the following:
var stringToHash = 'public=ID1000000001::routetype=POST::route=personsearch::key1=ID1000000001::key2=1043';
var privateKey = 'A_HEX_STRING_GOES_HERE';
var hash = CryptoJS.HmacSHA256(stringToHash, privateKey);
//this results in a WordArray, which can be converted to many types
//however i cannot get the byte array as in the .net example
//i.e. i just want to get [41,197,254,91,244,87....] etc.

I can see on the documentation for Crypto.js how to convert to base64, and other formats, but not to the ByteArray which i need.
Any ideas?
--UPDATE
Thanks for the advice on not using BlockCopy, and also for pointing me in the direction of the encoding issues which i had completely neglected.
This was part of the issue. The other part was that i had managed to misuse the HMACSHA256 class. I found (after several, several hours) that the .NET code was not producing the correct hash value.
It turns out this code DID produce the correct Hash:
        var hashInput = "a::string::to::hash";
        var privateKey = "C0B615950F9D577A4EAF64C9B4F2E50F3DA2C6BB6F790FA346E9732788B29A08AC5444F1B82984DB190A75D3861CC4802D598EBF0025FD1C327928F43EB1C80E";

        byte[] inputBytes = Encoding.UTF8.GetBytes(hashInput);
        byte[] keyBytes = Encoding.UTF8.GetBytes(privateKey);

        HMACSHA256 hmac = new HMACSHA256(keyBytes);
        hmac.Initialize();
        var clientHash = hmac.ComputeHash(inputBytes);
        var base64 = Convert.ToBase64String(clientHash);

Lucky for me my WebAPI is not live yet!

A: The problem is probably the character encoding. You should use for instance the method encode_utf8(stringValue) in JavaScript and new UTF8Encoding.getBytes(String value) in .NET, to make sure that the character encodings match. Note that modern cryptography is based on bytes, not on strings or characters. Using System.Buffer.BlockCopy() to encode characters is really bad practice.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I access SQLite database directly from DLL (without using app.config)? I'm trying to connect to and use an SQLite database file from a DLL.  So far I have the following
        ASSEMBLY_PATH = ReturnThisAssemblyPath();

        DB_PATH = ASSEMBLY_PATH + @"\Datastore\" + DB_FILENAME;
        try
        {
            DbProviderFactory fac = System.Data.SQLite.SQLiteFactory.Instance;

            var conn = fac.CreateConnection();

            conn.ConnectionString = "data source =" + DB_PATH + @"\SQLiteDatabase.db";
            using (var m = new ReportsContext(conn))
            {
                try
                {
                    m.Reports.Add(new Datastore.Report() { reportTypeId = "1", reportType = "HL7", originalString = "orig10", processedString = "mod10" });
                    m.SaveChanges();
                }
                catch (System.Exception ex)
                {

                }
                var res = m.Reports.Find(111);
            }

        }catch(System.Exception ex)
        {

        }

I also tried DbProviderFactory fac = System.Data.SQLite.EF6.SQLiteProviderFactory.Instance;
But when it tried to add a record it fails with the following error

Unable to determine the provider name for provider factory of type
  'System.Data.SQLite.SQLiteFactory'. Make sure that the ADO.NET
  provider is installed or registered in the application config.

A: using (SQLiteConnection connection = new SQLiteConnection(string.Format("Data Source={0};Version=3;", <your_database_file_path>)))
{

}


text:
Q: XSLT for each loop with an if else This is for a university purpose. My xslt is not working. I'm trying to do a for-each with and if statement. I try it with the = or != it doesn't work.
Any help would be greatly appreciated.
(Sorry the indentation is bad).
<xsl:for-each select="$rankingItems/userDefinedVectorLine[userDefinedField/fieldLabel='LIST'
and (userDefinedField[fieldLabel='COUP'] or userDefinedField[fieldLabel='PAY']) ]" >
<xsl:variable name="date" select="userDefinedField[fieldLabel='LIST']/fieldValue"/>
<xsl:variable name="Tempo" select="userDefinedField[2]/fieldLabel"/>
<xsl:if  test="$Tempo!='COUP'" >
    <xsl:variable name="coupon" select="'TITI'" />
</xsl:if>
    <xsl:value-of select="$date"/>
    <xsl:value-of select="$coupon"/>
 </xsl:for-each>

A: In your code coupon variable exists only inside the xsl:if block.
So when you try to use it (outside of the xsl:if block) you get an empty value.
Probably you should create this variable "unconditionally", but its content
should be created based on a condition, e.g.:
<xsl:variable name="coupon" select="if ($Tempo!='COUP') then 'TITI' else ''" />

One more question: Is it your intention that coupon variable
contained 'TITI' (a constant string)?
Or maybe its value should be the content of TITI (child) element?
If the second is true, then write just TITI without surrounding apostrophes.
And the last remark: Asking a question provide also the source XML code.


text:
Q: TinyMCE 5 - Is there a way to accept only uploaded Image, using the "image" plugin? I want to allow uploaded images only, not images linked from external websites. Is there a way to only display the "Upload" section of the "image" plugin/dialog?

A: The image plugin does not have a built in configuration option to do what you want.  As TinyMCE is released under an open source license you could certainly modify the code of that plugin to get your desired outcome.


text:
Q: How to allow VB scripts to run on an admin account I'm encountering an issue with the VBscripts while I try to run them. I'm working on Windows 8.1 update 1 Enterprise, connected to an Enterprise domain, and I'm logged with a domain account. This domain account has been added to the Administrators group.
My VBscript must create a folder and a log file into the Program Files (x86) directory. If I run this VBscript by double-clicking on it with the local administrator account, it works perfectly. But if I try to run the same VBscript with my domain account, I get the error message Access denied.
One solution is to totally deactivate the UAC (with the enableLUA registry value set to 1), but this method blocks the Modern UI applications, and we need to keep these applications execution.
Is it possible to grant the full control to VBScripts execution on any admin account, like it is the case under the local administrator built-in account ?  I didn't yet find any solution to this problem, and I can't believe that no solution exists, especially in enterprise.

A: the way I normally do this is to stick the following code at the top of my script:
If Not WScript.Arguments.Named.Exists("elevate") Then
  CreateObject("Shell.Application").ShellExecute WScript.FullName _
    , WScript.ScriptFullName & " /elevate", "", "runas", 1
  WScript.Quit
End If

This way, if I launch the VBS as a non admin - it tries to run, notices I'm not an admin and then relaunches - prompting me to run as admin and away we go.
I know its a pain, but its a fairly simple solution.
Hope this helps

A: This trick is useful if you are using command-line:

*

*Go to System32 (or Syswow4 for x64)

*Copy cscript.exe and wscript.exe and name them csadmin.exe and wsadmin.exe

*Open their properties, set "Run as admin" flag.

Now if you want to run your script as admin, use one of these:
csadmin myscript.vbs
wsadmin myscript.vbs

(And if you want to run as default, use wscript and cscript)
Note: If you want to run all scripts as admin (UAC window will appear each time), then just set "Run as admin" flag on cscript.exe and wscript.exe.
Hope it helps.


text:
Q: Asp.net MVC set validation date format fails on Chrome I'm having problems with setting validations date format Chrome in asp.net mvc, for other browsers like IE,Firefox works correctly .
I have defined dates in my model like next code:
[Required]
[Display(Name = "Data fi publicació")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime PublishingEndDate { get; set; }

And in my views :
@Html.TextBoxFor(model => model.PublishingEndDate)
@Html.ValidationMessageFor(model => model.PublishingEndDate)

The problem It seems that @Html.ValidationMessageFor, validates the date with format MM/dd/yyyy, but what I want is to validate with european format dd/MM/yyyy. How can I change default culture validations format date to dd/MM/yyyy ?
Thanks for your help

A: Finally I discover the problem only affects Chrome, with IE, Firexfox it works perfectly, it seems is a chrome bug, I found the solution in http://forums.asp.net/t/1729179.aspx/1
The validator method of jquery has to be override using the following code:
$(document).ready(function () {
    $('.calendarPicker').datepicker({ dateFormat: "dd/mm/yy" });

$.validator.addMethod('date',
    function (value, element, params) {
        if (this.optional(element)) {
            return true;
        }

        var ok = true;
        try {
            $.datepicker.parseDate('dd/mm/yy', value);
        }
        catch (err) {
            ok = false;
        }
        return ok;
    });
});

A: Be sure you've set your culture in web.config. This will use the appropriate date and number formatting for the culture chosen.
http://msdn.microsoft.com/en-us/library/bz9tc508(v=vs.100).aspx

A: This helped me:
$(function() {
            $(".datepicker").datepicker({
                todayBtn: true,
                language: "en-GB",
                format: "dd/mm/yyyy",
                clearBtn: true,
                pickTime: false
            });

            $.validator.addMethod("date",
                function(value, element) {
                    return this.optional(element) || parseDate(value, "dd-MM-yyyy") !== null;
                });
        });

A: To avoid client side validation, you don't want any data-val attributes associated with the input. So what I did is to write down the plain HTML instead of using TextFor or EditorFor etc...
<input type="text" class="datepicker form-control">

Works fine for me...

A: If you don't want to use datetime picker:
Client validation issues can occur because of MVC bug (even in MVC 5) in jquery.validate.unobtrusive.min.js which does not accept date/datetime format in any way. Unfortunately you have to solve it manually.
My finally working solution:
You have to include before:
@Scripts.Render("~/Scripts/jquery-3.1.1.js")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
@Scripts.Render("~/Scripts/moment.js")

You can install moment.js using:
Install-Package Moment.js

And then you can finally add fix for date format parser:
$(function () {
    $.validator.methods.date = function (value, element) {
        return this.optional(element) || moment(value, "DD.MM.YYYY", true).isValid();
    }
});


text:
Q: How to create an abstract function that returns inherited class type Assume that A is an abstract class with an abstract copy function that returns type A. I want that every inherited class implements copy that returns its own class. It is not allowed that copy returns the type of A.
abstract class A(
  open val property1: String = "A1"
) {
  abstract fun copy(): A
}

class B(
  override val property1: String = "B1",
  val property2: String = "B2"
): A() {
  override fun copy(): B {
    return B(property1 = this.property1, property2 = this.property2)
  }
}

A: The only thing I could think of is adding a generic to the class declaration :
abstract class Test<T> {
    abstract fun copy(): T
}

class Dummy: Test<Dummy>() {
    override fun copy(): Dummy {
        TODO("Not yet implemented")
    }
}


text:
Q: Outlook mobile does not pick up correct styling Iam tying to create an newsletter, but in outlook mobile it does not pick up the correct styling. The styling which is not picked up is as follow: bold text, color of text and uppercase
Here a link to the output

*

*The titles like Folio .... needs to be blue and bold.

*thereby the text in buttons needs to be white and bold.

*And the text in de full width button has to be uppercased and white
here is the html of an element with the image left text right:

                                                           Title

                                                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer pharetra hendrerit felis, eget auctor ex tincidunt eget. Vestibulum consequat quam nibh.

                                                                        Read more

                                                                    ▸

A: outlook does not support all css please go have a look at https://www.campaignmonitor.com/css/
outlook versions just as ie have different css to consider so you would need something like this to cater for all the options


text:
Q: $\nabla f(x)^T(y-x) \geq 0$ if $x$ is optimal for a convex $f(x)$. In the Convex Optimization book by Boyd and Vandenberghe, it states that if $x \in X$ and $X$ denotes the feasible set, and $f(x)$ is a convex objective function, then $x$ is optimal IFF
$$\nabla f(x)^T(y-x) \geq 0$$
if $x$ is optimal for a convex $f(x)$. I understand this logic, but I don't understand why it's $\geq$ instead of $=$. If $x$ is optimal, then isn't the gradient of the objective function $f(x)$ zero there?

A: This is probably in the context of a constrained optimization problem "minimize $f$ within convex set $X$." In constrained optimization, the gradient need not be zero at the optimizer (specifically, when the optimizer is not in the interior of $X$). The optimality condition is "$\nabla f(x)^\top (y-x) \ge 0$ for all $y \in X$."
When $X$ is the entire space, then this result generalizes to the "gradient equals zero" condition for unconstrained optimization, since the vector $y-x$ can point in any direction.


text:
Q: Everytime Celery is restarted all the scheduled tasks are acknowledged Everytime Celery is restarted all the scheduled tasks are acknowledged again.
And this is leading to a huge time lag to start processing new tasks.
How can we solve this?

A: You can simply purge all the tasks before starting Celery again:
$ celery purge
WARNING: This will remove all tasks from queue: celery.
         There is no undo for this operation!

(to skip this prompt use the -f option)

Are you sure you want to delete all tasks (yes/NO)?

A: If you don't want to purge the tasks which were in the QUEUE waiting to be executed i.e., you also want them to execute, then obviously those old tasks will be executed before the new tasks as the new tasks came in the QUEUE after the old ones AND because it is a QUEUE, it will follow First In First Out.
Now, if you want the old tasks to execute but don't want to wait for the old ones to execute first, from what I comprehend by you not wanting to PURGE the old ones and also not wanting the delay, then you can maintain two or more separate queues for the tasks.
Hence on every reload, your new tasks will be assigned to a new QUEUE, which won't be dependent on the Old tasks.
See this -> How to keep multiple independent celery queues?


text:
Q: Why closing p:dialog is reloading the page

There are not other form around the dialog, there is not form inside the dialog. Here is something very little that I miss but what. I don't know what other information to give because really don't understand how p:button would reload the page being client side only? There is not javascript included. Also there aren't error messages in the firebug console. Outside I'm using template like this:
<!DOCTYPE html>

<h:body>
<ui:composition template="/maintemplate.xhtml">
<ui:define name="content">
<p:dialog ....

A: Move from p:button to p:commandButton command button uses partial request by default

To understand the difference it is enough to see the HTML being rendered in one or the other case, so for

the rendered HTML is
<button type="button" onclick="PF('detailsDialog').hide();window.open('/ui/button.jsf','_self')" >
  Close
</button>

button does GET requests, notice the window.open('/ui/button.jsf','_self')
for

the rendered HTML is
<button onclick="PF('detailsDialog').hide();PrimeFaces.ab({s:'j_idt19'});return false;" type="submit">
  CloseCommandButton
</button>

notice the PrimeFaces.ab({s:'j_idt19'});return false; so it sends a partialUpdate instead of submitting the enclosing form


text:
Q: Is there a way to make a Facebook/Twitter share button that shares a div's innerHTML? Here is a CodePen that helps explain what I'm doing.
I have a site that generates a random fact with Javascript, and puts it into a div with the id="fact". Below this div is a simple "Share on Twitter" link using a very basic sharing link I found online:
http://twitter.com/share?url=http://www.thewikifix.com&text=Simple Share Buttons&hashtags=thewikifix
This works great and it's very simple, but I'm wondering if there's a way to share the contents of the

.
Basically, instead of
"text=SimpleShareButtons"
it would be
"text={document.getElementId("fact").innerHTML}"
(Obviously the second part is fictional, I know I can't just put a Javascript string into a link in HTML).
Is there a way to do what I'm doing? Even a completely different way of doing this is welcome as well.

A: There's two changes that were made to the HTML for simplicity's sake. Here's a fiddle the code that should do what you're looking for:
[css not changed]
HTML:

Babe Ruth once pitched a 4-pitch walk to start a game, got angry at the umpire's calls, and punched him, getting ejected. Reliever Ernie Shore came in and retired every batter for a combined no-hitter.

share on twitter

JS/JQUERY:
 $('#factLink').click(function () {

    // Get the fact text
    var factText = $('#fact').text();

    // Convert to string
    var factStr = factText.toString();

    // Fact length
    var factLen = factText.length;

    // This section formats the text that is too long, remove it if needed
    if (factLen > 103) { // max chacters allowed
        // trim, and allow space for '...'"
        var trimFact = factStr.substring(0, 100);
        var trimFact = trimFact.trim(); //<-- ensures the last character isnt ' '
        factStr = trimFact + "...";
    }

    // Update the link
    var linkRef = "http://twitter.com/share?url=http://www.thewikifix.com&text=" + factStr + "&hashtags=thewikifix";

    $('#factLink').attr('href', linkRef);

});

Hope this helps!

A: Your psudo code is pretty much exactly what you want to do. You just need to pass it as a variable
var inner = document.getElementId("fact").innerHTML;
"text=" + inner


text:
Q: Is it possible to alter multiple columns in one statement in MS SQL? I am trying to add default values to a group of columns, but I get a syntax error when I combine them all into one statement like this:
ALTER TABLE drawinglist
ADD CONSTRAINT ISOKEYPLAN_DWGTITLEPREFIX_def DEFAULT 0 FOR ISOKEYPLAN_DWGTITLEPREFIX,
ADD CONSTRAINT PIPE_VENDOR_def DEFAULT 0 FOR PIPE_VENDOR;

Is the above syntax (or something similar) possible or do I have to separate them all out into their own statements?

A: The documentation for ALTER TABLE says you can. The SQL below should work:
ALTER TABLE drawinglist
ADD
    CONSTRAINT ISOKEYPLAN_DWGTITLEPREFIX_def DEFAULT 0 FOR ISOKEYPLAN_DWGTITLEPREFIX,
    CONSTRAINT PIPE_VENDOR_def DEFAULT 0 FOR PIPE_VENDOR;
GO

I tested on a dev database I have and that syntax worked in SQL Server 2008.


text:
Q: WPF ColumnDataPoint Annotation partial visible I have chart with column series in my application. I'm using solution from this tutorial to add annotation on top of columns:
http://blogs.msdn.com/b/delay/archive/2009/07/27/simple-column-labels-you-can-create-at-home-re-templating-the-silverlight-wpf-data-visualization-columndatapoint-to-add-annotations.aspx
When the bar is really tall the top part of the annotation is only partial visible, or not visible.

I do not know range of my data, so I can not set Maximum value on the vertical Axis.
How to solve this problem?

A: Like Andre said, the problem is your Margin, so you could use Multibinding to calculate the Margin like so:
<ControlTemplate TargetType="charting:ColumnDataPoint">
      <Grid>
          <Rectangle Name="clmnRectangle"
                     Fill="{TemplateBinding Background}"
                     Stroke="Black"/>
          <Grid Background="#aaffffff"
                HorizontalAlignment="Center"
                VerticalAlignment="Top">
              <Grid.Margin>
                  <MultiBinding Converter="{StaticResource ResourceKey=HeightToMargin}">
                       <Binding Path="ActualHeight" RelativeSource="{RelativeSource AncestorType={x:Type charting:ColumnDataPoint}}"></Binding>
                       <Binding Path="ActualHeight" RelativeSource="{RelativeSource AncestorType={x:Type charting:ColumnSeries}}"></Binding>
                  </MultiBinding>
              </Grid.Margin>
              <TextBlock Name="tbValue"
                                    Text="{TemplateBinding FormattedDependentValue}"
                                    FontWeight="Bold"
                                    Margin="2"/>
         </Grid>
    </Grid>
</ControlTemplate>

The Converter could look like:
public class HeightToMarginConverter:IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo ci)
    {
        double clmnHeight = System.Convert.ToDouble(values[0]);
        double chrtHeight = System.Convert.ToDouble(values[1]);
        if (chrtHeight - clmnHeight < 20)
        {
            return new Thickness(0, clmnHeight - chrtHeight + 5, 0, 0);
        }
        else
        {
            return new Thickness(0, -20, 0, 0);
        }
    }

    public object[] ConvertBack(object value, Type[] targetType, object parameter, CultureInfo ci)
    {
        return null;
    }
}


text:
Q: How to rotate the image captured using the getscreenshot method in react-webcam? I am capturing images through react-webcam package but it is in a horizontal manner.
I am trying to view the image in a vertical manner. so I want the captured image to rotate at 90 degrees.
capture image is using a method that is this.webcam.getScreenshot().
so I am trying to set properties in this method so that the captured image is in a vertical manner, that it is rotated at 90 degrees.
I tried rotating the preview and capturing the image whereas, that doesn't work.
as images still are in a horizontal manner.
I want to rotate the image on capture
I tried    // imageSrc.css('transform','rotate(90deg)');
but that does not work.
the image is captured as a base64 image
here webcam is the preview and capture button gets triggered by a button
capture = () => {
    const imageSrc =  this.webcam.getScreenshot();
    this.setState({
        picsArray: [...this.state.picsArray, imageSrc],
    })
};

expected result: The picture is rotated 90 degrees on capturing the image using this method.
actual result: The image is not rotated at 90 degrees and doesn't know how to do it on capture.
Thank you for your time.

A: import React, { Component } from 'react';
import { render } from 'react-dom';
import Webcam from "react-webcam";

class App extends Component {
  state = {
    url: '',
  };

  setRef = webcam => {
    this.webcam = webcam;
  };

  capture = () => {
    const imageSrc = this.webcam.getScreenshot();
    this.rotateImage(imageSrc, 180, (url) => {
    this.setState({ url});
    console.log(url, imageSrc);
    });
  };

  rotateImage = (imageBase64, rotation, cb) => {
            var img = new Image();
            img.src = imageBase64;
            img.onload = () => {
              var canvas = document.createElement("canvas");
              // var canvas = document.createElement("canvas");
              canvas.width = img.width;
              canvas.height = img.height;
              var ctx = canvas.getContext("2d");
              ctx.setTransform(1, 0, 0, 1, img.width / 2, img.height / 2);
              ctx.rotate(rotation * (Math.PI / 180));
              ctx.drawImage(img, -img.width / 2, -img.height / 2);
              cb(canvas.toDataURL("image/jpeg"))
            };
};

  render() {
    const videoConstraints = {
      width: 1280,
      height: 720,
      facingMode: "user"
    };

    return (

        <Webcam
          audio={false}
          height={350}
          ref={this.setRef}
          screenshotFormat="image/jpeg"
          width={350}
          videoConstraints={videoConstraints}
        />
        <button onClick={this.capture}>Capture photo</button>

        <canvas id="canvas" style={{display: 'none'}}></canvas>

    );
  }
}

render(<App />, document.getElementById('root'));

Update
Below code work for any dimension, only need to adjust in this.dim to reflect your need
import React, { Component } from 'react';
import { render } from 'react-dom';
import Webcam from "react-webcam";

class App extends Component {
  state = {
    url: '',
  };

  dim = {
    height: 300, // adjust your original height
    width: 200, // adjust your original width
  };

  setRef = webcam => {
    this.webcam = webcam;
  };

  capture = () => {
    const imageSrc = this.webcam.getScreenshot();
    this.rotateImage(imageSrc, (url) => {
    this.setState({ url});
    console.log(url, imageSrc);
    });
  };

  rotateImage = (imageBase64, cb) => {
            var img = new Image();
            img.src = imageBase64;
            img.onload = () => {
              var canvas = document.createElement("canvas");
              const maxDim = Math.max(img.height, img.width);
              canvas.width = img.height;
              canvas.height = img.width;
              var ctx = canvas.getContext("2d");
              ctx.setTransform(1, 0, 0, 1, maxDim / 2, maxDim / 2);
              ctx.rotate(90 * (Math.PI / 180));
              ctx.drawImage(img, -maxDim / 2, -maxDim / 2);
              cb(canvas.toDataURL("image/jpeg"))
            };
};

  render() {
    const videoConstraints = {
      width: this.dim.width,
      height: this.dim.height,
      facingMode: "user"
    };

    return (

        <Webcam
          audio={false}
          height={this.dim.height}
          ref={this.setRef}
          screenshotFormat="image/jpeg"
          width={this.dim.width}
          videoConstraints={videoConstraints}
        />
        <button onClick={this.capture}>Capture photo</button>

        <canvas id="canvas" style={{display: 'none'}}></canvas>

    );
  }
}

render(<App />, document.getElementById('root'));

A: You should put your base64 image in an img tag in this way:

and then apply the CSS transform that you mentioned the img.

A: You can rotate the image immediately in the preview using the style property:
90:
<Webcam style={{ transformOrigin: '0 0', transform: `translateX(${(480 + 640) / 2}px) rotate(90deg)` }} /> // height + width
180:
<Webcam style={{transform: 'rotate(180deg)'}} />,
270:
<Webcam style={{ transformOrigin: '0 0', transform: `translate(${(480 - 640) / 2}px, ${480}px) rotate(-90deg)` }} />


text:
Q: Lookup Table to Produce Extracted Lists My code below extracts the correct lists, but within each list the output jumbles the order of the elements when the code reads a number like "3" or "3.1" or E (which it sees as Euler's "e") or (A-B0) which it sees as a difference.
I'm looking for the elements in the extracted lists to be in the same order as they appear in the set defined by m and for all elements to be treated as text and not a number or numerical difference. For example, when the Case extracts (say) N6102 it should show N6102, qaw - E (absb) which is the original element order in the m matrix.
ClearAll;
m = {{N6101, WES QWA 3 (zxs)}, {N6102, qaw - E (absb)}, {N6424,
    MIP 3.1 (dssa)}, {N6602, HGS 136.5 (tgf)}, {N6603,
    Mok (iop)}, {N6604, KG NEK (A - B0)}};
index = Association[(#[[2]] -> #[[1]]) & /@
    Table[{i, m[[i, 1]]}, {i, 1, Length[m]}]];
m[[index /@ {N6102, N6604, N6424}]];
Cases[m, {N6102 | N6604 | N6424, __}];
TableForm[%]


text:
Q: send custom parameters to user control ascx I need to use user controls (.ascx) on a page, it's a related post user control based in 2 parameters:
 1. Current post
 2. Relation type

the page needs to have 3 different instances of this control, each having the same Current post parameter, but different relation type (title, author, genre).
The 1st parameter I can get it through url, but what about the second parameter?
I've been googling for a while but i haven't found an answer yet. How can I pass the second parameter so the control can load the information based on these parameters?
I'd rather not to create a control for each parameter, else would be better to build no user control but direct into code :(
Thanks!

A: Create public properties of the user-control like:
public partial class SampleUC : UserControl
{
    public string CurrentPost {get;set;}
    public string RelationType {get;set;}

    //...

    //...
}

Assign those from the page using it either from markup like:
<%@ Register TagPrefix="cc" TagName="SampleUC" Src="SampleUC.ascx" %>
...
...
<cc:SampleUC id="myUC" runat="server" CurrentPost="Sample Post Title" RelationType="Title" />

or from code-behind (of the page using it):
protected void Page_Load(object sender, EventArgs e)
{
    //...

    myUC.CurrentPost = "Sample Post Title";
    myUC.RelationType = "Title" ;

    //...
}


text:
Q: Recursive Function, With Completion Block, That Retrieves Multiple MKDirections - Swift I'm trying to retrieve an array of MKRoute that contains multiple routes all starting at the same place, but each having a different destination.
The problem is that the only way I've been able to come up with to do this is through a recursive function, but I can't find anything on how to use recursive functions with completion blocks. Since loading the routes is done Asynchronously a completion block is needed.
How do I go about getting the following functionality but with completion blocks? The "add to the return" functionality?
func factorial(of num: Int) -> Int {
    if num == 1 {
        return 1
    } else {
        return num * factorial(of:num - 1)
    }
}

Here is my function code
func getDirections(originCoordinate: CLLocationCoordinate2D, destinationCoordinates: [CLLocationCoordinate2D], completion: @escaping(_ routes:[MKRoute]?, _ error: Error?) -> Void) {

    // Origin is the same for each route, what changes is the destination
    // A singular origin coordinate with an array of destination coordinates is passed in
    // The function would in theory be recursive, returning each route from the origin to each of the destinations.

    // Leave function if no more destination coordinates are passed
    if destinationCoordinates.count == 0 {return}

    // Origin
    let originPlacemark = MKPlacemark(coordinate: originCoordinate)
    let originItem = MKMapItem(placemark: originPlacemark)

    // Destination is made from the first element of the passed in destinationCoordinates array.
    let destinationPlacemark = MKPlacemark(coordinate: destinationCoordinates.first!)
    let destinationItem = MKMapItem(placemark: destinationPlacemark)

    // Direction Request setup
    let directionRequest = MKDirections.Request()
    directionRequest.source = originItem
    directionRequest.transportType = .automobile
    directionRequest.destination = destinationItem

    let directions = MKDirections(request: directionRequest)

    // Calculating directions
    // Heart of function
    directions.calculate { (response, err) in

        // Checking if a response is returned
        guard let response = response else {
            completion(nil, err)
            return
        }

        // Response is returned
        let route = response.routes[0]

        let tail = Array.dropFirst(destinationCoordinates)

        // Recursive part that I'm not sure how to properly implement
        completion([route].append(getDirections(originCoordinate, tail)), nil)

    }
    // If no response is retrieved, our guard let statement sends us here
}

A: With a function with a completion handler, in the recursive call, you need to provide a closure to the call and then call the completion handler in that closure.
Here is how you'd do that with factorial:
func factorial(of num: Int, completion: (Int) -> ()) {
    if num == 1 {
        completion(1)
    } else {
        factorial(of: num - 1) { partial in
            completion(num * partial)
        }
    }
}

factorial(of: 8) { result in
    print(result)
}

40320


text:
Q: Merge Successive Push into Single for Code Review If we make some changes after pushing a branch for review and then notice minor mistakes, such as comment typo and make changes to those (or any change) and push. Is it possible to merge these two (or more as per case) iterations into single one for review purpose.
The issue I am trying to address is, when reviewers look at the code and notices two iteration, they maybe tempted to compare the last two, but it should really be both iterations combined and then compared with previous.
Except for preventive measure from Developer, does Git provide any options to merge successive push into one.

A: You can do this fairly easily without git rebase or git merge --squash. In this example below I have squashed the last 2 commits.
If you want to write the new commit message from scratch, this suffices:
git reset --soft HEAD~2 &&
git commit

If you want to start editing the new commit message with a concatenation of the existing commit messages (i.e. similar to what a pick/squash/squash/…/squash git rebase -i instruction list would start you with), then you need to extract those messages and pass them to git commit:
git reset --soft HEAD~2 &&
git commit --edit -m"$(git log --format=%B --reverse HEAD..HEAD@{1})"

Both of those methods squash the last two commits into a single new commit in the same way. The soft reset just re-points HEAD to the last commit that you do not want to squash. Neither the index nor the working tree are touched by the soft reset, leaving the index in the desired state for your new commit (i.e. it already has all the changes from the commits that you are about to "throw away").
In your case, depending on if you want to just to put a review or to upload for review and commit you can choose.


text:
Q: C++ calls Java-NoClassDefFoundError I can debug my java application on eclipse,everything seems OK.But when I used C++ to call the class and catch the exception,I got the error:
 Exception in thread "main" java.lang.NoClassDefFoundError: ParserDemo/ParserNP
Caused by: java.lang.ClassNotFoundException: ParserDemo.ParserNP
  at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

OS:Windows
java version 1.8
How can I fix it?
Thanks :)
edit:
My c++ code:
    int res;
JavaVMInitArgs vm_args;
JavaVMOption options[3];
JavaVM *jvm;
JNIEnv *env;

options[0].optionString = "-Djava.compiler=NONE";
options[1].optionString ="-Djava.class.path=.";
options[2].optionString = "-verbose:NONE";

vm_args.version = JNI_VERSION_1_8;
vm_args.nOptions = 3;
vm_args.options = options;
vm_args.ignoreUnrecognized = JNI_TRUE;

typedef jint (WINAPI *PFunCreateJavaVM)(JavaVM **, void **, void *);
const wchar_t szJvmPath[]=L"C:\\Program Files (x86)\\Java\\jdk1.8.0_112\\jre\\bin\\client\\jvm.dll";

HINSTANCE hInstance = ::LoadLibrary(szJvmPath);

if (hInstance == NULL)
{
    cout<< "LoadLibrary False"<<endl;
    cout<<::GetLastError()<<endl;
    return -2;
}
PFunCreateJavaVM funCreateJavaVM = (PFunCreateJavaVM)::GetProcAddress(hInstance, "JNI_CreateJavaVM");
res = (*funCreateJavaVM)(&jvm, (void**)&env, &vm_args);
if (res < 0)
{
    return -1;
}      jclass cls = env->FindClass("ParserDemo/ParserNP");
   jthrowable exc;
   exc=env->ExceptionOccurred();

if(exc){
    jclass newExcCls;
    env->ExceptionDescribe();
    env->ExceptionClear();}


text:
Q: Php, Spl, SimpleXMLIterator I am trying to understand some guide part, I kind of really lost the logic at  the following explanation:
First The Code:Link
Now the guide:

A problem arises in XML when two documents may have similar names. If
  we had the xml document of animals, and another of animal owners, a
  conflict may arise in the name node. Each of the animals, and owners
  would have a name node and a method is required to distinguish between
  them. The SimpleXMLIterator provides several methods for the
  management of namespaces. These include as listed in the top of the
  this chapter. The script below shows a small change to the xml string
  that has been used and demonstrates the use of namespaces and how to
  utilize them within the SimpleXMLIterator.

This was the part coming before the code is given, Now this is the part given after the code:

In the script above we have declared a namespace in our root as
   Also not the
  addtion to the XML of a second name node. This is prefixed by the
  spec: prefix to identify the namespace and not confuse it with the
  regular animal names. The use of the
  SimpleXMLIterator::registerXPathNamespace() method ensures the
  document namespace prefixing is sane. To get the namespaces the
  SimpleXMLIterator::getDocNamespaces() method is used to get the names
  of all namespaces declared within the document. The
  SimpleXMLIterator::getNamespaces() method could also have been used.
  The SimpleXMLIterator::getDocNamespaces() method only gets those
  namespaces that are actually declared within the document itself.

The problem:
The problem is that i dont think i understand right the author, If some one please can explain this code with another words, I will name weak spots at the code my logic failed to understand:

*

*The Tag (spec:name) // At the XML code.

*$sxi-> registerXPathNamespace('spec', 'http://www.exampe.org/species-title'); // This method and the 2 parameters.

*$result = $sxi->xpath('//spec:name'); // This method with the parameter.

*$sxi->getDocNamespaces('animal') // At the foreach loop.
If can someone please focus on those parts i mentioned and try another words, Thank you all and have a nice day.


text:
Q: Mordell curves with many integral points For $k\in{\mathbb Z},k\neq 0$, denote by $f(k)$ the number of integral points on the Mordell curve $y^2-x^3=k$. According to the data at http://tnt.math.se.tmu.ac.jp/simath/MORDELL , the largest value of $f$ on the interval $[-10000,10000]$ is 32, attained for $k=1025$.
Is it known/conjectured whether $f$ can take arbitrarily high values ?

A: The largest value for $f(k)$ that I know of is an example due to Noam Elkies with
$k = 509142596247656696242225$, where there are (at least) $125$ pairs of solutions (so $f(k)=250$ in your notation). If ranks of elliptic curves over the rationals are absolutely bounded, then so is $f(k)$ (as long as one restricts to $6$th power free values of $k$ to avoid trivial scaling). Nothing is provable at this point, however.


text:
Q: Conjecture : an odd perfect square $n>1$ raised to the $m$-th power is never divisible by the sum of $n$'s divisors This is a conjucture that I created :

Let $\,n = (2k+1)^2  \,\,  $with $k\in \mathbb{N}$ and so $n>1$, and let
$$\,\,A = \sum_{d \in \mathbb{N}; \ d|n} d.$$ Then  $n^m$ is never divisible by $A$ for every $m \in \mathbb{N}$ .

I found a proof for the simpler case with $n$ odd but not a perfect square :

An odd number which is not a square has a even number of divisors all odd . So their sum is even but the number raised to the $m$-th power is odd.

So if the conjucture was true then the theorem would be true for all odd numbers greater than $1$.
However I have no idea how to proceed to prove it in the case of an odd perfect square.
It seems rather linked with perfect numbers.

A: Here is a heuristic argument (that is too long for a comment) for why you would not expect $A$ to divide $n^3$, or any $n^k$. If we consider the argument for $k$ arbitrary, what we are asking is: for odd $n > 1$, is it always the case that $\sigma(n)$ has a prime factor that is not a factor of $n$? As you've pointed out, if $n$ is non-square, then $\sigma(n)$ is even, so the conjecture is true, and this leaves the case when $n$ is a square.
If $n = p_1^{2k_1}p_2^{2k_2} \cdots p_l^{2k_l}$, then
$$
\sigma(n) = \prod_{i = 1}^l \sigma(p_i^{2k_i}) = \prod_{i=1}^l \frac{p_i^{2k_i + 1} - 1}{p_i - 1}.
$$
So, finding a counterexample comes down to the following problem: find a set of odd primes $\{p_1, \ldots, p_l\}$ with exponents $k_1, \ldots, k_l$ such that for each $i$, the number
$$
\frac{p_i^{2k_i + 1} - 1}{p_i - 1}
$$
factorizes into the primes $p_1, \ldots, p_l$. Now this number grows very fast (in $k$), and so it is unlikely to accidentally hit a fairly smooth number. Among the first 100 odd primes $p_i$, with $k_i$ ranging up to 10, there are only a few situations where this number is even $p_i$-smooth -- a necessity for the largest prime dividing $n$. This already shows that $n$ must be quite large, and this is in a sense a very weak argument.


text:
Q: AngularJS $location not changing the path I'm having an issue with changing the URL of the page after a form has been submitted.
Here's the flow of my app:

*

*Routes are set, URL is recognized to some form page.

*Page loads, controller sets variables, directives are fired.

*A special form directive is fired which performs a special form submission using AJAX.

*After the AJAX is performed (Angular doesn't take care of the AJAX) then a callback is fired and the directive calls the $scope.onAfterSubmit function which sets the location.

The problem is that after setting the location the nothing happens. I've tried setting the location param to / as well... Nope. I've also tried not submitting the form. Nothing works.
I've tested to see if the code reaches the onAfterSubmit function (which it does).
My only thought is that somehow the scope of the function is changed (since its called from a directive), but then again how can it call onAfterSubmit if the scope changed?
Here's my code
var Ctrl = function($scope, $location, $http) {
  $http.get('/resources/' + $params.id + '/edit.json').success(function(data) {
    $scope.resource = data;
  });

  $scope.onAfterSubmit = function() {
    $location.path('/').replace();
  };
}
Ctrl.$inject = ['$scope','$location','$http'];

Can someone help me out please?

A: I had to embed my $location.path() statement like this because my digest was still running:
       function routeMe(data) {
            var waitForRender = function () {
                if ($http.pendingRequests.length > 0) {
                    $timeout(waitForRender);
                } else {
                    $location.path(data);
                }
            };
            $timeout(waitForRender);
        }

A: Instead of $location.path(...) to change or refresh the page, I used the service $window. In Angular this service is used as interface to the window object, and the window object contains a property location which enables you to handle operations related to the location or URL stuff.
For example, with window.location you can assign a new page, like this:
$window.location.assign('/');

Or refresh it, like this:
$window.location.reload();

It worked for me. It's a little bit different from you expect but works for the given goal.

A: I had a similar problem some days ago. In my case the problem was that I changed things with a 3rd party library (jQuery to be precise) and in this case even though calling functions and setting variable works Angular doesn't always recognize that there are changes thus it never digests.

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).

Try to use $scope.$apply() right after you have changed the location and called replace() to let Angular know that things have changed.

A: I had this same problem, but my call to $location was ALREADY within a digest. Calling $apply() just gave a $digest already in process error.
This trick worked (and be sure to inject $location into your controller):
$timeout(function(){
   $location...
},1);

Though no idea why this was necessary...

A: In my case, the problem was the optional parameter indicator('?') missing in my template configuration.
For example:
.when('/abc/:id?', {
    templateUrl: 'views/abc.html',
    controller: 'abcControl'
})

$location.path('/abc');

Without the interrogation character the route obviously would not change suppressing the route parameter.

A: If any of you is using the Angular-ui / ui-router, use:$state.go('yourstate') instead of $location. It did the trick for me.

A: This wroks for me(in CoffeeScript)
 $location.path '/url/path'
 $scope.$apply() if (!$scope.$$phase)

A: In my opinion many of the answers here seem a little bit hacky (e.g. $apply() or $timeout), since messing around with $apply() can lead to unwanted errors.
Usually, when the $location doesn't work it means that something was not implemented the angular way.
In this particular question, the problem seems to be in the non-angular AJAX part. I had a similiar problem, where the redirection using $location should take place after a promise resolved. I would like to illustrate the problem on this example.
The old code:
taskService.createTask(data).then(function(code){
            $location.path("task/" + code);
        }, function(error){});

Note: taskService.createTask returns a promise.
$q - the angular way to use promises:
let dataPromises = [taskService.createTask(data)];
        $q.all(dataPromises).then(function(response) {
                let code = response[0];
                $location.path("task/" + code);
            },
            function(error){});

Using $q to resolve the promise solved the redirection problem.
More on the $q service: https://docs.angularjs.org/api/ng/service/$q

A: setTimeout(function() { $location.path("/abc"); },0);

it should solve your problem.


text:
Q: trying to download specific files from ftp recursively and run a command on them i'm trying to download every file with a certain file name from an ftp location, run a command on it then delete it.
ex: download every file that looks like "*_qwerty.jpeg" from "\some\random\ftp\location" then run a command on it. once command is finished, delete it. i need the script to ignore all other.jpeg files too.
i'm trying to do this in windows CMD or Powershell
does anyone have any suggestions?

A: The simplest way is to use Ftp.exe and drive it with a parameter file. Use mget to download files with wildcards. Iterate the files with foreach loop and do stuff. Like so,
<commandfile>
lcd <path-to-local-dir>
open <ftp-site>
<username>
<password>
bin
cd <path-to-remote-dir>
prompt
mget <filename-with-wildcards>
close
bye

Using the command file in Powershell is simple enough:
Ftp -s:<commandfile>
foreach($i in gci <path-to-images>) {
  <do-something> $i
}

You could do the same with batch scripting as well (remember to use double-% in script, single % in command line).
Ftp -s:<commandfile>
for /f "tokens=*" %j in ('dir /b <path-to-images') do <do-something> %j


text:
Q: Run Word 2013 from command line Some of our clients have a problem we can not reproduce here inhouse: Out software uses MS-Word for producing form letter. Since some of our clients use Office 2013, this function won't work anymore.
We tried to reproduce this and detect that on the affected systems Word won't start from command line. Starting via the link in the startmenu works. It also works to start Excel from command line.
Does anyone have an idea what the problem is and how to solve it?

A: Just an FYI similar to Word
for Excel on command line and parameters
c:\> start excel "file path and location"

c:\> start excel "c:\somepath\myfile.xlsx"

worked for us to open a file created in VB 6.0 for Excel 2013
c:\excel does not work on command line for us either

I think WinWord will work with a file parameter too.
c:\> start winword "c:\somepath\myfile.doc"

A: We found the solution:
Our software still uses old 8.3 filenames - also long filenames are replaced with short ones. And it seems that Office 2013 don't like them anymore.

A: You can try using start.exe from the command line:
c:> start winword

I'm wasn't familiar with it but tried it and it worked for me on Windows 7, with Office 2007.  Found this site (windows-commandline.com).  They claim it works for all versions of Word.

A: This is the executable location and file in Office 2013, as listed in the shortcut.  You cannot start it by using winword either, in Win 8 32 bit.
"C:\Program Files\Microsoft Office 15\root\office15\winword.exe"

A: Try using the run prompt by pressing the windowsbutton+R. The run prompt will open and then Type winword to open MS Word and excel to open MS Excel.


text:
Q: Can't explicitly instantiate templated function into templated class I don't understand why the following code isn't working, why can't I explicitly instantiate the templated function? If I remove that < int > I get a "no matching function call"
#include <iostream>
using namespace std;

template <typename T>
class Xclass
{
public:
  template <typename Y>
  void xfunc()
  {
    cout << "Hello";
  }
};

template<typename T2>
class Z
{
public:
  void x2()
  {
    Xclass<T2> obj;
    obj.xfunc<int>();
  }
};

int main() {

    Z<int> obj;

    obj.x2();

    return 0;
}

The error is:
prog.cpp: In member function 'void Z<T2>::x2()':
prog.cpp:24:15: error: expected primary-expression before 'int'
     obj.xfunc<int>();
               ^
prog.cpp:24:15: error: expected ';' before 'int'

A: Since the type of obj is a dependent type, you must use the template keyword to tell the compiler it is a template:
Xclass<T2> obj;
obj.template xfunc<int>();

See Where and why do I have to put the "template" and "typename" keywords? for a thorough explanation of when you have to use template.


text:
Q: Java.lang.NumberFormatException when trying to read in a file, so I can use the data with my objects I keep getting this error when I'm trying to read in a file and add the data to my objects. Can someone please help me? Here is the error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "N64"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:668)
at java.base/java.lang.Integer.parseInt(Integer.java:786)
at FinalProjectTests.main(FinalProjectTests.java:34)

Here are my objects. Also at the bottom I have setters and getters below the code as well as a toString() method generated by Eclipse:

Here is my code that is trying to read in a file and add the data to my objects:
public class FinalProjectTests {

    //create an arraylist so the objects can be used through them
    public static ArrayList<FinalProjectRecord> record = new ArrayList<FinalProjectRecord>();

    public static void main(String[] args) {
        Scanner input = null;
        try {
            input = new Scanner(new File("Video Games Sales.csv"));
        } catch (FileNotFoundException e) {
            System.out.println("file not found");
            e.printStackTrace();
        }//end try

        //skips the title columns in our data file
        input.nextLine();
        while(input.hasNext()) {
            String [] columns = input.nextLine().split(",");
            record.add(new FinalProjectRecord(Integer.parseInt(columns[0]),
                                              columns[1],
                                              columns[2],
                                              Integer.parseInt(columns[3]),
                                              columns[4],
                                              columns[5],
                                              Double.parseDouble(columns[6]),
                                              Double.parseDouble(columns[7]),
                                              Double.parseDouble(columns[8]),
                                              Double.parseDouble(columns[9]),
                                              Double.parseDouble(columns[10]),
                                              Double.parseDouble(columns[11])));
        }//end while
        for(FinalProjectRecord r: record)
            System.out.println(r);
    }//end main
}//end class

Here is a snippet of the data I am trying to read in:

Edit: I got the data from data.world.

A: Exception in thread "main" java.lang.NumberFormatException: For input string: "N64"
Exception is thrown because of "N64".(Integer.ParseInt or Double.ParseDouble in your code)  The image you have posted as data, appears its is from EXCEL Sheet, if so, please search for "N64" and check whether it is correct in that column?

A: You should really use a library for parsing csv files, this is an example using commons-csv
Here is my hastily made csv file.
'object','value'
'red', 255
'blue', 100
'green, yellow', 50

This simple program will parse it.
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVFormat;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;

public class CsvReading{

    public static void main(String[] args) throws Exception{
        CSVParser parsing = CSVParser.parse(
                                  Paths.get("junk.csv"),
                                  StandardCharsets.UTF_8,
                                  CSVFormat.DEFAULT
        );
        System.out.println(parsing.getHeaderNames());
        System.out.println(parsing.getRecords());
    }

}

That will give an output with no headers, and 4 records.

[]

[CSVRecord [comment='null', recordNumber=1, values=['object', 'value']], CSVRecord [comment='null', recordNumber=2, values=['red',  255]], CSVRecord [comment='null', recordNumber=3, values=['blue',  100]], CSVRecord [comment='null', recordNumber=4, values=['green,  yellow',  50]]]

You can see the last record has two elements, 'green, yellow' and 50. If we were to use String.split(",") then yellow and green would be incorrectly split. This library is very easy to use, I just downloaded the jar file and run the program with.
java -cp commons-csv-1.9.0.jar CsvReading.java


text:
Q: How do I treat $_SERVER? Is it safety? I can get the global ip of a client like below, but is it safety?
<?php
echo $_SERVER['REMOTE_ADDR'];

I saw some article that we have to sanitize $_GET, $_POST or $_COOKIE, but how do I treat about $_SERVER?

A: $_GET, $_POST and $_COOKIE come from user input, so they should be treated with caution.
While $_SERVER is generated by PHP interpreter, it also contains lots of user-provided data, such as argv, QUERY_STRING, PHP_SELF, all headers (called HTTP_header_name) and so on. Treat those as unsafe user input as well.
Never assume that it will only be a browser making a request to your server: attackers can craft special requests very easily.


text:
Q: passing variable from vbscript to batch file i am using vbscript to call a batch file. my script looks like:
dim shell
set shell=createobject("wscript.shell")
shell.run "a.bat"
set shell=nothing

my batch file is simple and looks like:
D:
cd D:\d
winzip32.exe -min -a D:\a

i want to pass a variable from a script to the batch file. lets say the destination folder.
how do i do that?
any help is very much appreciated.

A: I think that you can just pass variables to the batch file.
You can call it like:
shell.run "a.bat var1 var2"

And in your batch file, you can refer to them as:
%1 for "var1"
%2 for "var2"

And you can do this from %1 to %9.


text:
Q: SPList Replacelink method I am trying to find and replace url links in sharepoint lists. The ReplaceLink method(SPList class) does the job for straight forward urls like "www.google.com/test" but truncates the url parameter for links like "www.google.com?search=badReplace" .
  Is there a workaround for this method ? I found SPLink has a url and urlparameter properties but they don't have an associated setter method. Any Suggestions,thoughts would be helpful


text:
Q: Uploading to Discord with discord.py from Dropbox I made a Dropbox bot that can access all folders on the account and added the token to my discord bot's code. Access to files.content.read and files.metadata.read are enabled.
Some files such as mp3 files don't have previews when you only post a URL so I want to actually upload the files in a Dropbox folder using the bot.
I read the File Properties and Files section of the Dropbox API documentation but I couldn't find out how to return a file-like object. For now, I wanna do image and audio files.
I tried this:
@client.command()
async def test(ctx):
    print("Test was called.")

    file_name = "stonks.jpg"
    my_file = dropbox.files('/Reaction Pics/' + file_name)
    await ctx.channel.send(file=my_file)

But I get the following error: (I have checked that my drop box API has access to that file.)
    my_file = dropbox.files('/Reaction Pics/' + file_name)
TypeError: 'module' object is not callable

A: dropbox.files is a module, not a method for interacting with files on Dropbox.
Instead, to get the file content from Dropbox (so you can then upload it elsewhere), you should use the files_download method. There's an example of using that here.
(Alternatively, you can use files_download_to_file to save it to disk first. Example here.)


text:
Q: What is the best way to play music through speakers I have these speakers I recovered from an old iPod dock.

I want to hook these up to a big remote control truck I have but I have never worked with playing music. What is the easiest way to get music to play through them? I was looking at this breakout board but not sure if it's as easy as simply connecting the speakers to the board through their ground and vcc wires or what.

A: You need a lot more than just that CODEC chip to generate audio. You need something to control it, and something to amplify the sound to drive the speakers.
That means some microcontroller based system (maybe an Arduino or something like that) and a power amplifier board.  Oh, and of course enough battery power to run it all, and enough programming and electronics experience to get the whole lot working together.
Better off using a cheap MP3 player and a small power amplifier - maybe the one you threw away from the iPod dock?


text:
Q: How can I expand a div to compensate for removing the bordering div's margin? I'm using Bootstrap's responsive grid layout. I need to adjust one spot on the page so that there's no margin between two columns; the left column has a bottom border that I need to bring right up to the left border of the right column.
How can I expand a div to compensate for removing the right-bordering div's left margin?
Things I've been able to do:

*

*I'm able to dynamically set the height of the left div to drop the bottom border to where I want it: $('#indented_block .border-bottom').height( $('#indented_block').height()-3 );

*I'm able to determine the original width of the left div: $('#indented_block .border-bottom').width()

*I'm able to determine the left-margin of the right div: $('#indented_block .border-side').css('margin-left');

*I'm able to set the left-margin of the right div: $('#indented_block .border-side').css('margin-left',0);
I'm not able to use the jQuery .width() method to add the original width to the left-margin: $('#indented_block .border-bottom').width( $('#indented_block .border-bottom').width()+$('#indented_block .border-side').css('margin-left'));
Rather, I'm not able to accurately add those values together (for some reason the above line sets the width to be about the width of the screen).
I've created a JSFiddle with all the relevant HTML, JS and CSS.

A: In this case, the difference between $('#indented_block .border-side')'s .outerWidth(true) and .outerWidth(true) is the left-margin in a unit that can be used by .width().
So I fixed it using this jQuery:
var margin_gap=Math.floor( $('#indented_text').outerWidth(true)-$('#indented_text').outerWidth() );
$('#indented_block .border-bottom').height( $('#indented_block').height()-3 ).width( $('#indented_block .border-bottom').width()+margin_gap );
$('#indented_block .border-side').css('margin-left',0);

See this working example.


text:
Q: ASCII Grid to Raster with DX/DY Cell Values I have an ASCII grid file that has rectangular cells. The ESRI documentation does not specify how to convert from .asc to raster with a DX/DY value such that:
NCOLS 1900
NROWS 1100
XLLCORNER 115.834717
YLLCORNER 31.638744
XCELLSIZE ...
YCELLSIZE ...
NODATA_VALUE 0

I do not want to read into a NumPy array. So how would one do this, be it manually, in ArcGIS?

A: I suggest three steps workflow; (1) Edit header, (2) Import the file, and (3) Georeference it to its proper extent.
(1) Edit the header (XLLCORNER, YLLCORNER, CELLSIZE) to a dummy extent
NCOLS 1900
NROWS 1100
XLLCORNER 0.0
YLLCORNER 0.0
CELLSIZE 1
NODATA_VALUE 0

(2) Read this file by Ascii to Raster
(3) Georeference it by Warp
Source
0 0
1900 0
0 1100
1900 1100

Target
115.834717 31.638744
115.834717 + XCELLSIZE * 1900 31.638744
115.834717 31.638744 + YCELLSIZE * 1100
115.834717 + XCELLSIZE * 1900 31.638744 + YCELLSIZE * 1100

Above calculation comes from:
xLR= XLLCORNER + XCELLSIZE * NCOLS
yUL= YLLCORNER + YCELLSIZE * NROWS


text:
Q: How does (?) differs from (?:...) in Ruby regular expressions (Regex)? How does below mentioned differ from each other in Ruby regular expressions (Regex)?

*

*(?imx) and (?-imx)

*(?imx:..) and (?-imx:..)
How does (?ix-ix: ) work in Regex? I found this documentation:

*

*(?imx) Toggles i, m, or x options on.

*(?-imx) Toggles i, m, or x options off.

*(?imx:..) Toggles i, m, or x options on within parentheses.

*(?-imx:..) Toggles i, m, or x options off within parentheses.

*(?ix-ix: ) Turns on (or off) i and x options within this noncapturing group.

But within the code how they will going to be used, couldn't understand. So any help with tiny codes to demonstrate the differences as mentioned above?

A: (?x) applies through the end of the current set of parentheses, or the entire regex if it's not inside parentheses.  (?x:...) applies to whatever's inside the parentheses.
So, really, this:
(?x: ... )

is just an easier way to write this:
(?:(?x) ... )

And it works like this:
/red (?i) blue ( ( (?x) ( (?-i) green ) yellow ) purple )/
     ^^^^^^^^^^^^^^^^^^^^^             ^^^^^^^^^^^^^^^^^^^
     'i' is turned on here...          and here
                          ^^^^^^^^^^^^^
                          but 'i' is turned off here
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                    'x' is turned on here

(?s-m:...) is another shortcut: it turns s on, and m off.  You could also write it as (?:(?s)(?-m)...), but that's pretty hard to read.
(?ix-ix:...) is a pretty bad example, since it doesn't make any sense to turn i and x both on and off.

Examples:
This will match:
/one (?i)TWO THREE/.match 'one two three'

This will not, because the i flag only applies within the ():
/one ((?i)TWO) THREE/.match 'one two three'

This also won't, and is the same as the above, except that the parentheses won't capture:
/one (?i:TWO) THREE/.match 'one two three'

But these will match:
/one (?i:TWO THREE)/.match 'one two three'
/one (?i:TWO) three/.match 'one two three'


text:
Q: Android HttpURLConnection connection refused after few minutes in service when ui is not visible I am working on small chat application which is working fine when the app is visible to user. A service class which get and send data using post every 5 second when aap is visible to user and works fine. But when app.is closed and service works in background for few minutes fine. After few minutes i.e. apprx 3 minutes it get conmection refused error and never fetch data from server until.the app is again visible to user. I cant find any solution. please help.me
I uses HttpURLConnection for posting data, and a Thread and timer for regular posting.

A: Android suspend applications when they get into background, to make resources available for the foreground application. If you need to sync your data on the background you should use a Background Service or SyncAdapter.
Take a look at Best Practices for Background Jobs and Transferring Data Using Sync Adapters

A: Some tips:

*

*Do not use manual timed HTTP requests for chats messages, its a very bad practice,

*But, if you want to keep this, use some new http request library like "Volley" or "OkHttp" (this is my favorite),

*If you want more professional and highly "best practice" stuff, use the Google's Firebase Cloud Messaging for chats apps, its use native google services for send messages to others apps, highly recommended.

Connection Refused can be your client (service) sending wrong data/values, wrong URL, wrong ports and wrong query, please post a piece of your code.


text:
Q: How can I specify a 'formula' while building widgets: flutter I have something like this at multiple places (ignore the actual example). When I make changes to these formulae, I need to make the changes in multiple files.
SizedBox(
        width: parentPortHidden ? 0.01 : DevicePreferences.getViewPortWidth(context, Constants.defaultDeviceWidth) - 0.01,
        height: DevicePreferences.getDeviceHeight(context, Constants.getActualDeviceHeight) -
            DevicePreferences.getDeviceHeight(context, Constants.appBarRelativeHeight, Constants.appBarMinAbsHeight),
        child: CustomScrollView(

the values for width and height are computed with the same formula (and these are not constants)
Perhaps this question is the same as this one on the equivalent of #define in Flutter, but I am not sure if there is another solution, since there is none for #define...
If there is no code solution, what will be the best 'system' to use to ensure that changes are made everywhere these formulae need to change?

A: You can create simple function, that will implement your formula, like this:
double f(bool parentPortHidden, double ViewPortWidth)
{
  return parentPortHidden ? 0.01 : ViewPortWidth - 0.01;
}


text:
Q: How to say in a compact way: an increase of something is due to decrease in something else I am examining temporal trends in the sale numbers of apples, pears and bananas. And I found a significant 5 percentage point increase for apples and a significant 5 percentage point decrease for bananas. The sales of pears remained constant during the observed time period.
What is a better and more compact way for saying the following:

There was an increase in the sales of apples, simultaneously decreasing the number of bananas.

What is a good word for saying that apples increase can be attributed to the decrease of bananas?

A: EDIT:
This answer doesn't do justice to the demand of the question and I suggest that OP wait for the definitive answer. In fact, as has been brought to my notice by some enlightened members here, this answer is technically wrong.
I think inversely proportional is the term you're looking for.

[Pear sales being constant], apples sales were inversely proportional to banana sales— [the former registering a 5% increase, and the latter a 5% decrease.]

You could do away with the bracketed elements depending on what you wish to keep and what you wish to omit.
Thanks to @Jim for suggesting that I reconsider fine-tuning my answer to meet precisely the demand of the question.

A: The briefest statement may be :
Apple and banana sales were negatively correlated.

Correlate = to establish a mutual or reciprocal relation between
Merriam Webster

In positive correlation, both increase or decrease together; in negative correlation, one increases as the other decreases.

negative correlation means that there is an inverse relationship between two variables - when one variable decreases, the other increases.
Your dictionary

A: Simpler is always better in this kind of writing. You don't want to waste your reader's mental energy in decoding your language when it should be applied to grasping your argument (whatever it happens to be).
Sales that period: Apples up.  Bananas down.  Five percent each way. Pears went sideways.


text:
Q: how to disable intellij services tool window Well.. this is silly, but i've been struggling with it for hours.
I switched by mistake to services tool window following Intellij pop-up suggestion. Now I want to get back to the normal debug mode, but I can't find a way.
No matter what i try, when i hit the debug button, it's processing everything in the "Services" tool window, and "Debug" tool window is disabled saying "nothing to show".
Intellij version 2021.1
Please advise!
Thank you

A: Just remove run configuration type from services tool window:


text:
Q: NodeJS Listener for webhooks returns empty body I have been on this for about 2 days and ready to pull my hair out.
I have a system that fires off simple Webhooks that I need to capture and parse.  I have created a very simple Nodejs listener and am running Ngrok to create the public address. I am getting a request but the body is empty no matter what I do. Irrespective of content-type or app.use(bodyParser.urlencoded()).
The body still returns as {}
'use strict'

const express = require('express')
const bodyParser = require('body-parser')

// Create a new instance of express
const app = express()

// Tell express to use the body-parser middleware and to not parse extended bodies
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

// Route that receives a POST request to /sms
app.post('/', function (req, res) {
    console.log(req);
  const body = req.body
  console.log("body")
  console.log(body);
  res.set('Content-Type', 'text/plain')
  res.send(`You sent: ${body} to Express`)
})

// Tell our app to listen on port 4545
app.listen(4545, function (err) {
  if (err) {
    throw err
  }

  console.log('Server started on port 4545')
})

However if I set up the address as https://webhook.site or https://pipedream.com then the body is indeed published. I have tried combinations of content-type, urlencode, even thinking it was gzip or something and even deploying on Azure VM and others. Nothing.
But the moment I set the address as webhooks or pipedream the data shows without issue.
After some comments I wanted to add the result (partial result) of the console.log(req):
complete: false,
    headers: {
      connection: 'Keep-Alive',
      'accept-encoding': 'gzip',
      host: 'localhost:4646',
      'max-forwards': '10',
      'user-agent': 'Go-http-client/2.0',
      'content-length': '339'
    },
    rawHeaders: [
      'Connection',
      'Keep-Alive',
      'Accept-Encoding',
      'gzip',
      'Host',
      'localhost:4646',
      'Max-Forwards',
      '10',
      'User-Agent',
      'Go-http-client/2.0',
      'X-Original-URL',
      '/',
      'Content-Length',
      '339'
    ],
    trailers: {},
    rawTrailers: [],
    aborted: false,
    upgrade: false,
    url: '/',
    method: 'POST',
    statusCode: null,
    statusMessage: null,
    client: Socket {
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: null,
      _readableState: [ReadableState],
      readable: true,
      _events: [Object: null prototype],
      _eventsCount: 8,
      _maxListeners: undefined,
      _writableState: [WritableState],
      writable: true,
      allowHalfOpen: true,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: [Server],
      _server: [Server],
      timeout: 120000,
      parser: [HTTPParser],
      on: [Function: socketListenerWrap],
      addListener: [Function: socketListenerWrap],
      prependListener: [Function: socketListenerWrap],
      _paused: false,
      _httpMessage: [Circular],
      [Symbol(asyncId)]: 115,
      [Symbol(kHandle)]: [TCP],
      [Symbol(kSetNoDelay)]: false,
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: Timeout {
        _idleTimeout: 120000,
        _idlePrev: [TimersList],
        _idleNext: [Timeout],
        _idleStart: 6602,
        _onTimeout: [Function: bound ],
        _timerArgs: undefined,
        _repeat: null,
        _destroyed: false,
        [Symbol(refed)]: false,
        [Symbol(asyncId)]: 116,
        [Symbol(triggerId)]: 115
      },
      [Symbol(kBuffer)]: null,
      [Symbol(kBufferCb)]: null,
      [Symbol(kBufferGen)]: null,
      [Symbol(kCapture)]: false,
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0
    },
    _consuming: false,
    _dumped: false,
    next: [Function: next],
    baseUrl: '',
    originalUrl: '/',
    _parsedUrl: Url {
      protocol: null,
      slashes: null,
      auth: null,
      host: null,
      port: null,
      hostname: null,
      hash: null,
      search: null,
      query: null,
      pathname: '/',
      path: '/',
      href: '/',
      _raw: '/'
    },
    params: {},
    query: {},
    res: [Circular],
    body: {},
    route: Route { path: '/', stack: [Array], methods: [Object] },
    [Symbol(kCapture)]: false
  },
  locals: [Object: null prototype] {},
  [Symbol(kCapture)]: false,
  [Symbol(kNeedDrain)]: false,
  [Symbol(corked)]: 0,
  [Symbol(kOutHeaders)]: [Object: null prototype] {
    'x-powered-by': [ 'X-Powered-By', 'Express' ]
  }
}

You can see that the body is empty when console.log(req)
Can anyone send me on the right path to sort this out?
Much appreciated.

A: So for anyone else who struggles with something similar, this is what I did to resolve:
I had to inject a content-type into the headers and then viola the body started to appear:
var customParser = bodyParser.json({type: function(req) {
    if (req.headers['content-type'] === ""){
        return req.headers['content-type'] = 'application/json';
    }
    else if (typeof req.headers['content-type'] === 'undefined'){
        return req.headers['content-type'] = 'application/json';
    }else{
        return req.headers['content-type'] = 'application/json';
    }
}});

app.use(bodyParser.json({
  limit: '50mb',
  extended: true
})); // support encoded bodies

app.use(bodyParser.urlencoded({
  limit: '50mb',
  extended: true
})); // support encoded bodies

app.post("/hook", customParser, (req, res) => {
    //console.log(req);
    //const fs = require('fs');
    console.log("Events req.body", req.body) // Call your action on the request here

    res.status(200).end()
  })

That did it for me.
Thanks

A: You can get body data in req.body
Include body-parser middleware which parses the body and sets req.body property.
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))

// Route that receives a POST request to /sms
app.post('/', function (req, res) {
  console.log(req);
  const body = req.body
  console.log("body")
  console.log(body);
  res.set('Content-Type', 'text/plain')
  res.send(`You sent: ${body} to Express`)
})


text:
Q: JQuery Image load fails on MobiOne iPhone simulator I dynamically update an image on a JQTouch site using the following code:
  $('#sv_map')
            .one('load', function() {
                $(this).fadeIn();
            })
            .attr('src', imgURL);

Got the basics of this from here. sv_map is an image, and imgURL points to a valid, existing JPG file.
This code works as expected on all major browsers (Chrome, Safari, Firefox, IE) as well as on actual devices (several iPhones and iPods).
I don't want to conclude that the simulator has a bug (it seems like such a trivial issue). What additional code is needed to ensure that the image file gets loaded? Has anyone had a similar experience with MobiOne?

A: Not all browsers fire the load event correctly (especially when loading from cache), so you'll need to do it manually by checking .complete on the image, like this:
  $('#sv_map').one('load', function() {
               $(this).fadeIn();
            }).attr('src', imgURL)
              .each(function() {
               if(this.complete) $(this).load();
            });


text:
Q: JavaScript: A countdown timer that uses only TIME Apologies, I know this question has been asked severally but none of the questions/answers meet my exact need. I have tried writing, Googling and even Stackoverflow.
My use-case is to start a timer using JavaScript (as gotten from the database using PHP) for a test to be taken immediately the student clicks on "Start Test", when the time is up, submission is made and result is collated unless the student submits before time.
A teacher enters the duration for the test in the format (also saved to DB as) "2:30:45" for 2hrs 30mins 45secs. I need this to countdown until its "0:00:00" before automatic submission is made.
Thanks a lot.

A: I'm not sure what level of trust you are giving your students, but the best idea to keep track of time spent on something like this is server side, and probably best to starting session for the duration of the test.
I would use a javascript function that asynchronously updates the time remaining. Also I would write a javascript that async updates the students submissions so less likely answers are lost (plus you can get more interesting statistics that way like how long students spend on answer)


text:
Q: Uncaught SyntaxError: Cannot use import statement outside a module - Chrome Extension Manifest 3.00 I'm converting my manifest v2 Chrome extension to v3, and getting the error below when I imported a function from another javascript file, to background.js file;
Uncaught SyntaxError: Cannot use import statement outside a module

background.js
import test_123 from './test.js';

test.js
export function test_123()
{
  alert('test ok');
}

manifest.js
  "background":{
    "service_worker": "background.js"
},

I have too many functions in the test.js file, so it's great if there is any way to import the whole test.js at once using something like require('./test.js')
Can anyone please point me in the right direction to identify the issue and solve it?


text:
Q: Debian Linux - run script/app on boot I have a .jar file which I run like this:
java -jar server.jar 4242

So I have a script java-server.sh to launch it:
#!/bin/sh
java -jar server.jar 4242 &

server.jar should start working on system boot, so I tried:

*

*Adding @reboot /home/user/java-server.sh to crontab -e

*Adding bash java-server.sh || exit 1 to rc.local

*Adding java-server.sh to /etc/init.d

None of which work. If I log into the system and launch my script I works like clockwork until I log out. What is the problem here?

A: You should call your script will full path, for example put in /etc/rc.local:
 bash /usr/local/bin/java-server.sh > /tmp/java-server.log 2>&1

if your script is in /usr/local/bin, of course... This will also create a log file to debug other potential problems. (Note that in production you should never create such log files in /tmp for security reasons, but in /var/log with proper permission, rettention and log rotating, but this is simplified for purposes of answer)


text:
Q: pycuda seems nondeterministic I've got a strange problem with cuda,
In the below snippet,
#include <stdio.h>

#define OUTPUT_SIZE         26

typedef $PRECISION REAL;

extern "C"
{
    __global__ void test_coeff ( REAL* results )
    {
        int id      = blockDim.x * blockIdx.x + threadIdx.x;

        int out_index  = OUTPUT_SIZE * id;
        for (int i=0; i<OUTPUT_SIZE; i++)
        {
            results[out_index+i]=id;
            printf("q");
        }
    }
}

When I compile and run the code (via pycuda), it works as expected. When I remove the printf, then the results are weird - most of the array is populated correctly, but some of it seems completely random.
here's the full python code:
import numpy as np
import string

#pycuda stuff
import pycuda.driver as drv
import pycuda.autoinit

from pycuda.compiler import SourceModule

class MC:

    cudacodetemplate = """
    #include <stdio.h>

    #define OUTPUT_SIZE         26

    typedef $PRECISION REAL;

    extern "C"
    {
        __global__ void test_coeff ( REAL* results )
        {
            int id      = blockDim.x * blockIdx.x + threadIdx.x;

            int out_index  = OUTPUT_SIZE * id;
            for (int i=0; i<OUTPUT_SIZE; i++)
            {
                results[out_index+i]=id;
                //printf("q");
            }
        }
    }
    """

    def __init__(self, size, prec = np.float32):
        #800 meg should be enough . . .
        drv.limit.MALLOC_HEAP_SIZE = 1024*1024*800

        self.size       = size
        self.prec       = prec
        template        = string.Template(MC.cudacodetemplate)
        self.cudacode   = template.substitute( PRECISION = 'float' if prec==np.float32 else 'double')

        #self.module     = pycuda.compiler.SourceModule(self.cudacode, no_extern_c=True, options=['--ptxas-options=-v'])
        self.module     = SourceModule(self.cudacode, no_extern_c=True)

    def test(self, out_size):
        #try to precalc the co-efficients for just the elements of the vector that changes
        test  = np.zeros( ( 128, out_size*(2**self.size) ), dtype=self.prec )
        test2 = np.zeros( ( 128, out_size*(2**self.size) ), dtype=self.prec )

        test_coeff =  self.module.get_function ('test_coeff')
        test_coeff( drv.Out(test), block=(2**self.size,1,1), grid=( 128, 1 ) )
        test_coeff( drv.Out(test2), block=(2**self.size,1,1), grid=( 128, 1 ) )
        error = (test-test2)
        return error

if __name__ == '__main__':
    p1  = MC ( 5, np.float64 )
    err = p1.test(26)
    print err.max()
    print err.min()

Basically, with the printf in the kernel, the err is 0 - without it it prints some random error (on my machine around 2452 (for the max), and -2583 (for the min))
I have no idea why.
I've running cuda 4.2 on pycuda 2012.2 (windows 7 64bit) with a geforce 570.
Thanks.

A: This is most likely due to compiler optimization.  You are setting a block of memory OUTPUT_SIZE in length to the loop-constant value of id.  In my experience the compiler will optimize that to a memcpy or whathaveyou unless there is something else going on in the loop -- ie your print statement.  Furthermore, if you do not utilize that block of memory the compiler may optimize the entire loop away.  Try fiddling with your optimization levels and see if you have different results.


text:
Q: RVM system-wide install script url broken -- what is replacement? My RVM system-wide installation scripts are broken, both in the form of Linode StackScripts and Chef-solo Recipes.
Per the instructions on the RVM website, my scripts execute the following commands as root to install RVM on a system-wide basis:
echo "Installing RVM system-wide" >> $logfile
bash < <( curl -L http://bit.ly/rvm-install-system-wide )
cat >> /etc/profile <<'EOF'
# Load RVM if it is installed,
#  first try to load  user install
#  then try to load root install, if user install is not there.
if [ -s "$HOME/.rvm/scripts/rvm" ] ; then
  . "$HOME/.rvm/scripts/rvm"
elif [ -s "/usr/local/rvm/scripts/rvm" ] ; then
  . "/usr/local/rvm/scripts/rvm"
fi
EOF

source /etc/profile

The key piece above is the url http://bit.ly/rvm-install-system-wide. As of today, 3/24/2011, this url no longer in service. It results in a GitHub 404 error.
The following url on the RVM website used to contain the instructions for the system-wide install: http://rvm.beginrescueend.com/deployment/system-wide/. However, that url now redirects to the RVM homepage.
In the interests of getting RVM system-wide installation scripts to work again, what are the new instructions?

A: Just received the following answer from the lead developer, wayneeseguin, on #rvm:

[12:53]  "the author" merged it into the ain installer
  [12:53]  so you should be doing
    bash < <( curl http://rvm.beginrescueend.com/releases/rvm-install-head )
    # http://rvm.beginrescueend.com/rvm/install/
  [12:53]  the code has just changed and the documentation hasn't caught up
  [12:53]  for both root and user installs

It is true that RVM 1.5.1 will successfully install into /usr/local/bin just by installing as root. However, for some reason, all the existing Chef and Puppet provisioning scripts that are in use today do not appear to survive this version bump. This is unfortunate, as Wayne E. Seguin has made clear that RVM below version 1.5.0 will not be supported.
That said, we need our systems to work today. In order to continue to use RVM 1.3.0, which the existing scripts support, you need to replace the following line:
bash < <( curl -L http://bit.ly/rvm-install-system-wide )

With the following line (found by phlipper):
bash -c "bash <( curl -L https://github.com/wayneeseguin/rvm/raw/1.3.0/contrib/install-system-wide ) --version '1.3.0'"

A: Here is my fix to install the last working version before he major change:
bash <( curl -L https://github.com/wayneeseguin/rvm/raw/1.3.0/contrib/install-system-wide ) --version '1.3.0'

This is working for me now in production. Good luck!
UPDATE
Also, if you are using the chef cookbook from https://github.com/fnichol/chef-rvm or something similar, you can use the following options:
:rvm => {
  :system_installer_url => "https://github.com/wayneeseguin/rvm/raw/1.3.0/contrib/install-system-wide",
  :version => "1.3.0"
}


text:
Q: Eliminate the values in the rows corresponding to a column which are zero in MATLAB I have a matrix of data which I am trying to analyse. I have a data and I applied some processing part and I managed to get some information below a certain level as in trying to apply threshold to it. So after I applied threshold the data goes to 0 point. So I was wondering if there was a way to just eliminate the points without it leaving 0 in between. This is what the figure looks like with the zeros in that

I was trying to plot it without the gap the X Axis is time, y axis is amplitude. So will that be possible to just plot the events which are in blue and the time together?
%Find time
N = size(prcdata(:,1),1);
t=T*(0:N-1)';
figure;
plot(t,U);
t1=t(1:length(t)/5);
X=(length(prcdata(:,4))/5);
a = U(1 : X);
threshold=3.063;
A=a>threshold;
plot_vals=a.*A;
figure;
plot(t2,plot_vals1); %gives the plot which i added with this

I also tried this code to club the events without the zeros but all it gives me is a straight line plot at 0.
%% Eliminate the rows and colomns which are zero
    B1=plot_vals1(plot_vals1 <= 0, :);
    figure;
    plot(B1);

Also is there any way to take the scatter of the figure above? Will using scatter(t2,plot_vals1); work?

A: If you want to only display those points that are above your threshold, you can use a logical index and set the value of the unwanted points to NaN:
threshold = 3.063;
index = (a <= threshold);
a(index) = NaN;
figure;
plot(t1, a);

Data points that are NaN simply won't be displayed, leaving a break in your plot. Here's a simple example that plots the positive points of a sine wave in red:
t = linspace(0, 4*pi, 100);
y = sin(t);
plot(t, y)
hold on;
index = (y < 0);
y(index) = nan;
plot(t, y, 'r', 'LineWidth', 2);

A:
So will that be possible to just plot the events which are in blue and the time together?

If the time of occurrence is not important to you, then the following will work:
After A=a>threshold;, change your code to
plot_vals=a(A);
figure;
plot(plot_vals);

If the time of occurrence is important, then you can try setting the x-ticks and labels programmatically using the 'XTick' and 'XTickLabel' properties of your plot.
Get the corresponding time of interest like so:
t2=t1(A);

This should give you an idea of how to go about it using 5 equally spaced ticks:
xTickLabels = t2(floor(linspace(1,t2(end),5)));
xTicks = floor(linspace(1,numel(plot_vals),5));
plot(plot_vals);
set(gca,'XTick',xTicks,'XTickLabel',xTickLabels); % gca gets current axis handle

It is a bit of an art to determine which time points of interest you want, since your blue segments do not occur in equal sized clumps.


text:
Q: Deployment of Puma with Nginx and Capistrano I am running into some issues when I'm trying to deploy my Rails app with Puma and Nginx.
I have a regular Capistrano setup, that has the puma/capistrano included.
When running cap deploy:cold it works perfectly fine the first time.
After this initial deploy, I'm trying to deploy my changes via cap deploy, which results in
Bad response from server: 500

After I try to use cap deploy:stop I'm getting following error:
undefined method `split' for nil:NilClass

When running cap deploy:restart it results in:
no such file or directory - "/home/deployer/apps/teachmeo/shared/sockets/pumactl.sock"

So, the only way for me after all this to redeploy is cleaning up the /shared/sockets/ dir and  using cap deploy:cold again
What could be going wrong here?

A: This is a known issue which as of today has been patched - although I don't believe a new version of puma containing the patch has been released yet.
If you're using Bundler, you could specifically install the patched version with:
gem 'puma', :github => "puma/puma", :ref => "3d1eefbd7e9c72a5173fe017f1b4fe41204beba2"

A: See this: Server deployments for Rails + Puma + Nginx + Capistrano 3
It's a guide that I compiled myself that covers Server Deployments in detail and includes complete nginx and puma configs, maybe comparing your configuration file with them would help you trace the problem better.


text:
Q: Sonarqube 6.0: How to override the issue description when they're created from a sensor plugin? I'm creating issues from a sensor whit the folowing code:
NewIssue newIssue = context.newIssue();
RuleKey ruleKey = RuleKey.of("horus", "H0001");
newIssue.forRule(ruleKey).at(newIssue.newLocation().on(file).at(file.selectLine(linea))).save();

But I can't figure how to override the issue description from the default one to something like: "The value of the metric is xxx which is larger than the yyy allowed". Any clue?

A: The NewLocation class contains the method message(string message) https://github.com/SonarSource/sonarqube/blob/master/sonar-plugin-api/src/main/java/org/sonar/api/batch/sensor/issue/NewIssueLocation.java#L54
So you can change your code to:
newIssue.forRule(ruleKey).at(newIssue.newLocation().message("My Message").on(file).at(file.selectLine(linea))).save();


text:
Q: awk : set start and end of match I have a LaTeX-like table like this (columns are delimited by &) :
foobar99   &     68
foobar4    &     43
foobar2    &     73

I want to get the index of the numbers at column 2 by using match.
In Vim, we can use \zs and \ze to set start and end of matching.
Thus, to match accurately number at colum 2, we can use ^.*&\s*\zs[[:digit:]]\+\ze\s*$.
How about awk? Is there an equivalent?
EDIT:
Matching for the first line:
foobar99   &     68
                 ^^

123456789012345678

Expected output : 18.
EDIT2:
I am writing an awk script to deal with block delimited by line break (Hence, FS="\n" and RS=""). The MWE above is just one of these blocks.
A possible way to get the index of number at column 2 is to do something like that
split(line, cases, "&");
index = match(cases[2], /[[:digit:]]\+/);

but I am looking for a beautiful way to do this.
Apologies for the XY problem. But I'm still interested in start/end matching.

A: Too little context, so a simple guess: have you tried splitting the table into columns? With something like awk -F '\\s*&\\s*' you have your second column in $2.
In fact, you can use split() to retrieve the exact column of a string:
split(s, a[, fs ])

Split  the  string  s into array elements a[1], a[2], ..., a[n], and
return n.  All elements of the array shall be deleted before the split is
performed. The separation shall be done with the ERE fs or with the field
separator FS if fs is not given. Each array  element  shall  have  a
string value  when  created  and,  if  appropriate, the array element
shall be considered a numeric string (see Expressions in awk).  The
effect of a null string as the value of fs is unspecified.

So your second column is something like
split(s, a, /\s*&\s*/)
secondColumn = a[2]

A: By default, awk sees three columns in your data, and column 2 contains & only (and column 3 contains numbers). If you change the field delimiter to &, then you have two columns with trailing spaces in column 1 and leading spaces in column 2 (and some trailing spaces, as it happens; try copying the data from the question).
In awk, you could convert column 2 with leading spaces into a number by adding 0: $2 + 0 would force it to be treated as a number.  If you use $2 in a numeric context, it'll be treated as a number. Conversely, you can force awk to treat a field as a string by concatenating with the empty string: $2 "" will be a string.
So there's no need for the complexity of regexes to get at the number — if the data is as simple as shown.
You say you want to use match; it is not clear what you need that for.
awk -F'&' '{ printf "F1 [%s], F2 [%10s] = [%d] = [%-6d] = [%06d]\n", $1, $2, $2, $2, $2 }' data

For your data, which has a single blank at the end of the first two lines and a double blank at the end of the third, the output is:
F1 [foobar99   ], F2 [       68 ] = [68] = [68    ] = [000068]
F1 [foobar4    ], F2 [       43 ] = [43] = [43    ] = [000043]
F1 [foobar2    ], F2 [      73  ] = [73] = [73    ] = [000073]

Note that I didn't need to explicitly convert $2 to a number.  The printf formats treated it as a string or a number depending on whether I used %s or %d.
If you need to, you can strip trailing blanks of $1 (or, indeed, $2), but without knowing what else you need to do, it's hard to demonstrate alternatives usefully.
So, I think awk does what you need without needing you to jump through much in the way of hoops.  For a better explanation, you'd need to provide a better question, describing or showing what you want to do.

A: You can try this way
awk '{print index($0,$3)}' infile


text:
Q: Error compiling freetype2 library for arm7 with OSX gcc: `limits.h: No such file or directory I am trying to compile the freetype2 library for arm7, using Xcode's command line tools in OSX. I am using the following parameterisation of the project's configure script:
Compiling FreeType for iPhone?
These errors were produced when running the script:

configure:3426: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc -E  conftest.c
  In file included from conftest.c:10:
  /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/llvm-gcc-4.2/bin/../lib/gcc/i686-apple-darwin10/4.2.1/include/limits.h:15:25: error: limits.h: No such file or directory
configure:3426: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc -E -traditional-cpp  conftest.c
  conftest.c:12: error: assert.h: No such file or directory
configure:3426: /lib/cpp  conftest.c
  /Volumes/DATA/filestore/development/libs/c/freetype2/extract/2.5.3/builds/unix/configure: line 1600: /lib/cpp: No such file or directory
configure:3465: result: /lib/cpp
  configure:3485: /lib/cpp  conftest.c
  /Volumes/DATA/filestore/development/libs/c/freetype2/extract/2.5.3/builds/unix/configure: line 1600: /lib/cpp: No such file or directory

I can see that the missing files actually do exist in the directories output in the error messages.
CFLAGS and LDFLAGS contain the following parameter, which should allow for the inclusion of system header files:

-isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.1.sdk/

The other odd thing that I noticed with these error messages, is that the architecture identifier in the directory structures is i686-apple-darwin10. The -arch armv7 compiler flag is being used, so why are i686-apple-darwin10 directories being inspected at all?
* UPDATED *
I also tried parameterising the configure script as per another example:
https://stackoverflow.com/a/12594507/1704014
The following error terminated its execution:

checking for suffix of native executables... ld: library not found for -lcrt1.10.6.o
  collect2: ld returned 1 exit status
  configure: error: native C compiler is not working

This also indicates that a different target architecture (OSX 10.6) is being built against, not arm7.
Any help much appreciated.

A: The problem in my OSX build environment was the Xcode command line tools installation. I reinstalled the latest distribution of the tools, and was able to compile successfully from then on.
To build the freetype2 library for arm7 and arm7s architectures, I found the following suggested commands useful:
https://stackoverflow.com/a/12594507/1704014