text:
Q: Bootstrap class formatting breaking my Flask WTForms I have this WTForms template which produces a simple form with text fields, radio buttons and a submit button.
{% extends "layout.html" %}

{% block content %}

    <form action="{{ url_for('home') }}" method=post>

Part I,

G1

        {{ form.node_1.label }}
        <form class="form-inline" role="form">
            {% for subfield in form.freq_1 %}
{{ subfield }}	{{ subfield.label }}
{% endfor %}
        </form>

G2

        {{ form.node_2.label }}
        <form class="form-inline" role="form">
            {% for subfield in form.freq_2 %}
{{ subfield }}	{{ subfield.label }}
{% endfor %}
        </form>

Part II

            {{ form.extra1.label }} {{ form.extra1}}
            {{ form.extra1Email.label }} {{ form.extra1Email }}
            {{ form.extra1Group.label }} {{ form.extra1Group }}
            <form class="form-inline" role="form">
                {% for subfield in form.extra1Freq %}
{{ subfield }}	{{ subfield.label }}
{% endfor %}
            </form>

            {{ form.extra2.label }} {{ form.extra2}}
            {{ form.extra2Email.label }} {{ form.extra2Email }}
            {{ form.extra2Group.label }} {{ form.extra2Group }}
            <form class="form-inline" role="form">
                {% for subfield in form.extra2Freq %}
{{ subfield }}	{{ subfield.label }}
{% endfor %}
            </form>

        {{ form.submit }}

    </form>

{% endblock %}

Here's the html Flask produces:
<!DOCTYPE html>

    <title>Title</title>
    <link rel="stylesheet" href="/static/css/bootstrap.css">

Title

Home

Network

        <form action="/" method=post>

Part I,

G1

                First name 1 Last name 1
                <form class="form-inline" role="form">

                            <input checked id="freq_1-0" name="freq_1" type="radio" value="0">

                            1

                            <input id="freq_1-1" name="freq_1" type="radio" value="1">

                            2

                            <input id="freq_1-2" name="freq_1" type="radio" value="7">

                            3

                            <input id="freq_1-3" name="freq_1" type="radio" value="30">

                            4

                            <input id="freq_1-4" name="freq_1" type="radio" value="183">

                            5

                            <input id="freq_1-5" name="freq_1" type="radio" value="365">

                            6

                </form>

G2

                First name 2 Last name 1
                <form class="form-inline" role="form">

                            <input checked id="freq_2-0" name="freq_2" type="radio" value="0">

                            1

                            <input id="freq_2-1" name="freq_2" type="radio" value="1">

                            2

                            <input id="freq_2-2" name="freq_2" type="radio" value="7">

                            3

                            <input id="freq_2-3" name="freq_2" type="radio" value="30">

                            4

                            <input id="freq_2-4" name="freq_2" type="radio" value="183">

                            5

                            <input id="freq_2-5" name="freq_2" type="radio" value="365">

                            6

                </form>

Part II

                First and Last name:
                <input id="extra1" name="extra1" type="text" value="">
                Email:
                <input id="extra1Email" name="extra1Email" type="text" value="">
                Company or Group:
                <input id="extra1Group" name="extra1Group" type="text" value="">
                <form class="form-inline" role="form">

                            <input id="extra1Freq-0" name="extra1Freq" type="radio" value="1">

                            1

                            <input id="extra1Freq-1" name="extra1Freq" type="radio" value="7">

                            2

                            <input id="extra1Freq-2" name="extra1Freq" type="radio" value="30">

                            3

                            <input id="extra1Freq-3" name="extra1Freq" type="radio" value="183">

                            4

                            <input id="extra1Freq-4" name="extra1Freq" type="radio" value="365">

                            5

                </form>

                First and Last name:
                <input id="extra2" name="extra2" type="text" value="">
                Email:
                <input id="extra2Email" name="extra2Email" type="text" value="">
                Company or Group:
                <input id="extra2Group" name="extra2Group" type="text" value="">
                <form class="form-inline" role="form">

                            <input id="extra2Freq-0" name="extra2Freq" type="radio" value="1">

                            1

                            <input id="extra2Freq-1" name="extra2Freq" type="radio" value="7">

                            2

                            <input id="extra2Freq-2" name="extra2Freq" type="radio" value="30">

                            3

                            <input id="extra2Freq-3" name="extra2Freq" type="radio" value="183">

                            4

                            <input id="extra2Freq-4" name="extra2Freq" type="radio" value="365">

                            5

                </form>

            <input id="submit" name="submit" type="submit" value="Send your form">
        </form>

I use Bootstrap 3 to format the lists of buttons by attributing a class to parts of the form:
<form class="form-inline" role="form">

For some reasons, using these classes "breaks" my form, in that clicking the "submit" button doesn't register or lead anywhere. When I remove the above line (and their relative "") from the form, I am then able to submit.
What is wrong with my use of these Bootstrap classes? What is the proper way to use them?


text:
Q: Markdown issue in private beta site Today I visited the sign up page of Interpersonal Skills from a browser which I didn't signed in to Stack Exchange and saw a message,

Warning: this site is currently in **private beta** for at least 1 more day.

I assume the double ** is used to indicate the private beta in bold text.
But it actually renders as

The same also happens in the Login message.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как сделать другую анимацию на третий клик? и Как сделать так чтобы префабы "выпадали" из объекта при разрушении? Сделал 2 анимации TreeDance.anim и Fall.anim. По моей задумке при первых двух кликах на дерево(мой объект) должна воспроизводиться анимация TreeDance.anim, а на третий Fall.anim.
Так вот, TreeDance.anim воспроизводится, а Fall.anim нет.
Объясните пожалуйста как сделать так чтобы при уничтожении дерева появлялись брёвна (ещё мои объекты).
Моя версия скрипта:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TreeDestroy : MonoBehaviour {

private int td;
public GameObject Log;

void Start () {

}

void Update () {
    if (td == 3) {
        Destroy (gameObject);
        Instantiate (Log);
        Instantiate (Log);
        Instantiate (Log);
    }
}
void OnMouseDown () {
    td = td + 1;
    if (td <= 2) {
        GetComponent<Animator> ().SetTrigger ("Dance");
    }
    else
        GetComponent<Animator> ().SetTrigger ("Fall");
    }
}

Заранее спасибо за ответ!

A: По коду вроде все правильно, вероятно ошибка в настройке анимации. Я бы посоветовал разумнее настроить AnimatorController. На сколько я понимаю у вас два состояния в нем и переходите вы в них устанавливая соответствующие переменные аниматора. Скорей всего дело в переходах. Я бы сделал параметр Stateтипа int и в него при клике передавал ваш td. А дальше настроил переходы в контроллере из AnyState в ваши анимации по требуемым условиям со State. Если ваша анимация не должна крутится без остановки, то не забудьте в настройках перехода отключить галочку с переходом если уже находитесь в этом состоянии Can Transition To Self.
Если вы потом надумаете что дерево должно падать на 4 раз, вам не придется в код лезть чтобы исправить это, просто подправите контроллер.

A: Попробуй это:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Destroyable : MonoBehaviour
{

    private int _td;

    public GameObject[] ObjectsToDrop;

    void OnMouseDown()
    {
        _td += 1;
        if (_td <= 2)
        {
            GetComponent<Animator>().SetTrigger("Dance");
        }
        else
        {
            GetComponent<Animator>().SetTrigger("Fall");
            StartCoroutine(WaitForAnimationEndDropItemsAndDestroy());
        }
    }

    IEnumerator WaitForAnimationEndDropItemsAndDestroy()
    {
        yield return new WaitForSeconds(1);//указать длинну анимации в секундах

        DropItems();

        Destroy(gameObject);
    }

    private void DropItems()
    {
        foreach (var item in ObjectsToDrop)
        {
            if (item != null)
            {
                var tmp = Instantiate(item);
                var zdvig = Random.Range(1,3);
                tmp.transform.location = new Vector3(tmp.transform.location.x + zdvig, tmp.transform.location.y+zdvig, tmp.transform.location.z);
            }
        }
    }

}


text:
Q: Contact Form auto save when typing in WordPress I have 2 forms, both of them are divided in 2.
First time I ask for name, email, phone and company than I have 2 buttons continue and call me
Some of them may not click continue button so I need to get this details before they run away from the page.
I need the form to do an auto save when all fields are completed even if user is not submitting the form.
How can I do this with contact form 7 or formidable forms?
I'm open to new suggestions too, other plugins etc..
Thank you.

A: u can try this plugin contact form 7 AutoSaver  ,
 Select some forms to enable auto-save on them, meaning when a user fill the form, without even submitting it, then navigates to another page and comes back or refreshes the page, they will see the data they previously filled still available for them!
https://wordpress.org/plugins/cf7-autosaver/


text:
Q: How to create circe whit GMap in VB.Net I'm looking for some function which can create a circle on map. I'm using Gmap library in VB.Net. Exist some function which can create a circle around of point on map, for examle with 500 meters radius ?
I found a code, but it isn't what I'm exactly looking for :
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports GMap.NET
Imports GMap.NET.WindowsForms

Namespace Map

    Public Class GMapMarkerCircle
        Inherits GMapMarker
        Private m_Radius As Integer
        'In Meters
        Public m_OutlinePen As Pen
        Public m_FillBrush As Brush
        Public m_Fill As Boolean

        Public Sub New(p As PointLatLng, Radius As Integer, OutlinePen As Pen, FillBrush As Brush, Fill As Boolean)
            MyBase.New(p)
            m_OutlinePen = OutlinePen
            m_FillBrush = FillBrush
            m_Radius = Radius
            m_Fill = Fill
        End Sub

        Public Overrides Sub OnRender(g As Graphics)
            g.SmoothingMode = SmoothingMode.AntiAlias

            Dim R As Integer = CInt((m_Radius) / Overlay.Control.MapProvider.Projection.GetGroundResolution(Overlay.Control.Zoom, Position.Lat)) * 2

            If m_Fill = True Then
                g.FillEllipse(m_FillBrush, New System.Drawing.Rectangle(LocalPosition.X - R \ 2, LocalPosition.Y - R \ 2, R, R))
            End If
            g.DrawEllipse(m_OutlinePen, New System.Drawing.Rectangle(LocalPosition.X - R \ 2, LocalPosition.Y - R \ 2, R, R))
        End Sub

    End Class
End Namespace

And in app:
Dim CircleMarker As New GMapMarkerCircle(New GMap.NET.PointLatLng(ZemSirka, ZemDlzka), 660, New Pen(Color.Azure, 1), Brushes.LightSeaGreen, True)
            Dim Overlay As New GMapOverlay("Circle")
            Overlay.Markers.Add(CircleMarker)
            GMapControl1.Overlays.Add(Overlay)

But when I zoom in/out the map circle disappears.
I have one beginners question: is any possibility to do Brushes semitransparent ?

A: Finally I create code which works fine for short distances for examle: 200,300,500 meters.
Public Function toRad(ByVal deegres As Double)
        Return deegres * (Math.PI / 180)
    End Function

    Public Function toDeg(ByVal radians As Double)
        Return radians * (180 / Math.PI)
    End Function

    Private Function pivotRadius(ByVal Dlzka As Double, ByVal Sirka As Double, ByVal dist As Double)

        Dim distance = (dist / earthRadius) / 1000
        Dim lat As Double = toRad(Sirka)
        Dim lng As Double = toRad(Dlzka)

        Dim points As IList(Of PointLatLng) = New List(Of PointLatLng)()

        Dim x As Integer = 0
        While x < 360
            Dim brng As Double = toRad(x)
            Dim latRadians As Double = Math.Asin(Math.Sin(lat) * Math.Cos(distance) + Math.Cos(lat) * Math.Sin(distance) * Math.Cos(brng))
            Dim lngRadians As Double = lng + (Math.Atan2(Math.Sin(brng) * Math.Sin(distance) * Math.Cos(lat), Math.Cos(distance) - Math.Sin(lat) * Math.Sin(latRadians)) / 1.6)
            points.Add(New PointLatLng(toDeg(lngRadians), toDeg(latRadians)))
            latRadians = 0
            lngRadians = 0
            x += 10
        End While

        Dim polyOverlay As New GMapOverlay("polygons")
        Dim polygon As New GMapPolygon(points, "mypolygon")
        polygon.Fill = New SolidBrush(Color.FromArgb(30, Color.Aqua))
        polygon.Stroke = New Pen(Color.Blue, 1)
        GMapControl1.Overlays.Clear()
        GMapControl1.Overlays.Add(polyOverlay)
        polyOverlay.Polygons.Add(polygon)

        Return 0

    End Function


text:
Q: Left join Without Subqueries I am getting the below output, I want the same out but without subqueries.I am looking to  refine the below query by removing the subquery as it is affecting the performance of the application. Could anyone  help me to remove subquery and fetch the required data using the joins.

SELECT DISTINCT rec.requestno as requestno
    , (SELECT min(dateandtime)
       from recruitersubmission
       where recruitersubmission.requestno = rec.requestno) as firstsubmsion
    , (SELECT max(dateandtime)
       from recruitersubmission
       where recruitersubmission.requestno = rec.requestno) as lastsubmission
    , cndinterview.dateandtime as  candidatefedtime
    , cndinterview.dateandtime AS recruitertime
    , CONCAT(availabledate,' ', availabletime) AS candidateavaibledatetime
    , cndfeedback.status AS status
    , cndfeedback.offereddate AS offereddate
    , cnd.status AS onboard
    , (SELECT COUNT(recruitersubmission.requestno)
       FROM recruitersubmission
       WHERE recruitersubmission.requestno=rec.requestno) AS totalSub
    , (select COUNT(candidatefeedback.requestno)
       from candidatefeedback
       WHERE candidatefeedback.requestno = rec.requestno
          && candidatefeedback.status = 'Selected' ) as totalsel
    , (select COUNT( candidatefeedback.requestno)
       from candidatefeedback
       WHERE candidatefeedback.requestno = rec.requestno
          && cndfeedback.status = 'Rejected' ) as totalrej
    , (select COUNT(candidatefeedbkonboard.requestno)
       from candidatefeedbkonboard
       WHERE candidatefeedbkonboard.requestno = rec.requestno
          && cnd.status = 'Drop' ) as totaldrop
    , (select COUNT(candidatefeedbkonboard.requestno)
       from candidatefeedbkonboard
       WHERE candidatefeedbkonboard.requestno = rec.requestno
          && candidatefeedbkonboard.status = 'Onboarded' ) as totalonboard
from recruitersubmission AS rec
LEFT JOIN candidatefeedbkonboard AS cnd
    ON rec.requestno=cnd.requestno
LEFT JOIN candidatefeedback AS cndfeedback
    ON rec.requestno=cndfeedback.requestno
LEFT JOIN candidatesinterview AS cndinterview
    ON rec.requestno=cndinterview.requestno
where rec.clientname = '$client'
   && rec.requestno != ''
   && rec.country = '$location'
   && date(rec.dateandtime) between '$fromdate'

I want to avoid these below subqueries.
(select COUNT(candidatefeedback.requestno) from candidatefeedback WHERE candidatefeedback.requestno = rec.requestno && candidatefeedback.status = 'Selected' ) as totalsel

A: Thank you for the help friends. I figured out how to do it. Below is the solution for your refernce.
SELECT
    rec.requestno,
    COALESCE(totalsub, 0) AS totalsub,
    COALESCE(totalsel, 0) AS totalsel,
    COALESCE(totalrej, 0) AS totalrej
FROM recruitersubmission rec
LEFT JOIN (
    SELECT requestno, COUNT(*) AS totalsub
    FROM recruitersubmission
    GROUP BY requestno
) recruitersubmission  ON recruitersubmission.requestno = rec.requestno
LEFT JOIN (
    SELECT  requestno,count(if(status = 'Selected',1,Null)) AS totalsel,count(if(status = 'Rejected',1,Null)) as totalrej
    FROM candidatefeedback
    GROUP BY requestno
) candidatefeedback  ON candidatefeedback.requestno = rec.requestno

GROUP by rec.requestno Limit 0,25

A: Re: your subqueries:
(SELECT min(dateandtime)
from recruitersubmission
where recruitersubmission.requestno = rec.requestno)
Needs INDEX(requestno, dateandtime).  Similarly for other subqueries.
Re: Seejith's answer:
count(if(status = 'Selected',1,Null))

Can be replaced by
SUM(status = 'Selected')

thereby eliminating the need for COALESCE(.., 0).


text:
Q: Dynamic css not applied in my menu (tiles + spring 3.0) I am using Spring 3.0 + tiles. I have created the common menu with anchor tag for all the pages and applied the css for the same. I am using Jquery for dynamically changing the css class for the menu when the menu is clicked.
When the menu/link is selected, "selectedTab" css class is to be applied and for all the normal links "tab" css class is to be applied. I am facing the problem that with each request/click on the menu the style class is applied and then after the response it gets unapplied again. That is, the style remains applied between the request and response. But not after the response. The code for menu links is as under:

        Dashboard

        Projects

        Milestones

        Tasks

        Discussions

        Reports

        History

        Project templates

        Users

The Jquery for the same is:
function changeCss(aid) {
//alert(aid);
jQuery("#menu a").removeClass("selectedTab");
jQuery("#menu a").addClass("tab");

jQuery("#"+ aid).removeClass("tab");
jQuery("#" + aid).addClass("selectedTab");

}
The Css classes for the menu are:
a.selectedTab:hover,
    .studioTopNavigationPanel
    .contentSection
    .navigationBox a
    .selectedTab:active
    {
        background-color: #B8D9ED;
        background-image: url("../images/tab_selected_bg.png");
        background-position: center top;
        background-repeat: repeat-x;
        color: #333333;
        cursor: pointer;
        display: block;
        float: left;
        font-size: 14px;
        margin-right: 3px;
        padding: 5px 12px;
        text-decoration: none;
    }
.studioTopNavigationPanel .contentSection .navigationBox a.tab,
.studioTopNavigationPanel .contentSection .navigationBox a.tab:visited,
.studioTopNavigationPanel .contentSection .navigationBox a.tab:hover,
.studioTopNavigationPanel .contentSection .navigationBox a.tab:active
{
    background-color: #ECF3F7;
    background-image: url("../images/tab_bg.png");
    background-position: center top;
    background-repeat: repeat-x;
    color: #333333;
    cursor: pointer;
    display: block;
    float: left;
    font-size: 14px;
    margin-right: 3px;
    padding: 5px 12px;
    text-decoration: none;
}

.studioTopNavigationPanel .contentSection .navigationBox a.selectedTab,
.studioTopNavigationPanel .contentSection .navigationBox a.selectedTab:visited,
.studioTopNavigationPanel .contentSection .navigationBox a.selectedTab:hover,
.studioTopNavigationPanel .contentSection .navigationBox a.selectedTab:active
{
    background-color: #B8D9ED;
    background-image: url("../images/tab_selected_bg.png");
    background-position: center top;
    background-repeat: repeat-x;
    color: #333333;
    cursor: pointer;
    display: block;
    float: left;
    font-size: 14px;
    margin-right: 3px;
    padding: 5px 12px;
    text-decoration: none;
}

Please tell where I am wrong and provide appropriate solution for the same as soon as possible.

A:

Our Mission

Company Info

All Services

Press

Careers

Try it simply. It will work only you have to change the styling whatever you require.
Its working.

A: I also think that a server-side menu construction, applying selectedTab to the current concerned element is the best solution, as exposed by Quaternion.
But if you really don't manage to do it, you can also (carefull... dirt) parse the document.location.href in js to know on which page you are, and then apply the selectedTab class to the right element.

A: Perhaps you could try something like this:
var urlProjectsController = 'http://yourdomain.com/projectscontroller.html';
var urlMilestones = 'http://yourdomain.com/milestones.html';
if (window.location.href == urlProjectsController ){
  jQuery("#projects").removeClass("tab");
  jQuery("#projects").addClass("selectedTab");
}else if (window.location.href == urlMilestones ){
  jQuery("#milestones").removeClass("tab");
  jQuery("#milestones").addClass("selectedTab");
}
......
......
and so on for the remaining links.

A: jQuery(function(){
  jQuery("#menu a").on("click",function(){
    jQuery("#menu a").removeClass("selectedTab");
    jQuery("#menu a").addClass("tab");
    jQuery(this).removeClass("tab");
    jQuery(this).addClass("selectedTab");
 })
});

A:    $(document).on("click", "#message", function(event) {

    $('.chat-type-msg').css('background-color','#FAFAFA');
    $('.chat-type-msg').css('color','#535353');
   });

A: Try this
.studioTopNavigationPanel .contentSection .navigationBox a.selectedTab,
.studioTopNavigationPanel .contentSection .navigationBox a.selectedTab:visited,
.studioTopNavigationPanel .contentSection .navigationBox a.selectedTab:hover,
.studioTopNavigationPanel .contentSection .navigationBox a.selectedTab:active
{
background-color: #B8D9ED !important;
background-image: url("../images/tab_selected_bg.png");
background-position: center top;
background-repeat: repeat-x;
color: #333333!important;
cursor: pointer;
display: block;
float: left;
font-size: 14px;
margin-right: 3px;
padding: 5px 12px;
text-decoration: none;
}

A: jQuery(function(){
  jQuery("#menu a").on("click",function(){
    if($('#test').attr('class')=="selectedTab")
      jQuery("#menu a").removeClass("selectedTab");
      jQuery("#menu a").addClass("tab");
   }
   else{ jQuery(this).removeClass("tab");
     jQuery(this).addClass("selectedTab");
    }
   });
});

A:  $(function(){
    $("#menu a").on("click",function(){
      var ths = $(this);
      if($('#test').hasClass("selectedTab")){ths.removeClass("selectedTab").addClass("tab");}
      else{ths.removeClass("tab").addClass("selectedTab");}
    });
 });


text:
Q: toExpontial is undefined in react native Always having this error: num.toExponential is not a funtion. num.toExponential is undefined.
Why is toExponential() doesn't run on react native? How to replicate this functionality in react native?
function ifLessOneSatoshi(raw_num){
  const num = raw_num;
  if(raw_num < 0){
    num = Math.abs(raw_num);
  }
  if(num < 0.000001){
    if(raw_num < 0){
      const abn = abs(num);
      return -1 * abn.toExponential();
    }
    return num.toExponential();
  }
  return raw_num;
}

Below is what I implemented based on the answer of Yunhai:
function ifLessOneMillionth(raw_num){
  var num = Number.parseFloat(raw_num); //<=this line you may use parseFloat(raw_num)
  if(raw_num < 0){
    num = Math.abs(raw_num);
  }
  if(num < 0.000001){
    if(raw_num < 0){
      //const abn = Math.abs(num);
      return -num.toExponential(); // this line
    }
    return num.toExponential();
  }
  return raw_num;
}

A: There are fewer problems your have.
First, your reassign const num, const mean you cannot reaasign variable after declaration. So you should change it to var .
Second, the reason of undefined comes from raw_num if it isn't a "number object". Depending on the format, you might want to have something like parseFloat(raw_num) (I am not sure if the raw_num might be decimal or something else). You need to be careful of that.
Then, the last problem is -1 * num.toExponential(),num.toExponential() returns a string, so in order to make it negative, you should use string concatenation instead of math operation.
function ifLessOneSatoshi(raw_num){
  var num = raw_num; //<=this line you may use parseFloat(raw_num)
  if(raw_num < 0){
    num = Math.abs(raw_num);
  }
  if(num < 0.000001){
    if(raw_num < 0){
      const abn = Math.abs(num);
      return -abn.toExponential(); // this line
    }
    return num.toExponential();
  }
  return raw_num;
}

There are some weird behavior when I check your code, you have to check out those conditions if(raw_num) and if(num) by yourself without knowing the intention logic.


text:
Q: Multiline String Post in Java Rest Controller I want to send the following to a Rest Controller in Java but I am having issues

The code I am using on Controller side is below
@PostMapping
public String postData(HttpEntity<String> httpEntity) {
log.info("In RatingController Post Data");
log.info(httpEntity.getBody());
return "Return";
}

I am only able to catch the last line. How can I catch the entire thing?
Thanks


text:
Q: How to catch session timeout in ajax call? Please note that I had already tried to apply the solution on Handling session timeout in ajax calls but did not worked for me.
In an ASP.NET MVC5 project, I open pages by rendering partialview via AJAX as shown below:
function renderPartial(e, controller, action) {

    var controllerName = controller;
    var actionName = action;

    if (String(actionName).trim() == '') {
        return false;
    }
    if (typeof (controllerName) == "undefined") {
        return false;
    }

    var url = "/" + controllerName + "/" + actionName;

    $.ajax({
        url: url,
        data: { /* additional parameters */ },
        cache: false,
        type: "POST",
        dataType: "html",
        error: function (jqXHR, textStatus, errorThrown) {
            var message = errorThrown;
            if (jqXHR.responseJSON != null) {
                message = jqXHR.responseJSON.message;
            }
        },
        success: function (data) {
            var requestedUrl = String(this.url).replace(/[&?]X-Requested-With=XMLHttpRequest/i, "");
            if (typeof (requestedUrl) == "undefined" || requestedUrl == 'undefined') {
                requestedUrl = window.location.href;
            }

            // if the url is the same, replace the state
            if (typeof (history.pushState) != "undefined") {
                if (window.location.href == requestedUrl) {
                    history.replaceState({ html: '' }, document.title, requestedUrl);
                }
                else {
                    history.pushState({ html: '' }, document.title, requestedUrl);
                }
            }
            //Load partialview
            $("#div-page-content").html(data);
        }
    });
};

On the other hand, when session timeout and call this method by a hyperlink, there is an empty white page on the partialview field where partialview page should be rendered. So, is it possible:
1) to display a partialview at this field?
2) to redirect user Login page?
Note: I would also be happy if you suggest a smart way to Handle Session Expire in ASP.NET MVC. Thanks in advance...


text:
Q: Android DragLinearLayout dosn't work correctly and poor drag and drop, or barely drags images I am using this library
I am adding ImageViews programatically, but the images can barely drag. it require very long press, sometimes it works and sometimes it doesn't.
this is the adding function
Java
private ScrollView llCanvusContainer;
private DragLinearLayout llCanvus;
llCanvus = (DragLinearLayout)findViewById(R.id.llCanvus);
llCanvusContainer = (ScrollView)findViewById(R.id.llCanvusContainer);
llCanvus.setContainerScrollView(llCanvusContainer);

private void appendImageToLinearLayout(DragLinearLayout layout,
                                           ParseFile parseFileImage,
                                           int w, int h,
                                           boolean fullWidth,
                                           boolean isPostImage,
                                           final int position)
            throws ParseException, IOException {

        ImageView imageView= new ImageView(this);
        //imageView.setBackgroundResource(R.drawable.ic_action_search);
        imageView.setImageBitmap(

                ImageTools.
                        getBitmapFromUri(Uri.fromFile(
                                parseFileImage.getFile()),
                                this, fullWidth
                        )
        );

        // params
        //DragLinearLayout.LayoutParams viewParamsCenter =
                new DragLinearLayout.LayoutParams(
                        w,
                        h);
        //viewParamsCenter.gravity = Gravity.CENTER_HORIZONTAL | Gravity.RIGHT;

        //imageView.setLayoutParams(viewParamsCenter);
        imageView.setId(position);
        imageView.setContentDescription(imageList.get(position).getObjectId());
        layout.addDragView(imageView, imageView);

        //layout.setViewDraggable(imageView, imageView);

        if(isPostImage){

            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //showImageFullScreen(position);
                    Toast.makeText(EditPostActivity.this, "clicked " + v.getId(), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

and here is how I add image views
        for (ParseObject imgObj : imageList) {

            // add the image to the linear layout
            appendImageToLinearLayout(
                    llCanvus,
                    imgObj.getParseFile("image"),
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    true,
                    true,
                    i
            );

XML
<ScrollView
    android:id="@+id/llCanvusContainer"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginTop="8dp"
    android:background="@android:color/white"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/switchIsPublic">

    <com.jmedeisis.draglinearlayout.DragLinearLayout
        android:id="@+id/llCanvus"
        style="@style/Gallery19crollbarStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/switchIsPublic" />

</ScrollView>

The images show correctly, but the dragging doesn't work correctly.
Edit
the drag and drop works fine when I remove the ScrollView.

A: If you don't mind to use recyclerView then linearlayout, you can happily use ItemTouchHelper.
I use ItemTouchHelper to reorder my list and it work nicely.
Here is the blog post I found


text:
Q: MS CRM Webservice Error : The partner DNS used in the login request cannot be found When I am making the call for Microsoft dynamics 2011 Integration, I am getting Error given below. Please check and correct the following :
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
             xmlns:a="http://www.w3.org/2005/08/addressing"
             xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
            <s:Header>
                <a:Action s:mustUnderstand="1">
                http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</a:Action>
                <a:MessageID>urn:uuid:8bd921a8-1aa7-4346-a656-97580efa9a51</a:MessageID>
                <a:ReplyTo>
                  <a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
                </a:ReplyTo>
                <VsDebuggerCausalityData xmlns="http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink">
                uIDPozBEz+P/wJdOhoN2XNauvYcAAAAAK0Y6fOjvMEqbgs9ivCmFPaZlxcAnCJ1GiX+Rpi09nSYACQAA</VsDebuggerCausalityData>
                <a:To s:mustUnderstand="1">
                https://login.live.com/liveidSTS.srf</a:To>
                <o:Security s:mustUnderstand="1"
                xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
                  <u:Timestamp u:Id="_0">
                   <u:Created>2013-12-13T07:08:26.00</u:Created>
                   <u:Expires>2013-12-14T07:08:26.00</u:Expires>
                  </u:Timestamp>
                  <o:UsernameToken u:Id="user">
                    <o:Username>sudhir@live2support.onmicrosoft.com</o:Username>
                    <o:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">xxxxxx</o:Password>
                  </o:UsernameToken>
                  <wsse:BinarySecurityToken ValueType="urn:liveid:device"
                  xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
                    <EncryptedData Id="BinaryDAToken0"
                    Type="http://www.w3.org/2001/04/xmlenc#Element"
                    xmlns="http://www.w3.org/2001/04/xmlenc#">
                      <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc">
                      </EncryptionMethod>
                      <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
                        <ds:KeyName>http://Passport.NET/STS</ds:KeyName>
                      </ds:KeyInfo>
                      <CipherData>
                      <CipherValue>AQyTlc3YylbDiwLxT1e/ISGEe/Wn0BIZLOnZSKFrC2EsV1+1Mf08dKFBMrGtgFhMYGKoKA9JSD9CgY8g1NkH/1tDjDhwqv+xoP2hhwK8PXoUjXABEN4229zuv0whG1te3jjtSaz8w4pAMGIjo4M5+xFlBpePhcIdPuH4RJjLEhWH0iSpBevE//j7qZN/rSEVCDXIT9WsW3Q6LRXMmlggGHO2IER9JrkCDLivm4qhXLEQwDZFjGISbVSM+egWO3UOdaVmBxZol9PA7qkCGm9TPaJp419jJYi2/XVwI5h8BTZ0IuNTxYne97to/H0jOUKkyCZSqKDWTiQbbeGYQWXG0NnRkEZci70b2CAw0yaFTySMntV/1ftVKBAlDdGBJ00snw9HnE/cMuMhnwtjC+rUbEZDDEwGKBubkZQcIlCLFUvAIrBkYskWTFBMQc49L0r0ajeH6dMRLfz6dxA9yqTBUJBQqoh5JuUY1fpES+gwYXfcLI0IbxMB9EmYllXZzwubgDZnfWGrIh4BEkaWu0r+ENUfCxQ5"</CipherValue>
                      </CipherData>
                    </EncryptedData>
                  </wsse:BinarySecurityToken>
                </o:Security>
             </s:Header>
              <s:Body>
                <t:RequestSecurityToken xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust">
                  <wsp:AppliesTo xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
                    <a:EndpointReference>
                      <a:Address>urn:crm5.dynamics.com</a:Address>
                    </a:EndpointReference>
                  </wsp:AppliesTo>
                 <wsp:PolicyReference URI="MBI_FED_SSL"
                  xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" />
                  <t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType>
                </t:RequestSecurityToken>
              </s:Body>
             </s:Envelope>

and RESPONSE ERROR:
The partner DNS used in the login request cannot be found.

A: FOUND :)
these "urn" are no more used in the new authentication model for CRM Online. Here is the new values you have to use:
Old value   New value
crm:dynamics.com    crmna:dynamics.com
crm4:dynamics.com   crmemea:dynamics.com
crm5:dynamics.com   crmapac:dynamics.com

Reference:
http://mscrmtools.blogspot.pt/2012/08/php-to-crm-online-easy-way-to-do.html


text:
Q: PathTooLongException C# 4.5 I having trouble of copying some folder 260+ chars (for example: F:\NNNNNNNNNNNNNNNN\NNNNNNNNNNN\ROOT\$RECYCLE.BIN\S-1-5-21-3299053755-4209892151-505108915-1000\$RMSL3U8\NNNNNNNNN NNNNNNNN\NNNNNNNNNNN\NNNNNNNNNN\NNNNNNNNNN\publish\Application Files\TNNNNNNNNNNNN_1_0_0_0\NNNNNNNNNNNN.exe.manifest) to some other place with standart DrectoryInfo.Create(); adding \?\ or \?\UNC\ (like "\\?\UNC\") just throw another ArgumentException.
What am i doing wrong? What else i can do without using Directory.SetCurrentDirectory() ?

A: Actually you need to call win32 from c#. We have done this
using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;

public static class LongPath
{
    static class Win32Native
    {
        [StructLayout(LayoutKind.Sequential)]
        public class SECURITY_ATTRIBUTES
        {
            public int nLength;
            public IntPtr pSecurityDescriptor;
            public int bInheritHandle;
        }

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool CreateDirectory(string lpPathName, SECURITY_ATTRIBUTES lpSecurityAttributes);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, SECURITY_ATTRIBUTES securityAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
    }

    public static bool CreateDirectory(string path)
    {
        return Win32Native.CreateDirectory(String.Concat(@"\\?\", path), null);
    }

    public static FileStream Open(string path, FileMode mode, FileAccess access)
    {
        SafeFileHandle handle = Win32Native.CreateFile(String.Concat(@"\\?\", path), (int)0x10000000, FileShare.None, null, mode, (int)0x00000080, IntPtr.Zero);
        if (handle.IsInvalid)
        {
            throw new System.ComponentModel.Win32Exception();
        }
        return new FileStream(handle, access);
    }
}

A sample code:
string path = @"c:\".PadRight(255, 'a');
LongPath.CreateDirectory(path);

path = String.Concat(path, @"\", "".PadRight(255, 'a'));
LongPath.CreateDirectory(path);

string filename = Path.Combine(path, "test.txt");

FileStream fs = LongPath.Open(filename, FileMode.CreateNew, FileAccess.Write);

using (StreamWriter sw = new StreamWriter(fs))
{
    sw.WriteLine("abc");
}

A: There's a great library on Microsoft TechNet for overcoming the long filenames problem, it's called Delimon.Win32.IO Library (V4.0) and it has its own versions of key methods from System.IO
For example, you would replace:
System.IO.Directory.GetFiles

with
Delimon.Win32.IO.Directory.GetFiles

which will let you handle long files and folders.
From the website:

Delimon.Win32.IO replaces basic file functions of System.IO and
  supports File & Folder names up to up to 32,767 Characters.
This Library is written on .NET Framework 4.0 and can be used either
  on x86 & x64 systems. The File & Folder limitations of the standard
  System.IO namespace can work with files that have 260 characters in a
  filename and 240 characters in a folder name (MAX_PATH is usually
  configured as 260 characters). Typically you run into the
  System.IO.PathTooLongException Error with the Standard .NET Library.

A: Yes, using the standard APIs will give you this kind of limitations (255 chars IIRC).
From .NET you can use the AlphaFS project which lets you use very long paths (using the "\\?\" style) and mimics the System.IO namespace.
You will probably be able to use this library just as if you were using System.IO, for example : AlphaFS.Win32.Filesystem.File.Copy() instead System.IO.File.Copy()
If you don't want or cannot use AlphaFS you'll have to pinvoke the Win32 API


text:
Q: Mary has 10 hair bows,(...) how many different ways can she give them to her friends?
Mary bought 10 hair bows, all different from each other, and 3 of them
  are red and the rest are blue. Now, she wants to give them to her best
  friends, Hannah and Sophie, so that:

*

*each friend will get the same number of hair bows

*Hannah will get exactly 2 red hair bows

  How many different ways can mary give the bows to her friends?

I did:

*

*How many bows Hannah gets = $^3C_2*^7C_3$

$^3C_2$ because she has to have 2 red bows, and $^7C_3$ because those are the remaining bows.

*

*How many bows Sophie gets = $^3C_1*^7C_4$

$^3C_1$ because if Hannah gets 2 of the red bows, then Sophie can only get one and $^7C_4$ because those are the remaining bows
So the result: $$^3C_2*^7C_3*^3C_1*^7C_4$$
But my book says the solution is $^3C_2*^7C_3$
What did I do wrong?

A: Fulfill the most stringent restriction first. Since Hannah is picky, we tackle her first.
We have to give her 5 total and exactly 2 red bows. There are
$$
{3}\choose{2}
$$
ways to do this, or $3$. Then we have to give her another 3 from the not red pile, and there are
$$
{7}\choose{3}
$$
ways to do this. The multiplication rule gives you your result ${{3}\choose2}*{{7}\choose{3}}$, since we have no choice but to give the other girl the remaining 5 bows.


text:
Q: Renewal ratio window function method I have a query such as
select count(case when t.cnt > 1 then 1 end)/count(t.*)
from
(select signup_id, count(date_transaction) as cnt
from transactions
group by signup_id) t

This gives me renewal ration based on if a signup_id has more than 1 date_transaction value or row
I am trying to do the same utilizing a window function below and was trying to figure out if there is a better method then what I have below or if the below looks correct?
select count(CASE WHEN t.rnk > 1 THEN 1 END) / count(t.*) as renewal_ratio
from
(select *, row_number() over (partition by signup_id order by date_transaction asc) rnk
from table) t


text:
Q: Circular permutation about pair Some six of people are men, and the other six are women. In how many ways can they join hands for a circle dance, assuming they alternate in gender around the circle?

A: You can think of it like this:
First you pick the places for the women.
The number of ways to arrange
$n$ distinct objects in a circle
is $(n-1)!$ and not $n!$.
This is because the circle can be rotated.
If you rotate the circle with the
six women you notice there
are only $5!$ distinguishable ways they
can be placed in the circle.
If you take the simpler scenario with
only three people in a circle you get
$123:$ $1$st arrangement
$132:$ $2$nd arrangement
$213:$ $2$nd arrangement rotated clockwise one turn
$231:$ $1$st arrangement rotated clockwise two turns
$312:$ $1$st arrangement rotated clockwise one turn
$321:$ $2$nd arrangement rotated clockwise two turns
Here the first digit is placed
in the top spot and the other
two going clockwise around the circle.
Then when you have picked the places
for the women you start to fill
in each gap between two women with a man.
In the first gap you can choose between
$6$ men, then $5$ and so on, i.e. there
are $6!$ ways arrange the men.
This give a total of $5!*6!$ ways they can join hands for a circle dance.


text:
Q: Accessing the Nelder-Mead simplex at every iteration using scipy.optimize.minimize Some background:
I am using the Nelder-Mead simplex optimization algorithm from scipy.optimize.minimize to do some hyperparameter optimization on a deep learning model. For an input x and a function f, minimize is trying to optimize the function value f(x) by changing x. In my case, x are the hyperparameters of the model, f, which is making predictions for a constant set of training examples.
Because f is very large, and there are many training examples, each call f(x) takes about 10 minutes when the embarrassingly parallel problem of making predictions on all training examples is distributed among 20 rtx-2080 GPUs. So every step is expensive.
For one reason or another (crashing, running out of time on the GPUs) the script will stop in the middle of optimizing. It is therefore desirable for me to save the state of the optimization so I can continue it from where it left off. I am able to save the hyperparameter values x during every N.M. step, but this only goes so far. Even if you've recovered x (let's call the recovered version x'), the Nelder-Mead simplex is lost. If you restart optimization of f at x', minimize has to rebuild the simplex by evaluating f(x' + p) N times, where p is some perturbation to one of the dimensions of x , and N is either dim(x) or dim(x) + 1. In my case, x is high dimensional (>20), so it takes ~3 hours just to recover the simplex.
The question:
I need a way to access the simplex at every step in case of a crash. Others have suggested using a callback to solve the problem of recovering parameter and function values during optimization with scipy.optimize.minimize (not necessarily with Nelder-Mead). However, in the documentation for minimize it states the only version of minimize that can return both the current parameter values (x) and an OptimizeResult object (an object which could contain the simplex in the case of N.M.) via a callback is the "trust_constr" method. In other words, I'm pretty sure using a callback with the "nelder_mead" version only gives you access to x.
The best solution we've come up with is to edit the _minimize_neldermead function within the minimize source code to save the simplex values after each step. Is there a more elegant way of accomplishing this? Does minimize already have this ability and we just can't find it?


text:
Q: Using Citrix StoreFront API endpoints? I'm trying to wire up a solution to use custom C# code to do the following:

*

*Authenticate against a StoreFront server

*Enumerate apps

*Launch the ICAs

I am able to do this following their example using basic authentication (user/domain and password).  However, I want to know if there is a way to do this with other authentication mechanisms.  I have searched for any documentation surrounding the /Resources/ directory of API endpoints with no success.  I am using the /Resources/List, /Resources/PostCredentialsAuth/Login, and /Resources/LaunchIca endpoints, so I know there are API endpoints to use.
Does anyone know where I can find more information about these endpoints?  My end goal is going to be passing credentials/certificates from a custom app to authenticate against StoreFront.
Any help would be appreciated.  Thanks in advance!

A: If you have not found this yet - I found references to those URLs in the WebAPI.pdf from the Citrix website. You have to have a Citrix login to access the documentation. Log into Citrix.com and select downloads, from the Find Downloads dropdown select Storefront/WebInterface, the WebAPI documentation is in the Storefront 3.0 API's along with the Store Services API documentation which is also helpful. Let me know if you cannot get to it and I can send it to you.


text:
Q: C#: If condition in Linq where clause I've a Linq query like this...
var path = paths.Where(p=>input_path.ToUpper().Contains(p.ToUpper()).Select(p);

I've C:\volume1 and C:\volume10 in paths variable. Possible values for input_path are
"C:\volume1"
"C:\volume1\myFolder\myfile.txt"
"C:\volume10"
"C:\volume10\myFolder\myfile.txt"

If input_path is set to C:\volume10\myFolder\myfile.txt, by the above query it returns me C:\volume1 where I'm expecting C:\volume10. I'd like to have a check something like the below
var path = paths.Where(p=>input_path.ToUpper().Contains(p.ToUpper()) && (if input_path.length > p.length then if input_path[p.length] == '\\') ).Select(p);

How do I do it using Linq? The "\" character check should happen only if input_path length is more than path length.
Edit:
"Paths" contain only the drive letter and first level directory, where as "input_path" can contain multilevel directories.

A: A lambda inside a LINQ method can have two syntaxes - either an expression or a statement.
An expression is something that evaluates to a value. It's what you can have on the right-hand side of an assignment, for instance, and by default, it's what you have in a lambda. If you want to have a complex expression, you can use logical operators like && or || or the ?: ternary to group conditions together into a compound logic expression which evaluates to True or False.
paths.Where (p => input_path.Contains(p)
           && (input_path.Length > p.Length && input_path[p.length] == '\\'))

Alternately, you can use a lambda statement by simply encasing the code in a set of {}, and then you can write a whole statement block, using return to return a value:
paths.Where(p =>
    {
        if (input_path.Contains(p))
           if (input_path.length > p)
              if (input_path[p.length] = '\\')
              {
                  return true;
              }
        return false;
    }

Although in your case, the statement syntax is pretty contrived, and the first seems simplest.

A: if you need just paths on subfolders of input_path, you can simply check if the path starts with your input path (adding the "\" at the end if necessary)
input_path = input_path.EndsWith('\\') ? input_path : input_path + '\\';
var path = paths.Where(p=> p.ToUpper().StartsWith(input_path.ToUpper())).Select(p);
         `

A: You can try this :
var path = paths.Where(p => input_path.ToUpper().Contains(p.ToUpper())
           && (input_path.Length > p.Length  && input_path[p.Length] == '\\'));

It will check input_path[p.Length] == '\' condition only if input_path.Length > p.Length is true.

A: This should do it for you
var path = paths.Where(p => input_path.ToUpper().Contains(p.ToUpper()) && (input_path.length > p.length && input_path[p.length] == '\\'))
                .Select(p => p);

A: I would do a couple of things:

*

*It's slightly faster code (and less typing) to get rid of the Where and just use Select

*If you're always comparing the start of the string, use StartsWith instead of Contains (and ToUpper). StartsWith takes a comparer, so you can specify that it ignores case

.
// Rules:
// if input_path is longer than path, then see if it begins with path
// (case-insensitive) and check for the backslash character
// otherwise, the two strings should be equal (case-insensitive)
var path = paths.Select(p =>
    (input_path.Length > p.Length &&
        input_path.StartsWith(p, StringComparison.OrdinalIgnoreCase) &&
        input_path[p.Length] == '\\') ||
    input_path.Equals(p, StringComparison.OrdinalIgnoreCase));


text:
Q: AVD Error in Android Studio I was using android studio happily, after replacing HDD to SSD and installing latest version of android studio, suddenly i couldn't use virtual devices.
I can create any device with any api i want (x86 or x86_64) but after i run my application in it or starting it with AVD Manager, i asked to type password (wtf, i just created my avd), and no matter what i give as input, it always redirected to a page below but "PHONE RESET" button won't do anything:

I tried many things:

*

*Uninstall and install Android Studio

*Remove old SDK and download SDK from google(through Android Studio) and install it again

*Wipe data, delete and create multiple AVDs

*Download API image inside AVD Manager

Log in terminal is like this:
D:\Workspace\New\tools>emulator -avd  Nexus_6_API_26
emulator: WARNING: encryption is off
HAX is working and emulator runs in fast virt mode.
emulator: WARNING: UpdateCheck: Failure: No error
none.xml:3: parser error : AttValue: " or ' expected
<html lang=en>
           ^
none.xml:3: parser error : attributes construct error
<html lang=en>
           ^
none.xml:3: parser error : Couldn't find end of Start Tag html line 3
<html lang=en>
           ^
none.xml:3: parser error : Extra content at the end of the document
<html lang=en>
           ^

I have windows 10 and Android Studio 3.1.2 and Gradle 4.4
If anyone else having same issue, please leave a comment to find out what's the similarity between those to tackle the problem. thanks.


text:
Q: ¿Como hago un input type radio con opciones de la base de datos? Construí un tipo "Select" pero necesitaba un "Radio", el "Select" trae opciones directamente de la base de datos:

 Tipo de Cita
 <select class="form-control select" name="{{ADMISSION_FIELD_TYPE_QUOTE_ID}}" id=" {{ADMISSION_FIELD_TYPE_QUOTE_ID}}">
    @foreach ($tiposCitas as $tipoCita)
      <option value="{{ $tipoCita->id }}"{{old(ADMISSION_FIELD_TYPE_QUOTE_ID) == $tipoCita->id ? ' selected' : '' }}> {{ $tipoCita->descripcion }} </option>
    @endforeach
 </select>

Así luce:

Pero lo necesito así:

Yo no se construir un radio que traiga de la base de datos, si no el normal donde se añade las opciones ahí mismo como:

Seleccione una opción:

  <input type="radio" id="consulta" name="gender" value="consulta">
  Consulta

Y bueno... ¿Alguien podría ayudarme? espero haberme explicado con claridad. De antemano ¡Gracias!

A: Si te he entendido bien, lo único que tienes que hacer es extender lo que tu mismo has propuesto, es decir:

Seleccione una opción:

@foreach ($tiposCitas as $tipoCita)
<input type="radio" id="consulta-{{$tipoCita->id}}" name="EL_MISMO_NOMBRE_PARA_TODOS" value="{{ $tipoCita->id }}" {{old(ADMISSION_FIELD_TYPE_QUOTE_ID) == $tipoCita->id ? ' checked' : '' }}>
id}}">{{ $tipoCita->descripcion }}
@endforeach

A: Al iterar los registros obtenidos de la base de datos, en lugar de generar <option> dentro de un <select>, necesitas generar <input type="radio">
Ejemplo:

Seleccione una opción:

  @foreach ($tiposCitas as $tipoCita)

    <input type="radio" name="{{ADMISSION_FIELD_TYPE_QUOTE_ID}}" value="{{ $tipoCita->id }}"{{old(ADMISSION_FIELD_TYPE_QUOTE_ID) == $tipoCita->id ? ' checked' : '' }}>
    {{ $tipoCita->descripcion }}

  @endforeach

A: @cooper y @Marcos
Muchas gracias sus 2 respuestas me ayudaron mucho, daba por seguro que no era posible por que al investigar no apareció nada, Asi me quedo:

Y así construí el código:

   Tipo de Cita
       @foreach ($tiposCitas as $tipoCita)

   <input type="radio" id="{{ADMISSION_FIELD_TYPE_QUOTE_ID}}" name="{{ADMISSION_FIELD_TYPE_QUOTE_ID}}" value="{{ $tipoCita->id }}"{{old(ADMISSION_FIELD_TYPE_QUOTE_ID) == $tipoCita->id ? ' checked' : '' }}>{{ $tipoCita->descripcion }}
       @endforeach

Nuevamente, Muchisimas gracias.


text:
Q: Can't recycle the ERRORLOG - error 17049 When we attempted to run sp_cycle_errorlog we get the following:

Msg 17049, Level 16, State 1, Procedure sp_cycle_errorlog, Line 9
  Unable to cycle error log file from
  'G:\SQL_DATA1\MSSQL10_50.ABC\MSSQL\Log\ERRORLOG.15' to
  'G:\SQL_DATA1\MSSQL10_50.ABC\MSSQL\Log\ERRORLOG.16' due to OS error
  '1392(failed to retrieve text for this error. Reason: 15105)'. A
  process outside of SQL Server may be preventing SQL Server from
  reading the files. As a result, errorlog entries may be lost and it
  may not be possible to view some SQL Server errorlogs. Make sure no
  other processes have locked the file with write-only access."
  DBCC execution completed. If DBCC printed error messages, contact your system administrator.

So far we have tried:

*

*Failing over the SQL cluster resource to second node, rebooting server, failing back and rebooting second node

*Using Process Explorer tool - this identified the only process using the ERRORLOG file to be sqlservr.exe
SQL version details:

Microsoft SQL Server 2008 R2 (SP3) - 10.50.6000.34 (X64)  Aug 19 2014
  12:21:34  Copyright (c) Microsoft Corporation Enterprise Edition
  (64-bit) on Windows NT 6.1  (Build 7601: Service Pack 1)

There are two SQL instances on this two node SQL cluster, on the other instance the log cycles over with no issue.
I have seen a couple of posts on this subject but both appear to have been resolved by killing the non-sqlserver process. I'm presuming that the sqlsrvr.exe process is expected to be locking the file?
Any help appreciated.

A: From System Error Codes (1300-1699): OS error 1392 indicates file corruption.

ERROR_FILE_CORRUPT
  1392 (0x570)
  The file or directory is corrupted and unreadable.

So it looks like you have corruption on your G: drive.
I would start with a chkdsk of that drive and all other drives.
Since corruption usually doesn't fix itself and can have the tendency to worsen, personally I would fail over to the other node ASAP before other files (I don't know what else lives on the drive) corrupt and the situation gets trickier and trickier.


text:
Q: select variable to compile one of multi tex file I have multi file text: Main, Main01, main02, Main03...main10
How can I open only one window of main.tex and select one parameter to compile main01 or main02 or main03. and then receive created pdf of main01, or main02, or main03 in same window of Main.tex
Note: main01.tex, main02.tex...can compile alone (with begin/end{document} inside)
Example: In Main.tex:
%%%Please select one file to compile:
\select{main03.tex}
…

And main03.pdf is created.
Thank you in advance

A: Here is a way:
main.tex:
\documentclass{article}
\usepackage{lipsum}
\usepackage{pgffor}

%Add the files you wish to be included here:
\def\onlyinput{main1,main2}

%Command definition
\newcommand{\minput}[1]{\def\xx{#1}\foreach \x in \onlyinput{\ifx\x\xx\input{#1}\fi}}

\begin{document}
\section{Standard Section}
\lipsum[1]
\minput{main1}
\minput{main2}
\end{document}

main1.tex:
\section{Main 1}
\lipsum[1]

main2.tex:
\section{Main 2}
\lipsum[1]

main3.tex:
\section{Main 3}
\lipsum[1]

Output:

A: You should use the ifthen package.
In your premable use:
\usepackage{ifthen}
\def\var{2}

And in the document:
\ifthenelse{\var=1}{
\input{file1.tex}
}{
\ifthenelse{\var=2}{
  \input{file2.tex}
}{}}

You can use \include or \input whether you want to start a new page or not respectively.


text:
Q: How to assign a unique_ptr value from within a lambda I have a situation where I need to assign a unique ptr value from within a lambda function.
std::unique_ptr<SomeType> unique_ptr_obj;

// Lambda below has fixed return type.
bool var = ()[unique_ptr_obj=std::move(unique_ptr_obj)]-> bool {
 unique_ptr_obj = GetUniqueObject();
 return true
} ();

// Should be able to use unique_ptr_obj
UseUniqueObject(unique_ptr_obj.get());

However, as expected unique_ptr_obj is nullptr as it was moved into lambda. Is there a way I can populate unique_ptr_obj from within a lambda and be able to reuse it later ?
Any suggestions on how to accomplish this ? Should I convert unique_ptr_obj to shared_ptr ?

A: You should change the declaration of your lambda to capture unique_ptr_obj by reference:
bool var = [&unique_ptr_obj]() -> bool {
    // Whatever the next line does, now it changes that variable by reference.
    // Otherwise you were changing a local copy.
    unique_ptr_obj = GetUniqueObject();
    return true;
} ();

A: You don't want to share ownership. Or maybe you do, but it won't help with the lambda assigning something to unique_ptr_obj, hence using a shared_ptr is not the solution.
You also do not want to move from unique_ptr_obj. Sloppy speaking, moving from something means leaving it in an empty state.
If you want a function to modify its argument then you pass by reference. If you want a lambda to modify something in the outer scope you let it capture it by reference.
This is the same whether its an int or a unique_ptr:
int x = 0;
bool value = [&x]() { x = 42; return true; } ();
         //   ^^ capture x by reference

assert(x == 42);


text:
Q: how to sort Ref in order using iEEE trans bibiliography Hi I am working on IEEE transaction template of overleaf and I have a separate bib file and I am citing this in main tex file using these tags
\bibliographystyle{IEEEtran}
\bibliography{IEEEabrv,biblio_traps_dynamics}

but the problem in bibliography section is the is the references are not listed in order
after 1-8 instead of no 9 its 13. how to solve this issue

A: You can try
\usepackage[backend=biber,style=numeric,sorting=none]{biblatex}
worked for me.


text:
Q: Run Linux PTP on crontab at boot I want to run 2 commands when a Beaglebone AI with Debian 10 starts up. The first one, which is a C code to initialize a Circular Microphone Board, it works (CMBini).
However, the second one it does not. It is a script it is a PTP network command (ptp4l -A -H -q -s), and I think that the problem might be that it is a command that stays running and printing results until cancelled with Ctrl+C.
So my question is how can I make this work? Is there anyway to keep that process running in the background?
My crontab file:
@reboot /home/debian/CMBini
@reboot /home/debian/startsript.sh

startscript.sh:
#! bin/bash
sleep 20
ptp4l -A -H -q -s  -i eth0
sleep 40
phc2sys -a -rr

A: I tried your crontab on macOS 12.6:

@reboot /Users/risner/bin/startsript.sh

#!/bin/sh

/usr/bin/screen -d -m -S ptp -c /Users/risner/.boot-screenrc

With this in .boot-screenrc:
screen -t ptp4l 1
stuff sleep 20; ptp4l -A -H -q -s  -i eth0\015
screen -t phc2sys 2
stuff sleep 40; phc2sys -a -rr\015

The commands failed (ptp4l & phc2sys), but screen ran them. So if they commands work on your system this is a solution.
This also allows you to attach to the session via:
screen -D -R ptp

From there you can view the commands it executed.


text:
Q: Databricks cannot connect to Azure Synapse Analytics: Unexpected version returned: Microsoft SQL Azure (RTM) - 12.0.2000.8 I am trying to write some data to Azure Synapse Analytics from Databricks notebook with following code:
write_to_synapse = (
  spark.readStream.format('delta').option('ignoreChanges',True).table('turbine_agg') # Read in Gold turbine readings from Delta as a stream
    .writeStream.format("com.databricks.spark.sqldw")                                     # Write to Synapse (SQL DW connector)
    .option("url",dbutils.secrets.get(<scope>, <secret>))                                # SQL Pool JDBC connection (with SQL Auth) string
    .option("tempDir", SYNAPSE_PATH)                                                      # Temporary ADLS path to stage the data (with forwarded permissions)
    .option("forwardSparkAzureStorageCredentials", "true")
    .option("dbTable", "turbine_agg")                                                # Table in Synapse to write to
    .option("checkpointLocation", CHECKPOINT_PATH+"synapse")                              # Checkpoint for resilient streaming
    .start()
)

Where secret is in JDBC connection string format:
jdbc:sqlserver://<on-demand-sql-pool>.sql.azuresynapse.net:1433;database=master;user=<user>;password=<password>;encrypt=true;trustServerCertificate=true;hostNameInCertificate=*.sql.azuresynapse.net;loginTimeout=30;

I am getting the following error:
IllegalArgumentException: Unexpected version returned: Microsoft SQL Azure (RTM) - 12.0.2000.8
    Aug 17 2020 07:52:53
    Copyright (C) 2019 Microsoft Corporation

Make sure your JDBC url includes a "database=<DataWareHouseName>" option and that
it points to a valid Azure Synapse SQL Analytics (Azure SQL Data Warehouse) name.
This connector cannot be used for interacting with any other systems (e.g. Azure
SQL Databases).

I have a database option included, and database master exists.
What is wrong and how I fix this issue?
Thank you!


text:
Q: Why Google Page Speed Insights say to minify JS I have ran Google Page Speed Insights and their main suggestion is to minify js file with over 70% of savings (from 423 KB to 312 KB to be exact) which is insane.
But the file is minified! What am I missing?
Resources:

*

*JS file.

*Web Page - https://www.eldorado.gg
P.S.
I have gone through other similar questions on SO and neither were similar to my problem.

A: Google Page Speed Insights should be taken with a pinch of salt
It can give you a very high level view of massive issues but once you start to optimise things, it falls short. It believes your js file is large and that minimising it will help. It can't actually tell that you have minimised it already.
I once had it tell me to use gzip compression for a single, cached 2k SVG file. Another time, it asked me to shrink the 200 or so tiny 12k jpegs that a site was using. Its not very clever - in the first case it was wasting my time, and in the second case there was a better answer (use sprite sheets) but its unable to look that deeply.

A: I'd recommend skimming your minified file and looking for human readable JS tokens.
From what I can see, the test is mainly looking at JS tokens length.
https://github.com/GoogleChrome/lighthouse/blob/master/lighthouse-core/audits/byte-efficiency/unminified-javascript.js
/**
 * @fileOverview Estimates minification savings by determining the ratio of parseable JS tokens to the
 * length of the entire string. Though simple, this method is quite accurate at identifying whether
 * a script was already minified and offers a relatively conservative minification estimate (our two
 * primary goals).
 *
 * This audit only examines scripts that were independent network requests and not inlined or eval'd.
 *
 * See https://github.com/GoogleChrome/lighthouse/pull/3950#issue-277887798 for stats on accuracy.
 */

If you see human readable tokens in your minified file, try looking at your minifier settings to see if there is an option you can toggle that gets rid of these.
If there is no setting that gets rid of them, try identifying where these are coming from and how they are different than other tokens that are minified successfully.  The culprit might be a coding pattern, framework, or transpiler.
Note: The source code is linked from their help page (https://web.dev/unminified-javascript/)


text:
Q: How do you translate Hibernate class mappings to a Spring application context? How do you configure the Hibernate class mappings of class org.springframework.orm.hibernate3.LocalSessionFactoryBean in the Spring application context?  I want to move the session factory class mappings from the following hibernate.cfg.xml to the corresponding Spring session factory bean so that I may eliminate hibernate.cfg.xml.
File hibernate.cfg.xml:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- ... -->
        <mapping resource="Queries.hbm.xml" />
        <mapping class="com.company.app.common.model.Account" />
        <mapping class="com.company.app.common.model.AccountCategory" />
        <mapping class="com.company.app.common.model.AssetType" />
        <mapping class="com.company.app.common.model.Book" />
        <mapping class="com.company.app.model.AssetTypeCategory" />
        <!-- ... -->
    </session-factory>
</hibernate-configuration>

File spring-application-context.xml:
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="configurationClass">
        <value>org.hibernate.cfg.AnnotationConfiguration</value>
    </property>
    <property name="configLocation">
        <value>classpath:hibernate.cfg.xml</value>
    </property>

    <!-- Instead of the above, I want to use the following. Where and
    how do I define the class mappings so that I may eliminate
    hibernate.cfg.xml? -->
    <--
    <property name="dataSource" ref="dataSource" />
    <property name="mappingResources">
        <list>
            <value>Queries.hbm.xml</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="dialect">org.hibernate.dialect.Oracle10gDialect</prop>
        </props>
    </property>
    -->
</bean>

A: As a slight variation on skaffman's answer, I used property packagesToScan of class AnnotationSessionFactoryBean to avoid listing all of the individual model class names:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan">
       <list>
           <value>com.company.app.common.model</value>
       </list>
    </property>
    <property name="mappingResources">
       <list>
          <value>Queries.hbm.xml</value>
       </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="dialect">org.hibernate.dialect.Oracle10gDialect</prop>
        </props>
    </property>
</bean>

I learned about this property from the excellent book Spring in Action, Third Edition.

A: If you're using JPA-annotated classes, you can use AnnotationSessionFactoryBean instead of LocalSessionFactoryBean, and inject the classes directly into the Spring bean:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="annotatedClasses">
       <list>
           <value>com.company.app.common.model.Account</value>
           <value>com.company.app.common.model.AccountCategory</value>
           <value>com.company.app.common.model.AssetType</value>
           <value>com.company.app.common.model.Book</value>
           <value>com.company.app.model.AssetTypeCategory</value>
       </list>
    </property>
    <property name="mappingResources">
       <list>
          <value>Queries.hbm.xml</value>
       </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="dialect">org.hibernate.dialect.Oracle10gDialect</prop>
        </props>
    </property>
</bean>

A: I was also facing the same issue, and this worked for me -
<bean id="auditCoreSessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource">
        <ref bean="auditCoreDataSource" />
    </property>
    <property name="packagesToScan" value="com.odeon.audit.dao.entity" />
    <property name="annotatedClasses">
        <list>
            <value>com.odeon.audit.dao.entity.AuditLogEntity</value>
            <value>com.odeon.audit.dao.entity.AuditLogApplicationEtity</value>
            <value>com.odeon.audit.dao.entity.AuditLogModuleEntity</value>
            <value>com.odeon.audit.dao.entity.AuditLogOperationEntity</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">#{auditCoreProp.getString('jdbc.dialect')}</prop>
            <prop key="hibernate.show_sql">#{auditCoreProp.getString('jdbc.show_sql')}</prop>
            <prop key="hbm2ddl.auto">#{auditCoreProp.getString('jdbc.hbm2ddl.auto')}
            </prop>
            <!-- prop key="hibernate.hbm2ddl.auto">create</prop -->
        </props>
    </property>
</bean>


text:
Q: How can I set font size for my entire HTML webpage using CSS? Hello I am a new beginner to CSS, and I wondered if anyone could help to advise how I could set the font size for my entire webpage?
The tutorials I've been looking at just show me how to set font size for each separate section.  I am using the same font-size for 99% of my page, so I don't want to have to code each and every single new paragraph, table row, cell, etc.
I'm already using a simple code for changing the font family for the ENTIRE page (see below), so I am assuming there is a simple code for the size that does the same.

Thank you!

A: You can use font-size in the same wildcard selector:
* {
  font-size: 1rem;
}

Keep in mind that the wildcard selector * carries the least specificity; any font sizes declared elsewhere will override this declaration.

A: Set your font family and size in the body tag, and with a few exceptions, all the elements in your page will inherit that size:
body{
   font-family: Verdana, sans-serif;
   font-size: 12px
}

Optionally, you can set any of your elements to an em font-size:
p{
   font-size: 1.5em;
}

1 em is equal to the font-size of an element's parent, so in this case the p tag is one and a half times the size of the div tag. Since the div tag is 12px (inherited from body), the p tag is 18px:

body{
   font-family: Verdana, sans-serif;
   font-size: 12px
}

p{
   font-size: 1.5em;
}

I'm in a p tag, my font size is 18px

A: Hello and welcome to Stack Overflow. You can do this by using the HTML tag. Some might disagree with the location, but I like to have it here since it's on the root of the element. When you get more in depth you will start to likely use REM and EM units more and this seems to make more sense to me. But in reality you can put it on the asterisk, body, or HTML. Each of these uses the same CSS:
font-size: XXpx;.
HTML {
  font-size: XXpx;
}

body {
  font-size: XXpx;
}

* {
  font-size: XXpx;
}

Here's a good link that might have some more advanced topics but has some good discussion
Best of luck on your development journey!

A:


text:
Q: problema com prompt de comando php,o código php -S 0.0.0.0:8080 não funciona no servidor(wamp),já tentei de tudo que eu pesquisei,pórem dá erro 404 o código é executado na página fashion.html
[1]: https://i.stack.imgur.com/3uVlM.png
resultado do código
[2]: https://i.stack.imgur.com/bsBEP.png

A: Tá faltando o index.php na raiz do seu projeto.
Mas você pode ver o conteúdo da tua página acessando:
http://localhost:8080/fashion.html


text:
Q: Webpack using perf_hooks for node/browser module I'm making a module that I would like to be available in the browser and Node. It relies on performance, which is giving me trouble with Webpack and the perf_hooks module in Node. No matter what I do I can only get it where it works in one or the other, but not both.
Below are most of the things I've tried. My question is, how do I configure Webpack to require perf_hooks in node, but use the built in performance global when in the browser?
Here is my base Webpack config:
const path = require('path');

module.exports = {
  entry: './src/UpdateLoop.js',
  mode: 'development',
  output: {
    library: 'UpdateLoop',
    libraryTarget: 'umd',
    path: path.resolve(__dirname, 'dist'),
    filename: 'updateloop.js',
    globalObject: 'this',
  },
};

Code thats giving me trouble:
const { performance } = require('perf_hooks');

This errors in webpack with:
Field 'browser' doesn't contain a valid alias configuration
    resolve as module
      C:\Users\joe.jankowiak\projects\update-loop\src\node_modules doesn't exist or is not a directory

I've seen suggestions for 'fs' to do the following:
// configuration.node has an unknown property 'perf_hooks'
  node: {
    perf_hooks: false,
  },

// configuration has an unknown property 'browser'.
  browser: {
    perf_hooks: false,
  },

I then saw people recommending using 'resolve':
// Compiles, but complains performance doesn't exist in node or browser.
resolve: {
  fallback: {
    perf_hooks: false,
  }
},

// Works in browser but doesn't work in node. Node complains about using performance before its defined:
performance = performance || require('perf_hooks').performance;

// Doesn't work in either
const performance = performance || require('perf_hooks').performance;

// Trying to check if its node, but with resolve its making perf_hooks null in node
if(typeof __webpack_require__ === 'function') {
  global.performance = require('perf_hooks').performance;
}

A: I ended up doing this out of laziness because I still don't quite understand how to use NodeJS functions with Webpack:
function portableMsecTimer () {
  if (process.hrtime) {
    return Number(process.hrtime.bigint()) / 1e6;
  } else {
    return window.performance.now();
  }
}


text:
Q: Why is specific volume of saturated water greater at 1 MPA than at 0.1 MPA during the phase change process? Why is specific volume of saturated water greater at 1 MPA than at 0.1 MPA during the phase change process?
check out the T-V diagram here in the link.
http://www.ohio.edu/mechanical/thermo/Intro/Chapt.1_6/Chapter2a.html

A: For saturated water, you must have vapor and liquid water together, presumably at thermal equilibrium.  In addition, the pressure of the saturated water must be the vapor pressure at the specified temperature. The Antoine equation specifies vapor pressure as a function of temperature, and it also says that a higher vapor pressure corresponds to a higher temperature.  At higher temperatures (hence, at higher pressures), the density of liquid water is lower, so the specific volume is higher.
For further info, see
http://antoine.frostburg.edu/chem/senese/101/liquids/faq/antoine-vapor-pressure.shtml


text:
Q: Is fwrite atomic? A simple question:
I need to add some logging to my program.
If two processes use "fwrite" on the same file but not the same file descriptor will the written log messages be atomic or mixed. Is there a length limit?
Is it defined ANSI-C behaviour or implementation defined?
If the later what is on MacOSX, Linux and Windows MSVC?

A: It can be mixed.
If you have more than one thread/process writing to the same file, you need to use locking.
An alternative is to send log messages to a dedicated service/thread.  An excellent tool to adopt is syslog, which is surely installed on all unixes and can be run on Windows.

A: From "man flockfile" on Debian lenny, the stdio functions are thread-safe.
There're thread-unsafe stdio functions, "man unlocked_stdio" for more details.
You can get more information from the man page.

A: After doing some research and I've found the following in this link:

POSIX standard requires that C stdio
  FILE* operations are atomic.
  POSIX-conforming C libraries (e.g, on
  Solaris and GNU/Linux) have an
  internal mutex to serialize operations
  on FILE*s.

It looks like that calls should be atomic, but it depends on your platform. In same link, there is also another paragraph that lets you think that the programmer should take care:

So, for 3.0, the question of "is
  multithreading safe for I/O" must be
  answered with, "is your platform's C
  library threadsafe for I/O?" Some are
  by default, some are not; many offer
  multiple implementations of the C
  library with varying tradeoffs of
  threadsafety and efficiency. You, the
  programmer, are always required to
  take care with multiple threads.

Also, as you have two different FILE* in two different processes, I think you have no choice.

A: fwrite for visual studio locks the calling thread and is therefore thread-safe


text:
Q: Show file extension in file name Is there any way to show file suffixes by default at the end of the file name in unity?
For example:
If I have a file called test.bin, it is shown as test in Unity. I'd like it to be shown as test.bin by default in Unity.


text:
Q: Set the same width of a "Position: fixed" div as parent div(flexbox item) How can I make the same width of the NavWrapper as parent?
I want these links at a fixed position even the main section overflows.
I know how to do this without Flex. Is there any pure CSS way to do that?

body {
  padding:0;
  margin:0
}
.wrapper {
  display: flex;
}
nav {
  flex: 1 1 150px;
  background: gray;
}
.nav-wrapper {
  width: 100%;
  position: fixed;
  top: 0; left: 0;
  display:flex;
  flex-direction: column;
}

.nav-wrapper a {
  flex: 1 1;
  border: 1px solid red;
}
section {
  flex: 5 1 500px;
  padding: 20px;
}

         Home
         About

Lorem

A: You don't need fixed position- you can see why I say this after looking at the example below:
Remove the fixed positioning and add height: 100vh to nav:
nav {
  flex: 1 1 150px;
  background: gray;
  height: 100vh;
}

Now wrap the contents on a section into an inner div that is positioned absolute like this:
section {
  flex: 5 1 500px;
  padding: 20px;
  position: relative;
  overflow-y: auto;
}
.inner {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

This will allow the section to remain at 100vh of the nav-wrapper and the extra height will overflow.

body {
  padding: 0;
  margin: 0
}
.wrapper {
  display: flex;
}
nav {
  flex: 1 1 150px;
  background: gray;
  height: 100vh;
}
.nav-wrapper {
  width: 100%;
  display: flex;
  flex-direction: column;
}
.nav-wrapper a {
  flex: 1 1;
  border: 1px solid red;
}
section {
  flex: 5 1 500px;
  padding: 20px;
  position: relative;
  overflow-y: auto;
}
.inner {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

      Home
      About

Lorem

      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae molestiae, libero inventore nobis et veritatis, laborum vitae, vel eaque omnis ad adipisci quia velit blanditiis qui. Cum voluptas quisquam itaque possimus accusamus repellendus quia iure
      asperiores. Unde, rerum nihil maiores nisi, iusto voluptate id cumque incidunt, perspiciatis facilis perferendis explicabo.

Lorem

      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae molestiae, libero inventore nobis et veritatis, laborum vitae, vel eaque omnis ad adipisci quia velit blanditiis qui. Cum voluptas quisquam itaque possimus accusamus repellendus quia iure
      asperiores. Unde, rerum nihil maiores nisi, iusto voluptate id cumque incidunt, perspiciatis facilis perferendis explicabo.

Lorem

      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae molestiae, libero inventore nobis et veritatis, laborum vitae, vel eaque omnis ad adipisci quia velit blanditiis qui. Cum voluptas quisquam itaque possimus accusamus repellendus quia iure
      asperiores. Unde, rerum nihil maiores nisi, iusto voluptate id cumque incidunt, perspiciatis facilis perferendis explicabo.

Check this out and let me know your feedback. Thanks!


text:
Q: Access to other components variables in react I'm using react three fiber and i have two components
one to make a box and the other is to make an array of this box
here's how they look like, the platform component:
export function Plat() {

    const [active, setActive] = useState(0)
    const { scale } = useSpring({ scale: active ? 1 : 0.4 })
    const [mat] = useState(() => new THREE.TextureLoader().load('/matcap.png'))

    function Shape(props) {
        return (
            <animated.mesh {...props} scale={scale} onPointerOver={() => setActive(Number(!active))} >
                <RoundedBox args={[60,20,60]} radius={4} smoothness={4} position={[0, -10, 0]} dispose={null} >
                    <meshMatcapMaterial matcap={mat} />
                </RoundedBox>
            </animated.mesh>
        );
    }

    useEffect(() => {
        (function() {
            setActive((1))
        })();
    },[]);

    return (
        <Shape />
    )
}

and the component that makes an array of this platform:
import {Plat} from './Plat'

export default function Boxes() {

    function MyShape(props) {
      return (
          <mesh {...props} >
              <Plat />
          </mesh>
      );
    }

    const [shapes, setShapes] = useState([<MyShape key={0} position={[100, 100, 100]} />, <MyShape key={1} position={[120, 120, 120]} />, <MyShape key={2} position={[130, 130, 130]} />]);

    return (
      <group >
        {[...shapes]}
      </group>
    )

  }

(I have more than 3 elements in the array)
I wanna know if there's a way to access the variables inside each of the array's platform components
how would I do something like this:
console.log(shapes[2].position) or change the position of this specific shape in the array
or this
shapes[1].setActive(1)
is it even possible?

A: Few pointer

*

*Avoid nesting functional components

Plat
Shape // declare this outside and pass it the params from parent

*

*If you need to change the position of the children, consider creating a array with the information you need to change
  const [shapes, setShapes] = useState<>([{ key: 1, position: { x: 5, y: 10 } }])

  const changeShapePostions = (key) => {
      setShapes(items => {

         return items.map(shape => {

           if (shape.id === key) {
              return { ...shape, position: { x: updatedX, y: updated: y} }
           } else {
              return shape
           }

        }

      }
  }

    const setActive = (key) => {
       setShapes(items => {

         return items.map(shape => {

           if (shape.id === key) {
              return { ...shape, isActive: true }
           } else {
              return shape
           }

        }

      }
}

return (
    <group >
      {
        shapes.map(shape => {
            return (<MyShape key={shape.key} position={shape.position} setActive={setActive} />)
        }
      }
    </group>
  )

you can check standard practices on working with arrays
Hope it helps in some ways


text:
Q: How to use XML attribute as search criteria in t-sql? I have an SQL Server table:
    CREATE TABLE [dbo].[XMLFiles](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [XML] [xml] NOT NULL,
    [processed] [int] NOT NULL,
    [createtime] [datetime] NOT NULL,
    [handletime] [datetime] NULL,
    [objectId] [varchar](50) NOT NULL,
    [ResultText] [varchar](200) NULL,
    [BatchID] [varchar](50) NOT NULL,
    [Type] [varchar](32) NOT NULL,
    CONSTRAINT [PK_XMLFiles] PRIMARY KEY CLUSTERED

The interesting columns in this context are XML and BatchID. The BatchID is unique identifier. My xml data in column XML has a section like this:
...
            <CLASSIFICATION>
                <CLASS name="Face Mills Indexable" id="TA_MILL_20_20">
                    <ATTRIBUTE id="-45001" name="Tool Description" datatype="STRING">T990 d100 highfeed</ATTRIBUTE>
                    <ATTRIBUTE id="-41210" name="Comments" datatype="STRING"/>
                    <ATTRIBUTE id="-41101" name="Supplier" datatype="STRING"/>
                    <ATTRIBUTE id="-45211" name="Plant" datatype="ENUM">4 Lahti</ATTRIBUTE>
                    <ATTRIBUTE id="160000" name="Machine Tool" datatype="ENUM">BW4 MCR 750</ATTRIBUTE>
                    <ATTRIBUTE id="-45212" name="Machine Group" datatype="ENUM"/>
                    <ATTRIBUTE id="-45210" name="Status" datatype="ENUM"/>
...

Let's say I'm interested in the value of attribute where id="160000", i.e. the fifth attribute. I can get the value by sql query:
SELECT
xml.value('(/PLM_PUBLISH_ITEM/ITEMS/ITEM/CLASSIFICATION/CLASS/ATTRIBUTE)[5]','varchar(30)') AS TCODE
FROM XMLFiles
WHERE batchid = '1553762782573'

The result is correct: BW4 MCR 750
But, I cannot be sure that this row is always the fifth row here. So I would like to use SQL where I can put the attribute id as search criteria.
Something like this:
SELECT something FROM XMLFiles WHERE BacthID='1553762782573'
AND something = '160000'

How to get this? I've ran out of ideas...

A: You can use an XPath predicate [@id='160000'] to get nodes where the attribute id has a value of 160000.
SELECT xml.value('(/PLM_PUBLISH_ITEM/ITEMS/ITEM/CLASSIFICATION/CLASS/ATTRIBUTE[@id=''160000''])[1]','varchar(30)') tcode
       FROM xmlfiles
       WHERE batchid = '1553762782573';

You can also use exist() if you're not interested in the actual value but just want to select rows, where such an element exists in the XML.
SELECT *
       FROM xmlfiles
       WHERE batchid = '1553762782573'
             AND xml.exist('/PLM_PUBLISH_ITEM/ITEMS/ITEM/CLASSIFICATION/CLASS/ATTRIBUTE[@id=''160000'']') <> 0;


text:
Q: Arithmetic operation on very large static arrays in C/C++ I am new to High Performance Computing and my first question in this forum where I have been a reader for much long.
Basically I need to do arithmetic operations on very large arrays like  for instance
double variable [9][4][300][300][300] (uninitialized)

case 1: If I declare the array above as local/automatic then I get run-time error  if I had compiled without optimization like  "g++ file.cpp"  .. (the error is segmentation fault -- stack overflow???)
case 2: In the same case as above if I had compile with optimization the code runs as expected. "g++ -O2 file.cpp" (is the array in bss now???)
case 3: If I make the variable global/static then it compiles fine but nonetheless it does not run and just gives a message "killed" on terminal and terminates.
There is no real problem but I am curious and want to learn what happens when extremely large arrays are declared and where do they reside in memory depending on their data type.
I am also aware of the method of generating these arrays at run-time using malloc or new. Then of course it would be on heap.
So the most important question for me is --> which is the most efficient method (i.e. smallest run-time during computation of arrays in memory) of dealing with large arrays when compiling with g++ and running on linux clusters.
Thank you for your patience for reading.

A: Local variables will always be on the stack, no matter optimization flags. And that array will be around 7 gigabyte! Way larger than any possible stack.
The size may also be a reason it doesn't start, as if you put it as a global/static variable then you need to have more than 7 GB or virtual memory free and contiguous to be able to even load the program.

A: May I suggest something along the lines of:
typedef double slice[300][300][300];

std::vector<slice> variable[9] = { 4, 4, 4, 4, 4, 4, 4, 4, 4 };

This way each vector of 4 slice objects will be dynamically allocated, the contents of the 9 vectors need not be contiguous with each other, and the stack consumption is only enough for metadata for 9 vectors.


text:
Q: When a sql result contains multiple rows, how can I fetch each row individually from it? When I send a query to my SQL database and it returns more than one row, how can I fetch each row individually? I've been failing without any result for hours.
For example:
There is a table, which contains names (fore- and surname):
Hans Hansen
Hans Petersen
Peter Petersen
My query looks like this:
$query = "SELECT * FROM names WHERE forename = 'Hans'";

I tried to use mysql_result(), but this function only returns one field. I thought about creating a second function, which is based on mysql_result() (counting columns -> for Loop to create array), but I made some research and many people say, mysql_result() is very slow, when your result gets bigger.
How can I store the result in different arrays for each row in a fast way to finally create a goodlooking table?

A: while($row=mysql_fetch_array($result))
{
    $results[] = $row;
}

A: I don't know what you are using but I guess a mysql database with the old php mysql functions than you use this:
$result = mysql_query("SELECT * FROM names WHERE forename = 'Hans'");

while($row = mysql_fetch_assoc($result)){
    echo "$row[forename] - $row[sirname] - etc. <br>";
}

I also guess you're new to php and did not understand any of this yet but the question you asked is asked multiple times and already answered so try to search and learn before asking this kind of simple questions.
Also you probably asked yourself why declare a variable inside a where loop. The while loop gets the response from mysql_fetch_assoc. When it is false it stops but everytime there is a row it will return an array. Well the array is assigned to the variable $row and does not affect the loop (try not putting $row = and see it still loops). You can then just use the array values and after every spin the mysql result pointer will move one row further. At the last row the function mysql_fetch_assoc will move and see there is no result and it will return false. The loop stops and continues to the next line of php code.


text:
Q: Computing the Follow Set Ok, I've understood how to compute the Follow_k(N) set (N is a nonterminal): for every production rule of the form A -> aBc you add First_k(First_k(c)Follow_k(A)) to Follow_k(B) (a, c are any group of terminals and nonterminals, or even lambda). ...and you repeat this until there's nothing left to add.
But what happends for production rules like: S -> ABCD (A, B, C, D are all nonterminals)?
Should I
add First_k(First_k(BCD)Follow_k(S)) to Follow_k(A) or
add First_k(First_k(CD)Follow_k(S)) to Follow_k(B) or
add First_k(First_k(D)Follow_k(S)) to Follow_k(C) or
add First_k(First_k(lambda)Follow_k(S)) to Follow_k(D) or
do all of the above?
UPDATE:
Let's take the following grammar for example:
S -> ABC
A -> a
B -> b
C -> c
Intuitively, Follow_1(S) = {} because nothing follows after S
Follow_1(A) = {b} because b follows after A,
Follow_1(B) = {c} because c follows after B,
Follow_1(C) = {} because nothing follows after C.
In order to get this result using the algorithm you must consider all cases for S -> ABC.
But my judgement or example may not be right so the question still remains open...

A: If you run into trouble on other grammar problems like this, give this online first, follow, & predict set finder a shot. It's automatic and you can compare answers to its output to get a feel for how to work through these.

But what happens for production rules like: S -> ABCD (A, B, C, D are all nonterminals)?

Here are the rules for finding follow sets.

*

*First put $ (the end of input marker) in Follow(S) (S is the start symbol)

*If there is a production A → aBb, (where a can be a whole string) then everything in FIRST(b) except for ε is placed in FOLLOW(B).

*If there is a production A → aB,  then everything in FOLLOW(A) is in FOLLOW(B)

*If there is  production A → aBb, where FIRST(b) contains ε, then everything in FOLLOW(A) is in FOLLOW(B)

Let's use your example grammar:

*

*S -> ABC

*A -> a

*B -> b

*C -> c

*

*Rule 1 says that follow(S) contains $.

*Rule 2 gives us: follow(A) contains first(B); also, follow(B) contains first(C).

*Rule 3 says that follow(C) contains follow (S).

*None of your productions are nullable, so we don't care about rule #4. A symbol is nullable if it derives ε or if it derives a nullable non-terminal symbol.

Nullability's transitivity can trip people up. Consider this grammar:

*

*S -> A

*A -> B

*B -> ε

Since B derives ε, B's nullable. Since A derives B, which derives ε, A's nullable too. S derives A, which derives B, which derives ε, so S is nullable as well.
Granted, you didn't bring that up, but it's a common source of confusion in compiler courses, so I figured I'd lay it out.
Also, if you need some sample grammars to work through, http://faculty.stedwards.edu/laurab/cosc4342/g1answers.txt might be handy.


text:
Q: Accessing ASP.NET Master Pager public properties in child page I'm embarrassed to ask this here because it's clearly been duplicated several times already on StackOverflow.  I've read a lot of stuff including:
http://msdn.microsoft.com/en-us/library/xxwa0ff0
http://msdn.microsoft.com/en-us/library/c8y19k6h.aspx
http://www.velocityreviews.com/forums/t110056-cannot-access-strongly-typed-properties-in-master-page.html
I think I've done exactly what those article say, but it's not working for me.
Here's the top of my master page, named "MasterNoNews.master":
<%@ Master Language="C#" %>
<%@ Import Namespace="MyMediHealth.DataAccess" %>
<%@ Import Namespace="MyMediHealth.DataAccess.Containers" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    public virtual UserContainer CurrentUser;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.IsAuthenticated)
            CurrentUser = new MembershipQueries().getUserFromUserIdName(Page.User.Identity.Name);
    }
</script>

Here's the top of my child page, named "MyProfile.aspx":
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterNoNews.master"
AutoEventWireup="true" CodeBehind="MyProfile.aspx.cs"
Inherits="MyMediHealth.Interface.MyProfile" %>
<%@ MasterType VirtualPath="~/MasterNoNews.master" %>

Here's the code-behind on my child page, named "MyProfile.aspx.cs" that's not working:
using System;
using System.Web.UI;
using MyMediHealth.DataAccess.Containers;
using MyMediHealth.DataAccess;

namespace MyMediHealth.Interface
{
    public partial class MyProfile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // doesn't work
            UserContainer user = Master.CurrentUser;
            // also doesn't work
            UserContainer user = ((MasterNoNews)this.Master).CurrentUser
        }
    }
}

In the first case, VS is telling me System.Web.Ui.MasterPage does not contain a definition for CurrentUser.  In the second case, VS says the type or namespace 'MasterNoNews' could not be found.
What am I doing wrong?

A: You'll probably still need to move the master page's code to the code behind, but if you put this,
<%@ MasterType VirtualPath="~/MasterPages/Site.master" %>
on the aspx page you'll be able to access the master page's public methods directly without all that casting. Like so:
UserContainer user = Page.Master.CurrentUser
If you're using the master page's code from loads of child pages then I'd create an interface and have the master page implement it.

A: This will not work because you have created properties within Master page (and not code-behind). Typically, master page code would get compiled dynamically and a class name (depending on file name) will be created in a temporary assembly. As you are not reffering to this generated class name within temp assembly, you get error. Correct way will be to have code behind file for the master. For example, master will be
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterNoNews.master.cs" Inherits="[Your Namespace].MasterNoNews" %>

And in code-behind file (MasterNoNews.master.cs) have your properties:
namespace [Your Namespace]
{

    public partial class MasterNoNews : System.Web.UI.MasterPage
    {
      public virtual UserContainer CurrentUser;

      protected void Page_Load(object sender, EventArgs e)
      {
        if (Request.IsAuthenticated)
            CurrentUser = new MembershipQueries().getUserFromUserIdName(Page.User.Identity.Name);
      }
    }
}

Now the second syntax would work i.e.
UserContainer user = (([Your Namespace].MasterNoNews)this.Master).CurrentUser