text:
Q: C# ASN.1 decoding fail I'm trying to decode the following simple ASN.1 structure in C#:
BIQAAADxPD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5k
YWxvbmU9Im5vIj8+Cjx4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4
eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4
eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4
eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4
eHh4eC8+Cg==

If I try decoding it using OpenSSL, it works as expected:
> openssl asn1parse -in sample.pem
    0:d=0  hl=6 l= 241 prim: OCTET STRING      :<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/>

However, if I attempt to parse it with C#, I only get binary output, as if it was just a plain byte array with no ASN.1 structure: executing the following code
using System;
using System.IO;
using System.Security.Cryptography;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
          var asndata = new AsnEncodedData(Convert.FromBase64String(File.ReadAllText("sample.pem")));
          Console.WriteLine(asndata.Format(true));
        }
    }
}

produces the following output:
04 84 00 00 00 f1 3c 3f 78 6d 6c 20 76 65 72 73 69 6f 6e 3d 22 31 2e 30 22 20 65 6e 63 6f 64 69 6e 67 3d 22 55 54 46 2d 38 22 20 73 74 61 6e 64 61 6c 6f 6e 65 3d 22 6e 6f 22 3f 3e 0a 3c 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 78 2f 3e 0a

which is identical to the binary contents of the file:
> cat sample.pem | base64 -d | hexdump -C
00000000  04 84 00 00 00 f1 3c 3f  78 6d 6c 20 76 65 72 73  |......<?xml vers|
00000010  69 6f 6e 3d 22 31 2e 30  22 20 65 6e 63 6f 64 69  |ion="1.0" encodi|
00000020  6e 67 3d 22 55 54 46 2d  38 22 20 73 74 61 6e 64  |ng="UTF-8" stand|
00000030  61 6c 6f 6e 65 3d 22 6e  6f 22 3f 3e 0a 3c 78 78  |alone="no"?>.<xx|
00000040  78 78 78 78 78 78 78 78  78 78 78 78 78 78 78 78  |xxxxxxxxxxxxxxxx|
*
000000f0  78 78 78 78 2f 3e 0a                              |xxxx/>.|

Is there any way to properly parse this natively using .NET, or do I have to use Bouncy Castle or some other third-party library?
My final objective in this specific use case is to get access to the XML payload using a safe approach to interpreting ASN.1 structures, as opposed to manually trimming bytes at the beginning of the array.


text:
Q: angular wide mat-table starts out of left container | overflows to the right just fine | problem with align-items: center; I have a mat-table like this:

 {{currentProject.name}}

 {{currentProject.description}}

        <button class="button-add-values" mat-button (click)="addValueSelectedRows()">Load Values</button>
        <button class="button-add-row" mat-button (click)="addRow()">Add Row</button>
        <button class="button-remove-rows" mat-button (click)="removeSelectedRows()">Remove Rows</button>

            <ng-container [matColumnDef]="col.key" *ngFor="let col of columnsSchema">

                    <mat-checkbox *ngIf="col.key === 'isSelected'" (change)="selectAll()"> </mat-checkbox>
                    {{col.label}}

                        <ng-container *ngSwitchCase="'isSelected'">

                            <mat-checkbox (click)="$event.stopPropagation()"
                                            (change)="$event ? selection.toggle(element.isSelected) : null"
                                            [checked]="selection.isSelected(element)">
                            </mat-checkbox>
                        </ng-container>

                            <button mat-button (click)="element.isEdit = !element.isEdit">
                                Edit
                            </button>
                            <button mat-button class="button-remove" (click)="removeRow(element.id)">
                                Delete
                            </button>

                            {{element[col.key]}}

                            <button mat-button (click)="editRow(element)">Done</button>

                        <ng-template #dataField>
                            <mat-form-field>
                                <input [type]="col.type" matInput [(ngModel)]="element[col.key]">
                            </mat-form-field>
                        </ng-template>

            </ng-container>

The relevant css currently is:
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  height: calc(100vh - 130px);
  border-radius: 10px;
  margin: 16px;
  margin-left: 32px;

  padding: 16px;
  overflow-x:auto;
}

.table-div {
  align-items: unset; // NOT WORKING; WHAT to do here?
}

.mat-cell,
.mat-header-cell {
  padding: 0px 10px;    // makes pretty spacing between cells
  white-space: nowrap;  // cause no breaks
}

I don't want my cells to have a word break. The table should start at the left of content div and overflows it to the right. It currently kind of looks nice except the table starts way to far left. I overflows to the right correctly. This is caused by align-items: center; within .content.
But I want to have my buttons etc centered, but not the table. I tried to archive this with align-items: unset in table-div, but it does not do the trick.
How can I unset align-items: centered?
how it looks
Thank you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to light on/off LEDs controlled by a LED driver? I want to use a step-down LED driver and configure it to deliver a constant current to some LEDs. This one looks nice:
https://www.diodes.com/assets/Datasheets/AL8843Q.pdf
I can control the brightness with a PWM signal into the CTRL pin. But how do I control the on/off of the LEDs?
Should I send a PWM signal with a 0 % duty cycle (is it possible?), or switch off the LED driver with an external transistor?
In the datasheet they seem to make the distinction between PWM frequency and switching frequency. Moreover they are talking about a soft-start which is 0.1 ms. Does it apply only when the LED driver is supplied with current, or each time the PWM signal reaches 0?

A:
I can control the brightness with a PWM signal into the CTRL pin. But how do I control the on/off of the LEDs?

The CRTL pin will control the LEDs on and off. As David said, 0 % duty cycle will turn them off.

Should I send a PWM signal with a 0 % duty cycle (is it possible?), or switch off the LED driver with an external transistor?

No external transistor. Just PWM the CTRL pin from your MCU.

In the datasheet they seem to make the distinction between PWM frequency and switching frequency. Moreover they are talking about a soft-start which is 0.1 ms. Does it apply only when the LED driver is supplied with current, or each time the PWM signal reaches 0?

I can't find if the soft-start will kick in each time you PWM it. Perhaps they did something clever here to disable the softstart once you start PWM it. Best way would be to test it by increasing the PWM frequency and see if the soft-start comes into play or not.


text:
Q: ArrayList with arrays in it. How to get them out. code is posted Little problem.. i want to add some arrays to my arraylist and later get acces to print them out.
Her is my code..
 import java.util.*;
 class List
{
 private ArrayList<int[]> X;
 private int[] list;

public X()
{
    X = new ArrayList<int[]>();
}

public void addList(int[] list)
{
     this.X.add(list);
}

public void showList(int listNumber)
{
    System.out.println(X.get(listNumber));
}

Problem is im not getting my list out, but the int code something ... dunno what it really is..

A: Your problem is in line System.out.println(X.get(listNumber));. Every java object has method toString(). Arrays also have such method but its implementation shows the array reference. To print the array content either iterate over it and print element-by-element or use utility like Arrays.toString():
System.out.println(java.util.Arrays.toString(X.get(listNumber)));

A: Iterate over all integer arrays in X and in each item (array) print it elements.
This function will do the job for you.
public void printAll(){
for(int [] item:X){
 for(int num :item){
  System.out.print(num);
  }
   System.out.println();
 }

}

A: This is because arrays toString() which is called here prints out array reference, not it's contents.
Use instead custom output:
    for (int i : X.get(listNumber))
        System.out.print(i + " ");

Or, as AlexR proposed, better use provided JDK method Arrays.toString();
By the way, you don't need to prefix this. everywhere in your class' code.

A: You need to use the Arrays class from java.util.Arrays:
System.out.println(Arrays.toString(X.get(listNumber)));

Just printing out an array prints out its memory location, so to get the actual values, you have to get each element individually, which is what Arrays.toString() does for you.

A: You are trying to get the array. If you want to display the results of the array you need to do loop through each value in X.get(listNumber) and display the results of the loop.


text:
Q: How to drag gameObject using touch(unity2d) I searched this on the internet but I still haven't found the answer I wanted.
So, I have a 2d tiled game and each tiles position is a multiple of 1.25 for example 7.5, 3.75. There is going to be a player walking on top it and i want to control the player by dragging it and if you release the touch it would be perfectly on a tile instead of in between the tiles. Right now, I can't even figure out how to drag the gameObject with touch. Can anyone help me and explain to me how to do that?

A: You need to have a collider on every object you plan to move. Then create a class whose sole purpose is to fire a Raycast. Detect when a touch happens. Then fire the Raycast.
RaycastHit hit;
if(Physics.Raycast(ray, out hit, 100))
    Debug.DrawLine(ray.origin, hit.point);

You will notice that you have what you hit; with that you can send a message to that particular object.
hit.collider.SendMessage("move");

Inside the object that you hit, you now have to use the coordinates of the touch position to update the transform.position.


text:
Q: Signing Word, Excel By Users Without Docusign Account Is it possible to sign a Microsoft word or excel document by a user without having Docusign account(embedded signing ceremony)? Can we download the signed document later in the same format(.doc or .xlsx) using API?

A: First question:
If you build an integration for someone else - they wouldn't need to have an account. Someone (you, your customer, etc.) would have to have an account, but not every signer.
Second question:
The complete document is only available as PDF. You can convert it to some other format, but I'm not sure the reason you need it. The idea is that end-users can't easily modify that document,  as you wouldn't want someone to sign something and than you changed what they signed, right?

A: Re:

Is it possible to sign a Microsoft word or excel document by a user without having Docusign account(embedded signing ceremony)?

The signer does not need an account. But the sender, the person initiating the signing request does need a DocuSign account.
Re:

Can we download the signed document later in the same format(.doc or .xlsx) using API?

The regular DocuSign eSignature service changes all source files, including Word and Excel files to the PDF format before they are signed.
DocuSign offers the DocuSign Signature Appliance which can digitally sign Word and Excel files in their native format. The result is a signed Word/Excel file which can still be used as a Word/Excel file. But any changes invalidate the digital signature.


text:
Q: In delta motors, the power factor angle refers to the phase current or line current? A 600V, 60Hz, ∆-connected, 8-pole synchronous motor has a synchronous reactance of 0.15Ω and armature resistance of 0.02Ω. This motor has an output power rating of 46 hp with a 0.90 lagging power factor. Motor losses can be approximated at 1kW.
I don't want a solution.
I only have a question about the lagging power factor of 0.9, is it the angle of the phase current or the angle of the line current?
knowing that delta connected loads phase current relation to line current is:

A 0.9 lagging power factor is :

Which current has the angle of -25.8?

A: Maybe study the phasor diagram for a delta load with a slightly lagging power factor (denoted by \$\Phi\$): -

Image from here.
If the power factor were 0°, \$I_{ab}\$ would be exactly in phase with \$V_{ab}\$. So, \$I_{ab}\$ can be called a phase current because it applies to the current that travels down the specific load phase directly connected between A and B. But, the line current (\$I_{a}\$) also involves \$I_{ca}\$; specifically \$I_{ac}\$ (the reverse of \$I_{ca}\$).
Thus, \$I_{a}=I_{ab}+I_{ac}\$.

I only have a question about the lagging power factor of 0.9, is it
the angle of the phase current or the angle of the line current?

The PF angle is the angle of the phase current \$I_{ab}\$ relative to line voltage \$V_{ab}\$. Ditto for the other two pairs of phasors.


text:
Q: Using Near (proximity) tool in ArcGIS for Desktop? I've tried changing GCS and PCS multiple ways but can't seem to figure out how to get the Near (from Proximity tools) to output the Near_DIST in feet. All it outputs is what looks like decimal degrees. Here is my data:
Data frame: NAD_1983_StatePlane_Texas_North_FIPS_4201_Feet
Input features (points): GCS_North_American_1927
Near features: GCS_North_American_1983
I'm not fond of the Data frame features but it's for my geographic area and ensures that when I draw buffer circles they actually look like circles and are not skewed to appear oblong. Based on the tool, it says the output Near_DIST will return units of measure based on the Input features. I'm not sure what I should change to get it to return the distance in feet.

A: Agree with above, need to reproject to match your data frame or vise versa... Don't know if this is large or small scale analysis, but if it's large.. you need a non ancient transverse Mercator projection to preserve conformality and eliminate scene based anomalies that would be present with a geographic projection. Either way.. match those projections


text:
Q: The timeout period elapsed prior to obtaining a connection from the pool - but the pool is not full I hate even bringing this up b/c there are so many hundreds of pages talking about this error dating back 7-8  years...  However, I cant quite figure this out.
I have a report service running on server A which connects to SQL Server 2008 R2 on Server B.  Both servers are running Windows Server 2008.  The report service is multi-threaded and runs up to 10 reports at a time each on its own thread.
My connection string is as follows:
Data Source=ServerB;Initial Catalog=DBName;trusted_connection=YES;Connection Timeout=0;Max Pool Size=500;

As you see, I have set the connect timeout to 0 to wait for a connection until its available, and max pool size to 500 b/c I wanted to make sure the pool was not too small for my multi-threaded service.  The error typically only shows up when the service starts and there is a queue of reports waiting to be processed.
So obviously, the first thing to do is look for leaking connections..  there have to be connections that are not being closed that are causing the pool to fill up, right?  Nope -looks like the pool never fills up.
I have spent the last several hours running Performance Monitor on the server watching ".NET Data Provider for SqlServer" and the NumberOfPooledConnections never gets above 20 or  so.  I also have perfmon running on the SQL server watching "SQLServer:General Statistics" and UserConnections never goes above 50.  During this time, I have caused this error to be reported 2 or 3 times by manually restarting the service.
What else can I look for?  What else would cause this error?
Full error message is:
System.InvalidOperationException: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()

Thanks,
Stephen

A: This is known bug as shown here

Posted by Microsoft on 8/15/2008 at 11:31 AM
  Thanks for your feedback. The fix was submitted to the source branch of the next major .Net release.


text:
Q: What is meant with "decision level of factor loading"? I have performed a PCA with some data sets. Prior to performing PCA, I tested the applicability of PCA with KMO and Bartlett's Sphericity tests.
I got some critics stating that I have to add "my decision level of factor loadings" instead of KMO or BS results!
Can anyone tell me what "decision level of factor loadings" means?


text:
Q: How to redirect from redux (w/ react router v6)? With react-router 5 I used library - react-connected-router to make redirect from redux store. This library doesnt work with react router 6. How I can implement this?
I can just put navigate from useNavigate to payload and then in store use it. But I think it's not good decision. What can you recommend?

A: Can't you just navigate after you have dispatched your action to redux? Then you keep your navigation strictly to ReactComponents

A: wrap it in a function
let history = useHistory();

const myActions = () => {
 dispatchAction1()
 dispatchAction2()
 history.push("/MY_ROUTE")
}


text:
Q: Rails helper method return NilClass I have this code in User#index view:
<%= User.find_each do |user| %>
  <%= user.name %>
<% end %>

which returns the user names:
user1 user2 user3 ...

Then I move this code to the UserHelper:
module UserHelper
  def get_users
    User.find_each do |user|
      user.name
    end
  end
end

And call it from the User#index view with:
<%= get_users %>

The problem is that this is not returning any user. If I use <%= get_users.class %> it outputs NilClass. Why is the helper method not returning the user names?

A: Your helper method implicitly returns the result of calling find_each, which is different than returning a collection of user names.
Think of it like running 5.times { |n| puts n }: what's the value of that? Not "0 1 2 3 4", but "5", because times returns what it was called on, not what's run in its block.
Your original code, by the way, returns the exact same thing--you are relying on a side effect inside the find_each block, i.e., appending user.name to the response.
If you want to return a collection of the users' names you'd want to map/etc. and grab each user's name. Or, IIRC, you can do a find and a pluck so you only get back the users' names instead of all user fields.

A: You can use as below also,
  <%= User.all.map(&:name).join(' ') %>


text:
Q: Using a BJT to enhance battery life I have a little project going on, that involves turning on and off a led strip.
The led strip specs :  5M Led SMD 600 Lights
LED : 3528 SMD
600 Lights, 5m : 120 LED / m
According to this site, it will drain 48 watts for the full length.
I am looking to use about 0.5m and power it through a 9V battery. According to this site, the current that the strip will drain will be :
Wattage / Voltage = 4,8W / 12V = 0,4 A

I am not sure if I should be using the 9V as the denominator, but either way I am looking at about 0.5 Amperes.
My Question :
A 9V MN1604 6LR61 alkaline battery provides with 560mAh, which gives me roughly 1 hour of battery life.
I know that BJTs can amplify the current, by providing a base current and getting it amplified at the emitter/collector.
Ib will be Ie / hFE , so I am reducing the current I drain from the battery hFE times.

simulate this circuit – Schematic created using CircuitLab
(resistors chosen randomly)
So what is wrong with this picture? I must be making a mistake otherwise I am generating the missing power out of thin air.

A: This is fine if you are having an external power supply at the collector of the BJT but in reality you aren't and the current for the base, as you said, would be taken from the battery but so would the current through the collector!
So while the base current is sort of negligible it will still actually be draining more current than originally so there is no point in this being here. And with the voltage drop of the base-emitter junction there may not be enough left for the voltage drops required over the LEDs you have.
While the battery may claim to have a 560mAH, it is not likely that it will actually play out this way, they are quite often conservative with these values and it may actually be higher and last longer than you expect but as mention by Andy, the terminal voltage will droop due to increases in the internal resistance of the battery which again could stop the LEDs lighting up to a satisfactory level.

A: BJTs can amplify current but they can't conjure energy from nowhere. If you need 500mA then your battery has to supply it and, you might not get the full 60 minutes usage because over that time period the battery terminal voltage will droop/sag and may reach a point where your LEDs get too dim.

A: In practice you are turning that transistor full on by raising the base more than a diode drop (approx 0.6V) above emitter. You have a simple switch. If you want to use it to modulate current you need much more precise control over the base voltage, almost certainly involving some feedback

A: Your initial assumption is incorrect, by about an order of magnitude.
The calculation is not

Wattage / Voltage = 4,8W / 12V = 0,4 A

It is

48W / 9V = 5.3A

Your 0.565Ah battery will last, at best:

0.565Ah/5.3A = 0.1h, or 6.4 minutes

I believe that battery was characterised at a much lower drain current than 0.565A for 1 hour (I believe typically at 1/10th, but I can find the reference).
When you run a battery at significantly higher drain current that it is characterised at, it will go flat much faster than 6.4 minutes.
Then others have explained why a transistor can't break the laws of thermodynamics, and be a perpetual motion machine.


text:
Q: Converting MySQL code to PostgreSQL using foreign keys I am trying to create tables with a primary key and foreign key in Postgresql. Originally was created in MySQL but I do not know how to convert can someone assist.
I converted the first table but the instructor table is giving me problems
CREATE TABLE instructor_detail (
  id SERIAL PRIMARY KEY,
  youtube_channel VARCHAR(128) NULL,
  hobby VARCHAR(45) NULL
);

DROP TABLE IF EXISTS instructor;

`CREATE TABLE instructor (
id SERIAL PRIMARY KEY,
first_name VARCHAR(45) NULL,
last_name VARCHAR(45) NULL,
email VARCHAR(45) NULL,
instructor_detail_id INT NULL,
CREATE INDEX fk_detail_idx ON instructor (instructor_detail_id),  CONSTRAINT fk_detail FOREIGN KEY (instructor_detail_id) REFERENCES instructor_detail (id) ON DELETE NO ACTION ON UPDATE NO ACTION
);`

ERROR:  syntax error at or near "CREATE"
LINE 7:   CREATE INDEX fk_detail_idx ON instructor (instructor_detai...

A: The foreign key constraint will work in PostgreSQL, no change is required.
The KEY clause is a MySQL extension to create an index within CREATE TABLE, which PostgreSQL does not support.
You'll have to convert the KEY clause to a separate CREATE INDEX statement in PostgresSQL.


text:
Q: java conversion of arabic numbers to roman numerals Im writing this program for a java class im having. The point of this program is to convert an Arabic number input, into a Roman numeral.
here is my code:
import java.util.Scanner;

public class RomanDigit{
public static void main(String arg []){
    System.out.println("Please enter a number to be converted to roman numerals: ");
    Scanner scan = new Scanner (System.in);
    int number = scan.nextInt();
    String romanDigit = "";
    if (number < 0 || number > 3999) {
        System.out.println( "This number cannot be converted");
    }
    else
    {
        System.out.println("The number you input, converted into roman numerals is: " + romanDigit);
        System.out.println(convert(number));
    }
}

    public static String romanDigit(int n, String one, String five, String ten){

    if(n >= 1)
    {
        if(n == 1)
        {
            return one;
        }
        else if (n == 2)
        {
            return one + one;
        }
        else if (n == 3)
        {
            return one + one + one;
        }
        else if (n==4)
        {
            return one + five;
        }
        else if (n == 5)
        {
            return five;
        }
        else if (n == 6)
        {
            return five + one;
        }
        else if (n == 7)
        {
            return five + one + one;
        }
        else if (n == 8)
        {
            return five + one + one + one;
        }
        else if (n == 9)
        {
            return one + ten;
        }

    }
    return "";
}

public static String convert(int number){

    String romanOnes = romanDigit( number%10, "I", "V", "X");
    number /=10;
    String romanTens = romanDigit( number%10, "X", "L", "C");
    number /=10;
    String romanHundreds = romanDigit(number%10, "C", "D", "M");
    number /=10;
    String romanThousands = romanDigit(number%10, "M", "", "");

    String result = romanThousands + romanHundreds + romanTens + romanOnes;
    return result;

}
}

I edited the code now for the given suggestions. I noticed I was missing the number /= 10; statement in the end. For some reason i deleted it before and forgot to put it back. Seems to be working fine now. The reason it was not working besides the number/=10 statement, was that I had the If statement in the wrong place.

A: You should change convert method to be something like this.
public static String convert(int number) {
    if (number < 0 || number > 3999) {
        return "This number cannot be converted";
    }

    String romanOnes = romanDigit(number % 10, "I", "V", "X");
    number /= 10;

    String romanTens = romanDigit(number % 10, "X", "L", "C");
    number /= 10;

    String romanHundreds = romanDigit(number % 10, "C", "D", "M");
    number /= 10;

    String romanThousands = romanDigit(number % 10, "M", "", "");
    number /= 10;

    String result = romanThousands + romanHundreds + romanTens + romanOnes;
    return result;
}

Also, you should remove checking is a number greater than zero and less than 4000 from romanDigit method.
As @eis has noticed, the check does a number is valid for conversion you should check outside of convert method. In this case, in the main method.


text:
Q: Asymptotic expansion of a Laplace-type integral with a "manifold of maxima" Moved this here from MathSE because I had no luck there and suspect the question may be harder than I first thought.
Consider the integral
$$
I(\alpha)=\int_0^1 dx_1 \int_0^1 dy_1\int_{x_1}^1dx_2\int_{y_1}^1dy_2\,e^{-\alpha(x_2-x_1)(y_2-y_1)}
$$
in the limit $\alpha\rightarrow\infty$. To find the asymptotic expansion in this case is not hard: you can evaluate the integral in closed form in terms of Exponential Integral functions and then look up asymptotic expansions, which give
$$
I(\alpha)\sim \frac{\log\alpha}{\alpha}.
$$
However, I am interested in more complicated versions these kinds of integral where the integrand might be more complicated and therefore I will need to "expand before integrating" (since I cannot evaluate the integral in closed form).
This looks a lot like a problem for Laplace's method, which finds the maximum in the exponential and expands the integrand near it, leading to a Gaussian integral. But my integrands all have the same property: the exponent is maximal not at an isolated point, but on a 1-dimensional subspace of points. Is there a theory of such integrals? I haven't found much. Any texts that mention things like "Laplace's method with a manifold of maxima" that I came across are very technical.
So my questions:

*

*Is there a straight-forward derivation of the the asymptotic expansion for the simple integral above using a Laplace-like method, i.e. without evaluating the integral in closed form to start with?

*Can anyone recommend not-too-technical texts that might help me?

A: You can perform a linear change of variables so that one of coordinates corresponds to the maximum of the integrand, and then integrate over this direction first ( you will be integrating a constant function, so this is easy!)
After this, you will be in the setting where Laplace method will apply.


text:
Q: Saving value from html input > date using ajax I'm trying to save date using html input = date and ajax. but it didn't save.
html code:
<input type="text" class="dtreq" name="dtreq" id="dtreq">

Ajax:
$('#save').click(function(){
var dtreq = [];

$('.dtreq').each(function(){
    dtreq.push($(this).val());
    });

    $.ajax({
      url:"insert_punchlist_form.php",
      method:"POST",
      data:{dtreq:dtreq},
      success:function(data){
        alert(data);
        $("td[contentEditable='true']").text("");
        $('select').prop('selectedIndex',0);
        for(var i=2; i<= count; i++){
          $('tr#'+i+'').remove();
        }
      }
    });
});

A:

$('#save').click(function(){
var dtreq = [];

$('input.dtreq').each(function(){

    dtreq.push($(this).val());
    });

    console.log(dtreq);
    $.ajax({
      url:"insert_punchlist_form.php",
      method:"POST",
      data:{dtreq:dtreq},
      success:function(data){
        alert(data);
        $("td[contentEditable='true']").text("");
        $('select').prop('selectedIndex',0);
        for(var i=2; i<= count; i++){
          $('tr#'+i+'').remove();
        }
      }
    });
});

<input type="text" class="dtreq" name="dtreq" id="dtreq">
<input type="text" class="dtreq" name="test1" id="test1">
<input type="text" class="dtreq" name="test2" id="test2">
<button id="save">Save</button>

A: data : { "dtrec" : dtrec }
the key in the data JSON object  should be quoted or else it is parsed as a variable and of course the variable dtrec of the value part of data JSON object should be serialized as valid json

A: Hello I have modified your code please check.

$('#save').click(function(){
var dtreq = [];

$('.dtreq').each(function(){
    console.log($(this).val());
    dtreq.push($(this).val());
    });

    $.ajax({
      url:"insert_punchlist_form.php",
      method:"POST",
      data:{dtreq:dtreq},
      success:function(data){
        alert(data);
        $("td[contentEditable='true']").text("");
        $('select').prop('selectedIndex',0);
        for(var i=2; i<= count; i++){
          $('tr#'+i+'').remove();
        }
      }
    });
});

<input type="text" class="dtreq" name="dtreq" id="dtreq">

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


text:
Q: Boostrap tooltip doesn't render after inserted comment I have implemented a comment system on my web app where the comment is returned from the server as a JSON format if the record was saved correctly into the database.
Everything else seems to render properly except tooltip which holds links for editing and deleting the comment. After comment is been appended to a div, the tooltip isn't holding those links hidden.
I'm using CodeIgniter as a PHP framework, although this information may not be useful since it's an UI problem.
Here's my PHP code for inserting the comment (../application/controllers/comments):
public function add() {

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

        $event_id = $this->input->post('event_id');
        $user_id = $this->session->userdata('user_id');

        $this->form_validation->set_rules('event_comment', 'Kommentti', 'trim|xss_clean|required|htmlspecialchars');

        if ($this->form_validation->run() === false) {

            $this->output->set_content_type('application_json');
            $this->output->set_output(json_encode(array('st' => 0)));
            return false;
        } else {

            $data = array('event_id' => $event_id, 'user_id' => $user_id, 'comment' => $this->input->post('event_comment'));

            $comment = $this->comment_model->addComment($data);
        }

        if ($comment === true) {

           $this->load->model('comment_model');
                $new_comment = $this->comment_model->getNewestComment($event_id, $user_id);

                $this->output->set_content_type('application_json');
                $this->output->set_output(json_encode($new_comment));
                return true;
        } else {

            $this->output->set_content_type('application_json');
            $this->output->set_output(json_encode(array('st' => 0)));
            return false;
        }
    }
}

Here's my AJAX (../public/js/ajax.js):
$("#event_comment").keypress(function(e) {
    if(e.which == 13) {
        var from = $('.form-comments');

        $.ajax({
            url: from.attr('action'),
            type: from.attr('method'),
            data: $(from).serialize(),
            dataType: 'json',
            beforeSend: function() {
                    // Piilotetaan "Luo tapahtuma" - painike ja korvataan se
                    // "spinner" - ikonilla
                    from.find(".form-comment-send").hide();
                    from.find("#spinner_comment").show();
                },
                success: function(data) {
                    if(data) {

                        // RENDER MESSAGE HERE AND APPEND IT TO COMMENT BODY
                        renderCommentHTML( data[0] );

                    }

                }, complete: function() {
                    from.find("#spinner_comment").hide();
                    from.find(".form-comment-send").show();
                }
            });
        return false;
    }
});

And finally the function for rendering the HTML (../public/js/functions.js)
function renderCommentHTML(data) {

var comment = '';

comment += '
';

        // tooltip starts here
        comment += '
';
        comment += '';
        comment += '
';
        comment += 'Muokkaa';
        comment += '<form action="comments/delete" method="post">';
        comment += '<input type="hidden" name="event_id" value="'+ data.event_id +'">';
        comment += '<input type="hidden" name="comment_id" value="' + data.id +'">';
        comment += '<button type="submit" name="delete_comment">Poista</button>';
        comment += '</form>';
        comment += '
';
        comment += '
'
        // Tooltip ends here

        comment += '';
            if(data.is_fb_img == 0) {
                comment += '';
            } else {
                comment += '';
            }
        comment += '';

        comment += '
';
        comment += '
'+ data.name +'
';
        comment += '
';
        comment += '
';
        comment += '<form action="events/edit" method="post" class="edit-comment">';
        comment += '<input type="hidden" name="c_id" value="'+ data.id +'">';
        comment += '
'+data.comment+'
';
        comment += '</form>';
        comment += '
';
        comment += '
';

        comment += '
';
        comment += '';
        comment += '
';
        comment += '
';
        comment += '
';

        $('.comment-holder').append(comment);
}


text:
Q: Warning: mysql_fetch_array() expects parameter 1 to be resource, array given It is a simple PHP MySQL search engine,
in which the searching element is "adm_no".
<?php
require_once("lib/connection.php");
require_once("lib/functions.php");
$adm_no=$_POST['adm_no'];
//if (!$adm_no==ctype_digit) echo "You Entered wrong Admission no Recheack Admission no" ; exit();
$clas=$_POST['clas'];
$query="SELECT * FROM $clas WHERE adm_no = $adm_no";
$result = mysql_query($query);
//searchs the query in db.
while($result = mysql_fetch_array( $result))
{
echo $result['adm_no'];
echo " ";
echo $result['adm_dt'];
echo "";
echo $result['name'];
echo "";
echo $result['dob'];
echo " ";
echo $result['f_name'];
echo " ";
echo $result['f_office'];
echo " ";
echo $result['f_o_no'];
echo " ";
echo $result['m_name'];
echo " ";
echo $result['m_office'];
echo " ";
echo $result['addr'];
echo " ";
} ;

And the error I am getting is

Warning: mysql_fetch_array() expects parameter 1 to be resource, array given in C:\wamp\www\st_db_1\search_db.php on line 10

A: You do realize that while($result = mysql_fetch_array( $result)) stomps on the existing value of $result, right? Use a different variable.

A: Three issues:

*

*Where are you calling mysql_connect()?

*You're overwriting $result in your loop statement.

*There's a huge SQL-injection hole in your code.

A: RAVI you can fix the SQL-injection code by changing this code:
Coding horror
$adm_no=$_POST['adm_no'];
$clas=$_POST['clas'];
$query="SELECT * FROM $clas WHERE adm_no = $adm_no";

to this approved code:
$allowed_tables = array('table1', 'table2'); //list of allowed tables
$clas = $_POST['clas'];
$adm_no= mysql_real_escape_string($_POST['adm_no']);
if (in_array($clas, $allowed_tables)) {
    $query="SELECT * FROM `$clas` WHERE adm_no = '$adm_no'";
//                        ^     ^ backticks      ^       ^ single quotes
}

Don't forget to add the backticks ` around tablenames.
And even more important don't forget the single quotes ' around parameters or you will still be vulnerable!
See: How does the SQL injection from the "Bobby Tables" XKCD comic work?
For SQL-injection in general.
And: How to prevent SQL injection with dynamic tablenames?
For SQL-injection problems when using dynamic table or field names.


text:
Q: PrestaShop Webservice not returning product created by Webservice I have successfully used the PrestaShop Webservice to create a new product from our custom application. The product gets created using the product XML schema and I can view it in the Catalog.
However, I cannot retrieve the product using the Webservice filtering on the 'reference' field. An empty  node is returned, but I can retrieve it by ID.
Anyone have any ideas as to why this might be? Do I need to set something within the product via the Webservice to make it filterable?
Regards
Andrew

A: I have found the problem after debugging the WPS Webservice code down to the function getFilteredObjectList() in classes/webservice/WebserviceRequest.php line 1199.
My product reference was being created as ' my-text-ref ' (with the space either side), so my filter for 'my-text-ref' without spaces was not found.
This is because in my XML used to create the product I had:

I've changed this to:

And it all works!


text:
Q: The package system is broken: I can't update my apps on Ubuntu 12.10 64bit screen shot:

text:
"Check if you are using third party repositories. If so disable them, since they are a common source of problems.
Furthermore run the following command in a terminal: apt-get install -f"
details:
The following packages have unmet dependencies:
fgfs-models-base: flightgear: Depends: libc6 (>= 2.14) but 2.15-0ubuntu20 is installed
        Depends: libgcc1 (>= 1:4.1.1) but 1:4.7.2-2ubuntu1 is installed
        Depends: libstdc++6 (>= 4.6) but 4.7.2-2ubuntu1 is installed
        Depends: libudev0 (>= 147) but 175-0ubuntu13 is installed
        Depends: zlib1g (>= 1:1.1.4) but 1:1.2.7.dfsg-13 is installed

A: First, try this commands in the Terminal (CTLR+ALT+T):
sudo apt-get update --fix-missing
sudo dpkg --configure -a

If your problem still persists, try downgrading (using Synaptic Package Manager) the packages:

*

*libc6

*libgcc1

*libstdc++6

*libudev0

*zlib1g

Tutorial about downgrading packages
Hope it helps!


text:
Q: How can I return the count of objects for an FRC fetch? I am trying to use the count of objects from my FRC fetch so that I can create an "Add" cell after all of my fetched objects have been listed in a UITableView. Is there a method for returning the number of objects fetched? I can only find a method that returns the count of sections for a given FRC.

A: Simplistically, you You want a count of fetchedObjects. So:
[[myFRC fetchedObjects] count];

The problem that you're going to have with adding an additional cell, is that every time the table ask for the count of sections and rows, you're going to have add 1 to the count so the table knows to add the extra row.
Bjarne Mogstad is correct. It's quicker and cleaner to put the add element in a header or footer for the table itself. That way, the table directly and cleanly represents the data structure without having to constantly adjust for the phantom row.

A: The easiest way to do this is by setting the tableFooterView property of your table view. The footer view will be displayed below the last table view cell.


text:
Q: Связывание ViewHolder вместе с GridView Подскажите пожалуйста, как правильно связывать ViewHolder вместе с GridView и его действиями, скажем, простенький пример, если можно, для понимания структуры.

A: ViewHolder это объект, держащий ссылки на поля - поскольку метод findViewById() очень ресурсо-затратный. GridView это компоновщик лаяута.
Все, что вам нужно знать о "связывании" этих двух вещей:
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

// Используйте этот метод, если уверены, что размер адаптера не будет меняться

mRecyclerView.setHasFixedSize(true);

// Первый входной параметр это контекст, второй количество колонок.

GridLayoutManager glm=new GridLayoutManager(this,2);

// Программно устанавливаете компоновщик (тут и происходит "связывание" в вашем понимании)

mRecyclerView.setLayoutManager(glm);

// Создаете инстанс ресайклера

mAdapter = new CardViewDataAdapter(myDataset);

// Устанавливаете адаптер к ресайклервью

mRecyclerView.setAdapter(mAdapter);

A: Вот пример для ListView, думаю для GridView он тоже подойдет!
public class DataAdapter extends BaseAdapter {

    private Context mContext;
    private String[] mData;

    public DataAdapter(Context context, String[] objects) {
        mContext = context;
        mData = objects;
    }

    static class ViewHolder {
        TextView txtItem;
    }

    @Override
    public String getItem(int i) {
        return mData[i];
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        ViewHolder viewHolder;

        if (convertView == null){
            LayoutInflater inflater = (LayoutInflater) mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.list_item, viewGroup, false);
            viewHolder = new ViewHolder();
            viewHolder.txtItem = (TextView) convertView.findViewById(R.id.txtItem);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.txtItem.setText(getItem(position));

        return convertView;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public int getCount() {
        return mData.length;
    }
}


text:
Q: New-AzApiManagementSubscription A positional parameter cannot be found that accepts argument 'True' I am trying to create a subscription for an API using the cmdlet New-AzApiManagementSubscription. Got the error "A positional parameter cannot be found that accepts argument 'True'".
Following is the code.
$envID = "DEV"
$apimContext = New-AzApiManagementContext -ResourceGroupName "RGNM" -ServiceName "APIM-SRVC"
Write-Host "Creating the product"
#Create Product.
New-AzApiManagementProduct -Context $apimContext -ProductId "Prjname-$envID-Product" -Title "Prjname-$envID-Product" -Description "APIM Product for Prjname " -ApprovalRequired $False -SubscriptionRequired $True -State "Published"
Write-Host "Creating the Subscription"
#Create Subscriptions
New-AzApiManagementSubscription -Context $apimContext -SubscriptionId "Prjnam-test-Subscription" -Name "Prjnam-testcomp-$envID-Subscription1" -Scope "/products/Prjname-$envID-Product" -AllowTracing $True -State "Active".
Product is created successfully, but the Subscription is throwing the error.

A: This is a simple explanation for this line below,
New-AzApiManagementSubscription -AllowTracing $True
The cmdlet New-AzApiManagementSubscription has a parameter named AllowTracing, and you've specified a value of $True for this parameter
AllowTracing is not a boolean parameter and doesn't require a True or False input


text:
Q: Unable to launch a java/javaFX code after a clone on IntelliJ It's very complicated to explain so sorry if it's not clear. Basically, I'm on a group project in javaFX, and every time I clone it, my PC doesn't recognize either Java or JavaFX on THAT project exactly. All the others work fine. So I have to do a lot of manipulation each time for it to "work" (I explain below).
And today I have clone because of an error. Except that impossible to make it work again.
What I did on IntelliJ after cloning:
-I reloaded the MAVEN project
-I imported the java libraries
-I put the right folder in ROOT

-I created the configuration

From there, Java and JavaFX are recognized. After that, I have other problems. In particular that of "The output path is not specified for module structure" and after that it redirects me to File -> Project Structure -> Project and compile output. Except that in my previous problems, I didn't have to define a Compiler Output. Usually the steps above were enough. And the problem is that I have no idea what to put in this section. I searched all over the internet, but 90% of the time it's an old version of IntelliJ and it was asking them for a path. There, I am asked for a file (impossible to choose a destination path, it is greyed out). And in CTRL C + V the path directly (for example an excluded "Out" folder like what I have read on the internet), I have this error at launch:
Error occurred during initialization of boot layer java.lang.module .FindException: Module start.structure not found

I want to re-specify that there is no error in the code, we have exactly the same with my team, and with them it works without worries.
If someone know how to resolve theses problems

A: This isn't really fully answerable here in a general sense, because there are too many environmental and project-specific things that may occur.
Instead, I'll provide a suggested approach for a new project:

*

*Create a new JavaFX project in Idea.

*

*Choose Maven for the build tool.

*Follow the execution instructions from the linked documentation to ensure the project runs in your environment.

*Share your new JavaFX project on GitHub.

*Clone the newly shared project to a new Idea project.

*

*This is emulating somebody else checking out the project from GitHub.

*Run the newly checked out project in your Idea environment exactly as you did for Step 1.
That is really all you need to do to use JavaFX + Idea + GitHub.
A pre-existing project may require additional steps for configuration and use which may be project specific, so I can't generally advise on that.

Some comments on the approach outlined in your question:

*

*You mention "every time I clone it".

*

*You only really need to clone a project once, after that you can just update it.

*The image has a folder ${project.build.directory}.

*

*That looks wrong, kind of like an expansion variable name was applied literally rather than being expanded (I don't know what you did to cause that).

*Your resources folder isn't marked with a resources icon.

*

*This indicates that you haven't imported the project from Maven correctly.

*Normally Idea will recognize a Maven project and import it automatically, mapping the standard directory structure, e.g. src/main/java is Java source and src/main/resources are resources.

*"I have put the right folder in ROOT"

*

*I am not sure what that means, but it should not be necessary to manually configure things like this.  As mentioned, Idea knows the standard Maven project structure and is able to apply it without manual intervention.

*"I created a configuration."

*

*You don't need to create configuration manually.

*The configuration you have created is wrong.

*If you right-click on your JavaFX application class and choose run, an appropriate run configuration for the application will be created automatically.

*The configuration does not need to specify a JavaFX SDK.

*You don't need to (and should not for this purpose), install a JavaFX SDK on your machine.

*The configuration does not need to specify a module path or modules to add.

*Idea and Maven are smart enough to know that:

*

*your application is modular (because you have provided a module-info.java)

*the required modules are provided as Maven dependencies (this includes the JavaFX modules that you need)

*the modules should be placed on the modulepath (Idea and Maven will do this automatically, you don't need to do anything manual for this to occur).

*For the message "The output path is not specified for module structure":

*

*I don't know what this means, but, if you follow the suggested approach, you don't need to manually specify an output path, Idea and Maven will automatically assign appropriate values and use them without user intervention.

*"Error occurred during initialization of boot layer java.lang.module .FindException: Module start.structure not found"

*

*This indicates that you have specified somewhere that a module start.structure should be used and either:

*

*Your application's module (specified in its module-info.java) is defined using a different name.

*Your application's source code is not on the module path (perhaps it is mistakenly on the classpath instead).

*Your apps module isn't correctly added.

*Usually Idea will be smart enough to know that you have a module-info.java and therefore to place your application code on the modulepath, so you don't need to manually specify modulepath and add-modules options to find your application's module.


text:
Q: Can I secure my cloud function using Firebase Auth, but without using callable cloud functions. (HTTP request only) In my project I use a bunch of GCP services, including Firestore, Cloud Functions and Firebase auth.
Taking the fact that users are able to login via Firebase auth service, I assume that it should be possible to check and authenticate users calling my cloud function. Issue is that I can not find any docs or example of how to do that.
I understand that there are special callable functions but it doesn't suit me. I am using express for handling requests.
Is it possible to retrieve some kind of JWT token from user logged in on client side (firebase auth) then send it with request to my cloud function and then check it somehow there? Or is there any other mechanism to achieve CF protection described above?
P.S.
I saw this question, but it is not about what I am asking, because it is related to Firebase Functions and I am talking about Cloud Functions which is very similar but not exact same thing.

A: You can very easily duplicate the effect of callable functions by mimicking the protocol that is uses.  Just send the user's token in the header of the client request, and parse that out of the headers in your function.
Callable functions use the header Authorization: Bearer <token>, but you are free to do whatever you want.  You are just passing data into the function like any other piece of data.

A: So, according to Dougs suggestion and after some additional googling I found out the way which should work for me.
On client side we need to retrieve id token of authenticated user:
const token = await firebase.auth().currentUser.getIdToken(true);

Now we can actually add this token to any request we need. I am going to put in request headers while calling my HTTP triggered cloud function. For example:
...
const headers = {
    'Authorization': token
}
const response = await fetch('CF_URL', {headers});
....

The last and most important thing here is to have verification logic on the serverside (Cloud functions in my case):
try {
    const userData = await admin.auth().verifyIdToken(tokenFromHeaders);
    console.log(userData.uid) // here we have uid of verified user
    // check user access or do whatever we need here
} catch (e) {
    // something go wrong
}


text:
Q: Android WiFi Direct Demo Issues im testing the new technology wifi direct and im having some issues using
the wifi direct demo from the samples that come with the android-sdk.
So, I have two devices A and B, both with android 4.0.3.
First, from device A, I send a file to B. Nothing wrong here, B
receives the file.
Then A disconnects from B.
Now, from device B I try to send a file to A.
But the device that receives the file is B, instead of A.
To fix, i need to turn off and on both devices...
Also, sometimes when i click disconnect and try to
connect again, connection fails and i have to disable and
enable wifi direct...
Anyone else experiencing this?
Is it because the new technology is not mature yet or maybe
something wrong with my build/driver/etc or maybe this demoapp
doesnt support two-way sharing.
Any ideas and/or explanations would be apreciated.

A: When providing a WifiP2pConfig instance to the connect() function, you can set the groupOwnerIntent property of this configuration object as follows:
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = "...";                 // insert ip here
config.groupOwnerIntent = 0;
config.wps.setup = WpsInfo.PBC;
manager.connect(..., config, ...);

From the android reference:

This (the groupOwnerIntent) is an integer value between 0 and 15 where
  0 indicates the least inclination to be a group owner and 15 indicates
  the highest inclination to be a group owner.

Furthermore, the demo probably repeatedly sends the file to the same device because there is always made a socket connection to the ip-address obtained from:
WifiP2pInfo.groupOwnerAddress

If you would like to support bidirectional communication, the first step in setting this up would be sending the ip-address of the non group owner to the group owner.
As far as the disconnect/reconnect problem goes, I seem to have the same inconsistencies with Android 4.0.2 devices.

A: I have been trying for a while to transfer files between two devices using wifi direct. I have use the Android SDK WifiDirectDemo as base. My experience:
GO address is always the same (at least in Samsung Nexus), but this is not really a problem, because you can use this to know who is the server (or client).
Another strange thing was that MAC address of devices were different when you got it from Android WifiManager and when you read it from "/proc/net/arp" file.
At the end I did it, and you can see the code here.
I hope it helps you!

A: I have been struggling with the same problem lately. I suppose this is an OS issue. To give you a brief background, I have installed Wi-Fi Direct application to both devices with different OS versions, one with OS 4.0.1 and one with OS 4.0.2. The connection fails from time to time when I disconnect and reconnect the devices. It goes same while searching for devices too. But the thing is, this only happens on the device with OS 4.0.2. Other device does not crash or disconnect.
While searching for that problem, I have found the links below. People discussed about that and they share the same idea. Apparently this is an OS 4.0.2 issue. I am not sure if it is the same for OS 4.0.3 but there is no problem with the previous version OS 4.0.1 for sure.
Here are the links:
http://code.google.com/p/android/issues/detail?id=24402
http://osdir.com/ml/android-platform/2012-01/msg00226.html


text:
Q: Can't open .tex files after update When I installed LaTeX I followed an online guide a bit blindly, so forgive me if I mix up things.
I just updated TeX Live (via TeX Live Manager in the command line) and now I can't open .tex files with TeXworks. When I double click in the files, nothing happens, same thing when I try to start a new texworks.exe process, it simply doesn't do anything.
Updating TeX Live was the only thing I did, and before this it all worked perfectly and without issue.
What could be causing this problem?

A: Blindly following obscure guide lines often leads to b0rK3d!#" update procedures or installations. If that is the case, try the following:

*

*Try a repair of the installed program and update any installed package.

*If that fails, try to uninstall the program.

*

*If the uninstall fails, delete the installed folders manually. Use ccleaner or Wise Disk Cleaner to get rid of zombie entries in the Windows registry.

*Install the latest TeX Live environment and LaTeX editor/IDE to your liking, but as clean as possible.


text:
Q: Regular Expressions - match pattern but return subpattern I want to match a pattern (using java programming), but I need only parts of it.
Example... from the following text:
0 - Amount: 3 - Class 29
1 - Amount: 2 - Class 21
2 - Amount: 11 - Class 1

I want to match the pattern "Amount: \d* - Class \d*", but return only the pairs of numbers, so that the output is something like an array:
{
    {3, 29},
    {2, 21},
    {11, 1}
}

Can I do it using something implemented in java regular expressions? I think searching the matched strings is unnecessary, regex seems to have something ready for this kind of problem.
And... do regular expressions (in general, not only java regular expressions) have a tool for it so that no much additional programming is necessary to extract the information from the matched strings? It is possible for me to switch the programming language, if some other regex implementation is better than java's for this job.

A: You have just to use capturing groups by using parentheses in your regex:
Amount: (\d*) - Class (\d*)
        ^--^-- Here---^---^

Working demo
Then you have to grab the content from them with \1 and \2. In java you have to use the matcher.group(n). For instance, you can have a code like this:
String str = "0 - Amount: 3 - Class 29\n1 - Amount: 2 - Class 21\n2 - Amount: 11 - Class 1";

Pattern pattern = Pattern.compile("Amount: (\\d*) - Class (\\d*)");
Matcher matcher = pattern.matcher(str);

StringBuffer sb = new StringBuffer("{");
while (matcher.find()){
    sb.append(String.format("{%s, %s},", matcher.group(1), matcher.group(2)));
}
sb.setLength(sb.length()-1); // remove last comma
sb.append("}");

System.out.println(sb.toString())

Full IdeOne code


text:
Q: Change date type of entire image collection from Julian to gregorian date GEE I am having an image collection which contains two bands, one of them is called 'Date'. The format is in Julian format. However, for my analysis I need the dates in gregorian (normal calender i believe). I know that I can tranform each date using the function ee.Number.parse(ee.Date('2021-12-01').format('yyDDD')) if I want to convert from gregorian to Julian, but is it possible to map over the entire collection FROM Julian TO GREGORIAN without specifying each date?
My code is as follows:
var radd = ee.ImageCollection('projects/radar-wur/raddalert/v1');

print(radd);

var filterConfirmed = function(image){
  // get properties to copy over to output image
  var properties = image.propertyNames();

  // check if the 'Alert' property exists, if so, filter the confirmed alerts, if not set a new property called isBaseline
  var outImg = ee.Image(ee.Algorithms.If(

    // condition to check
    ee.List(image.bandNames()).contains('Alert'),

    // do if true
    image.updateMask(image.select('Alert').eq(2))        // mask out pixels that are not Alert=2
         .copyProperties(image, properties),

    // do if false
    ee.Image(0).set('isBaseline', 'baseline')));

    return outImg;

};

// map over original collection and select the confirmed alerts (if band exists)
var raddConfirmedCollection = radd.map(filterConfirmed);

// remove images that have the 'isBaseline' property
var raddConfirmedCollection = raddConfirmedCollection.filter(ee.Filter.neq('isBaseline', 'baseline'));

Alternatively, I could also change the way the code reads by dates to Julian. For example, I have this:
var dateSelect1 = ui.Textbox({placeholder:'aaaa-mm-dd', value: '2021-03-01'});
var dateSelect2 = ui.Textbox({placeholder:'aaaa-mm-dd', value: '2021-05-01'});
panel.add(dateSelect1);
panel.add(dateSelect2);

var fecha1 = ee.Date(interfazUser.dateSelect1.getValue());
var fecha2 = ee.Date(interfazUser.dateSelect2.getValue());
var date1 = ee.Number(fecha1.getRelative('day','year')); //convert analysis dates to julian formats,
var date2 = ee.Number(fecha2.getRelative('day','year'));
var dateYear1 = dateSelect1.slice(0,4);
var dateYear2 = dateSelect2.slice(0,4);

However, I do not know how to proceed.
My code is not working, for example here:
var date1 = ee.Number(fecha1.getRelative('day','year'));
var date2 = ee.Number(fecha2.getRelative('day','year'));
var dateYear1 = dateSelect1.slice(0,4);
var dateYear2 = dateSelect2.slice(0,4);

var timeNow = ee.Date(Date.now());
var yearNow = timeNow.get('year');
var yearPre = timeNow.advance(-1,'year').get('year');
var yearNowS = ee.String(yearNow).getInfo();
var yearPreS = ee.String(yearPre).getInfo();
var yearNowShort = ee.String(yearNow).slice(2,4).getInfo();
var yearPreShort = ee.String(yearPre).slice(2,4).getInfo();

var bandasPre = ['Date' + yearPreShort,'Alert'+ yearPreShort];
var bandasAct = ['Date'+ yearNowShort,'Alert'+ yearNowShort];
var bandasRADD;
var raddfilter;
//var mosaicoLandsatEnero;
var raddLast;
var lastAlerts,lastAlerts2,lastAlerts3,lastAlerts4,lastAlerts5;
var raddRegion = raddConfirmedCollection.filterBounds(region);
print(raddRegion, 'raddregion')

//Seleccion de alertas caso 1(añopre-añopre)
if(dateYear1 === yearPreS && dateYear2 === yearPreS ){
  raddfilter = raddRegion.filterDate(yearNowS +'-01-01',yearNowS +'-01-02');
  //raddfilter = raddRegion.filterDate(fecha1,fecha2);
  bandasRADD = bandasPre;
  //mosaicoLandsatEnero = funciones.landsatMosaic(ee.Date(yearPreS+'-01-01'),region).select(['red','nir','swir1','obsDate']);
  raddLast = raddfilter.sort('system:time_start',false).first();
  lastAlerts = raddLast.select(bandasRADD[1]).clip(region);
  lastAlerts2 = lastAlerts.selfMask();
  lastAlerts3 = lastAlerts2.where(raddLast.select(bandasRADD[0]).lt(date1),0);
  lastAlerts4 = lastAlerts3.where(raddLast.select(bandasRADD[0]).gt(date2),0);
  lastAlerts5 = lastAlerts4.selfMask();
}
//Seleccion de alertas caso 2(añopre-añoActual)
else {
if (dateYear1 === yearPreS && dateYear2 === yearNowS){
  radddfilter = raddRegion.filterDate(fecha1,fecha2);
  bandasRADD = bandasAct;
  //mosaicoLandsatEnero = funciones.landsatMosaic(fecha1,region).select(['red','nir','swir1','obsDate']);
  raddLast = raddfilter.sort('system:time_start',false).first();

  //Seleccion Año Pre
  lastAlerts = raddLast.select(bandasPre[1]).clip(region);
  var lastAlerts2_pre = lastAlerts.selfMask();
  var lastAlerts3_pre = lastAlerts2_pre.where(raddLast.select(bandasPre[0]).lt(date1),0);
  var lastAlerts5_pre = lastAlerts3_pre.selfMask().select([bandasPre[1]],[bandasAct[1]]);

  //Seleccion Año Actual
  lastAlerts = raddLast.select(bandasAct[1]).clip(region);
  var lastAlerts2_act = lastAlerts.selfMask();
  var lastAlerts3_act = lastAlerts2_act.where(raddLast.select(bandasAct[0]).gt(date2),0);
  var lastAlerts5_act = lastAlerts3_act.selfMask();

  //Union
  print(lastAlerts5_pre,lastAlerts5_act);
  lastAlerts2 = ee.ImageCollection.fromImages([lastAlerts2_pre.select([bandasPre[1]],[bandasAct[1]]),lastAlerts2_act]).reduce(ee.Reducer.lastNonNull()).select([bandasAct[1] +'_last'],[bandasAct[1]]);
  lastAlerts5 = ee.ImageCollection.fromImages([lastAlerts5_pre,lastAlerts5_act]).reduce(ee.Reducer.lastNonNull()).select([bandasAct[1] +'_last'],[bandasAct[1]]);
}
//Seleccion de alertas caso 3(añopre-añoActual)
else{
if (dateYear1 === yearNowS && dateYear2 === yearNowS){
  raddfilter = raddRegion.filterDate(fecha1,fecha2);
  bandasRADD = bandasAct;
  //mosaicoLandsatEnero = gladfilter.sort('system:time_start',true).first().select(['red','nir','swir1','obsDate']);
  radddLast = raddfilter.sort('system:time_start',false).first();
  lastAlerts = raddLast.select(bandasRADD[1]).clip(region);
  lastAlerts2 = lastAlerts.selfMask();
  lastAlerts3 = lastAlerts2.where(raddLast.select(bandasRADD[0]).lt(date1),0);
  lastAlerts4 = lastAlerts3.where(raddLast.select(bandasRADD[0]).gt(date2),0);
  lastAlerts5 = lastAlerts4.selfMask();
}}}

//var fechaExactaAlertayMosaico = ee.String(dateYear2).cat(ee.String('-')).cat(ee.String(raddLast.get('system:index')).slice(0,5).replace('_','-'));

print(dateYear2, 'dateyear2')
print(bandasRADD, 'bandasRADD')
print(raddfilter, 'radfilter')
//print(dateYear2,bandasRADD,raddRegion,raddfilter,fechaExactaAlertayMosaico);
print(dateYear2,bandasRADD,raddRegion,raddfilter)

//Imagen Landsat mes anterior
var fecha3 = fecha1.advance(-2,'month');
var fecha4 = fecha1.advance(-1,'day');
var raddfilter2 = raddRegion.filterDate(fecha3,fecha4);
var raddLast2 = raddfilter2.sort('system:time_start',false).first();

My raddfilter is empty, I think because it can not read the dates properly.
The entire code can be found here: https://code.earthengine.google.com/251087daf2580acb000d77fc70e03bd8?accept_repo=users%2FPrioGLADpy%2Fui_ES
Can anyone help me?

A: Your question is not clear to me. First, I'll boil this down as far as I can. It doesn't matter if you have an image collection, or if each image in that collection contains multiple bands. You have images where each pixel value represents a date. They're "formatted" as yyDDD. So, a pixel value of 21030 represents the date 2021-01-30.
You're asking how to convert such an image to a different format. You say you want to convert FROM Julian TO GREGORIAN. However, I would argue that you don't actually start with a Julian date. According to this, the Julian date for 2021-01-30 is 2459244.5, not 21030.
You're working with an image where dates are pixel values, not image properties, hence these dates can only be represent as numbers, I'm not sure what format you want to convert the dates to. Your idea of using ee.Date doesn't work when you're working with pixel values. It would be fine if the date was an image property.
Now, if you wanted to convert these dates to actual Julian dates, that's tricky, and an interesting challenge. I understand that it's not the question you're actually asking, but maybe it can give you some ideas how you can work with these types of date bands. Inspect the pixel values in the resulting layers:
var date = randomDateImage()
Map.addLayer(date, null, 'date')

var julian = toJulianDate(date)
Map.addLayer(julian, null, 'julian')
// Validate here: https://ssd.jpl.nasa.gov/tools/jdc/#/jd

function toJulianDate(yyDDD) {
  // With the yyDDD date format, it's impossible to tell which century the date is in.
  // Here we assume it's 2000.
  var year = yyDDD.divide(1000).int8()
    .add(2000)
  var dayOfYear = yyDDD.mod(1000)

  var leapYears = ee.Image(ee.Array( // Array image with leap years
    ee.List.sequence(1901, 2050)
      .map(function isLeapYear(year) {
        year = ee.Number(year)
        return ee.Date.fromYMD(year.add(1), 1, 1).advance(-1, 'day') // Last of year
          .getRelative('day', 'year').gt(364) // Got the extra day
          .multiply(year) // Return the actual year if a leap year or 0
      })
      .filter(ee.Filter.neq('item', 0))
  ))
  var numberOfLeapYears = leapYears
    .arrayMask(leapYears.lt(year)) // Mask out leap years after the year of the pixel
    .arrayLength(0) // Results in an image where the pixel value represents the number of leap years

  // https://www.typecalendar.com/julian-date
  return ee.Image().expression(
    '2415020 + 365 * (year - 1900) + N + L - 0.5', {
      year: year,
      N: dayOfYear,
      L: numberOfLeapYears
    }
  )
}

function randomDateImage() {
  var year = ee.Image.random().multiply(22).int8()
  var dayOfYear = ee.Image.random().multiply(364).int16()
  return year.multiply(1000).add(dayOfYear)
}

https://code.earthengine.google.com/61650eda74a5e84807fcb99368d0803f


text:
Q: How can i find if a variable has a special character in it? Im trying to find, in my javascript, if i can identify in a variable if a "@" sign is present in the variable.
 e = _("email").value;

 if(e don't contain "@"){
     alert("Dosnt contain @");
 }
 else {
     alert("email has @");
 }

A: You can use regular expressions to validate an email. Would be more easy to maintain and manage.
$('form input[name="email"]').blur(function () {
    var email = $(this).val();
    var re = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/igm;
    if (re.test(email)) {
        $('.msg').hide();
        $('.success').show();
    } else {
    $('.msg').hide();
    $('.error').show();
    }
});

LIVE EXAMPLE


text:
Q: How to define classes such that there will be only one Product object and multiple Product Details objects in c# Can someone give example how to "define classes such that there will be only one Product object and multiple Product Details objects in c#"?

A: Without knowing more information:
public class Product {
   public Product() {
      Details = new List<ProductDetails>();
   }
   public string Name {get; set;}
   public ICollection<ProductDetails> Details {get; private set;}
}

public class ProductDetails {
   public string SomeDetailedText {get; set;}
}


text:
Q: State not updating when using react hooks and progressCallback from Amplify Storage.put function I am attempting to use the Amplify Storage progressCallback function to add a visual indicator of upload progress but I am unable to update the state from inside the progressCallback function. The code below runs without any errors but fails to update the loading hook.
I believe this is an issue with how i am trying to pass the state to the  callBack function, but if this is the case i am not sure what the solution is. Would love some help.
const CustomCard = () => {
  const [loading, setLoading] = useState(null);

  const CustomFunc = progress => {
    setLoading(progress);
    console.log(loading);
  };

  const onChange = async e => {
    const file = e.target.files[0];
    const fileName = "test";
    const result = await Storage.put(fileName, file, {
      customPrefix: { public: "public/" },
      progressCallback: progress => {
        CustomFunc(progress.progress);
      },
    });
  };

  return (
    <React.Fragment>
       <input
           id="add-image-file-input"
           type="file"
           accept="image/*."
           onChange={onChange}
           style={{ display: "none" }}
       />
       <FileUploadProgress loading={loading} />
    </React.Fragment>
  )
}


text:
Q: Assembly not found after deleting package and Rebuild? New to asp.net i am trying to run the project described in asp.net zero docs using visual studio 2017.
When i build the project , i get warnings telling the absence of certain assemblies in the project:
System.RunTime
System.ObjectModel
System.Collections
System.Runtime

Searching for a solution  i deleted the package folder and then rebuilt the project but the same issue repeared.
 i find that i can download the assemblies using package manager  with help of nuget Gallery website , however when i install a missing package i get a message telling that the package already exist !!?
The package 'System.Collections.4.3.0' already exists in the project 'src \ Acme.PhoneBookDemo.Mobile.Droid'

what do you suggest to fix that problem ? or that is just a warning and it isn't important ?


text:
Q: 0-based index Combobox in Excel I am using Combobox Form control in Excel for my drop lists. I read on the net that the combobox is 0-based index. But when I use it, I find that it is 1-based index.
When I select the first element, it shows 1 in the linked cell and not zero.
Is there an easy way to make it 0-based index ? I want to display 0 when I select the first element and select the first element when i type 0 in the linked cell.
thanks,

A: *

*link the combo box to set its output to cell A1 for example.

*in cell B2 type =A1-1


text:
Q: How can I set the MAILTO variable for an at job on AIX? I'm calling at jobs on AIX servers using this method:
/usr/bin/at now +1 minute << EOF
chmod 700 /var/tmp/somescript.sh
cd /var/tmp
sh /var/tmp/somescript.sh > 2>&1
EOF
If ever some output is generated (because i.e. the script I'm calling doesn't exist), an email is sent to the default mail configured for cron jobs. I know this is default behavior and that is fine. However, if I want to change the MAILTO variable used, how can I do it using the method above ?
I tried adding MAILTO=myaddress@mydomain.com in the at script but that didn't work. The mail still went to the default address.
i.e.
/usr/bin/at now +1 minute << EOF
MAILTO=myaddress@mydomain.com
chmod 700 /var/tmp/somescript.sh
cd /var/tmp
sh /var/tmp/somescript.sh > 2>&1
EOF
The reason I'm using this method is because the jobs are created on a fly by another system, but this is irrelevant. I need to do it this way and can't edit the crontab.

A: Turns out there was an alias defined for root in /etc/mail/aliases and this is where it was coming from. There's no way for me to bypass it per-command with this on, as any mail sent to root's mailbox will automatically get forwarded to that alias.


text:
Q: Input a list of files I want to include multiple files in my source.
The files are to be included in a file liste.tex in the following format:
fichier1.tex
files2.tex
test3.tex
....

I relied on answering the questions TikZ read out file
but the last comma added problem
How not add (or remove) the last comma
\documentclass{article}
\usepackage{catchfile,tikz}

\begin{document}

  \CatchFileDef{\tempa}{assocFile.dat}{\endlinechar=`,}
\edef\tempb{\unexpanded{\foreach\tt in }{\unexpanded\expandafter{\tempa}}}
\tempb{\tt \par}

\tempb{
\input{\tt}
\clearpage
}

\end{document}

A: Here's an implementation along the same idea, where the trailing comma is not a problem because \clist_map_inline:nn ignores empty items:
\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\multinput}{sm}
 {
  \IfBooleanTF{#1}
   {
    \rpapa_multinput_list:n { #2 }
   }
   {
    \rpapa_multinput_file:n { #2 }
   }
 }

\tl_new:Nn \l_rpapa_multinput_files_tl

\cs_new_protected:Nn \rpapa_multinput_file:n
 {
  \tl_set_from_file:Nnn \l_rpapa_multinput_files_tl { \endlinechar=`, } { #1 }
  \rpapa_multinput_list:V  \l_rpapa_multinput_files_tl
 }
\cs_new_protected:Nn \rpapa_multinput_list:n
 {
  \clist_map_inline:nn { #1 } { \input{##1}\par }
 }
\cs_generate_variant:Nn \rpapa_multinput_list:n { V }
\ExplSyntaxOff

\begin{document}

\multinput{assocFile.dat}

\bigskip

\multinput*{fichier1,files2,test3}

\end{document}

The input files just contain `I am ". Note that the *-variant takes as argument a comma separated list of file names.

A second implementation, where the "filename" case is dealt with doing a mapping on the file itself:
\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\multinput}{sm}
 {
  \IfBooleanTF{#1}
   {
    \rpapa_multinput_list:n { #2 }
   }
   {
    \rpapa_multinput_file:n { #2 }
   }
 }

\cs_new_protected:Nn \rpapa_multinput_list:n
 {
  \clist_map_inline:nn { #1 } { \input{##1}\par }
 }

\ior_new:N \g_rpapa_multinput_file_stream

\cs_new_protected:Nn \rpapa_multinput_file:n
 {
  \ior_open:Nn \g_rpapa_multinput_file_stream { #1 }
  \ior_map_inline:Nn \g_rpapa_multinput_file_stream
   {
    \input{##1}\par
   }
 }
\ExplSyntaxOff

\begin{document}

\multinput{assocFile.dat}

\bigskip

\multinput*{fichier1,files2,test3}

\end{document}

A: Say you have ch1.tex, ch2.tex, ch3.tex and you want to include them in main.tex
main.tex
\documentclass{article}

\usepackage{pgffor}    % for \foreach
\usepackage{blindtext} % for blind text in ch1, ch2, ch3

\begin{document}

\foreach \i in {ch1,ch2,ch3}{
        \input{ \i }
}

\end{document}

ch1.tex
\begin{center}
\Large{Chapter 1.}
\end{center}
\blindtext

ch2.tex
\begin{center}
\Large{Chapter 2.}
\end{center}
\blindtext

ch3.tex
\begin{center}
\Large{Chapter 3.}
\end{center}
\blindtext

The output is


text:
Q: SilverStripe ModelAdmin searchableFields function to map the fields with main text search box at the top I am working on a SilverStripe project. In my project, I am creating a ModelAdmin class to display the custom DataObject. I am also customizing the search/ filter fields by overriding the searchableFields function of the DataObject.
This is my simple searchableFields function of my DataObject class called Item.
public function searchableFields()
{
    return [
        'Title' => [
            'filter' => 'PartialMatchFilter',
            'title' => 'Title',
            'field' => TextField::class,
        ],
    ];
}

I can see the field in the filter form as in the screenshot below.

As you can see in the code, the title field will be mapped to the Title column of the Item data object in the database. But I also want to do some more customization on the search. As you can see, there is a big long search box above the filter form. For example, I want to configure that main search box to search through the Title column. Maybe other columns too. Maybe ID and Title columns. How can I configure that?


text:
Q: Trigger all buttons of the same Id I have a grid in which I have a series of buttons (made using the ASP.Net MVC helper) that send Ajax requests. However I have also added a master button to trigger all buttons implemented in the grid. All my Ajax button have the same ID. However when I use the trigger method like
$("#myBtn").trigger("click")

only the first button is triggered. Is it possible to trigger all buttons with the same id using a similar approach?

A: Not recommended since id should be unique, but you can do this to trigger the click action on all elements with id myBtn:
$('[id=myBtn]').trigger('click');

A: Value of the attribute id should be unique. The same id value cannot be assigned to different elements. Selector by id returns a single element. Use class selector instead
$(".myBtn").trigger("click")


text:
Q: How to use triggers in Mysql Guys I'm exploring triggers in MySQL and I'm a bit confused. I have created this tables:
persons

pid #primary key
last_name
first_name

then this table:
employee_hierarchy

emp_id #primary key
pid #foreign key
role

And created this trigger:
CREATE TRIGGER after_person_insert
AFTER INSERT ON persons
FOR EACH ROW
INSERT INTO employee_hierarchy
VALUES('','LAST_INSERT_ID()','employee');

TRIGGER Successfully created. But whenever I try to insert to persons table, i got a foreign key something error. So I dropped the foreign key and it was a success. But whats the use of this trigger thingy? Can you site a good example where this is useful? cause maybe this is not designed  to update foreign keys, i dont know.

A: Instead of trying to get a value from LAST_INSERT_ID() (BTW you insert a string since it is in quotes) you just need need to read assigned value from NEW.pid. It is available to you at this point AFTER INSERT of time.
CREATE TRIGGER after_person_insert
AFTER INSERT ON persons
FOR EACH ROW
  INSERT INTO employee_hierarchy
  VALUES(NULL, NEW.pid, 'employee');

Here is SQLFiddle demo


text:
Q: Speedometer using HTML5 and websocket Hi all i developed a speedometer using javascript and i have given a button and a textfeild in which if we give some values on text feild the needle in the speedometer will move. Now i also created a websocket and i want to move the neddle dyanmically using the websocket server. The thing is the websocket code is working fine but i cant move the needle dynamically using the web socket. So, can anyone please help me out with code. this is the code for speedometer.So guys please help me to move the needle on the speedometer dynamically using the websocket.
(function () {
    "use strict";
    // this function is strict...
}());
var iCurrentSpeed = 20,
    iTargetSpeed = 20,
    bDecrement = null,
    job = null;

function degToRad(angle) {
    // Degrees to radians
    return ((angle * Math.PI) / 180);
}

function radToDeg(angle) {
    // Radians to degree
    return ((angle * 180) / Math.PI);
}

function drawLine(options, line) {
    // Draw a line using the line object passed in
    options.ctx.beginPath();
    // Set attributes of open
    options.ctx.globalAlpha = line.alpha;
    options.ctx.lineWidth = line.lineWidth;
    options.ctx.fillStyle = line.fillStyle;
    options.ctx.strokeStyle = line.fillStyle;
    options.ctx.moveTo(line.from.X,
        line.from.Y);
    // Plot the line
    options.ctx.lineTo(
        line.to.X,
        line.to.Y
    );
    options.ctx.stroke();
}

function createLine(fromX, fromY, toX, toY, fillStyle, lineWidth, alpha) {
    // Create a line object using Javascript object notation
    return {
        from: {
            X: fromX,
            Y: fromY
        },
        to: {
            X: toX,
            Y: toY
        },
        fillStyle: fillStyle,
        lineWidth: lineWidth,
        alpha: alpha
    };
}

function drawOuterMetallicArc(options) {
    /* Draw the metallic border of the speedometer
     * Outer grey area
     */
    options.ctx.beginPath();
    // Nice shade of grey
    options.ctx.fillStyle = "rgb(127,127,127)";
    // Draw the outer circle
    options.ctx.arc(options.center.X,
        options.center.Y,
        options.radius,
        0,
        Math.PI,
        true);
    // Fill the last object
    options.ctx.fill();
}

function drawInnerMetallicArc(options) {
    /* Draw the metallic border of the speedometer
     * Inner white area
     */
    options.ctx.beginPath();
    // White
    options.ctx.fillStyle = "rgb(255,255,255)";
    // Outer circle (subtle edge in the grey)
    options.ctx.arc(options.center.X,
        options.center.Y, (options.radius / 100) * 90,
        0,
        Math.PI,
        true);
    options.ctx.fill();
}

function drawMetallicArc(options) {
    /* Draw the metallic border of the speedometer
     * by drawing two semi-circles, one over lapping
     * the other with a bot of alpha transparency
     */
    drawOuterMetallicArc(options);
    drawInnerMetallicArc(options);
}

function drawBackground(options) {
    /* Black background with alphs transparency to
     * blend the edges of the metallic edge and
     * black background
     */
    var i = 0;
    options.ctx.globalAlpha = 0.2;
    options.ctx.fillStyle = "rgb(0,0,0)";
    // Draw semi-transparent circles
    for (i = 170; i < 180; i++) {
        options.ctx.beginPath();
        options.ctx.arc(options.center.X,
            options.center.Y,
            i,
            0,
            Math.PI,
            true);
        options.ctx.fill();
    }
}

function applyDefaultContextSettings(options) {
    /* Helper function to revert to gauges
     * default settings
     */
    options.ctx.lineWidth = 2;
    options.ctx.globalAlpha = 0.5;
    options.ctx.strokeStyle = "rgb(255, 255, 255)";
    options.ctx.fillStyle = 'rgb(255,255,255)';
}

function drawSmallTickMarks(options) {
    /* The small tick marks against the coloured
     * arc drawn every 5 mph from 10 degrees to
     * 170 degrees.
     */
    var tickvalue = options.levelRadius - 8,
        iTick = 0,
        gaugeOptions = options.gaugeOptions,
        iTickRad = 0,
        onArchX,
        onArchY,
        innerTickX,
        innerTickY,
        fromX,
        fromY,
        line,
        toX,
        toY;
    applyDefaultContextSettings(options);
}

function drawLargeTickMarks(options) {
    /* The large tick marks against the coloured
     * arc drawn every 10 mph from 10 degrees to
     * 170 degrees.
     */
    var tickvalue = options.levelRadius - 8,
        iTick = 0,
        gaugeOptions = options.gaugeOptions,
        iTickRad = 0,
        innerTickY,
        innerTickX,
        onArchX,
        onArchY,
        fromX,
        fromY,
        toX,
        toY,
        line;
    applyDefaultContextSettings(options);
    tickvalue = options.levelRadius - 2;
    // 10 units (major ticks)
    for (iTick = 50; iTick < 145; iTick += 20) {
        iTickRad = degToRad(iTick);
        /* Calculate the X and Y of both ends of the
         * line I need to draw at angle represented at Tick.
         * The aim is to draw the a line starting on the
         * coloured arc and continueing towards the outer edge
         * in the direction from the center of the gauge.
         */
        onArchX = gaugeOptions.radius - (Math.cos(iTickRad) * tickvalue);
        onArchY = gaugeOptions.radius - (Math.sin(iTickRad) * tickvalue);
        innerTickX = gaugeOptions.radius - (Math.cos(iTickRad) * gaugeOptions.radius);
        innerTickY = gaugeOptions.radius - (Math.sin(iTickRad) * gaugeOptions.radius);
        fromX = (options.center.X - gaugeOptions.radius) + onArchX;
        fromY = (gaugeOptions.center.Y - gaugeOptions.radius) + onArchY;
        toX = (options.center.X - gaugeOptions.radius) + innerTickX;
        toY = (gaugeOptions.center.Y - gaugeOptions.radius) + innerTickY;
        // Create a line expressed in JSON
        line = createLine(fromX, fromY, toX, toY, "rgb(127,127,127)", 3, 0.6);
        // Draw the line
        drawLine(options, line);
    }
}

function drawTicks(options) {
    /* Two tick in the coloured arc!
     * Small ticks every 5
     * Large ticks every 10
     */
    drawSmallTickMarks(options);
    drawLargeTickMarks(options);
}

function drawTextMarkers(options) {
    /* The text labels marks above the coloured
     * arc drawn every 10 mph from 10 degrees to
     * 170 degrees.
     */
    var innerTickX = 0,
        innerTickY = 0,
        iTick = 0,
        gaugeOptions = options.gaugeOptions,
        iTickToPrint = 80;
    applyDefaultContextSettings(options);
    // Font styling
    options.ctx.font = 'italic 10px sans-serif';
    options.ctx.textBaseline = 'top';
    options.ctx.beginPath();
    // Tick every 20 (small ticks)
    for (iTick = 50; iTick < 145; iTick += 20) {
        innerTickX = gaugeOptions.radius - (Math.cos(degToRad(iTick)) * gaugeOptions.radius);
        innerTickY = gaugeOptions.radius - (Math.sin(degToRad(iTick)) * gaugeOptions.radius);
        // Some cludging to center the values (TODO: Improve)
        if (iTick <= 10) {
            options.ctx.fillText(iTickToPrint, (options.center.X - gaugeOptions.radius - 12) + innerTickX, (gaugeOptions.center.Y - gaugeOptions.radius - 12) + innerTickY + 5);
        } else if (iTick < 50) {
            options.ctx.fillText(iTickToPrint, (options.center.X - gaugeOptions.radius - 12) + innerTickX - 5, (gaugeOptions.center.Y - gaugeOptions.radius - 12) + innerTickY + 5);
        } else if (iTick < 90) {
            options.ctx.fillText(iTickToPrint, (options.center.X - gaugeOptions.radius - 12) + innerTickX, (gaugeOptions.center.Y - gaugeOptions.radius - 12) + innerTickY);
        } else if (iTick === 90) {
            options.ctx.fillText(iTickToPrint, (options.center.X - gaugeOptions.radius - 12) + innerTickX + 4, (gaugeOptions.center.Y - gaugeOptions.radius - 12) + innerTickY);
        } else if (iTick < 145) {
            options.ctx.fillText(iTickToPrint, (options.center.X - gaugeOptions.radius - 12) + innerTickX + 10, (gaugeOptions.center.Y - gaugeOptions.radius - 12) + innerTickY);
        } else {
            options.ctx.fillText(iTickToPrint, (options.center.X - gaugeOptions.radius - 12) + innerTickX + 15, (gaugeOptions.center.Y - gaugeOptions.radius - 12) + innerTickY + 5);
        }
        // MPH increase by 10 every 20 degrees
        iTickToPrint += Math.round(2160 / 9);
    }
    options.ctx.stroke();
}

function drawSpeedometerPart(options, alphaValue, strokeStyle, startPos) {
    /* Draw part of the arc that represents
     * the colour speedometer arc
     */
    options.ctx.beginPath();
    options.ctx.globalAlpha = alphaValue;
    options.ctx.lineWidth = 5;
    options.ctx.strokeStyle = strokeStyle;
    options.ctx.arc(options.center.X,
        options.center.Y,
        options.levelRadius,
        Math.PI + (Math.PI / 360 * startPos),
        0 - (Math.PI / 360 * 10),
        false);
    options.ctx.stroke();
}

function drawSpeedometerColourArc(options) {
    /* Draws the colour arc.  Three different colours
     * used here; thus, same arc drawn 3 times with
     * different colours.
     * TODO: Gradient possible?
     */
    var startOfGreen = 100,
        endOfGreen = 180,
        endOfOrange = 220,
        endofRed = 260;
    drawSpeedometerPart(options, 1.0, "rgb(82, 240, 55)", startOfGreen);
    drawSpeedometerPart(options, 0.9, "rgb(198, 111, 0)", endOfGreen);
    drawSpeedometerPart(options, 0.9, "rgb(255, 0, 0)", endOfOrange);
    drawSpeedometerPart(options, 1.0, "rgb(0,0, 0,2)", endofRed);
}

function drawNeedleDial(options, alphaValue, strokeStyle, fillStyle) {
    /* Draws the metallic dial that covers the base of the
     * needle.
     */
    var i = 0;
    options.ctx.globalAlpha = alphaValue;
    options.ctx.lineWidth = 3;
    options.ctx.strokeStyle = strokeStyle;
    options.ctx.fillStyle = fillStyle;
    // Draw several transparent circles with alpha
    for (i = 0; i < 30; i++) {
        options.ctx.beginPath();
        options.ctx.arc(options.center.X,
            options.center.Y,
            i,
            0,
            Math.PI,
            true);
        options.ctx.fill();
        options.ctx.stroke();
    }
}

function convertSpeedToAngle(options) {
    /* Helper function to convert a speed to the
     * equivelant angle.
     */
    var iSpeed = (options.speed / 10),
        iSpeedAsAngle = ((iSpeed * 20) + 10) % 180;
    // Ensure the angle is within range
    if (iSpeedAsAngle > 180) {
        iSpeedAsAngle = iSpeedAsAngle - 180;
    } else if (iSpeedAsAngle < 0) {
        iSpeedAsAngle = iSpeedAsAngle + 180;
    }
    return iSpeedAsAngle;
}

function drawNeedle(options) {
    /* Draw the needle in a nice read colour at the
     * angle that represents the options.speed value.
     */
    var iSpeedAsAngle = convertSpeedToAngle(options),
        iSpeedAsAngleRad = degToRad(iSpeedAsAngle),
        gaugeOptions = options.gaugeOptions,
        innerTickX = gaugeOptions.radius - (Math.cos(iSpeedAsAngleRad) * 20),
        innerTickY = gaugeOptions.radius - (Math.sin(iSpeedAsAngleRad) * 20),
        fromX = (options.center.X - gaugeOptions.radius) + innerTickX,
        fromY = (gaugeOptions.center.Y - gaugeOptions.radius) + innerTickY,
        endNeedleX = gaugeOptions.radius - (Math.cos(iSpeedAsAngleRad) * gaugeOptions.radius),
        endNeedleY = gaugeOptions.radius - (Math.sin(iSpeedAsAngleRad) * gaugeOptions.radius),
        toX = (options.center.X - gaugeOptions.radius) + endNeedleX,
        toY = (gaugeOptions.center.Y - gaugeOptions.radius) + endNeedleY,
        line = createLine(fromX, fromY, toX, toY, "rgb(255,0,0)", 5, 0.6);
    drawLine(options, line);
    // Two circle to draw the dial at the base (give its a nice effect?)
    drawNeedleDial(options, 0.6, "rgb(127, F27, 127)", "rgb(255,255,255)");
    drawNeedleDial(options, 0.2, "rgb(127, 127, 127)", "rgb(127,127,127)");
}

function buildOptionsAsJSON(canvas, iSpeed) {
    /* Setting for the speedometer
     * Alter these to modify its look and feel
     */
    var centerX = 210,
        centerY = 210,
        radius = 140,
        outerRadius = 200;
    // Create a speedometer object using Javascript object notation
    return {
        ctx: canvas.getContext('2d'),
        speed: iSpeed,
        center: {
            X: centerX,
            Y: centerY
        },
        levelRadius: radius - 10,
        gaugeOptions: {
            center: {
                X: centerX,
                Y: centerY
            },
            radius: radius
        },
        radius: outerRadius
    };
}

function clearCanvas(options) {
    options.ctx.clearRect(0, 0, 800, 600);
    applyDefaultContextSettings(options);
}

function draw() {
    /* Main entry point for drawing the speedometer
     * If canvas is not support alert the user.
     */
    console.log('Target: ' + iTargetSpeed);
    console.log('Current: ' + iCurrentSpeed);
    var canvas = document.getElementById('tutorial'),
        options = null;
    // Canvas good?
    if (canvas !== null && canvas.getContext) {
        options = buildOptionsAsJSON(canvas, iCurrentSpeed);
        // Clear canvas
        clearCanvas(options);
        // Draw the metallic styled edge
        drawMetallicArc(options);
        // Draw thw background
        drawBackground(options);
        // Draw tick marks
        drawTicks(options);
        // Draw labels on markers
        drawTextMarkers(options);
        // Draw speeometer colour arc
        drawSpeedometerColourArc(options);
        // Draw the needle and base
        drawNeedle(options);
    } else {
        alert("Canvas not supported by your browser!");
    }
    if (iTargetSpeed == iCurrentSpeed) {
        clearTimeout(job);
        return;
    } else if (iTargetSpeed < iCurrentSpeed) {
        bDecrement = true;
    } else if (iTargetSpeed > iCurrentSpeed) {
        bDecrement = false;
    }
    if (bDecrement) {
        if (iCurrentSpeed - 10 < iTargetSpeed)
            iCurrentSpeed = iCurrentSpeed - 1;
        else
            iCurrentSpeed = iCurrentSpeed - 5;
    } else {
        if (iCurrentSpeed + 10 > iTargetSpeed)
            iCurrentSpeed = iCurrentSpeed + 1;
        else
            iCurrentSpeed = iCurrentSpeed + 5;
    }
    job = setTimeout("draw()", 5);
}

function drawWithInputValue() {
    var txtSpeed = document.getElementById('txtSpeed');
    if (txtSpeed !== null) {
        iTargetSpeed = txtSpeed.value;
        // Sanity checks
        if (isNaN(iTargetSpeed)) {
            iTargetSpeed = 20;
        } else if (iTargetSpeed < 20) {
            iTargetSpeed = 20;
        } else if (iTargetSpeed > 60) {
            iTargetSpeed = 60;
        }
        job = setTimeout("draw()", 5);
    }
}

and this is the code for websocket
<!DOCTYPE html>

        <title>Jeff Test HTML5 WebSocket</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">

            <input type="text" id="messageinput"/>

            <button type="button" onclick="openSocket();" >Open</button>
            <button type="button" onclick="drawWithInputValue();" ></button>
            <button type="button" onclick="closeSocket();" >Close</button>

This is the code i missed at the end of the web socket code.

A: So the best i can tell, the only thing you need to get working is somehow trigger the canvas draw when a websocket message is delivered. I made some changes to the code you provided just so its complete, you have some things missing like the canvas and correct text input id, and created a jsfiddle with it. Essentiall all you have to change is the onmessage eventhandler and the drawWithInputValue function, to something like :
webSocket.onmessage = function(event){
  if(event.data.type == "speed"){
     drawWithInputValue(event.data.value);
  }
  writeResponse(event.data);
};

function drawWithInputValue(txtSpeed) {
    if (txtSpeed !== null) {
        iTargetSpeed = txtSpeed.value;
        // Sanity checks
        if (isNaN(iTargetSpeed)) {
            iTargetSpeed = 20;
        } else if (iTargetSpeed < 20) {
            iTargetSpeed = 20;
        } else if (iTargetSpeed > 60) {
            iTargetSpeed = 60;
        }
        job = setTimeout("draw()", 5);
    }
}

function drawWithInputValueLocal(){
     var txtSpeed = document.getElementById('messageinput');
   drawWithInputValue(txtSpeed)
}

Now in your onclick handler in your draw button, just change it to this:
 <button type="button" onclick="drawWithInputValueLocal();" >Draw</button>

So now when your websocket server sends a message in the format like:
{
   type : 'speed',
   value : 30
}

The onmessage event handler will check for that message type, then send the value over to the drawInputValue function.
On a final note, i'm not entirely sure why you have this closure at the top of your code seemingly doing nothing:
(function () {
    "use strict";
    // this function is strict...
}());

If you want to make your code modular, you'll need to put all your variables and functions inside it, then export it to be used by your page.
https://jsfiddle.net/wbotr9pw/23/


text:
Q: How to check whether stored procedure executed successfully If you have a stored procedure that executing multiple queries, doesn't return values and doesn't have error-handling in it, how can you ascertain whether the stored procedure ended successfully when calling from VB code?
For example, if the stored procedure is something like:
create stored procedure some_procedure
    Insert  into ...
    delete ...
    update ...
end

... and the VB code is like this:
Cmd.ActiveConnection = cn
Cmd.CommandText = "some_procedure"
Cmd.CommandType = adCmdStoredProc
Set rs = Cmd.Execute
Debug.Print rs(0)

... then how can I get a return value that is 0 for success or 1 for failure?

A: I believe passing the optional RecordsAffected parameter with the Execute statement will work for you. Since you're so scarce on the details you'll have to try it, but this has worked for me with SQL, and FoxPro OLEDB providers. Also, why no error handling? IMHO not having an error handler in code that has a good possibility of producing an error is asking for trouble.
...
Dim lngRecsAffctd As Long

Cmd.ActiveConnection = cn
Cmd.CommandText = "some_procedure"
Cmd.CommandType = adCmdStoredProc
Cmd.Execute lngRecsAffctd, ,adCmdStoredProc   'why set to a recordset when the sproc doesn't return anything?
Debug.Print lngRecsAffctd
...

The complete details of the Execute command and the RecordsAffected parameter can be found at msdn.microsoft.com/en-us/library/ms681559%28v=vs.85%29.aspx


text:
Q: MySql: How to reduce execution time of this Query? How to customize this query, It takes around 30 Second to take out results, total records in 'videos' table are about 0.5 million, 3 million members are present in 'Members' Table, is there any alternate Query or should i break this query in 2 select queries ?
user_id is Indexed
vid_id  is Indexed
select a.ref_url , a.source , a.video_name , a.viewers , b.username ,
c.points from
members_videos a
inner join Members b on a.user_id = b.user_id
inner join rankings      c on c.user_id = b.user_id

where a.cat_ids in (123,234,52,234,423,122) not in (110,99)
order by a.vid_id Desc limit 10

A: There are multiple factors:

*

*Make sure members_videos, Members and rankings have index on user_id column.

*Break the query; eliminate Order By clause. Get the data in temporary table.

*Select the data from temporary table and put Order By Clause over there.

Alternate, try sub-query.
SELECT *
FROM
(
select a.ref_url , a.source , a.video_name , a.viewers , b.username ,
c.points from
members_videos a
inner join Members b on a.user_id = b.user_id
inner join rankings      c on c.user_id = b.user_id
where a.cat_ids in (123,234,52,234,423,122) not in (110,99)
) as T
order by T.vid_id Desc limit 10