text:
Q: Android.Media.MediaRecorder - delay when recording audio, with sections of silence Please help solve the problem. To record an audio file, I use Android.Media.MediaRecorder. As a result, I get a section with silence 650 milliseconds at the beginning and at the end of the file. And it turns out that part of the phrase at the beginning and at the end is not recorded, only silence.
public static async Task Record(CancellationToken token)
    {
        try
        {
            var filename = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "/temp.amr";
            var tmp = new Java.IO.File(filename);
            if (tmp.Exists()) tmp.Delete();
            var recorder = new MediaRecorder();
            recorder.SetAudioSource(AudioSource.Mic);
            recorder.SetOutputFormat(OutputFormat.AmrNb);
            recorder.SetAudioEncoder(AudioEncoder.AmrNb);
            recorder.SetOutputFile(filename);
            recorder.Prepare();
            recorder.Start();
            try
            {
                var div = MAX_RECORD_TIME / 100;
                for(int i=0; i<div; i++)
                {
                    IncrementProgressBar(100 / div);
                    await Task.Delay(div, token);
                }
                fSave = true;
            }
            catch (OperationCanceledException) { }
            recorder.Stop();
        }
        catch (Exception e)
        {
            string s = context.GetText(Resource.String.err_unexpected) + "\r" + e.Message;
            handler.ToastMessage(s, ToastLength.Short);
        }
    }

A: This problem cannot be adressed through code, It seems like it is a hardware problem.
You can see the same delay in the default Camera app, which also uses MediaRecorder.
Unfortunately some device will behave differently.
The Solution is to use the AudioRecorder class which is by far more flexible since it is closer to the hardware

A: Found a solution for myself. The following code is working, it may be useful to someone.
    public static async Task Record(CancellationToken token)
    {
        var filename = Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "/wav.pcm";
        System.IO.Stream outputStream = System.IO.File.Open(filename, FileMode.Create);
        BinaryWriter bWriter = new BinaryWriter(outputStream);
        var audioBuffer = new byte[8000];
        var audRecorder = new AudioRecord(AudioSource.Mic, 8000, ChannelIn.Mono, Encoding.Pcm16bit, audioBuffer.Length);
        while(audRecorder.State != State.Initialized) { }
        audRecorder.StartRecording();
        while (!token.IsCancellationRequested)
        {
            try
            {
                var audioData = await audRecorder.ReadAsync(audioBuffer, 0, audioBuffer.Length);
                bWriter.Write(audioBuffer);
                IncrementProgressBar(1);
            }
            catch (Exception ex)
            {
                System.Console.Out.WriteLine("INFO: " + ex.Message);
                break;
            }
        }
        outputStream.Close();
        bWriter.Close();
        audRecorder.Stop();
        audRecorder.Release();
        fSave = true;
    }
    public static async Task Play(CancellationToken token)
    {
        var filename = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "/wav.pcm";
        var audBuffer = await System.IO.File.ReadAllBytesAsync(filename, token);
        var bufferSizeInBytes = audBuffer.Length / 2;
        AudioTrack audioTrack;
        if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
        {
            AudioAttributes attributes = new AudioAttributes.Builder().SetLegacyStreamType(Android.Media.Stream.Music)
                                                                    .Build();
            AudioFormat format = new AudioFormat.Builder().SetChannelMask(ChannelOut.Mono)
                                                            .SetEncoding(Encoding.Pcm16bit)
                                                            .SetSampleRate(8000)
                                                            .Build();
            audioTrack = new AudioTrack(attributes, format, bufferSizeInBytes, AudioTrackMode.Stream, 1);
        }
        else
        {
            audioTrack = new AudioTrack(Android.Media.Stream.Music, 8000, ChannelOut.Mono,
                                        Encoding.Pcm16bit, bufferSizeInBytes, AudioTrackMode.Stream);
        }
        audioTrack.Play();
        await audioTrack.WriteAsync(audBuffer, 0, bufferSizeInBytes*2);
        try
        {
            await Task.Delay(((bufferSizeInBytes/8000)-1)*1000, token);
        }
        catch (OperationCanceledException) { }
        audioTrack.Stop();
        audioTrack.Release();
    }
    public static async Task SaveAsAmr()
    {
        var encoder = MediaCodec.CreateEncoderByType(MediaFormat.MimetypeAudioAmrNb);
        MediaFormat format = new MediaFormat();
        format.SetString(MediaFormat.KeyMime, MediaFormat.MimetypeAudioAmrNb);
        format.SetInteger(MediaFormat.KeySampleRate, 8000);
        format.SetInteger(MediaFormat.KeyChannelCount, 1);
        format.SetInteger(MediaFormat.KeyBitRate, 7936);
        encoder.Configure(format, null, null, MediaCodecConfigFlags.Encode);

        try
        {
            Java.IO.File pcmFile = new Java.IO.File(Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "/wav.pcm");
            FileInputStream fis = new FileInputStream(pcmFile);
            Java.IO.File armFIle = new Java.IO.File(Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "/wav.amr");
            FileOutputStream fos = new FileOutputStream(armFIle);
            fos.Write(System.Text.Encoding.ASCII.GetBytes("#!AMR\n"));
            encoder.Start();

            var tempBuffer = new byte[8000];
            var hasMoreData = true;
            MediaCodec.BufferInfo outBuffInfo = new MediaCodec.BufferInfo();
            double presentationTimeUs = 0;
            int totalBytesRead = 0;

            do
            {
                int inputBufIndex = 0;
                while (inputBufIndex != -1 && hasMoreData)
                {
                    inputBufIndex = encoder.DequeueInputBuffer(0);
                    if (inputBufIndex >= 0)
                    {
                        Java.Nio.ByteBuffer dstBuf;
                        if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
                        {
                            dstBuf = encoder.GetInputBuffer(inputBufIndex);
                        }
                        else
                        {
                            dstBuf = encoder.GetInputBuffers()[inputBufIndex];
                        }
                        dstBuf.Clear();

                        int bytesRead = await fis.ReadAsync(tempBuffer, 0, dstBuf.Limit());
                        if (bytesRead == -1)
                        { // -1 implies EOS
                            hasMoreData = false;
                            encoder.QueueInputBuffer(inputBufIndex, 0, 0, (long)presentationTimeUs, MediaCodecBufferFlags.EndOfStream);
                        }
                        else
                        {
                            totalBytesRead += bytesRead;
                            dstBuf.Put(tempBuffer, 0, bytesRead);
                            encoder.QueueInputBuffer(inputBufIndex, 0, bytesRead, (long)presentationTimeUs, 0);
                            presentationTimeUs = 1000000L * (totalBytesRead / 2) / 8000;
                        }
                    }
                }
                // Drain audio
                int outputBufIndex = 0;
                while (outputBufIndex != (int)MediaCodecInfoState.TryAgainLater)
                {
                    outputBufIndex = encoder.DequeueOutputBuffer(outBuffInfo, 0);
                    if (outputBufIndex >= 0)
                    {
                        Java.Nio.ByteBuffer encodedData;
                        if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
                        {
                            encodedData = encoder.GetOutputBuffer(outputBufIndex);
                        }
                        else
                        {
                            encodedData = encoder.GetOutputBuffers()[outputBufIndex];
                        }
                        encodedData.Position(outBuffInfo.Offset);
                        encodedData.Limit(outBuffInfo.Offset + outBuffInfo.Size);
                        byte[] outData = new byte[outBuffInfo.Size];
                        encodedData.Get(outData, 0, outBuffInfo.Size);
                        fos.Write(outData, 0, outBuffInfo.Size);
                        encoder.ReleaseOutputBuffer(outputBufIndex, false);
                    }
                }
            } while (outBuffInfo.Flags != MediaCodecBufferFlags.EndOfStream);
            fis?.Close();
            fos?.Flush();
            fos?.Close();
        }
        catch(Exception ex)
        {
            System.Console.Out.WriteLine("INFO: " + ex.Message);
        }
    }


text:
Q: Javascript code executes before it have to why does "cars[0].name = 37" executes earlier than it have to?

var cars = [{name: "First"}, {name: "Second"}, {name: "Third"}];
var guns = [];

for (var i = 0; i < cars.length; i++) {
  guns.push(cars[i]);
}

console.log(guns);  // [{name: 37}, {name: "Second"}, {name: "Third"}]

cars[0].name = 37;

I've heard about hoisting, does it have something to do with it?
https://jsfiddle.net/r3wu867c/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ajax PHP not inserting into MySQL database I'm using Ajax to get POST values from a form. However, when I try to insert the form values in a database on submit, it doesn't get inserted. I still have no idea why it does not work.
Here is my HTML
<form method="post" action="" id="home-sign-up-form">
    <input type="text" name="suFirstName" placeholder="First Name" class="text-input-minor" id="sign-up-first-name-text-input">
    <input type="text" name="suLastName" placeholder="Last Name" class="text-input-minor" id="sign-up-last-name-text-input">
    <input type="text" name="suEmail" placeholder="Email" class="text-input-minor" id="sign-up-email-text-input">
    <input type="password" name="suPassword" placeholder="Password" class="text-input-minor" id="sign-up-password-text-input">
    <input type="password" name="suConfirmPassword" placeholder="Confirm Password" class="text-input-minor" id="sign-up-confirm-password-text-input">
    <input type="text" name="suDisplayName" placeholder="Display Name (you can change this later)" class="text-input-minor" id="sign-up-display-name-text-input">

    <input type="checkbox" name="suRememberMe" value="yes" id="sign-up-remember-me-checkbox">Remember me
    <input name="signUp" type="submit" value="Sign Up" id="sign-up-submit">
</form>

My JS (the console.log does go through and work):
if (validForm)
{
    console.log("valid form");
    $.ajax(
    {
        type:'POST',
        url:'form-submit.php',
        data:$('#home-sign-up-form').serialize(),
        success:function(response)
        {
            $suForm.hide();
            $tosppText.hide();
            $mailSentIcon.show();
            $emailSentText.show();
            $emailSentTextEmail.text($suEmail);
            $suBox.css("padding-left", "10px");
            $suBox.css("padding-right", "10px");
        }
    });
}

And my PHP/MySQL:
if (isset($_POST['signUp']))
{
    echo "";
    $suFirstName = mysqli_real_escape_string($_POST['suFirstName']);
    $suLastName = mysqli_real_escape_string($_POST['suLastName']);
    $suEmail = mysqli_real_escape_string($_POST['suEmail']);
    $suPassword = mysqli_real_escape_string($_POST['suPassword']);
    $suDisplayName = mysqli_real_escape_string($_POST['suDisplayName']);
    $code = substr(md5(mt_rand()),0,15);

    $query = $connection->query("INSERT INTO users (firstName,lastName,email,password,displayName,confirmCode,verified)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}','{$confirmCode},'{$verified}')");
}

The alert in the PHP code so I would assume that it isn't getting the 'signUp' POST variable. Thanks so much! Any help is appreciated! :D

A: You get the signUp post variable when you click on the button. If you are posting via ajax call the button variable will not be available as $_POST variable. Please check any other input value.
Another options is have and hidden input set it to some value. And check it on server side. But it is better to check any normal required input of form instead of having extra input control.

A: $mysqli = new mysqli("localhost", "root", "", "test");

if (isset($_POST['signUp'])){
    echo "";
    echo $suFirstName = mysqli_real_escape_string($mysqli,$_POST['suFirstName']);
    echo $suPassword = mysqli_real_escape_string($mysqli,$_POST['suPassword']);
    $sql="INSERT INTO users (`username`, `password`) VALUES ('$suFirstName', '$suPassword')";
}

if (!mysqli_query($mysqli,$sql)) {
    die('Error: ' . mysqli_error($mysqli ));
}

echo "1 record added";

mysqli_real_escape_string requires two arguments the connection and the string.
You can read more :https://www.w3schools.com/php/func_mysqli_real_escape_string.asp


text:
Q: Changing legend label when cycling through Atlas created with QGIS composer I have project which gets updated regularly and can have multiple areas which need to be mapped individually to go into separate reports. I generate an atlas in the composer and I have created a rule-based style using the following:
attribute(  $currentfeature , 'id') =  attribute(  @atlas_feature , 'id')

This allow the user to go through each property, and if they are close together, then you only see the features for that specific area, not adjacent ones that might be in the map view. In the map composer, I can get the name of the area I am mapping and use in the title of the map using the string below (which changes each time you go to the next area within the atlas.
[% @atlas_pagename %] Rest of Title

One of the key issues i'm facing now is showing in the legend the areal measurement of what I am mapping. The following code; if I use a categorized style; will give me that label I am looking for (Property Boundary 100ha), but as it is not rule based, the surrounding features are not filtered out based on the atlas.
  concat('Property Boundary ',round(area(transform($geometry,'EPSG:4283','EPSG:3308') )/10000), 'ha')

I tried using a rule based system and then applied a categorised style, but the label came out as the following in the label.
concat('Property Boundary ',round(area(transform($geometry,'EPSG:4283','EPSG:3308') )/10000), 'ha') = 'Property Boundary = 100ha'
Is there a way I can filter polygons based upon the atlas and dynamically change the label/legend value to reflect the area using the tools within QGIS (without running Python scripts).

A: I think it may be a problem with where your /10000 is.
Try: concat('Property Boundary: ',round(area(transform($geometry,'ESPG:4283','ESPG:3308')))/10000,' ha')


text:
Q: displaying a list of entities in jsp file by using java I am trying to display list of entities in a .jsp file, but I this error:
Unable to compile class for JSP:

An error occurred at line: 28 in the jsp file: /guestbook.jsp
Can only iterate over an array or an instance of java.lang.Iterable
25:

26:

27:     <%
28:         for (Entity drugtarget : "${drugtargets}") {
29:         %>
30:
31:     <%

Here is my query from servlet class:
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query query = new Query("DrugTarget").addSort("drug", Query.SortDirection.DESCENDING);
List<Entity> drugtargets = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(10));

req.setAttribute("drugtargets", drugtargets);

And this is how I send drugtargets to jsp file:
String url = "/guestbook.jsp";
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
try {
    rd.forward(req, resp);
} catch (ServletException e) {
    e.printStackTrace();
}

Finally here is how I write jsp part:

    Drug Names
    Target Names

    <%
      for (Entity drugtarget : "${drugtargets}") {
    %>

    <%
      pageContext.setAttribute("drug_content",
                                drugtarget.getProperty("drug"));
    %>
    ${fn:escapeXml(drug_content)}

    <%
      pageContext.setAttribute("target_content",
                                drugtarget.getProperty("target"));
    %>
    ${fn:escapeXml(target_content)}

    <%
      }
    %>

I think I'm making a syntax mistake, but I'm not sure. I checked some examples and the same way (to send list of entities from servlet to jsp and to reach entities in jsp file) was used. How can I resolve this error?

A: You shouldn't be using scriptlets (those oldschool <% %> things with Java code) at all when using servlets and EL. Use taglibs like JSTL instead. It offers the <c:forEach> tag to iterate over a collection.
For example,
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...

    Drug Names
    Target Names

  <c:forEach items="${drugtargets}" var="drugtarget">

      ${fn:escapeXml(drugtarget.drug)}
      ${fn:escapeXml(drugtarget.target)}

  </c:forEach>

(note that I also fixed the rendering of table rows by putting the
 inside the loop)
Much simpler, isn't it? You can by the way also just use <c:out value="${drugtarget.drug}"/> instead of those functions.
If you can, I suggest to add the following to your webapp's web.xml in order to disable scriptlets altogether so that you will be forced to do things the right way.
<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>

    </jsp-property-group>
</jsp-config>

See also:

*

*How to avoid Java code in JSP files?

A: In this case "${drugtargets}" is a String, not the list you passed.  I would recommend using the  looping. It's way cleaner.
<c:forEach var="drugtarget " items="${drugtargets}">
.... Your code here ...
</c:forEach>


text:
Q: Google sheets - Count if column A text includes keywords from column B AND C In Google sheets, I have three columns (as set out below) each cell in column A has a block of text in. Column B is a set of keywords on coronavirus and column C is a set of keywords around data.
My goal is to find how many blocks of text talk about coronavirus statistics. I want to do that by counting how many cells in column A (text) contain any keyword from column B (coronavirus keywords) AND any keyword from column C (data keywords).

text
coronavirus keywords
data keywords

Yadda Yadda coronavirus yadda statistics
coronavirus
data

Yadda covid yadda
covid
statistics

Yadda covid statistics yadda yadda
COVID-19
stats

yadda yadda yadda
virus
trends

yadda yadda yadda yadda
illness

COVID-19 trends yadda yadda

covid yadda yadda stats

I've been trying with:
=ArrayFormula(SUM(COUNTIFS(A:A,B:B,A:A,C:C)))
Which produces an answer but I know it's wrong - it comes out as '1' but I know there's at least 5 matches.
Is there a way I can get this count?
Sorry, I can't share the actual sheets - work info.
Thanks!

A: try:
=INDEX(SUM(N(REGEXMATCH(A:A, "(?i)"&TEXTJOIN("|", 1, B2:C)))))

A: If an 'AND' function between the two lists of keywords is required (and possibly case insensitive match), I suggest
=SUMPRODUCT(REGEXMATCH(A:A, "(?i)"&TEXTJOIN("|", 1, B2:B))*REGEXMATCH(A:A, "(?i)"&TEXTJOIN("|", 1, C2:C)))


text:
Q: Passing a String Array Between Java Classes Android App I am writing an Android app where I need to pass a string array between two classes. The string initializes fine and I can output the contents of the string fine in the one class but as I try to pass it to another class I get a Null Pointer Exception error. The following is the stripped down version of my code:
accelerometer.java:
    public class accelerometer extends Service {

 public String movement[];

 public void onCreate() {

  movement = new String[1000000];

 }

 public void updatearray() {
  movement[arraypos]=getCurrentTimeString();
  //Toast.makeText(this, movement[arraypos] , Toast.LENGTH_SHORT).show(); //this correctly displays each position in the array every time it updates so I know the array is working correctly in this file
  arraypos+=1;
 }

 public String[] getmovement(){
  return movement;
 }
    }

wakeupalarm.java:
    public class wakeupalarm extends Activity {

 private TextView herestext_;

 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.wakeup);

  herestext_ = (TextView) findViewById(R.id.TextView01);

  accelerometer accelerometercall = new accelerometer();

  String movearray[] = accelerometercall.getmovement();

  herestext_.setText(movearray[2]);
  }

    }

I have a feeling I'm missing something very simple but any help would be greatly appreciated!
Thanks,
Scott

A: You're creating a new accelerometer class, which is completely uninitialized since there is no constructor, then you access its member. Of course it'll be null.
Not sure how your two classes are related, but if the activity is called by the service, then you need to pass the string through the intent (through an extra, for example).
Side note: Class names should always start with a capital letter. Method/variable names should have camel case, i.e. "updateArray". Also, you can format your code here by selecting it and pressing CTRL+K.

A: Your first problem, I think, is that you are creating an array with a million slots in it. Do you really mean to be doing that? It's going to take a lot of memory---quite possibly more than is available. You should instead look to having a Vector of Strings that you extend as necessary.


text:
Q: Замутированный value Как сделать, чтоб в текстовом поле (type='text') перед нажатием на него была замутированная запись типа "Логин" или "Пароль", а после нажатия надпись стиралась и поле становилось чистым?
A: В HTML5 можно так:
<input type="text" placeholder="mail@somehost.com">

Для кроссбраузерности можно взять библиотечку placeholder.js и писать так:
<input type="text" placeholder="mail@somehost.com" id="someinput">

A:

<input type="text" id="login" value="Логин" />

Это с jQuery, думаю, идея понятна.
A: Вот один из достаточно простых вариантов с использованием jQuery:

    <form action="" method="post">

            login
            <input type="text" name="username" id="username" />

            password
            <input type="password" name="password" id="password" />

    </form>

input'ы в параграфы забираем специально для safari.
A: если не бояться html5 то можно использовать атрибут placholder:
<input type="text" name="login" placeholder="Введите сюда Login" />


text:
Q: closed sets which are strictly contained in open set I wanted to ask the following:
Suppose I am in the complex plane with the usual topology.
Suppose I have a closed set A such that A ⊂ B, where B is an open set. I wanted to know if I can always find a closed set A' such that A ⊂ A' ⊂ B?
But with one more demand - That the smallest distance between boundaries of A and A' will be strictly positive. You can visualize my question as: is it possible to "inflate" A a bit so it could still be totally contained in B?
Thank you in advance.

A: No. Let $B = \{(x,y):\space y < 1/(1+x^2)\}$ and $A$ the $x$-axis.
EDIT: If $A$ is compact, the answer is yes.
Proof: For each point $x\in A$ put a closed ball that is inside $B$ to $x$. Since $A$ is compact it's covered with finitely many of these balls. Take the union of the balls as $A'$. To make sure you "inflate", cover the boundary of $A$ "thickly enough" (i.e make sure you don't have a place where two balls would be just tangent to each other).
This would need some argument to make it rigorous but hope you get the idea.

A: Assuming A compact, then the continuous function $d(A,B)$  takes on a max and a min. Then, if $A \subset B, d(A,B)>0$ , and the result is possible.
I think this should work: Assume A compact, contained in B. Then, for every $a \in A $, there is a ball $B(a,r) \subset B ; r>0$ . Cover the boundary of $B$ by these balls $B(a,r)$ and take a finite subcover. In this finite subcover, take  EDIT $Min r: B(a,r) \subset B $. This $r$ should give you the room to expand ino $B$ while still being contained in it.


text: Q: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/ I am using CORS and while sending rest call i am getting this "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at "example.com:8080" error. On windows machine same call works across all browser but when I do it on Ubuntu I get this error no matter what ever browser I use.


text:
Q: The product of three consecutive natural numbers is divisible by $6$ Please give me feedback for my answer to this question.

Prove or find a counterexample: The product of any three consecutive
  natural numbers is divisible by $6$

My answer: True. Suppose $n$ is a natural number, such that the $3$ consecutive natural numbers is $n, n+1, n+2$. Then,
$$\begin{align}\frac{n(n+1)(n+2)}{6}
&= \frac{1(1+1)(1+2)}{6} \\
&= \frac 66 \\
&= 1\end{align}$$
Thus, $n(n+1)(n+2)$ is divisble by 6.

A: You have proved that $1\times2\times3$ is divisible by six, not that the product of any 3 consecutive natural numbers is divisible by $6$.
If a number is divisible by $6$, then it must be divisible by both $2$ and $3$. Your product is $$n(n+1)(n+2)$$ so you could try showing that at least one of $n$, $n+1$ or $n+2$ is a multiple of 3, and at least one is even.


text:
Q: The init script to several Unicorn.rb instance I use now thin to serve my rack application on my webserver. I have a lot of web application so I have a init script who check all file in my /etc/thin and start all of then with configuration inside.
I want migrate to unicorn so I want same behaviour, but when I check the example in unicorn, I found only init script to start one unicorn instance.
What I can use like init script to do that ?

A: I was looking for the same thing. You'll need to create an init script for each app. I modified this init.d script which uses a PID file instead of the program name:
http://gist.github.com/308216


text:
Q: How to display error validation summary Header in ASP.Net MVC 5 I am a beginner in ASP.Net MVC 5 and I want to know how to display validation summary "Header Message" on top of page above all the errors.
Below is what I have till now:
View:
@model WebApplication3.Models.Form
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

Form

        @* first parameter false means show all the errors *@
        @* second parameter means the message to display as Header on top*@
        @Html.ValidationSummary(false,"Fix below error", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "*", new { @class = "text-danger" })

            @Html.LabelFor(model => model.age, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.age, new { htmlAttributes = new { @class = "form-control" } })
                @*star meaning show the star sign to keep show field required.  *@
                @Html.ValidationMessageFor(model => model.age, "*", new { @class = "text-danger" })

                <input type="submit" value="Create" class="btn btn-default" />

}

@* CLIENT SIDE VALIDATION*@
@section Scripts
 {
 @Scripts.Render("~/bundles/jqueryval")
 }

Model
 public class Form
    {
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
        [Required]
        [Remote("IsAgeUnique", "Form", ErrorMessage = "Age is not unique")]
        public int age { get; set; }
    }

P.S:
I have used @Html.ValidationMessageFor(prop, "*") wildcard for each property to display star message side to the UI field.
Issue:
When the page loads the error header is already there displayed on the page. Functionality wise everything is working fine. But during initial page load why the "Header message gets displayed"

A: You can try to add css rule like following to make header error part unvisible initially.
Validation summary text has validation-summary-valid class initially. If there are some errors it becomes validation-summary-errors so your initial value dont have any error, I think you can use css rule
.validation-summary-valid {
    display:none;
}


text:
Q: How to fetch asset modification history in hyperledger fabric I am using IBM bluemix blockchain service to tryout some smart contract logic for my asset sharing demo.
Is there anyway to query the asset modified history in hyperledger fabric network.
I have checked with documentations for both fabric 0.6 and 1.0 versions, but I can find only the stub.pushState(key,value_json) and stub.getState(key) to interact width the ledger. But using stub.getState(key), I can fetch only the latest entry of the key, but how can I fetch and display the series of changes/modification written for the same key.
I have iterated through the block using {peeraddress}/Block/getBlock/{Block}, but I am getting the encrypted transaction payloads only since its security is on. I am not getting the idea to display the history of asset modifications for the same key.
Please suggest me the correct way to do this.
Thanks in advance

A: You can use GetHistoryForKey() API as following:
    historyIter, err := stub.GetHistoryForKey(key)

    if err != nil {
        errMsg := fmt.Sprintf("[ERROR] cannot retrieve history for key <%s>, due to %s", key, err)
        fmt.Println(errMsg)
        return shim.Error(errMsg)
    }

    for historyIter.HasNext() {
        modification, err := historyIer.Next()
        if err != nil {
            errMsg := fmt.Sprintf("[ERROR] cannot read record modification for key %s, id <%s>, due to %s", key, err)
            fmt.Println(errMsg)
            return shim.Error(errMsg)
        }
        fmt.Println("Returning information about", string(modification.Value))
    }

Here is the link to the interface with API description:
// GetHistoryForKey returns a history of key values across time.
// For each historic key update, the historic value and associated
// transaction id and timestamp are returned. The timestamp is the
// timestamp provided by the client in the proposal header.
// GetHistoryForKey requires peer configuration
// core.ledger.history.enableHistoryDatabase to be true.
// The query is NOT re-executed during validation phase, phantom reads are
// not detected. That is, other committed transactions may have updated
// the key concurrently, impacting the result set, and this would not be
// detected at validation/commit time. Applications susceptible to this
// should therefore not use GetHistoryForKey as part of transactions that
// update ledger, and should limit use to read-only chaincode operations.

GetHistoryForKey(key string) (HistoryQueryIteratorInterface, error)

In case you'd like to inspect history of changes not in context of chaincode you can use QSCC (Query System Chaincode), which provide following capabilities:
// These are function names from Invoke first parameter
const (
    GetChainInfo       string = "GetChainInfo"
    GetBlockByNumber   string = "GetBlockByNumber"
    GetBlockByHash     string = "GetBlockByHash"
    GetTransactionByID string = "GetTransactionByID"
    GetBlockByTxID     string = "GetBlockByTxID"
)

A: IF you need. Java SDk and go chaincode combination. Here is the example

Java code

public List<HistoryDao> getUFOHistory(String key) throws Exception {
    String[] args = { key };
    Logger.getLogger(QueryChaincode.class.getName()).log(Level.INFO, "UFO communication history - " + args[0]);

    Collection<ProposalResponse> responses1Query = ucc.getChannelClient().queryByChainCode("skynetchaincode", "getHistoryForUFO", args);
    String stringResponse = null;
    ArrayList<HistoryDao> newArrayList = new ArrayList<>();
    for (ProposalResponse pres : responses1Query) {
        stringResponse = new String(pres.getChaincodeActionResponsePayload());
        Logger.getLogger(QueryChaincode.class.getName()).log(Level.INFO, stringResponse);
        newArrayList = gson.fromJson(stringResponse, new TypeToken<ArrayList<HistoryDao>>() {
        }.getType());
    }
    if (null == stringResponse)
        stringResponse = "Not able to find any ufo communication history";
    return newArrayList;
}

and you go chancode implemetation is as follows

Go code

func (t *SmartContract) getHistoryForUFO(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {

    if len(args) < 1 {
            return shim.Error("Incorrect number of arguments. Expecting 1")
    }

    ufoId := args[0]
    resultsIterator, err := APIstub.GetHistoryForKey(ufoId)
    if err != nil {
            return shim.Error(err.Error())
    }
    defer resultsIterator.Close()

    var buffer bytes.Buffer
    buffer.WriteString("[")

    bArrayMemberAlreadyWritten := false
    for resultsIterator.HasNext() {
            response, err := resultsIterator.Next()
            if err != nil {
                    return shim.Error(err.Error())
            }
            // Add a comma before array members, suppress it for the first array member
            if bArrayMemberAlreadyWritten == true {
                    buffer.WriteString(",")
            }
            buffer.WriteString("{\"TxId\":")
            buffer.WriteString("\"")
            buffer.WriteString(response.TxId)
            buffer.WriteString("\"")

            buffer.WriteString(", \"Value\":")
            // if it was a delete operation on given key, then we need to set the
            //corresponding value null. Else, we will write the response.Value
            //as-is (as the Value itself a JSON)
            if response.IsDelete {
                    buffer.WriteString("null")
            } else {
                    buffer.WriteString(string(response.Value))
            }

            buffer.WriteString(", \"Timestamp\":")
            buffer.WriteString("\"")
            buffer.WriteString(time.Unix(response.Timestamp.Seconds, int64(response.Timestamp.Nanos)).String())
            buffer.WriteString("\"")

            buffer.WriteString(", \"IsDelete\":")
            buffer.WriteString("\"")
            buffer.WriteString(strconv.FormatBool(response.IsDelete))
            buffer.WriteString("\"")

            buffer.WriteString("}")
            bArrayMemberAlreadyWritten = true
    }
    buffer.WriteString("]")

    fmt.Printf("- History returning:\n%s\n", buffer.String())
    return shim.Success(buffer.Bytes())
}

There you go. Have fun.

A: From the Fabric FAQ, A. The chaincode API GetHistoryForKey() will return history of values for a key.

A: For NodeJS SDK:
You can use 'GetHistoryForKey'.
It returns a history of key values across time. For each historic key update, the historic value and associated transaction id and timestamp are returned.
You can find it here (doc. link):
https://fabric-shim.github.io/release-1.3/fabric-shim.ChaincodeStub.html#getHistoryForKey__anchor


text:
Q: Golang is timing out on my stream I am trying to write a go server that receives a stream of data from an http request. The problem is that it times out once it receives {status: connected} How do I keep the connection alive?
func stream() {
    t := time.Now()
    a := t.Format("15:03")
    if a > string("08:30") && a < string("15:00") {
        color.Red("Streaming. . .")
        config := oauth1.NewConfig("HIDDEN", "HIDDEN")
        token := oauth1.NewToken("HIDDEN", "HIDDEN")
        httpClient := config.Client(oauth1.NoContext, token)
        path := "https://stream.tradeking.com/v1/market/quotes.json?symbols=aapl"
        resp, _ := httpClient.Get(path)
        fmt.Println(resp)
        body, _ := ioutil.ReadAll(resp.Body)
        fmt.Printf("Raw Response Body:\n%v\n", string(body))
        defer resp.Body.Close()
    } else {
        color.Red("%s \nMarkets are closed! Please, come back later.", t)
    }
}

I call this function in main. I also receive what looks like the header:
&{200 OK 200 HTTP/1.1 1 1 map[Date:[Mon, 16 Jan 2017 17:45:36 GMT] X-Powered-By:[Express] Server:[cloudflare-ngi
nx] Content-Type:[application/json] Connection:[keep-alive] Set-Cookie:[__cfduid=dcfcf86c79c56e659ce2b1bade3643c
981484588736; expires=Tue, 16-Jan-18 17:45:36 GMT; path=/; domain=.tradeking.com; HttpOnly] Vary:[Accept-Encodin
g] Cf-Ray:[322361d0efd40938-DFW]] 0xc42032e0c0 -1 [chunked] false true map[] 0xc4200d21e0 0xc42040cbb0}

A: Turn out that the the market was closed for MLK Day and hence there was no response from the sever.
After a certain timeout, the remote server times out.


text:
Q: Why does my recieved from database data is undefined? I`m creating API on my express.js server, so when it takes "get" request, some function placed in module file asking data from graph db:
module.js file:

function getGraphData() {
  const cityName = 'Milan';
  const readQuery = `MATCH (City {name: $cityName})-[:LINKED*1..3]-(city:City) RETURN city`;
  const cities = [];
  session
    .run(readQuery, { cityName })
    .then(function (result) {
      result.records.forEach(function (record) {
        cities.push({
          title: record._fields[0].properties.name,
        });
      });
      return cities;
    })
    .catch((err) => console.log(err));
}
module.exports.getGraphData = getGraphData;

After receiving data it stores in array named cities and looks like this:

cities: [ { title: 'City1' }, { title: 'City2' }, { title: 'City3' } ]

So, function is returning this array, and then I import function from module and use it in my router file:
const { getGraphData } = require('./../db/neo4j');

router.get('/', async (req, res) => {
  try {
    const p = await getGraphData();
    console.log('p:', p); //p is undefined
    //return res.status(200).send(p);
    return res.status(206).json(p); // empty response, not any data only status code
  } catch (e) {
    console.log(e);
});

So, what I'm doing wrong? Why does api response is empty?
Im use debugger. Data realy comes to function in module, but doesn`t passing to api response to "p" variable.

A: Your getGraphData function is using .then . When it executes it makes the session call and returns immediately that is why it returns empty.
Although, you are doing await on getGraphData, your getGraphData function needs to be defined as async and use await with session for it to work.
    async function getGraphData() {
      const cityName = 'Milan';
      const readQuery = `MATCH (City {name: $cityName})-[:LINKED*1..3]-(city:City) RETURN city`;
      const cities = [];
      try{
          const result = await session.run(readQuery, { cityName });
          result.records.forEach(function (record) {
                cities.push({
                  title: record._fields[0].properties.name,
                });
              });
          return cities;
        }
        catch(err){
           console.log(err);
           return err;
        }
  }


text:
Q: SQL Concat_ws all columns I have to concat_ws all columns in my table.
I use sakila schema.
I try to use this as subquery but i cant put it after select in main query.
select column_name from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='film'

also if this query found NULL i have to  return "-"
select concat_ws(",",COALESCE(film.title,"-"),COALESCE(film.rental_rate,"-"),COALESCE(language.name,"-")) as dane
from film
inner join language
    on film.language_id = language.language_id;

Edit sorry my bad i dont specify my question.
I want to get data like in second query but in second query i have only 3 columns, I need to create query to have all the columns.

A: You can create it with MySQL and must execute it as PREPARED statement like this:
SELECT
    CONCAT( "SELECT CONCAT_WS(',',"
    , GROUP_CONCAT( CONCAT("COALESCE( `",TABLE_NAME,'`.`',column_name,'`,"-")')
      )
    , ") AS dane FROM `", @mySchema, '`.`', @tableName, '`'
    , " INNER JOIN language on film.language_id = language.language_id")
    INTO @msql
FROM INFORMATION_SCHEMA.COLUMNS
JOIN ( SELECT @mySCHEMA:="Kazoku", @tableName:="film" ) as INIT
WHERE
    TABLE_NAME= @tableName
AND
    TABLE_SCHEMA= @mySchema
ORDER BY
    `ORDINAL_POSITION`;

SELECT @msql; -- only for debug output

PREPARE stmt FROM @msql;

EXECUTE stmt;

DEALLOCATE PREPARE stmt;

sample
MariaDB [Kazoku]> SELECT
    -> CONCAT( "SELECT CONCAT_WS(',',"
    -> , GROUP_CONCAT( CONCAT("COALESCE( `",TABLE_NAME,'`.`',column_name,'`,"-")')
    ->   )
    -> , ") AS dane FROM `", @mySchema, '`.`', @tableName, '`'
    -> , " INNER JOIN language on film.language_id = language.language_id")
    -> INTO @msql
    -> FROM INFORMATION_SCHEMA.COLUMNS
    -> JOIN ( SELECT @mySCHEMA:="Kazoku", @tableName:="film" ) as INIT
    -> WHERE
    -> TABLE_NAME= @tableName
    -> AND
    -> TABLE_SCHEMA= @mySchema
    -> ORDER BY
    -> `ORDINAL_POSITION`;
Query OK, 1 row affected (0.07 sec)

MariaDB [Kazoku]>
MariaDB [Kazoku]>
MariaDB [Kazoku]> SELECT @msql; -- only for debug output
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| @msql                                                                                |
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| SELECT CONCAT_WS(',',COALESCE( `film`.`id`,"-"),COALESCE( `film`.`datetime`,"-"),COALESCE( `film`.`language_id`,"-")) AS dane FROM `Kazoku`.`film` INNER JOIN language on film.language_id = language.language_id |
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

MariaDB [Kazoku]>
MariaDB [Kazoku]> PREPARE stmt FROM @msql;
Query OK, 0 rows affected (0.00 sec)
Statement prepared

MariaDB [Kazoku]>
MariaDB [Kazoku]> EXECUTE stmt;
+-------------------------+
| dane                    |
+-------------------------+
| 1,2021-01-01 00:00:00,1 |
+-------------------------+
1 row in set (0.00 sec)

MariaDB [Kazoku]>
MariaDB [Kazoku]> DEALLOCATE PREPARE stmt;
Query OK, 0 rows affected (0.00 sec)

MariaDB [Kazoku]>


text:
Q: Referencing a model from a string How can I call the model from a string?
$model = 'User';

I tried the following:
\App\.$model::get();
\App\{$model}::get();
\App\.{$model}::get();
\App\${$model}::get();
\App\.${$model}::get();

I feel like I'm missing something although a workaround it would be:
$model = 'App\User';
$model::get();

But for learning purposes im trying to see how i can mix it up like above.

A: Make a string out of the whole thing:
namespace App;

class Model {
    public static function go() {
        echo 'yay!';
    }
}

$someString = 'Model';
$className = 'App\\' . $someString;
var_dump(new $className());
$className::go();

Working example.


text:
Q: Wondering what the words "confront" & "personality" really are talking about in this piece of news
On the third day of his cross-examination, Mr Nel pressed the Olympic
  sprinter to explain the final moments leading up to the shooting.He
  asked why he had not checked whether Ms Steenkamp had heard his calls
  for her to phone the police, or why he had not taken her to safety
  instead of going to confront the supposed intruder.Mr Pistorius said
  it was his personality to confront what he believed was an intruder.
  The trial has been adjourned until Monday morning.

http://www.bbc.com/news/world-africa-26984472
What does "personality" mean here? Is it a typo? Should it not be "responsibility"?

A:
...Mr Pistorious said it was [in the nature of] his personality to confront what he believed was an intruder...

I believe this is what is implied, I don't think it would be a typo.

A: It is not a typo. What it means is that his personality led him to confront an intruder, where someone with a different personality might have investigated further, or gone for help, or made some other choice. It means his nature, and he's saying that for him to have made other choices in that situation would have required that he be a different type of person. It's his excuse for why he did what he did, not a way to claim or deny responsibility.
Full Transcript is at http://news.sky.com/story/1240765/oscar-pistorius-trial-court-transcript. Page 10, Pistorius is quoted saying he acted in his nature, and it fits the context of the article you cited.


text:
Q: Networked programs in Python import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com', 80))
mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
while True:
    data = mysock.recv(512)
    if ( len(data) < 1 ) :``
       break
    print data
mysock.close()

I am a bit confused, can anyone in short explain the above code?


text:
Q: SQL return row if no result found I have two tables:
person
id
name

car
name
person_id

Currently the query goes like:
SELECT
person.name
car.name
FROM
person, car
WHERE
person.id = car.person_id

Now this works fine if there is a car associated with a person. However if there isn't, then the person won't get returned. If a person has no car, I want to return a row with the text 'No Car' in column car.name.

A: select person.name, coalesce(car.name, 'no car')
from person
left outer join car on person.id = car.person_id

A: SELECT person.name, CASE WHEN car.name IS NULL THEN 'no car' ELSE car.name END
FROM person
LEFT JOIN car ON person.id = car.person_id

A: select person.name, ISNULL(car.name, 'no car')
from person
left join car on person.id = car.person_id


text:
Q: How to assign html to variable in rails view in php twig template I could do:
{% set chunk %}

     bar {{ another_var_or_helper }}
     ...

{% endset %}

{{ chunk }}  {# displays div #}

in rails I can do it with render partial or <% chunk = '..' %>. But how to do "twig style"?

A: Use a Helper function.
module SomeModelNameHelper
    def html_chunk
        "
Bar
".html_safe
    end
end

Then in your view you can call it thusly:
<%= html_chunk %>


text:
Q: How to represent a rotation/orientation in N dimensions? I'm trying to represent coordinate systems (and transformations between them) in arbitrary dimensions. A coordinate system can be described by its pose (position + orientation) and I am unsure how to best represent its orientation in arbitrary dimensions.
Based on my search, it should be possible to represent an arbitrary pose as a sequence of rotations (source). Further, it should be possible to represent an arbitrary rotation by an angle (amount to rotate), and a plane in which to rotate (source). This means I should be able to do something like this in code
from dataclasses import dataclass
from typing import List
from numpy.typing import ArrayLike

@dataclass
class Rotation:
    # amount to rotate
    alpha: float
    # two vectors spanning the plane
    u: ArrayLike
    v: ArrayLike

@dataclass
class Orientation:
    orientation: List[Rotation]

This seems quite naive and inefficient. Each rotation has to be applied one at a time, which may not be very efficient computationally speaking. It is also non-unique. For example, these three objects represent the same orientation
Orientation(Rotation(np.pi, (0, 1), (1, 0)))
Orientation(Rotation(-np.pi, (1, 0), (0, 1)))
Orientation([Rotation(np.pi, (0, 1), (1, 0)), Rotation(0.42, (0, 1), (1, 0)), Rotation(-0.42, (0, 1), (1, 0))])

How can I improve this and what is the best data structure to use here?

A: Rotation matrices can represent rotations in arbitrary N dimensions.
It is possible to compose rotation matrices using the matrix product. So you'd need only to store a single matrix to represent an orientation, even if it's constructed from multiple individual rotations.
While a single plane/angle representation is more memory efficient than a full matrix, one matrix can represent the combination of multiple plane/angle rotations.
Also, applying a matrix transformation is very efficient - just a couple of dot products.
In 3D space it's often beneficial to represent rotations as quaternions, but I don't think they can be generalized to arbitrary dimensionality. Although they can be generalized to ND space, this is is not very intuitive1.

1Thank you, Spektre, for the clarifying comment.


text:
Q: javascript object undefined $.couch.urlPrefix = "http://192.168.0.5:5984";
var db = $.couch.db("disastri");

var doc;
 db.openDoc("esempio",{
  success: function(data){
   doc = data;
  },
  error: function(err){
   alert("ERRORE: " + err);
  },
  attachments: true
});

console.log(doc);

why? the object doc is undefined?
if I try to initialize doc to an empty object, the value of doc remain the empty object.
I'm sure that is not called the error function, because the browser not show me the alert window.

A: db.openDoc() - this is the asynchronous call, it means that next operator console.log(doc) not wait it complete and run before callbacks functions success or error calls.
Put console.log() into callback:
var doc;
 db.openDoc("esempio",{
  success: function(data){
   doc = data;
   console.log(doc); // <--- HERE
  },
  error: function(err){
   alert("ERRORE: " + err);
  },
  attachments: true
});

now it will be called when openDoc() finished and doc defined.

A: db.openDoc works asynchronously - it means that js interpreter doesn't wait for db.openDoc to perform its work. It starts asynchronous function, and proceeds to execute following lines of code - while asynchronous still works. So, in this case console.log(doc); executes before db.openDoc. What you need to do is move log invocation into success callback:
$.couch.urlPrefix = "http://192.168.0.5:5984";
var db = $.couch.db("disastri");

var doc;
db.openDoc("esempio", {
    success: function(data){
        doc = data;
        console.log(doc);
    },
    error: function(err){
        alert("ERRORE: " + err);
    },
    attachments: true
});


text:
Q: Why may a mongoose document not get saved? I've been using the following middleware for sometime, then suddenly it stops saving new docs. Further explanation in the comments
var body = req.body;

new ordersModel (body).save(function(err, newOrder, rowCount) {
    if (err) throw err;
    console.log(rowCount) // logs 1

    updateEstimatedTime(newOrder); /* updateEstimatedTime runs but inside
   it, trying to find this document newOrder returns null,
   meaning it was never saved */
});

If I try something like
var pleaseWork = new ordersModel (body);
console.log(pleaseWork) // it dumps a loaded mongoose object
pleaseWork.save(function(err, newOrder, rowCount) {

So why doesn't it get persisted? I also tried reloading the server several times with this at the top just in case I was getting collections loaded during server setup
ordersModel.find({}, 'customer', function (err, docs) {
    if (err) throw err;
    console.log(docs)
})

But it just returns the documents that existed before this fault began. I've triple checked the model name, it's the same all over the script. What could the code be lacking?
I have seen some examples online also that suggested something in the region of
var pleaseWork = new ordersModel ();
pleaseWork.foo = body.foo;
pleaseWork.bar = body.bar;
pleaseWork.john = body.john;

console.log(pleaseWork) // dumps a loaded mongoose object
pleaseWork.save(function(err, newOrder, rowCount) {

Now, this is not feasible for me; the ordersModel table has more than 10 columns-- dropping the body object in the model's constructor is sane enough and worked the last time the program was run.
Although I don't think it's necessary but if you need to see my model, I can make that available. Also the full server code in case you need to deploy and test.

A: Thanks to @NeilLunn's comment and my subsequent debug data I noticed on line 10 that I was removing documents with estimatedDeliveryTime = null which would include this new order. This line wasn't in the middleware but in a proxy initializing server variables
ordersModel.remove({estimatedDeliveryTime: null}).exec()

I was/am using it to cleanse the collection from invalid orders


text:
Q: 55-650V to 5V DC/DC convertor design For an application I am building I need a custom DC/DC convertor that can convert a voltage ranging from 60V-600V to a contant voltage of around 5V.
Using the TI Webench with the paramaters Vin_min = 55V, Vin_max = 650V, V_out = 5V and Iout = 0.5A gave me the following schematic:

I tried to buy as many of the components that were provided by the TI Webench, and where I wasn't able to find the exact suggested component I bought an equivalent one. The design also required me to wind my own transformer (T1).
After building the PCB and testing it I've gotten mixed results which do not satisfy my need. I've already tried to understand the schematic, went through all the datasheets and asked around with my colleagues but no one seemed to be able to explain to me how this schematic works.
The output I get is a sawtooth with Vpeak of ~4.8V and Vmean of ~3V, which I think means the switcher turns off too fast since the output doesn't reach the desired 5V. The UCC2813-0D does behave like it should we think, since it's Vcc is around 7.5V (turn-on threshold is 7.2V) and we can see switching happening on the output. However, the switching frequency is around 66kHz instead of the 102kHz we expect (can be calculated with F = 1.5/(Rt*Ct)). I will add some oscilloscope screenshots later.
After some testing and measuring we noticed that when the CS pin (current sense comparator used for overcurrent protection) on the UCC2813-0D went above ~1.35V, the IC seemed to shut down. This is reflected in the electrical characteristics, which state that overcurrent threshold on CS has a minimum of 1.32V. We tried replacing the Rsns (current sense resistor) with a lower resistance value, but still reach the over current threshold and get the same behavior on the output.
I was hoping someone on this forum could explain to me how this schematic works, and maybe point me to a possible solution as to why this design doesn't work for me. Pointing me in another direction that could also satisfy my design requirements is also greatly appreciated (req: Vin_min = 55V, Vin_max = 650V, Vout = 5V, Iout ~= 50mA).
Thanks in advance!
Note: in my design I connected both grounds with each other, since I didn't need and isolated DC/DC. I don't know if this matters for the functionality of the schematic but I think it is worth mentioning anyway.


text:
Q: C# Edit existing excel file and save to another place with NPOI I'm using NPOI in my .net5 console application.
My project SDK and NPOI package I installed:
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="DotNetCore.NPOI" Version="1.2.3" />
  </ItemGroup>

</Project>

Code:
static void Main(string[] args)
        {
            IWorkbook wb = null;
            using (FileStream fs = new FileStream(@"C:\Users\xxx\Downloads\Account.xlsx",FileMode.Open,FileAccess.Read))
            {
                wb = new XSSFWorkbook(fs);
            }

            ISheet sht = wb.CreateSheet("test");
            sht.CreateRow(0).CreateCell(0).SetCellValue(0);

            using (FileStream fs = new FileStream(@"C:\Users\xxx\Downloads\Test.xlsx", FileMode.Create, FileAccess.Write))
            {
                wb.Write(fs);
            }
        }

I got a 0KB excel file 'Test.xlsx' which is not able to be opened.


text:
Q: Create several new dataframes or dictionaries from one dataframe I have a dataframe like this:
evt    pcle    bin_0    bin_1    bin_2    ...    bin_49
 1      pi      1        0         0               0
 1      pi      1        0         0               0
 1      k       0        0         0               1
 1      pi      0        0         1               0
 2      pi      0        0         1               0
 2      k       0        1         0               0
 3      J       0        1         0               0
 3      pi      0        0         0               1
 3      pi      1        0         0               0
 3      k       0        1         0               0
 ...
 5000   J       0        0         1               0
 5000   pi      0        1         0               0
 5000   k       0        0         0               1

With this information, I want to create several other dataframes df_{evt} (or maybe dictionaries should be better?):
df_1 :
pcle    cant    bin_0    bin_1    bin_2   ...    bin_49
 pi      3        2        0        1              0
  k      1        0        0        0              1

df_2 :
pcle    cant    bin_0    bin_1    bin_2   ...    bin_49
 pi      1        0        0        1              0
  k      0        1        0        0              0

In total there would be 5000 dataframes (1 for each evt) where in each of them:
*the column "cant" has the ocurrences of "pcle" in the particular "evt".

*bin_0 ... bin_49 have the sum of the values for this particular "pcle" in
 the particular "evt".

Which is the best way to achieve this goal?

A: Here's a possible solution:
import pandas as pd
import numpy as np
columns = ["evt", "pcle", "bin_0", "bin_1", "bin_2", "bin_3"]
data = [[1, "pi", 1, 0, 0, 0],
        [1, "pi", 0, 0, 0, 0],
        [1, "k", 0, 0, 0, 1],
        [1, "pi", 0, 0, 1, 0],
        [2, "pi", 0, 0, 1, 0],
        [2, "k", 0, 1, 0, 0],
        [3, "J", 0, 1, 0, 0],
        [3, "pi", 0, 0, 0, 1],
        [3, "pi", 1, 0, 0, 0],
        [3, "k", 0, 1, 0, 0]]

df = pd.DataFrame(data=data, columns=columns)

# group your data by the columns you want
grouped = df.groupby(["evt", "pcle"])

# compute the aggregates for the bin_X
df_t = grouped.aggregate(np.sum)

# move pcle from index to column
df_t.reset_index(level=["pcle"], inplace=True)

# count occurrences of pcle
df_t["cant"] = grouped.size().values

# filter evt with .loc
df_t.loc[1]

If you want to make it into a dictionary then you can run:
d = {i:j.reset_index(drop=True) for i, j in df_t.groupby(df_t.index)}


text:
Q: Upgrading Oh My Zsh gives me 'not a git repository' error Since I upgrade my OSX to El Capitan when I want to update Oh My Zsh upgrade_oh_my_zsh I got the following error:
Upgrading Oh My Zsh
fatal: Not a git repository (or any of the parent directories): .git
There was an error updating. Try again later?

I never used git before, searching this fatal error on the internet they advice to do git init in the /.oh-my-zsh folder. After running this command a new fatal error occur when I try to run upgrade_oh_my_zsh again.
fatal: 'origin' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I don't know if it has anything to do with with it but when I open the terminal (iTerm2) I also got this notification:
/Users/peter/.zshrc:1: command not found: Path

Anyone has experience with this or knows a solution for my problem?

A: For me, the root cause of the error was the upgrade to macOS Ventura.  Doing xcode-select --install and restarting the terminal fixed the issue.

A: Looks like your git repo was removed from oh-my-zsh? You can re-add the remote and update to the latest version of Zsh by running:
cd ~/.oh-my-zsh
git init # you've already done this step, so you can skip
git remote add origin https://github.com/ohmyzsh/ohmyzsh.git
git fetch
git reset --hard origin/master

After that, restart your terminal instance and you should be good to go.

A: When I had this issue, I started by seeing what happened to my git
$git --version

Then it prompts to accept the new agreement on XCODE. So I ran
$sudo xcodebuild -license

After that, it will install the updates, then open XCODE.
Then all will be fine.

A: I just encountered that message. In my case (on a Mac) it just so happens that I just installed Xcode, and that git stopped working until I accepted its terms and conditions. Just in case...

A: The above solution didn't work for me.
The problem in my case was that I have an alias
alias gpucb="git pull origin $(git branch --show-current)"
As soon as I commented it the error was gone.
I need a fix for this.
Also, the weird part is that the error is encountered only in the second git command.

A: In my case macOS Ventura 13.x.
Download and installed Command Line Tools for Xcode 14.1
it's solved my issue

A: rm -rf "$ZSH"
sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"

A: I had exactly same error message and it was because of Xcode update. I had to start Xcode and accept some license & feature changes. Afterwards, the message has gone.
I believe the message is result of multiple processes. Not only git problems but also for Xcode.
It's better to check Xcode if you face with this error.

A: This is due Xcode upgrade.
Open Xcode.app in your MAC, accept new terms and conditions and then it will install some upgrades and error will disappear from oh-my-zsh.

A: In my case, I needed to do a system update. The issue was resolved after the update.

A: By trying the accepted solution, I got this error:
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun

However, running this (and restarting the terminal) helped me:
$ xcode-select --install

see also this answer


text:
Q: How to find the element with an attribute and change the attribute value in javascript?

function allowDrop(ev) {
    ev.preventDefault();
  }

  function drag(ev) {
    ev.dataTransfer.setData("Text", ev.target.id);
  }

  function drop(ev) {
    var data = ev.dataTransfer.getData("Text");
    ev.target.appendChild(document.getElementById(data));
    ev.preventDefault();
  }

After dropping the image how can i change the attribute value draggable="true" to draggable="false" by finding the available elements with attribute draggable="true" inside the function drop() ?

A: I would use querySelectorAll and setAttribute
document.querySelectorAll('[draggable="true"]').forEach(elem =>
  elem.setAttribute("draggable",false)
);

Older JS
var elems = document.querySelectorAll('[draggable="true"]');
for (var i=0;i<elems.length;i++) {
  elems[i].setAttribute("draggable",false);
}

Using a class:
document.querySelectorAll('.someClass[draggable="true"]')

A: Use querySelectorAll to get all the elements having draggable set to true. using setAttribute set draggable to false

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("Text", ev.target.id);
}

function drop(ev) {
  var data = ev.dataTransfer.getData("Text");
  ev.target.appendChild(document.getElementById(data));
  ev.preventDefault();
  var elem = document.querySelector('.className');
  elem.querySelectorAll('[draggable="true"]').forEach(e => e.setAttribute('draggable', false))
}

A: You can use
document.querySelectorAll('[draggable="true"]');

in order to find elements with a certain attribute.
Note that this works only for HTML attributes, for classes you shall use
document.querySelectorAll('.classname[draggable="true"]')


text:
Q: WCF service hosted in IIS with netTCP binding I have a WCF service hosted in IIS7 with netTCP enabled.
This is my web.config in %apppath%\ , where the SVC file is.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="Search.Querier.WCF.Querier" behaviorConfiguration="SearcherServiceBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8050/SearcherService"/>
          </baseAddresses>
        </host>
        <endpoint address="net.tcp://localhost:9000/SearcherService"
                  binding="netTcpBinding"
                  bindingConfiguration="Binding1"
                  contract="Search.Querier.WCF.IQuerier" />
      </service>
    </services>
    <bindings>
      <netTcpBinding>
        <binding name="Binding1"
                     hostNameComparisonMode="StrongWildcard"
                     sendTimeout="00:10:00"
                     maxReceivedMessageSize="65536"
                     transferMode="Buffered"
                     portSharingEnabled="false">
          <security mode="None">
            <transport clientCredentialType="None" />
            <message clientCredentialType="None" />
          </security>
        </binding>
      </netTcpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="SearcherServiceBehavior">
          <serviceMetadata httpGetEnabled="true" httpGetUrl=""/>
          <serviceDebug includeExceptionDetailInFaults="true"  />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
  <system.web>
    <compilation debug="true" />
  </system.web>
</configuration>

For some reason, instead of loading on port 8050 as I specified, I see the blue and beige site showing the site at:
http://localhost/SearcherService/searcherservice.svc
and not
http://localhost:8050/SearcherService/searcherservice.svc
Additionally, when I try to run
svcutil.exe http://process.mycomp.com/SearcherService/SearcherService.svc?wsdl
as the page rendered on the URL says, I get an error:
Metadata contains a reference that cannot be resolved: 'http://process.mycomp.com/SearcherService/SearcherService.svc?wsdl'

But I have that specified nowhere else in my web.config
Is there anywhere else it could be?

A: You are missing a MEX endpoint, have a look at this link:
http://bloggingabout.net/blogs/dennis/archive/2006/11/09/WCF-Part-4-3A00-Make-your-service-visible-through-metadata.aspx


text:
Q: PHP - Reading ftp text files and extract required data This is my first php script. I actually code in vb.net.. I am making this licensing system for .net applications. This licensing system has a manager which the admin can easily control and view. Also Iam making a class library to login and register for the same. I have succeeded in doing so using only vb.net code but as the credentials need to be stored inside the application there always is a threat. Using php this problem can be overcomed somewhat :tongue: . So I decided to make the login + register system using this kinda php scripts. I am using a only admin read,write text file instead of a mysql database ( Easily maneagable for all hosting services ). So, I have come up with this following piece of code and I need some help in the confirming the login part.
The text file is like this :
username password hwid lastdate membershiptype
All separated by 'space' and one account per line.
I hope I have given enough information, If extra information is needed, I will give it.
<?php
$user = addslashes($_GET['username']);
$pass = addslashes($_GET['password']);

  $username = "theusername";
  $password = "thepassword";
  $url = "mywebsite.com/file.txt";
  $hostname= "ftp://$username:$password@$url";
  $contents = file_get_contents($hostname);
// That gives me the txt file which can only be read and written by the admin
if (strpos($contents,$user) !== false) {
   // Need code here to check if the adjacent word and the $pass are same to establish a successfull login
} else {
 echo "Username does not exist, please register"
}
?>

A: Here try this, hope it helps:
file.txt would need tobe in this format, values seperated by :, spaces are not a good way to seperate values.
username:password:hwid:lastdate:membershiptype

The PHP bit:
<?php
$user = $_GET['username'];
$pass = $_GET['password'];

if(check_auth(get_auth(),$user,$pass)==true){
    echo 'Yes';
}else{
    echo 'No';
}

/**
 * This function will grab the text file and create a user array
 *
 * @return array(0=>username,1=>password)
 */
function get_auth(){
    $username = "theusername";
    $password = "thepassword";
    $url = "mywebsite.com/file.txt";
    $location = "ftp://$username:$password@$url";

    $users = file($location);
    function split_auth(&$value){
        $value = explode(':',$value);
    }
    array_walk($users,'split_auth');
    return $users;
}

/**
 * This Function will check the username and password
 *  against the users array
 *
 * @param array $users
 * @param string $username
 * @param string $password
 * @return bool (true|false)
 */
function check_auth($users,$username,$password){
    foreach($users as $user){
        if($user[0]==$username && $user[1]==$password){
            return true;
        }
    }
    return false;
}
?>


text:
Q: How to draw CheckBox in rotated layout? I have rotated a RelativeLayout with Canvas.rotate().
public class MyLayout
extends RelativeLayout
{
    @Override
    protected void dispatchDraw(Canvas canvas){
        canvas.save();
        canvas.rotate(
            ANGLE,
            getWidth()/2,
            getHeight()/2);
        super.dispatchDraw(canvas);
        canvas.restore();
    }
}

If I place a Checkbox in this layout, it is not drawn correctly after being checked, because CheckBox's draw() is not called from layout's dispatchDraw().
Does anybody know how to fix this?

A: See if this is what you want
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Angle to rotate"/>

    <EditText
        android:id="@+id/angle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="30"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set Rotation"
        android:onClick="onClick"
        />

    <your.package.name.MyLayout
        android:id="@+id/myLayout"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:visibility="visible"
        android:gravity="center" >

        <CheckBox
            android:id="@+id/checkbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="CheckMe"/>

    </your.package.name.MyLayout>

</LinearLayout>

Activity.java
public class MainActivity extends Activity {

    private MyLayout myLayout;
    private EditText edAngle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myLayout = (MyLayout) findViewById(R.id.myLayout);
        edAngle = (EditText) findViewById(R.id.angle);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void onClick(View v){

        float angleToRotate = Float.parseFloat(edAngle.getText().toString());
        myLayout.setRotationAngle(angleToRotate);
    }
}

MyLayout.java
public class MyLayout
extends RelativeLayout
{
    public float myAngle = 0;
    public MyLayout(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    public MyLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    public MyLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void dispatchDraw(Canvas canvas){
        canvas.save();
        canvas.rotate(
            myAngle,
            getWidth()/2,
            getHeight()/2);
        super.dispatchDraw(canvas);
        canvas.restore();
    }

    public void setRotationAngle(float angle){

        this.myAngle = angle;
        this.invalidate();
    }

}

A: Working solution :
public class MyLayout extends RelativeLayout
{
private drawn = false;
@Override
protected void dispatchDraw (Canvas canvas )
{
    canvas .save();
    canvas .rotate(
        ANGLE,
        getWidth ()/ 2,
        getHeight ()/ 2
    );
    super.dispatchDraw (canvas);
    canvas .restore();

    if(!drawn){
        drawn = true;
        invalidate();
        drawn = false;
    }
}
}


text:
Q: Actionscript function definition How can I define functions that can receive unknown/variable amount of parameters?

A: It is called rest parameter, Use this:
function getItems(...rest):void
{
    // ... logic goes here
}

Inside the function you deal with rest as the name of the array.
When creating a rest parameter you should keep these in mind:

*

*Rest parameters are untyped. It is up to you to validate any special type requirements as you loop through the rest parameter array.

*Rest parameters must be at the end of a method's parameters.

*The rest parameters must have ... in front of it, but the variable name can be anything.

A: private function someFunction(...args) : void
{
  for(var i : int = 0; i < args.length ; i++)
  {
     trace(i, args[i]);
  }
}


text:
Q: AppleScript to append date to file I was recently able to make a drag and drop script in Automator that allowed me to zip and name a file and then automatically apply the date (DDMMYY) but now it's defaulting to (DDMMYYYY) and I can't change it. I've googled for a solution and nothing works since this needs to be at the end of the file name.
Does anyone know what I'm doing wrong or does anyone have an actual script that can help me? Everything I've found only works if the date is at the start of the file name, not at the end (but before the extension).

A: Since you didn't provide any code I can't guess how you name your files, but the way to get DDMMYY is to use shell with the do shell script command:
tell application "Finder"
    set theFile to (choose file)
    set theName to name of theFile
    set name of theFile to theName & "_" & (do shell script "date +%d%m%y") & ".xxx"
end tell

This doesn't get rid of the file extension of the original file. For that to work you would have to use something like this:
tell application "Finder"
    set theFile to (choose file)
    set theName to name of theFile
    set periodIndex to offset of "." in theName
    set theName to text 1 thru (periodIndex - 1) of theName
    set name of theFile to theName & "_" & (do shell script "date +%d%m%y") & ".xxx"
end tell

The code responsible for removing the file extension comes from this post.
You can add punctuation how you like by putting the desired symbols before the next %. So date +%d.%m.%y is possible and improves readability.

A: You can use this AppleScript inside a Run AppleScript action, it renames the archive inserting the date before the file extension
on run {input, parameters}
    set thePath to POSIX path of (item 1 of input)
    set currentDate to do shell script "date +%d%m%y"
    set newPath to text 1 thru -5 of thePath & "_" & currentDate & ".zip"
    do shell script "mv " & quoted form of thePath & space & quoted form of newPath
    return {POSIX file newPath as alias}
end run


text:
Q: How do I write an array of contents into a text file? The code is supposed to open an existing text file, transfer the contents into the array, then create a new text file and then write the array contents into the new text file. The problem I'm having is that the code only outputs the last line of the content from the new text file.
file.open("Patient.txt", ios::in);
    while (!file.eof()) {
        file >> arr[i].name >> arr[i].DOB >> arr[i].address >> arr[i].Dr_name >> arr[i].V_date;
        /*cout << arr[i].name << arr[i].DOB << arr[i].address << arr[i].Dr_name << arr[i].V_date << endl;*/
    }
    file.close();

    files.open("Patients_2.txt");

    if (files.is_open()) {
        for (i; i < 30; i++) {
            files << arr[i].name << arr[i].DOB << arr[i].address << arr[i].Dr_name << arr[i].V_date;
        }
    }
    files.close();

    patientss.open("Patients_2.txt");

    cout << "Patient 2: " << endl;
    while (!patientss.eof()) {
        getline(patientss, line);
        cout << line << endl;
    }

    patientss.close();
    system("pause");
    return 0;
}

A: This loop has a few problems:
 while (!file.eof()) {
        file >> arr[i].name >> arr[i].DOB ....

*

*You never increase i so the same arr[i] will be overwritten time and time again.

*You use !file.eof() as a condition to stop reading. eof() does not get set until after you've tried to read beyond the end of the file, which means that if you had increased i as you should, the last arr would be empty / broken. Instead check if the extraction from the stream succeeded. Since the stream is returned when you do stream >> var and has an overload for explicit operator bool() const which returns !fail() you can do this check directly in your loop:
while(stream >> var) { extraction success }
Using formatted input (>>) for string fields that are likely to contain spaces is however not a good idea. Your name, nung khual, would be split so nung would go into name and khual would go into DOB. It's better to use a field separator that is very unlikely to be included in anyone's name. \n is usually good and works well with std::getline.
std::getline returns the stream that you gave as an argument which means that you can chain getlines similarly to stream >> var1 >> var2, except it's a little more verbose.
getline(getline(stream, var1), var2) will put the first line in var1 and the second line in var2.
To make input and output a little simpler you can add stream operators for your data type and make the input stream operator use getline for your fields.
Example:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

struct data_t {
    std::string name;
    std::string DOB;
    std::string address;
    std::string Dr_name;
    std::string V_date;
};

// input stream operator using chained getlines
std::istream& operator>>(std::istream& is, data_t& d) {
    using std::getline;
    return getline(getline(getline(getline(getline(is,
           d.name), d.DOB), d.address), d.Dr_name), d.V_date);
}

// output stream operator
std::ostream& operator<<(std::ostream& os, const data_t& d) {
    return os << d.name << '\n'
              << d.DOB << '\n'
              << d.address << '\n'
              << d.Dr_name << '\n'
              << d.V_date << '\n';
}

int main() {
    std::vector<data_t> arr;

    if(std::ifstream file("Patient.txt"); file) {
        data_t tmp;
        while(file >> tmp) {                           // remember, no eof() needed
            arr.push_back(tmp);
        }
    }

    if(std::ofstream file("Patients_2.txt"); file) {
        for(const data_t& d : arr) {
            file << d;
        }
    }

    if(std::ifstream patientss("Patients_2.txt"); patientss) {
        data_t tmp;
        while(patientss >> tmp) {
            std::cout << tmp;
        }
    }
}

A: IMHO, you should overload the formatted insertion and extraction operators in your patient class:
struct Patient
{
    std::string name;
    std::string dob;
    std::string address;
    std::string dr_name;
    std::string v_date;
    friend std::istream& operator>>(std::istream& input, Patient& p);
    friend std::ostream& operator<<(std::ostream& output, const Patient& p);
};

std::istream& operator>>(std::istream& input, Patient& p)
{
    std::getline(input, p.name);
    std::getline(input, p.dob);
    std::getline(input, p.address);
    std::getline(input, p.dr_name);
    std::getline(input, p.v_date);
    return input;
}

std::ostream& operator<<(std::ostream& output, const Patient& p)
{
    output << p.name << "\n";
    output << p.dob << "\n";
    output << p.address << "\n";
    output << p.dr_name << "\n";
    output << p.v_date << "\n";
    return output;
}

The above makes input and output easier:
std::vector<Patient> database;
Patient p;
while (input_file >> p)
{
    database.push_back(p);
}

const unsigned int quantity = database.size();
for (unsigned int i = 0; i < quantity; ++quantity)
{
    output_file << database[i];
}

The above code also supports the concepts of encapsulation and data hiding.  The Patient struct is in charge or reading its members because it knows the data types of the members.  The code external to the Patient is only concerned with the input and output of a Patient instance (doesn't care about the internals).


text:
Q: JavaScript: confusion about WeakSet and its effects on garbage collection I have been grinding leetcode and I encountered this question https://leetcode.com/problems/intersection-of-two-linked-lists/ where it asks you to find the intersection of two LinkedList. One solution (not the best one I know) is to use a hash set to keep track of the first linked list while traversing through it and then traversing through the second list. When we found out that there is a duplicate node then that is the intersection.
For example, E is the intersection
A -> B
       \
         E -> F
       /
C -> D

The way I solved it is to use a WeakSet as the hash set to store the reference of the first linked list.
Here is the code
var getIntersectionNode = function(headA, headB) {
    let hashSet = new WeakSet()

    while(headA){
        hashSet.add(headA)
        headA = headA.next
    }
    while(headB){
        if(hashSet.has(headB)) return headB
        headB = headB.next
    }
    return null
};

My question is, since WeakSet has this nice feature - when no other references to an object stored in the WeakSet exist, those objects can be garbage collected. If we go back to the example here, when we are iterating through A -> B -> E -> F, we are adding every node into  the hash set, but we don't preserve the reference for every node, i.e. headA = headA.next. So that means after I added one node into the hash set and I advanced to the next node, the reference to the previous node is gone, then it should be garbage collected from the hash set right? Then how come the solution would pass?
For example, when we are at A, we store the A into the hash set, and we advance to B, now there is no way to reference back to A, with WeakSet it should have been garbage collected. But clearly if that is the case the solution wouldn't work. Can someone point out where my understanding is wrong here?

A: There are a couple issues here:

*

*The original objects passed into getIntersectionNode from the caller will still exist at least until the function finishes. If you do
someFn({ foo: 'bar' })

The object won't get garbage collected until synchronous JS processing has finished; the GC only runs once JS is idle, and even then, it'll often take a few seconds. If you add an element to a WeakSet, and you were somehow able to observe when exactly it gets removed from it due to there no longer being any references to it, it would take some time.

*Even then, even if unreferenceable objects were GC'd immediately, in this case, all that's needed is for the one intersection node to remain referenceable. If there's an intersection, that intersection node will be a child of headA somewhere, and that node will also exist somewhere nested inside headB; a reference still exists to it inside headB even after iterating through headA.
Unless your script carries out asynchronous tasks (like wait for user input, or a setTimeout), there's no benefit to using a WeakSet over a Set (or a WeakMap over a Map), since the garbage collector won't run in time for it to be of any use.


text:
Q: Sequence of Tense Which one is correct?

*

*Centuries ago, people weren't aware that the planets revolved around the sun.

*Centuries ago, people weren't aware that the planets revolve around the sun.

In my grammar book it has mentioned the first one as "grammatical correct sentence", but it has not done such a comparison.

A: Grammatically it seems both are correct, but reading it, the second one makes more sense to me, since planets still revolve around the sun.

A: The first one is correct.
The grammar in the first suggests the people's awareness related to the planets at their time. You could rephrase this sentence for clarity: "Centuries ago, people weren't aware that the planets that they viewed in the night sky revolved around the sun.
The grammar in the second suggests the people's awareness related to the planets in our time. Depending on how you dissect the second, it could mean: "Even though planets didn't revolve around the sun then, centuries ago, people weren't ware that the planets revolve around the sun now."


text:
Q: Xamarin form: How to override the OnBackButtonPressed on iOS The OnBackButtonPressed doesn't get called. I have looked at other places, the function worked on android hardware back button. I wanted to alert user to enter the pin before they can go back to previous screen. My page was not a normal page. It's a tab page.. What should I do to override the navigation back button on iOS.

A: You need to replace the default back button with a custom back button, Xamarin Forms's Navigation Bar is mapped to the UINavigationBar in iOS so you need to set custom back button to UILeftBarButtonItem like below
public override void ViewWillAppear(bool animated)
{
    var backBtn = new UIButton(UIButtonType.Custom)
    {
        // setup your custom back button with title, image etc
    }
    backBtn.TouchDown += (sender, e) =>
    {
        //Handle back click here
    };

    NavigationController.TopViewController.
    NavigationItem.LeftBarButtonItem = new UIBarButtonItem(backBtn);
}

You also need to bridge between Native to Forms so that you can get a callback in your Xamarin PCL or shared project.
There is a full implementation with code in this article


text:
Q: Загрузка главного изображения сообщества Как отправить "POST-запрос" с полем photo?
Это поле должно содержать изображение в формате "multipart/form-data" для загрузки фотографии через API "Вконтакте"?
Какую библиотеку лучше всего использовать?

A: Для организации работы с сервером есть любимая многими библиотека Retrofit. Но Retrofit ценен только в том случае, если с сервера приходят структуры данных в JSON или XML, которые для работы нужно парсить.
При передаче туда или обратно бинарных данных Retrofit будет мешать, в этом случае стоит использовать чистый HTTP-клиент, без всяких "обвесов". Берите OkHttp.
В документации к OkHttp есть достаточно примеров, там вы найдете подходящий для вашего случая: https://github.com/square/okhttp/wiki/Recipes


text:
Q: NumericUpDown controls linked dynamically I have a label with an integer, and I have multiple NumericUpDown Controls.
How do I make it so, that the NUDs are collectively is limited to the value of the label?
So for example:
int_lbl.Text = "0";
NUD1.Value = "3";
NUD2.Value = "7";

So if I increase either NumUpDown, it should throw an error since it's ran out of integers to allocate. but if i decrease the NumUpDown, it should add the integers back to the label. And vice versa to update them dynamically during ValueChanged Event.
The idea is to adjust the other variables accordingly during ValueChanged.
I've disabled keyboard entry, so the user is only limited to the use of the Arrows.


text:
Q: A proper universal name for any city or town, regardless of its size I'm facing a pressing issue with choosing a proper way to call a place (city, town), regardless of its size.
1) Has to describe places of any size (from pop. 5 to 5 mil.)
2) Must describe any location that is inhabited and/or has any administrative boundaries
3) Should be easy-to-understand by Americans specifically
Basically, things like "locality", "community", "municipality", "administrative unit", "metropolitan area" etc cross my mind, but I am not too sure how exactly it will be perceived - which one is more common, and which one will be the best fit for a native ear to hear to describe both NYC and a village of 2 houses (given it is on the map).
Thanks in advance for your options, which I hope will be a great many for me to choose from! :-)

A: To be very general, you might choose settlement:

"A settlement is a place where people have come to live and have built homes."1

An interesting article on settlement to refer to different sizes can be found on the BBC's GCSE Bitesize. I added an image they use for clarification below (credit goes to the BBC's GCSE Bitesize):

Example sentences:

"The village is a settlement of just fifty houses."1
"A large Roman settlement has been discovered just outside the French town."4
"'In the 1730s Slovenians and Croatians established small agricultural settlements in Georgia.'"5
"'By the end of the nineteenth century, Cajuns had established settlements in the Louisiana-Texas border region.'"5
"'Libya boasts the ruins of ancient Greek outposts, Phoenician settlements and Berber cities.'"5
"London [...] is the capital and most populous city of England and the United Kingdom. Standing on the River Thames in the south east of the island of Great Britain, London has been a major settlement for two millennia."6


text:
Q: Scala: Iterate over 20k images once, crop 100 ways to make 100 Iterators requirement
I need to iterate over images, splitting each into 100 blocks (ROIs) and calculating something independently per block. I can't store anything other than the file paths in a list in memory, and I can't perform disk IO more than once. Performance is more important than simplicity here. How do I build 100 iterators while iterating over images?
code
I've written this a few ways but always get a StackOverflowError after ~5 hours (should finish in under 20 minutes).
The following is the way that made the most sense to me: Iterate over an in-memory list of paths and build a map of iterators.
def calcAll(run: ImageBase, rois: Traversable[Roi]): Map[Roi, TraversableOnce[T]] = {
    val results: mutable.Map[Roi, Iterator[T]] = emptyMutableMap(rois)

    // calculate feature between every two frames
    var prevImage: RichImage = null // it'll be ok, I promise
    for (frame <- ImageStore.walk(run) { // iterates over nio Path objects
        val image = RichImages.of(frame)
        if (prevImage != null) for (roi <- rois) {
            val next: Iterator[T] = calc(Iterator(prevImage.crop(roi), image.crop(roi)))
            results(roi) = results(roi) ++ next // StackOverflowError!!
        }
        prevImage = image
    }

    results.toMap // immutable
}

background
I have a directory of 20k grayscale frames from a video. The video has a set of 100 Regions of Interest (ROIs), non-overlapping rectangles that we care about. I need to calculate features between consecutive images, but independently for each ROI. The amount of data and number of ROIs prohibits reading an image more than once.

A: I believe you need something similar to this:
def calcAll(run: ImageBase, rois: Seq[Roi]): Traversable[Map[Roi, T]] = {
  ImageStore.walk(run).map(RichImages.of).sliding(2).map {
    case Seq(image1, image2) =>
      rois.map(roi => roi -> calc(image1.crop(roi), image2.crop(roi)).toMap
  }
}

Given that ImageStore.walk returns an Iterator or Traversable, this code will load each image only once and won't have to store more than two images in memory at a time.
This gives you a single iterator though. Having 100 iterators will require either storing all images in memory, or traversing them 100 times. So, unfortunately, I believe you'd have to do with a Traversable[Map[Roi, T]].


text:
Q: android question about service and the method onstartcommand In a service class there is a method to start the service. If that service gets done executing does it runs onstartcommand from the beginning? Is onstartcommand sorta like a loop as long as the service is running.  For example i have
onStartCommand {
  int x = 0;
  if(x == 0){

  } else {
  }
}

After that is complete does it run it again. If you know that answer please explain. I have read google explanation of services and it did not explain that part very well. Is onstartcommand sorta like a loop as long as the service is runnning

A: No, it isn't. onstartcommand is run once. If you want to do something that takes long or does something recursively, you probably want to create a thread to do the hard job and just return from onStartCommand().


text:
Q: Progress Bar not showing when setting visibility to VISIBLE I am creating a program that is supposed to show a progress bar when it is doing something in the background (using AsyncTask) and when the task finishes the progress bar goes and the result is shown.
I've included a progress bar in the RecyclerView but set it visibility to gone.
and in the AsyncTask PreExecute I set its visibility to VISIBLE and in OnPostExecute I set its visibility to GONE but when I run the application the progress bar doesn't show at all.

I have included the XML :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
tools:showIn="@layout/activity_main">

<android.support.v4.widget.ContentLoadingProgressBar
    android:id="@+id/rv_progress_bar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:indeterminate="true"
    android:indeterminateTint="@color/plus_icon_color"
    android:visibility="gone" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/train_rv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="vertical" />

and the Java Code:

public class MainActivity extends AppCompatActivity {
private RecyclerView mTrainsRv;
private TrainAdapter mTrainAdapter;
ArrayList<Train> trains = new ArrayList<>();
ProgressBar mRvProgress;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mRvProgress = (ProgressBar)findViewById(R.id.rv_progress_bar);
    mTrainsRv = (RecyclerView) findViewById(R.id.train_rv);
    mTrainsRv.setLayoutManager(new LinearLayoutManager(this));
    mTrainAdapter = new TrainAdapter(createDefaultTrains());
    mTrainsRv.setAdapter(mTrainAdapter);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            trains.add(new Train(4, "Berowra Platform 4", 12, "Late", "Beverly", "15:18"));
            mTrainAdapter.notifyDataSetChanged();
        }
    });
}

private List<Train> createDefaultTrains() {
    trains.add(new Train(0, "Albion Park Platform 1", 3, "On Time", "Allawah", "14:11"));
    trains.add(new Train(1, "Arncliffe Platform 2", 4, "Late", "Central", "14:34"));
    trains.add(new Train(2, "Artarmion Platform 3", 7, "On Time", "Ashfield", "15:01"));
    trains.add(new Train(3, "Berowra Platform 4", 12, "Late", "Beverly", "15:18"));
    return trains;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    // Handle item selection
    switch (item.getItemId()) {
        case R.id.action_delete:
            trains.clear();
            mTrainAdapter.notifyDataSetChanged();
            return true;
        case R.id.action_refresh:
            new RefreshProgressAsync().execute();
            return true;
        case R.id.action_quit:
            Toast.makeText(this, R.string.quit_menu,
                    Toast.LENGTH_LONG).show();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
private class RefreshProgressAsync extends AsyncTask<Void,Void,Integer> {
private int mGenerated;

    @Override
    protected Integer doInBackground(Void... voids) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        int ran = 0;
        Random r = new Random();
        for(int i=0; i<trains.size(); i++) {
            int min = 1;
            int max = 20;
            ran = r.nextInt(max - min + 1) + min;
            mGenerated = ran;
        }
        return mGenerated;
    }

    @Override
    protected void onPreExecute() {
        mRvProgress.setVisibility(View.VISIBLE);
        mTrainsRv.setAlpha(0);
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Integer arrivalTime) {
        super.onPostExecute(arrivalTime);
        for (int i=0; i<trains.size();i++){
            trains.get(i).setArrivalTime(arrivalTime);
        }
        mTrainAdapter.notifyDataSetChanged();
        mTrainsRv.setAlpha(1);
        mRvProgress.setVisibility(View.GONE);
    }
}

I don't know why it isn't showing.
Thanks

A: It is behaving as expected. Purpose of ContentLoadingProgressBar is to show the progress only when necessary. If the operation take trivial amount of time, then the progress bar won't be shown. This is to avoid having flashing effect of progress bar, showing and disappearing in quick succession.
If you want to make it visible for testing purpose (I won't recommend in production code), then increase your sleep time to 10 seconds:
 @Override
  protected Integer doInBackground(Void... voids) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ....
  }

Alternatively you can just use normal ProgressBar