text:
Q: How to use shiny's actionButton in DataTable through shiny module? I have successfully implemented an actionButton inside a DataTable of a shiny App. However, it only works without the module. Implementing it through shiny module doesn't give any response.
I wonder, what are the changes required while implementing action button inside DataTable through shiny module?
App without module
library(shiny)
library(DT)
#>
#> Attaching package: 'DT'
#> The following objects are masked from 'package:shiny':
#>
#>     dataTableOutput, renderDataTable
  ui <- fluidPage(
    fluidRow(
      DT::dataTableOutput(outputId = "my_data_table"),
      textOutput(outputId = "myText")
    )
  )

  server <- function(input, output) {

    myValue <- reactiveValues(check = '')

    shinyInput <- function(FUN, len, id, ...) {
      inputs <- character(len)
      for (i in seq_len(len)) {
        inputs[i] <- as.character(FUN(paste0(id, i), ...))
      }
      inputs
    }

    my_data_table <- reactive({
      tibble::tibble(
        Name = c('Dilbert', 'Alice', 'Wally', 'Ashok', 'Dogbert'),
        Motivation = c(62, 73, 3, 99, 52),
        Actions = shinyInput(actionButton, 5,
                             'button_',
                             label = "Fire",
                             onclick = paste0('Shiny.onInputChange( \"select_button\" , this.id)')
        )
      )
    })

    output$my_data_table <- renderDataTable({
      my_data_table()
    }, escape = FALSE)

    observeEvent(input$select_button, {
      selectedRow <- as.numeric(strsplit(input$select_button, "_")[[1]][2])
      myValue$check <<- paste('click on ', my_data_table()[selectedRow,1])
    })

    output$myText <- renderText({
      myValue$check
    })

  }

  shinyApp(ui, server)
#>
#> Listening on http://127.0.0.1:3424

Created on 2019-09-17 by the reprex package (v0.3.0)
App with module
library(shiny)
library(DT)
#>
#> Attaching package: 'DT'
#> The following objects are masked from 'package:shiny':
#>
#>     dataTableOutput, renderDataTable

## module UI
test_data_table_ui  <- function(id){
  ns <- NS(id)
  tagList(
    DT::dataTableOutput(outputId = ns("my_data_table")),
    textOutput(outputId = ns("my_text"))
  )

}

## module server
test_data_table_server <- function(input, output, session ){
  ns = session$ns

  myValue <- reactiveValues(check = '')

  shinyInput <- function(FUN, len, id, ns, ...) {
    inputs <- character(len)
    for (i in seq_len(len)) {
      inputs[i] <- as.character(FUN(paste0(id, i), ...))
    }
    inputs
  }

  my_data_table <- reactive({
    tibble::tibble(
      Name = c('Dilbert', 'Alice', 'Wally', 'Ashok', 'Dogbert'),
      Motivation = c(62, 73, 3, 99, 52),
      Actions = shinyInput(actionButton, 5,
                           'button_',
                           label = "Fire",
                           onclick = paste0('Shiny.onInputChange(' , ns("select_button"), ', this.id)')
      )
    )
  })

  output$my_data_table <- DT::renderDataTable({
    return(my_data_table())
  }, escape = FALSE)

  observeEvent(input$select_button, {
    print(input$select_button)
    selectedRow <- as.numeric(strsplit(input$select_button, "_")[[1]][2])
    myValue$check <<- paste('click on ',my_data_table()[selectedRow,1])
  })

  output$my_text <- renderText({
    myValue$check
  })

}

ui <- fluidPage(
  test_data_table_ui(id = "test_dt_inside_module")
)

server <- function(input, output, session) {
  callModule(module = test_data_table_server , id = "test_dt_inside_module")
}

shinyApp(ui, server)
#>
#> Listening on http://127.0.0.1:7922

Created on 2019-09-17 by the reprex package (v0.3.0)

A: Your code:
paste0('Shiny.onInputChange(' , ns("select_button"), ', this.id)')

generates
"Shiny.onInputChange(NS_select_button, this.id)"

where NS is the name space. The object NS_select_button does not exist and clicking the button throws an error for this reason. You need quotes:
"Shiny.onInputChange('NS_select_button', this.id)"

To include some quotes, you can do:
onclick = sprintf("Shiny.onInputChange('%s', this.id)", ns("select_button"))


text:
Q: WidgetPreviewContext is not working in a framework I made a widget using new and shiny WidgetKit. It looks good and working as expected. Then I put all its logic into separate framework to share constant values between extension and main app as well as to provide a unit-testable target. And after introducing a framework SwiftUI previews stopped working. I'm getting error: Cannot preview in this file - Could not find host for previews. It seems that WidgetPreviewContext is not working. I'm wondering why. Could it be because I'm on macOS Catalina 10.15.6?

A: I fixed this because I guess some of the files I had open in the workspace wasn't part of the same target?
Anyways I fixed this error by closing all files I had open in Xcode except the SwiftUI Code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Changesets candidates for merging showing up over and over again I have a main line called "Main" and a "Dev" line. Dev is child of Main.
Main
  ^
  |
Dev

Actually, Main is used as a normal Dev branch, so both are checked-in new work continuously.
From time to time, we decide to merge both. Pull Dev changesets to Main and the other way around. I guess we've not doing this correctly. We change files during merges, etc. In one situation we have created a branch from Dev to stabilize. Guess this was a mistake.
The problem is, some changesets are "persistents", they keep showing up in merge window, also in "tf merge /candidate" command, as if they weren't merged already.
I guess I could do a tf /discard and that would make the changeset disappear. Shouldn't it be this way?
What is more, sometimes a merge reappers or even disappers after merging another changeset. Guess it is a somehow related changeset from another merge operation. In the course of getting rid of these, one single changeset is merged more than once.
PS: Have tried tf /discard, tf /discard /baseless, tf /baseless handling conflicts. Nothing works. Did not try /force because I'm not keen on redoing all conflicts AFAIK.

A: It looks to ne like you are suffering from the pick-n-mix anti pattern.
http://nakedalm.com/avoid-pick-n-mix-branching-anti-pattern/
Change your branching method and the issue will go away.

A: Since I could not merge in the reverse direction (as mentioned in another solution), I tried to solve this in another way.
I rolled back the merge, checked in, and merged again. This time, trying to make no invasive changes.
I did have to 'change' the project file, since the merge tool listed a single chunk of lines that I needed to merge partially. So I excluded the chunk but manually copied the lines that I did need, still inside VS's merge tool, during conflict resolution. Then I accepted the resolution.
During my first attempt, I had left out these lines completely, causing some files and folders to be wrongfully excluded from the project. Then, in the Solution Explorer, I had re-included those files and folders.
Somehow it seems that my first attempt caused TFS to see the merge as incomplete, leaving it in the list. My second attempt was seen as a complete merge and successfully swallowed the candidate.

A: You shouldn't need to discard changesets.  If you want to "sync" them, just merge MAIN->DEV, then DEV->MAIN, potentially resolving conflicts at both steps.
After that no changesets should show up in the merge list and they should be in sync.  If this isn't happening for you, we need some kind of reproducible scenario or detailed description of a specific scenario so we can help you out.


text:
Q: awk checking for multiple patterns in file Here's my code:
/usr/bin/gawk '{
!/simsX.ip-17-31-28-19/ { a[".*Unauthorized.*Dup.*"] += gsub("(| ).*Unauthorized.*Duplication.*( |)", "&") }
!/simsX.ip/ { a[".*En_NoConn-.*"] += gsub("(| ).*En_NoConn-.*( |)", "&") }
} END {
for (i in a)
printf("%s=%s\n", i, a[i])
}' /home/nagios/graphite-web_access.log

When I run the above code I get the following error:
gawk: cmd. line:2:                                                                      !/simsX.ip-17-31-28-19/ { a[".*Unauthorized.*Dup.*"] += gsub("(| ).*Unauthorized.*Duplication.*( |)", "&") }
gawk: cmd. line:2:                                                                                ^ syntax error
gawk: cmd. line:3: !/simsX.ip/ { a[".*En_NoConn-.*"] += gsub("(| ).*En_NoConn-.*( |)", "&") }
gawk: cmd. line:3:             ^ syntax error

This code is suppose to search a file for the specified strings and then output results in the following format:
.*Unauthorized.*Dup.*=48
.*En_Conn-.*=0

I'm having issues identifying where the problem lies or how to fix it.  Please advise.

A: You put a standalone condition inside an action part of the script instead of a condition part of the script.
Good:
awk '<condition> { <action> }'

Bad:
awk '{ <condition> { <action> } }`

You wrote:
awk '{   # <<<< NOTE!!!!
    !/simsX.ip-17-31-28-19/ { a[".*Unauthorized.*Dup.*"] += gsub("(| ).*Unauthorized.*Duplication.*( |)", "&") }
    !/simsX.ip/ { a[".*En_NoConn-.*"] += gsub("(| ).*En_NoConn-.*( |)", "&")
}    # <<<< NOTE!!!
'

so your conditions (!/simsX.ip-17-31-28-19/ and !/simsX.ip/) are inside an action block ({...}). You probably meant to write:
awk '
    !/simsX.ip-17-31-28-19/ { a[".*Unauthorized.*Dup.*"] += gsub("(| ).*Unauthorized.*Duplication.*( |)", "&") }
    !/simsX.ip/ { a[".*En_NoConn-.*"] += gsub("(| ).*En_NoConn-.*( |)", "&") }
'

or less likely:
awk '{
    if (!/simsX.ip-17-31-28-19/) { a[".*Unauthorized.*Dup.*"] += gsub("(| ).*Unauthorized.*Duplication.*( |)", "&") }
    if (!/simsX.ip/) { a[".*En_NoConn-.*"] += gsub("(| ).*En_NoConn-.*( |)", "&")
}
'


text:
Q: Convert QR decoding solution from Python to C# (EU DGC) I am trying to convert this Python code to C# (.NET Core ideally).
Source
My goal is to convert the QR input string to another string containing the data in json. See the provided links.
#! /usr/bin/env python3
import json
import sys
import zlib

import base45
import cbor2
from cose.messages import CoseMessage

payload = sys.argv[1][4:]
print("decoding payload: "+ payload)

# decode Base45 (remove HC1: prefix)
decoded = base45.b45decode(payload)

# decompress using zlib
decompressed = zlib.decompress(decoded)
# decode COSE message (no signature verification done)
cose = CoseMessage.decode(decompressed)
# decode the CBOR encoded payload and print as json
print(json.dumps(cbor2.loads(cose.payload), indent=2))

I couldn't find any NuGet package for Zlib, that would work correctly. So I am stuck straight after base45 decoding. Thanks for any tips.
using System.Text; //Rystem.Text.Base45 NuGet

var removedHeader = testQrData.Substring(4);
var decoded = removedHeader.FromBase45();
byte[] rawBytes = Encoding.ASCII.GetBytes(decoded);

This link might be helpful for further investigation.
Decoding scheme

A: IBarcodeReader reader = new BarcodeReader();//using Zxing
var barcodeBitmap = (Bitmap)Bitmap.FromFile("qrcode.png");

var barcodeReader = new BarcodeReader();

var qrcontent = barcodeReader.Decode(barcodeBitmap).Text;

var qrmessage = qrcontent.Substring(4);//remove first 4 chars

byte[] decodedBase45 = Base45Encoding.Decode(qrmessage);//using base45 lib
var cose = ZlibStream.UncompressBuffer(decodedBase45);//using zlib or similar

var decrypted = Message.DecodeFromBytes(cose).GetContent(); //using COSE
CBORObject cbor = CBORObject.DecodeFromBytes(decrypted);    //using Peter.O.. CBOR

var jsonDecoded = cbor.ToJSONString(); //or deserialize it to custom class

A: I added "Zlib.Portable" from NuGet and used "ZlibStream.UncompressString"
byte[] decoded = Base45Encoding.Decode(input);
var stringResult = ZlibStream.UncompressString(decoded);`

I'm stuck in the next step "CoseMessage.decode" :/

A: I have used the ZXing library in the past to decode and create QR Codes:
https://github.com/micjahn/ZXing.Net
You could also try: https://github.com/codebude/QRCoder
A quick ZXing example from their github page:
// create a barcode reader instance
IBarcodeReader reader = new BarcodeReader();
// load a bitmap
var barcodeBitmap = (Bitmap)Image.LoadFrom("C:\\sample-barcode-image.png");
// detect and decode the barcode inside the bitmap
var result = reader.Decode(barcodeBitmap);
// do something with the result
if (result != null)
{
   txtDecoderType.Text = result.BarcodeFormat.ToString();
   txtDecoderContent.Text = result.Text;
}

This example reads a QR Code image.
I'm not sure what your input is but i would assume it's also an image in binary format so you might have to play around to get it working.

A: This solution works for me.
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using System;
using System.IO;
using Com.AugustCellars.COSE;
using PeterO.Cbor;
using Newtonsoft.Json;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Collections.Generic;

namespace DGCVerification.Services {
  public class DGCVerificationService: IDGCVerificationService {
    private readonly string _certificatePrefix = "HC1:";

private readonly ILogger < DGCVerificationService > _logger;

public DGCVerificationService(ILogger < DGCVerificationService > logger) {
  _logger = logger;
}

private bool TryTrimPrefix(string certificateString, out string result) {
  if (!certificateString.StartsWith(_certificatePrefix)) {
    result = null;
    return false;
  }

  result = certificateString.Substring(_certificatePrefix.Length);
  return true;
}

private byte[] DecompressFromZlib(byte[] input) {
  using(var memoryStream = new MemoryStream(input)) {
    using(var decompressionStream = new InflaterInputStream(memoryStream)) {
      using(var resultStream = new MemoryStream()) {
        decompressionStream.CopyTo(resultStream);
        var result = resultStream.ToArray();
        return result;
      }
    }
  }
}

private bool VerifyCoseSignature(Sign1Message coseMessage, string signature) {
  var signatureAsBytes = Convert.FromBase64String(signature);

  var publicKey = OneKey.FromX509(signatureAsBytes);
  var result = coseMessage.Validate(publicKey);

  _logger.LogInformation($"cose message signature {signature} verified as {result}");
  return result;
}

private DGCPayload DecodeAndDeserialize(string certificateString, out Sign1Message coseMessage) {
  coseMessage = null;
  if (!TryTrimPrefix(certificateString, out
      var trimmedPrefixString)) {
    _logger.LogInformation($"certificate {certificateString} didn't have proper prefix {_certificatePrefix}");
    return null;
  }

  var bytesBase256 = Base45Encoding.Decode(trimmedPrefixString);
  _logger.LogInformation($"certificate {certificateString} base45 decoded to  {Convert.ToBase64String(bytesBase256)}");

  var decompressedFromZlib = DecompressFromZlib(bytesBase256);
  _logger.LogDebug($"certificate {certificateString} zlib decompressed to {Convert.ToBase64String(decompressedFromZlib)}");

  coseMessage = Message.DecodeFromBytes(decompressedFromZlib) as Sign1Message;
  var coseMessagePayload = coseMessage.GetContent();
  var cborResult = CBORObject.DecodeFromBytes(coseMessagePayload);
  var jsonResult = cborResult.ToJSONString();
  var result = JsonConvert.DeserializeObject < DGCPayloadCzechVersionRoot > (jsonResult);
  return result.DGCPayloadWrap.DGCPayload;
}

private bool IsNotExpiredDGC(DGCPayload dGCPayload, UzisData uzisData) {
  var vaccine = dGCPayload.Vaccination?.FirstOrDefault();

  if (vaccine != null) {
    var vaccinationValidityRules = uzisData.DGCValidityCzechRules.Rules
      .FirstOrDefault()
      .PlatnostiVakcinace;

    var rule = vaccinationValidityRules.FirstOrDefault(x => x.VaccineMedicinalProduct == vaccine.Mp) ??
      vaccinationValidityRules.FirstOrDefault(x => x.VaccineMedicinalProduct == null);

    if (!DateTime.TryParse(vaccine.Dt, out
        var vaccinatedOnDate)) {
      _logger.LogError($"couldn't parse date of vaccination for DGC : {JsonConvert.SerializeObject(dGCPayload)}");
      return false;
    }

    var result = DateTime.Now.Date <= vaccinatedOnDate.AddMonths(rule.OdolnostMesicDo);
    return result;
  }

  var test = dGCPayload.Test?.FirstOrDefault();

  if (test != null) {
    var testValidityRule = uzisData.DGCValidityCzechRules.Rules
      .FirstOrDefault()
      .PlatnostiTestu
      .FirstOrDefault(x => x.TypeOfTest == test.Tt);

    if (!DateTime.TryParse(test.Tr, out
        var testedOnDate)) {
      _logger.LogError($"couldn't parse date of test for DGC : {JsonConvert.SerializeObject(dGCPayload)}");
      return false;
    }

    var result = DateTime.Now.Date <= testedOnDate.AddHours(testValidityRule.PlatnostHod);

    return result;
  }

  var recovery = dGCPayload.Recovery?.FirstOrDefault();

  if (recovery != null) {
    if (!DateTime.TryParse(recovery.Du, out
        var recoveryValidUntil)) {
      _logger.LogError($"couldn't parse recovert valid until for DGC : {JsonConvert.SerializeObject(dGCPayload)}");
      return false;
    }

    var result = DateTime.Now.Date <= recoveryValidUntil;
    return result;
  }

  return false;
}

private string GetCountryFromDGC(DGCPayload dGCPayload) {
  var result = dGCPayload.Vaccination?.FirstOrDefault()?.Co ??
    dGCPayload.Test?.FirstOrDefault()?.Co ??
    dGCPayload.Recovery?.FirstOrDefault()?.Co;

  if (result == null) {
    throw new ArgumentException($"couldn't retrieve country from DGC. dgc : {JsonConvert.SerializeObject(dGCPayload)}");
  }

  return result;
}

private List < SignatureCertificate > GetFittingSignatures(DGCPayload dGCPayload, UzisData uzisData) {
  try {
    var country = GetCountryFromDGC(dGCPayload);

    var result = uzisData.NationalCertificateSignatures.SignatureCertificate
      .Where(x => x.Active)
      .Where(x => x.Country == country)
      .Where(x => x.CertificateType == "DSC")
      .ToList();

    return result;
  } catch (Exception e) {
    _logger.LogError(e, $"Filtering signatures from UZIS failed with exception");
    return null;
  }
}

private bool IsProperlySignedDGC(string certificateString, DGCPayload dGCPayload, Sign1Message coseMessage, UzisData uzisData) {
  var fittingSignatures = GetFittingSignatures(dGCPayload, uzisData);
  var result = false;
  foreach(var signature in fittingSignatures) {
    try {
      var signatureVerificationResult = VerifyCoseSignature(coseMessage, signature.RawData);

      _logger.LogInformation($"certificate {certificateString} signature validation against signature {signature} resulted in {signatureVerificationResult}");

      result |= signatureVerificationResult;
    } catch (Exception e) {
      _logger.LogError(e, $"certificate {certificateString} signature validation against signature {signature} failed with exception");
    }
  }

  return result;
}

public bool IsValidDgc(string certificateString, UzisData uzisData, out DGCPayload decodedDGCPayload, out VerificationResult verificationResult) {
  decodedDGCPayload = null;
  Sign1Message coseMessage = null;

  try {
    decodedDGCPayload = DecodeAndDeserialize(certificateString, out coseMessage);

    if (coseMessage == null) {
      _logger.LogInformation($"certificate {certificateString} decoded to null COSE");
      verificationResult = VerificationResult.UnableToDecode;
      return false;
    }
  } catch (Exception e) {
    _logger.LogError(e, $"certificate {certificateString} decoding failed with exception");
    verificationResult = VerificationResult.UnableToDecode;
    return false;
  }

  var isProperlySigned = IsProperlySignedDGC(certificateString, decodedDGCPayload, coseMessage, uzisData);

  if (!isProperlySigned) {
    verificationResult = VerificationResult.InvalidSignature;
    return false;
  }

  var isNotExpired = IsNotExpiredDGC(decodedDGCPayload, uzisData);

  if (!isNotExpired) {
    verificationResult = VerificationResult.Expired;
    return false;
  }

  verificationResult = VerificationResult.Valid;
  return true;
    }
  }
}

And the tricky base45
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DGCVerification
{
public class Base45Encoding
{
    private static readonly Dictionary<byte, char> _encodingTable = new Dictionary<byte, char>
    {
            {0x0,'0'},
            {0x1,'1'},
            {0x2,'2'},
            {0x3,'3'},
            {0x4,'4'},
            {0x5,'5'},
            {0x6,'6'},
            {0x7,'7'},
            {0x8,'8'},
            {0x9,'9'},
            {0xA,'A'},
            {0xB,'B'},
            {0xC,'C'},
            {0xD,'D'},
            {0xE,'E'},
            {0xF,'F'},
            {0x10,'G'},
            {0x11,'H'},
            {0x12,'I'},
            {0x13,'J'},
            {0x14,'K'},
            {0x15,'L'},
            {0x16,'M'},
            {0x17,'N'},
            {0x18,'O'},
            {0x19,'P'},
            {0x1A,'Q'},
            {0x1B,'R'},
            {0x1C,'S'},
            {0x1D,'T'},
            {0x1E,'U'},
            {0x1F,'V'},
            {0x20,'W'},
            {0x21,'X'},
            {0x22,'Y'},
            {0x23,'Z'},
            {0x24,' '},
            {0x25,'$'},
            {0x26,'%'},
            {0x27,'*'},
            {0x28,'+'},
            {0x29,'-'},
            {0x2A,'.'},
            {0x2B,'/'},
            {0x2C,':'},
    };

    private static readonly Dictionary<char, byte> _decodingTable;

    static Base45Encoding()
    {
        _decodingTable = _encodingTable.ToDictionary(x => x.Value, x => x.Key);
    }

    private static List<byte> ToBytesBase45(string charsBase45)
    {
        var result = new List<byte>(charsBase45.Length);
        foreach (var character in charsBase45)
        {
            if (!_decodingTable.TryGetValue(character, out byte asByte))
            {
                throw new FormatException($"input string contains {character} with numeric value {char.GetNumericValue(character)} on index {charsBase45.IndexOf(character)} which is not valid base45 character");
            }
            result.Add(asByte);
        }

        return result;
    }

    private static List<ushort> ToShortsBase10(List<byte> bytesBase45)
    {
        var result = new List<ushort>(bytesBase45.Count);
        ushort num = 0;
        double pow = 0;

        for (int i = 0; i != bytesBase45.Count; ++i, ++pow)
        {
            num += (ushort)(bytesBase45[i] * Math.Pow(45, pow));

            if (pow == 2 || i == (bytesBase45.Count -1))
            {
                result.Add(num);
                num = 0;
                pow = -1;
            }
        }

        return result;
    }

    private static List<byte> ToBytesBase256(List<ushort> shortsBase10, int charBase45Length)
    {
        var result = new List<byte>(shortsBase10.Count);

        for (int i = 0; i != shortsBase10.Count; ++i)
        {
            var num = (byte)(shortsBase10[i] / 256);

            if(!(i == (shortsBase10.Count - 1)
                && charBase45Length % 3 != 0
                && num == 0))
            {
                result.Add(num);
            }
            result.Add((byte)(shortsBase10[i] % 256));
        }

        return result;
    }

    public static byte[] Decode(string charsBase45)
    {
        if (charsBase45.Length % 3 == 1)
        {
            throw new FormatException("input string does not have correct length. mod 3 == 1. it isnt base45");
        }

        var bytesBase45 = ToBytesBase45(charsBase45);
        var shortsBase10 = ToShortsBase10(bytesBase45);
        var bytesBase256 = ToBytesBase256(shortsBase10, charsBase45.Length);

        return bytesBase256.ToArray();
    }
}
}

A: Decode/encode base45:
/// <summary>
/// https://tools.ietf.org/html/draft-faltstrom-baseBaseSize-01
/// TL/DR:
/// This encoding takes a byte array, splits it into 2 byte chunks and encodes each chunk as 3 characters.
/// Any remaining byte is encoded as 2 characters, padded with a '0' when the remaining byte has value < 45.
/// </summary>
public static class Base45Encoding
{
    private const int BaseSize = 45;
    private const int BaseSizeSquared = 2025;
    private const int ChunkSize = 2;
    private const int EncodedChunkSize = 3;
    private const int SmallEncodedChunkSize = 2;
    private const int ByteSize = 256;

    private static readonly char[] _Encoding = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                                                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
                                                'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                                                'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '$', '%', '*',
                                                '+', '-', '.', '/', ':' };

    private static readonly Dictionary<char, byte> _Decoding = new(BaseSize);

    static Base45Encoding()
    {
        for(byte i = 0; i < _Encoding.Length; ++i)
            _Decoding.Add(_Encoding[i], i);
    }

    public static string Encode(byte[] buffer)
    {
        if (buffer == null)
            throw new ArgumentNullException(nameof(buffer));

        var wholeChunkCount = buffer.Length / ChunkSize;
        var result = new char[wholeChunkCount * EncodedChunkSize + (buffer.Length % ChunkSize == 1 ? SmallEncodedChunkSize : 0)];

        if (result.Length == 0)
            return string.Empty;

        var resultIndex = 0;
        var wholeChunkLength = wholeChunkCount * ChunkSize;
        for (var i = 0; i < wholeChunkLength;)
        {
            var value = buffer[i++] * ByteSize + buffer[i++];
            result[resultIndex++] = _Encoding[value % BaseSize];
            result[resultIndex++] = _Encoding[value / BaseSize % BaseSize];
            result[resultIndex++] = _Encoding[value / BaseSizeSquared % BaseSize];
        }

        if (buffer.Length % ChunkSize == 0)
            return new string(result);

        result[^2] = _Encoding[buffer[^1] % BaseSize];
        result[^1] = buffer[^1] < BaseSize ? _Encoding[0] : _Encoding[buffer[^1] / BaseSize % BaseSize];

        return new string(result);
    }

    public static byte[] Decode(string value)
    {
        if (value == null)
            throw new ArgumentNullException(nameof(value));

        if (value.Length == 0)
            return Array.Empty<byte>();

        var remainderSize = value.Length % EncodedChunkSize;
        if (remainderSize == 1)
            throw new FormatException("Incorrect length.");

        var buffer = new byte[value.Length];
        for (var i = 0; i < value.Length; ++i)
        {
            if (_Decoding.TryGetValue(value[i], out var decoded))
            {
                buffer[i] = decoded;
                continue; //Earliest return on expected path.
            }

            throw new FormatException($"Invalid character at position {i}.");
        }

        var wholeChunkCount = buffer.Length / EncodedChunkSize;
        var result = new byte[wholeChunkCount * ChunkSize + (remainderSize == ChunkSize ? 1 : 0)];
        var resultIndex = 0;
        var wholeChunkLength = wholeChunkCount * EncodedChunkSize;
        for (var i = 0;  i < wholeChunkLength; )
        {
            var val = buffer[i++] + BaseSize * buffer[i++] + BaseSizeSquared * buffer[i++];
            result[resultIndex++] = (byte)(val / ByteSize); //result is always in the range 0-255 - % ByteSize omitted.
            result[resultIndex++] = (byte)(val % ByteSize);
        }

        if (remainderSize == 0)
            return result;

        result[^1] = (byte)(buffer[^2] + BaseSize * buffer[^1]); //result is always in the range 0-255 - % ByteSize omitted.
        return result;
    }
}


text:
Q: springboot project deploy with gradle : Execution failed for task ':deploytest' I write a springboot project with gradle, and I want to deploy it.
Here comes part of my code in build.gradle :
remotes {
  localtest {
    host = '192.168.0.116'
    user = 'root'
    password = '*****'
  }
}

task deploytest(dependsOn: build) << {
  ssh.run {
    session(remotes.localtest) {
      put from: 'build/libs/test-0.0.1-SNAPSHOT.jar', into: '/opt/test/'
      execute "cd /opt/tieba"
      execute 'nohup java -jar -Dspring.profiles.active=test test-0.0.1-SNAPSHOT.jar & echo $! > application.pid'
    }
  }
}

Then I run gradle deploytest, but it meets a problem :
FAILURE: Build failed with an exception.

* Where:
Build file 'E:\github\spring-projects\test\build.gradle' line: 97

* What went wrong:
Execution failed for task ':deploytest'.
> reject HostKey: 192.168.0.116

Details
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':deploytest'.
Caused by: com.jcraft.jsch.JSchException: reject HostKey: 192.168.0.116
gradle error details 01
gradle error details 02

A: Got the same issue, the server was using ED25519.
I deleted the corresponding line in ~/.ssh/known_hosts, retrieved the rsa banner with ssh-keyscan -t rsa myserver.tld and copied the result back to known_host
Looks better than setting knownHosts = allowAnyHosts

A: I fix it by setting knownHosts = allowAnyHosts in ssh config, complete setting is
remotes {
   localtest {
     host = '192.168.0.116'
     user = 'root'
     knownHosts = allowAnyHosts
     password = '*****'
   }
}


text:
Q: Replace Function Pointers with Functions Which level is the best place to do points-to analysis and replace function pointers with real functions? Frontend (Clang) or IR?
Suppose that the points-to analysis is a simple heuristic based approach as follows:

*

*Check for all assignments to a function pointer, and

*Check for all struct initializations (the code is in C) that contain a function pointer.


text:
Q: In how many ways can 10 identical laptops be distributed among five electronic stores In how many ways can 10 identical laptops be distributed among five electronic stores if

*

*there are no restrictions?

*each store gets at least one?

*the largest store gets at least three?

*each store gets at least two?

Would I used the r-combination with repetition for part 1?
so for part 1 you do$\binom{14}{10}$
I am learning r-combination and r-permutation and now I keep getting confused when given a problem


text:
Q: Migrating data from public schema to table in another schema in postgreSQL I need to migrate data from multiple tables in the db public schema to one table in a schema called fs. Then I need to match the migrated data, now is the fs schema, to data in a different table in the fs schema.
Would something like this work?
INSERT INTO targetTable
SELECT * FROM [sourceserver].[sourcedatabase].[dbo].[sourceTable]

Very new to postgreSQL and SQL in general, so please let me know if clarification is necessary. Thank you.

A: This will work
INSERT INTO Table2 (<columns>)
SELECT <columns>
FROM schema.Table1


text:
Q: jquery- is document.ready necessairry I want to make use of JS module (iffys) in order to structure my JS functions. I'm using jQuery and pure JS. My JS modules are loaded at the end of the HTML body, so the page shall be loaded and rendered.
Is a document.ready necessairry closure?
How do I have to put it, if I'm working with iffys?
JS Module
app.input = (function () {
    var updateSize = function (data) {.....
    }
    $(".tool").click(function () {....
    });
    return {
        updateSize: updateSize,
    }
})();


text:
Q: Help on R squared, Mean Squared Error (MSE), and/or RMSE as individual measures in regression model perfomance evaluation? Just a question on regression model evaluation statistics. Here we go.
I seem to be under the impression that $R^2$, MSE, and RMSE are all very closely related and essentially all play a part in determining the fit of a model, but somehow I am still confused about which one, then, I should be using as a final determinant of how good/bad my model is performing, or how is it that I can consider all three as separate indicators (with them being so similar)?
It just seems like no matter what, the model with the $R^2$ closest to 1 also has the lowest MSE and RMSE values. I read that "sometimes" the $R^2$ doesn't determine the fit properly, and so the other metrics should be the determinants of fit, but if they all correlate (one goes up, the other goes up, and vice versa), is there even reason to separately consider them? (<- my bad if this seems redundant)
That's all I've got. Thanks for your time!

A: Mean square error (MSE) and root mean square error (RMSE) obviously have a one-to-one relationship, as MSE can't be negative. Confusion can arise, however, from what MSE means in a particular context. As the Wikipedia page on mean squared error notes:

In regression analysis, the term mean squared error is sometimes used to refer to the unbiased estimate of error variance: the residual sum of squares divided by the number of degrees of freedom.

If that is what you have in mind for MSE then the standard $R^2$ reported for linear regression necessarily increases as MSE decreases, other things being equal, as it is defined as:
$$ R^2 \equiv 1 - {SS_{\rm res}\over SS_{\rm tot}}$$
where $SS_{\rm res}$ is the residual sum of squares and $SS_{\rm tot}$ is the total sum of squares.
Sometimes, however, MSE refers to the mean-squared error in predictions made on a new data set. It's quite possible for a regression model to overfit the data at hand by including too many predictors relative to the number of observations. In that case you could have very small MSE from your regression but large MSE when you apply the regression model to a new data set. The adjusted $R^2$ often reported by statistical software starts to take overfitting into account by adjusting for the numbers of predictors and observations.
One example of using MSE in this second context is to separate the data into a training set and a test set, develop the regression on the training set, and then evaluate MSE on the test set as a test of the quality of your regression model. That approach works best if you have very large numbers of observations. With smaller data sets, analogous approaches based on cross-validation or bootstrapping use MSE of predictions to serve a similar purpose.


text:
Q: Unable to update livereload IONIC I am new to IONIC. I have successfully installed ionic and cordova. But when I am editing html template it is showing me this error. I am behind a corporate proxy.

edit 1


text:
Q: Get N random equidistant points from a given point I need a function that let me find n random points. These points must have the same distance from a given point. Can you help me?
void createCpoints()
{
    int xcenter=3;
    int ycenter=3;
    int radius=3;
    double x[N];
    double y[N];
    //...
}

A: Just generate N angles, and calculate the (x,y) coordinates from there using
x1 = xCenter + r * cos(theta1)
y1 = yCenter + r * sin(theta1)

(Note: this is not supposed to be ready-to-use C++ code. If you need help with the language, you need to be more specific.)

A: As @5gon12eder says, you could use polar coordinates with the initial point as virtual midpoint:
#include <math.h>

//...

for(int i = 0; i < n; i++) {
    double alpha = 2.0d*M_PI*((double) rand() / RAND_MAX);
    x[i] = radius*cos(alpha)+x0;
    y[i] = radius*sin(alpha)+y0;
}

With (x0,y0) the coordinates of the original point.


text:
Q: solve $y^\prime=\frac {y^2}{x^2} -\frac {y}{x}$ can't find my mistake I've been trying to solve
$ y'=\frac{y^2}{x^2} - \frac{y}{x} $
but something went wrong but I can't find my mistake
$$y^\prime=y^2/x^2\ -y/x \\
y^\prime+y/x=y^2/x^2\\
y=v/x \\
(v/x)^\prime+(v/x\ \ )/x=(v/x)^2/x^2\\
v^\prime/x-v/x^2\ +v/x^2 =v^2/x^3\\
v^\prime/v^2 =1/x^2\\
-1/v=-1/x+c\\
v=1/(x+c)\\
yx=1/(x+c)\\
y=1/(x^2+cx)
$$
can you find it?
edit:
I tried @lostInspace correction and now I get this:
$
-1/v=-1/2x^2 +c
v=2x^2+c
yx=2x^2+c
y=2x+c/x
$
which is not the answer.

A: $$y^\prime=y^2/x^2\ -y/x \\
y^\prime+y/x=y^2/x^2\\
y=v/x \\
(v/x)^\prime+(v/x\ \ )/x=(v/x)^2/x^2\\
v^\prime/x-v/x^2\ +v/x^2 =v^2/x^3\\
$$
You should have
$$ \dfrac {v'x-v}{x^2} +v/x^2 =v^2/x^4 $$
A better choice of substitution is
$$y=vx \implies y'=v'x+v$$
The equation becomes:
$$v'x=v^2-2v$$

A: As already said, start with $y= z x$ to make
$$x z'-z^2+2 z=0$$ which is separable.
You could even do now $z=\frac 1u$
$$x u'-2 u+1=0$$ which is still simpler


text:
Q: List of objects with a list as a property of the object Declaring a list of objects:
List<object> result = new List<object>();

and a list of int to store the ids:
List<int> ids = new List<int>();

I want to store in result objects containing the pair (string, list of int).
It works fine for the pair (string, int) but I want that when there are 2 identical strings to have only one object and the int values to be stored in a list.
ex: {pars = "xxx", id = 1} , {pars = "xxx", id = 2} becomes {pars = "xxx", id = (1,2 )}
For doing the initial functionality, I use a foreach through an object from which I take the string(pars) and the id:
    foreach (dataBinding in myData)
    {
        var x = string.Join(" ", dataBinding.Params.Select(p => p.myDescription));

        result.Add(new { pars = x, id = dataBinding.Id });

    }

there could be more strings in Params, that's why I use the join.
As it is here it works by creating objects having the form (string, int). But my aim is to make it (string, list of int) and if there are two objects with same string to combine them as I wrote before.
I tried to add ids list as the second property of the object but probably I'm not doing it correctly.
 result.Add(new { pars = x, ids = dataBinding.Id });

A: Perhaps I am not understanding the scenario fully but I suspect using the following would server your purpose.
List<Dictionary<string, List<int>>>

When the key doesn't exist you add it and when it does you just add to the List.

A: You can use LINQ, especially GroupBy:
Dictionary<string, List<int>> descriptionIDs = myData
    .GroupBy(x => x.myDescription)
    .ToDictionary(g => g.Key, g => g.Select(x => x.Id).ToList());

Now you have even a dictionary, not just a strange List<object> that contains anonymous types.
As someone mentioned, you can also use ToLookup which i'd also prefer:
var descriptionLookup = myData.ToLookup(x => x.myDescription);

Now you can get the ID-List easily:
var result = descriptionLookup.Select(g => new { pars = g.Key, ids = g.Select(x=> x.Id).ToList() }).ToList():

A: Below program depicts the current generic collection type, also allow to add a new value if Key Already exists.
using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {

        MyProgram p = new MyProgram();

        p.Add("First" , 5);
        p.Add("Second" , 8);
        p.Add("Third" , 9);
        p.Add("First" , 6);
        p.Add("First" , 7);

        p.PrintDictionary();
    }
}

public class MyProgram
{
    private Dictionary<string, List<int>> dict = new Dictionary<string, List<int>>();

    public void Add(string key, int value)
    {
        if (dict.ContainsKey(key))
        {
            dict[key].Add(value);
        }
        else
        {
            dict.Add(key, new List<int>() {value});
        }
    }

    public void PrintDictionary()
    {
        foreach(var keyValue in dict)
        {
            Console.WriteLine("Key : " + keyValue.Key);

            foreach(var val in keyValue.Value)
            {
                Console.WriteLine(string.Format("\t Value : {0}", val));
            }
        }
    }
}

Output :

Key : First
Value : 5

Value : 6

Value : 7

Key : Second
Value : 8

Key : Third
Value : 9

Check this Live Fiddle.


text:
Q: React native absolute path - Jest setup I'm using this technique to import packages in a react native project
https://medium.com/@davidjwoody/how-to-use-absolute-paths-in-react-native-6b06ae3f65d1
It suggests to
1) Add a package.json file with { "name": "FOLDER_NAME" } in it to the folder you'd like to import from.
2) import Thing from 'FOLDER_NAME/thing'.
This works but my Jest tests are unable to find those modules.
How can I setup Jest to find those modules?

A: You can tell Jest to search your modules in your root folder by adding this to package.json:
"jest": {
    "moduleDirectories": ["node_modules", "/"]

Note the default value is node_modules so you should include it as well.
You can also tell it to search in your specific folder depending on your folder structure:
"jest": {
    "moduleDirectories": ["node_modules", "FOLDER_NAME"]


text:
Q: Visual Studio Team System 2008 & Domain Issues We have TFS installed in a US server. We need to login into VPN to access the TFS server. TFS is configured to use with company's domain user account. However my system is part of the domain. Hence I couldn't access the TFS. I have Visual Studio Team System Developer edition. Can someone here help how to access TFS server installed with different domain?
Regards,
Krish

A: TFS uses the domain information of the current logged in Windows account, it's part of the TFS API.
If you're logging into the machine with an account which is on a different domain (Note: Local users are also on a different domain) you will not get single-sign-on.
As far as I'm aware there isn't a way around the authentication model which VSTS uses. You could write your own VSTS-style extensions using the existing VS API which say, uses a config file for the authentication credentials as the TFS API does support authentication through a manually-created user (we have an external application at work which authenticates against our TFS server and is used by employees of our many offices on different domains).

A: For codeplex you have to connect to TFS using 'SND\username_cp', maybe you can use 'DOMAINNAME\username' as well.


text:
Q: How to show my Spinner to right of Toolbar my Layout looks like below

You can see spinner added to my toolbar, but what I want is to make it right align, show it to most right of toolbar.
below is the xml code I used
<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical" >

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:elevation="4dp"
            android:gravity="right"                          //gravity set to right
            android:background = "@color/color_toolbar"
        >
             <Spinner
                android:id="@+id/spinner_category"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </android.support.v7.widget.Toolbar>
   </LinearLayout>

spinner is not showing android:layout_gravity

I tried setting gravity to right but it doesn't work. how can I do this?

A: I had the same issue. I have fixed the alignment issue based on the comments of question. So keeping the answer here to help someone directly.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary">
    <Spinner
        android:id="@+id/toolbar_spinner"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:visibility="visible"
        android:layout_gravity="right"/>
</android.support.v7.widget.Toolbar>


text:
Q: Bloc Listener not working after phone is locked and then unlocked Bloc listener isn't working on the view section once the device is locked and unlocked even though the bloc events are handled inside the bloc and is being emitted.
The bloc is being provided as an inherited widget to the root of the application which is getting reset after device is locked -> unlocked.
In main
OrderBlocProvider(
                child: MaterialApp(

Inherited widget
class OrderBlocProvider extends InheritedWidget {
  final OrderBloc orderBloc;
  OrderBlocProvider({Key? key, Widget? child})
      : orderBloc = OrderBloc(), super(key: key, child: child!);

  bool updateShouldNotify(_) => true;

  static OrderBloc? of(BuildContext context) {
    return context
        .dependOnInheritedWidgetOfExactType<OrderBlocProvider>()
        ?.orderBloc;
  }
}

It is accessed as
    _orderBloc = OrderBlocProvider.of(context) as OrderBloc;

Events are being received on the view inside the build method
BlocListener<OrderBloc, OrderState>(listener: (context, state) {

UPDATE

I was able to resolve this by adding the provider to the builder method of the MaterialApp but now BlocListener is being called multiple times whenever the route is being called.
MaterialApp(
                  builder: (BuildContext context, Widget? child) {
                    return Provider<OrderBloc>(
                      create: (_) => _orderBloc,
                      child: MediaQuery(
                        data: MediaQuery.of(context).copyWith(
                          textScaleFactor: 1.0,
                        ),
                        child: child!,
                      ),
                    );
                  },

UPDATE 2

Finally it worked after replacing BlocListener with StreamSubscription sub and then cancelling it on the dispose of the widget.


text:
Q: Which is faster comparing an uniqueidentifier or a string in tsql? I have a table which holds the guid for an user and their actual name as a string. I would like to grab some information based on an user. But which field should I use? Should my code say:
select *
from userinboxcount
where countDate >= startDate and countDate <= endDate and userid = '<guid here>'

or

select *
from userinboxcount
where countDate >= startDate and countDate <= endDate and username = "FirstName LastName"

A: The biggest difference is if one field has an index that the database can use, and the other doesn't. If the database has to read all the data in the table to scan for the value, the disk access takes so much resources that the difference in data type is not relevant.
If both fields have indexes, then the index that is smaller would be somewhat faster, because it loads faster, and it's more likely that it remains in the cache.
Ideally you would have an index for all the fields in the condition, which has the fields that you want to return as included fields. That way the query can produce the result from only the index, and doesn't have to read from the actual table at all. You should of course not use select *, but specify the fields that you actually need to return.
Other than that, it would be somewhat faster to compare GUID values because it's a simple numeric comparison and doesn't have to consider lexical rules.

A: See the query plan and you can see it for yourself.
But the unique identifier usually has an index and the string (username) might not have. If so, and if there are many records, prolly the unique identifier would be faster!

To the the query plan, check THIS article.

A: GUID will be good enough.
1. GUID will produce unique values in the table.
2. Create Non Clustered Index on this column.

Reference -   Non-clustered indexes are particularly handy when we want to return a single row from a table.

A: Are you completely married to the GUID?  You should use a GUID when you need a primary key that will be unique across multiple systems.  I would suggest skipping the GUID and using a composite key.  For example, you could use an identity plus a GETDATE() as a composite key.  This would give you an easy way to query your data (try to remember a GUID over an integer).  This will also perform much, much better than GUID.  Probably twice as fast.

A: If userid is a primary key, you should use that.  If you use first and last name, you could have two John Smith entries, for example, and that could create an issue for you. Using the PK should be safer
On the performance side, it's a good idea to become familiar with explain plan (execution path?) of the query.  I'd expect using the userid would be faster, but checking the plan should tell you for certain.


text:
Q: for loops and negative numbers This is a very basic Javascript question. See, I have a for loop which starts like this
for (i=0;i<=negativeorpositivenumber;i++) {

As the name suggests, the positiveornegativenumber variable can contain either a positive or negative number. As a result, if said variable is positive, the for loop works. If it is negative, the loop exits immediately because i is already larger than negativeorpositivenumber.
Is there a way, without using two for loops (one for negative and one for positive) to have this work both ways? So change i<= to i>= and i++ to i-- if the variable negativeorpositivenumber is negative?
I suppose this question could also apply to more than one language as well.
EDIT: perhaps I should've made this more clear. I can't use absolute value because the value of i actually needs to count down. Thanks to all the people who were helpful and answered using Math.abs, however.

A: for (i=0;i<=Math.abs(negativeorpositivenumber);i++) {
    var original = negativeorpositivenumber > 0 ? i : -i;    // optional

Documentation here.

A: Why not use Absolute value.
for(int i = 0; i < abs(positiveorneativenumber); i++)
{
    //do stuff
}

A: similar to the above comments but based on the sign of the number, you can do a while loop like this:
var sign = negativeorpositivenumber? negativeorpositivenumber <0?-1:1:0
while(i != 0){
  i -= sign;
}

A: To loop in either direction, you can first check where you are going, and what the bounds are:
var dir = negativeorpositivenumber > 0 ? 1 : -1;
var min = negativeorpositivenumber > 0 ? 0 : negativeorpositivenumber;
var max = negativeorpositivenumber > 0 ? negativeorpositivenumber : 0;

for (var i = 0; i >= min && i <= max; i += dir) {
  ...
}

Demo: http://jsfiddle.net/Guffa/cbh5c7rb/


text:
Q: E or natural log problem, solve the equation If someone could explain to me the first step or two so I could solve this that would be great. All the e's are confusing me
Solve the equation. (Round your answer to four decimal places.)
$$e^x − 6e^−{^x} − 1 = 0$$

A: If you multiply the whole equation by $e^x$, you will get a quadratic on $e^x$:
$$
(e^x)^2-6-e^x=0.
$$

A: You can start out by multiplying all terms of the equation by $e^x$:
$$e^x\cdot e^x - e^x\cdot 6e^{-x} - e^x = 0.$$
You can reduce this to
$$(e^x)^2 - e^x - 6 = 0.$$
Substitute $t=e^x$, and get
$$t^2-t-6=0.$$
This is a quadratic equation in $t$, which you can solve with the usual methods. When you have the solutions for $t$, remember to go back and find the solutions for $x$.

A: HINT:
$$e^x-6e^{-x}-1=0\Longleftrightarrow$$
$$(e^{-x})(e^x-3)(e^x+2)=0\Longleftrightarrow$$
$$(e^{-x})=0\vee(e^x-3)=0\vee(e^x+2)=0\Longleftrightarrow$$
$$e^{-x}=0\vee e^x-3=0\vee e^x+2=0\Longleftrightarrow$$
$$e^{-x}=0\vee e^x=3\vee e^x=-2$$


text:
Q: Duvida Lista duplamente encadeada com inserção ordenada Criei tudo porém o minha função de deletar está apagando o registro porém mantendo no print o código 0.
Alguém poderia me ajudar a encontrar meu erro? Também gostaria de saber se o meu algorítimo foi desenvolvido de maneira correta, sabendo que era para ser desenvolvido com lista duplamente encadeada com inserção ordenada.

A: O problema está na função exclusao.Você está excluindo o registro mas não está diminuindo o tamanho da lista, já que a função print está usando a variável lista->tamanho como parâmetro de parada do loop for, a saída acaba sendo lixo de memória.É só colocar no final da função exclusao lista->tamanho-- que resolve esse problema.
Aliás parece que você está usando uma lista cíclica, se você colocar NULL nos ponteiros pode dar falha de segmentação.
Com as correções:
void exclusao(Lista* lista, int codigo)
{
    int achei = 0;
    Item* aux;
    Item* item = lista->primeiro;
    aux = item;
    while (aux && !achei)
    {
        if (aux->codigo == codigo)
        {
            if (aux == lista->primeiro)
            {
                if (aux == lista->ultimo)
                    lista->primeiro = lista->ultimo; //CASO 1
                else
                {
                    lista->primeiro = lista->primeiro->proximo; //CASO 2
                    lista->primeiro->anterior = lista->ultimo;
                }
            }
            else if (aux == lista->ultimo)
            { //CASO 3
                lista->ultimo = lista->ultimo->anterior;
                lista->ultimo->proximo = lista->primeiro;
            }
            else
            {//CASO 4
                aux->anterior->proximo = aux->proximo;
                aux->proximo->anterior = aux->anterior;
            }
            achei = 1;
            free(aux);
        }
        else aux = aux->proximo;
    }
    if (!achei)
        printf("\nCodigo inexistente!\n");
    else
        printf("\nExclusao realizada!\n");
   lista->tamanho--;
}


text:
Q: Help with Gravity question I need some help with this question from my homework.
An Oort cloud comet moves on an orbit so eccentric that it can be well approximated by a radial straight line through the Sun. The comet starts at a large distance from the Sun, with zero velocity, and falls inward. (a) What is the comet's speed when it reaches a distance of 1 AU from the Sun?
So I am lost on really how to start. I can't use the force of gravity because we aren't given the mass of the comet or the distance between that and the sun. I can't use $v_f^2 = v_i^2 + 2ad$ because we don't have a constant acceleration.
Maybe this is supposed to be a problem where I use variables for the mass and distance? But even then, the distance changes as we approach the sun, which changing the force. I guess I'd need to integrate something? I really have no clue how to start, and any help would be appreciated.

A: Have you learned about gravitational potential? The force of gravity follows an inverse square law, $F=\frac{GM_1M_2}{r^2}$; the potential, which is the integral $\int F dr$, goes as $-\frac{GM_1M_2}{r}$. As you go from "infinity" (where the potential is zero) to some smaller radius, some potential energy is released and converted to kinetic energy, $\frac12 m v^2$.
The mass of the comet cancels out. Take it from there...


text:
Q: jquery toggle event within toggle event creates unexpected behavior $('button').toggle({
    function(e){
        //turn on effects for all elements clicked
        $('*').toggle(
            function(e){
                //some nice effects when you click on elements
            },
            function(e){
                //nice effects turned off when you click again.
            }
        );
    },

    function(e){
        // turn off all effects. aka unbind all click event
    });
});

It doesn't quite behave the way i expected. I wanted to basically, on clicking the button, that effects are turned on when you click an element. Its turned off when you click that element again.  Click the button and all effects are disabled.
However, what i end up with is:

*

*click the button

*effects are turned on when i click an element

*effects do not turn off when i click it again.

*effects turn off when i click once more.

also

*

*click the button.

*effects turned on.

*click button again

*effects doesn't turn off.

*click button again

*effects turn off.

why does it do this ??

A: I'm not exactly sure I understand what you're trying to do, but my advice is to never use the $('*') selector. Do you really, really want your 'effects' to operate on EVERY DOM element in the page? Remember, that includes your "turn off/turn on" button.
I constructed an example which I think does what you're trying to do:

    <title>Test</title>

    <input type="button" id="btnToggle" value="Toggle effects" />

This is like, you know, a test.

This is like, you know, a test.

This is like, you know, a test.

This is like, you know, a test.

The key here was in using the "this" keyword to refer to the object being toggled, and (to reiterate what I said above) NOT using the $('*') selector.
Is this what you meant?


text:
Q: Immersion between spheres. Let $F:\mathbb{S}^{2}\to \mathbb{S}^{5}$ be given by $F(x,y,z)=(x^{2},y^{2},z^{2},\sqrt{2}xy,\sqrt{2}yz,\sqrt{2}xz)$. Prove that is an immersion. I have a minor with order three with determinant equal to $xyz$ then $Jac F(x,y,z)$ has rank $3$ except when $x=0$ or $y=0$ or $z=0$, now i have a problem for to be continue.Any tips?

A: You're right that the rank of ${\rm Jac \ } F(x,y,z)$ (viewed as a linear map from $\mathbb R^3 $ to $\mathbb R^6$) is less than $3$ when $x = 0$, $y = 0$ or $z = 0$. But this is not a problem! Your real goal is to prove that ${\rm Jac \ } F(x,y,z)$ is injective on the space of tangent vectors for any point $\vec x\in \mathbb S^2$. Any such tangent space is only two-dimensional. So you could approach this by finding two basis vectors for the tangent space, and verify that the images of these two tangent vectors under ${\rm Jac \ } F(x,y,z)$ are linearly independent.
For example, let's look at the $z = 0$ case. A typical point on $\mathbb S^2$ with $z = 0$ looks like this:
$$ \vec x = (\cos \phi, \sin \phi, 0).$$
The tangent space at this point is generated by the basis vectors,
$$ \vec v_1 =(-\sin \phi, \cos \phi, 0), \ \ \ \vec v_2 = (0, 0, 1).$$
Your task is to show that the images ${\rm Jac }F(\vec x)(\vec v_1)$ and ${\rm Jac }F(\vec x)(\vec v_2)$ are linearly independent. Hopefully this should be too difficult to verify!


text:
Q: Understanding operator() overloading I'm trying to understand overloading method, especially concerning bool operator().
Please, try to be understanding. I did try to read some articles about overloading operators but still can't get it ;/
I have the set container from STL, which automatically sorts its' 'objects' in alphabetic order, but I would like to modify it so that it will sort string according to their length.
Here's working code, which I struggle to understand
#include <iostream>
#include <set>
#include <iterator>

using namespace std;

struct MyOrder
{
   bool operator()(const string &first, const string &second)
   {
      int length1 = first.length(); //** assigning length of strings (arguments)
                                    //** to int, so that we will compare their lengths

      int length2 = second.length(); //** same story**//

      if(length1 == length2) //** if both strings are the same length, code will return
                             //** true, but what does is mean first < second ?, will it
                                  swap places of arguments or what ?
         return (first < second);

      return (length1 < length2); //** same story, if they are not the same length, than
                                  //** what ? return true, and swap arguments' places ?
    }
  }

int main(void)
{
   set<string, Myorder> names;

   names.insert("Tony Soprano");
   names.insert("Christopher Moltisanti");

   set<string>::iterator it;

   for(it = names.begin(); it != names.end(); ++it)
   {
      cout << *it << endl;
   }
 }

A: The second template parameter to set<>, if provided, is an operator that determines how you want elements ordered. The default operator is the result of using std::less<>, which will return true if the first argument is less than the second argument. When using the default comparison operator, elements e0 .. eN in the set will be ordered such that ei < ei+1 is true.
The operator overload of () enables an instance of MyOrder to be invoked as if it was a function. By providing MyOrder as the second template parameter, you are changing the order of the elements in the set to be so that if order is an instance of MyOrder, order(ei, ei+1) is true.
MyOrder has been implemented to behave as follows:

*

*If the two arguments are of equal length, return the result of first < second.
-- This means that if the strings are of equal length, return true if the first string is alphabetically less than the second, and false otherwise.

*If the two arguments are not equal in length, return true if first is shorter than the second, and false otherwise.
How set<> maintains ordering of the elements is an implementation detail, but it does so as you add new elements. Initially, when there are no elements, there is no restriction for adding the first element. As each new element is added, it is added as if it had been compared to all the existing elements using the provided operator to determine its correct relative position.
So if the set contained { "m", "zz", "aaa" }, and you want to add "ii" to it, it would be placed after "m" (since it is longer than it), but before "zz" (since it is alphabetically less than it). So the result would become { "m", "ii", "zz", "aaa" }.

A: The < operator means less than and it evaluates to true or false. For example:
3 < 4    // true
6 < 5    // false
7 < 7    // false

It doesn't "swap the arguments" or anything.
When applied to a class type such as std::string, operators such as < call the overloaded operator< function for that class. For std::string , it has that operator overloaded to do a lexicographical comparison, i.e. dictionary order. For example:
string("computer") < string("dog")     // true
string("a") < string("abc")            // true

The other thing to understand is how the std::sort (and other standard containers' sorting) uses operator<. The rules are:

*

*if a < b it means that a comes earlier in the sort order than b

*otherwise, either a comes later than b, or a and b are equal in the sort order.

If it needs to distinguish the last two cases (i.e. whether whether a comes later than b, or whether they're equal) it can check b < a. If a < b && b < a it means that they are equal.
Don't worry about which sorting algorithm is being used, or how it does its thing. Your code just needs to make sure that its operator< function returns false or true as just described. The sorting algorithm will use that information to produce the sorted result.
So, going back to the line you are looking at in your code:
if(length1 == length2)
     return (first < second);

return length1 < length2;

It means:

*

*If the lengths are not equal, then the shorter one comes first in the sort order

*If the lengths are equal, then the one that comes first in the dictionary comes first in the sort order.

So if the set was dog car cheese boat dog then the sorted order is car dog dog boat cheese.

A: Questions in comments area shows that you expect MyOrder::operator() to swap actual elements. This is not true. Your MyOrder functor used to compare values in internals of std::set, which you do not need to know. This way you can abstract of details of implementation of std::set and just provide your sorting criteria in form of MyOrder functor. So you can use the same functor for example for std::sort:
int main(void)
{
   std::vector< std::string> names;

   names.push_back("Tony Soprano");
   names.push_back("Christopher Moltisanti");

   std::sort( names.begin(), names.end(), MyOrder() );
   std::vector<std::string>::iterator it;

   for( it = names.begin(); it != names.end(); ++it)
   {
      std::cout << *it << std::endl;
   }
}

and do not need to know how std::sort is moving elements around.

A: The operator overload of operator() enables an instance of your class MyOrder to be invoked as if it was a function. A class with operator() is also called a functor. () is application operator.
You can apply this way custom sort criterion to algorithm - std::sort will use a call to MyOrder::operator()( std::string, std::string) on an instance of your class MyOrder to ask about how to treat these two strings.
Now we will sort based on length and using alphabetic order in case of equal length.
#include <iostream>
#include <set>
#include <iterator>

struct MyOrder
{
   bool operator()( const std::string &first, const std::string &second)
   {
      size_t length1 = first.length();
      size_t length2 = second.length();
      if ( length1 == length2) return first < second;
      return ( length1 < length2);
   }
};

the rest as before (with some error correction, MyOrder instead Myorder)
int main(void)
{
   std::set< std::string, MyOrder> names;

   names.insert("Tony Soprano");
   names.insert("Christopher Moltisanti");

   std::set<std::string>::iterator it;

   for( it = names.begin(); it != names.end(); ++it)
   {
      std::cout << *it << std::endl;
   }
}

http://ideone.com/1zTAn7


text:
Q: WPF listbox template horizontal with line break In my WPF document i have something like:
<ListBox x:Name="lbNames" Height="400" Width="400">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding Element[Icon].Value}" />
                <TextBlock Text="{Binding Element[Name].Value}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

But I want this list horizontal and if there is not enough space, I want the next item in a new line.
At the end it should look like a grid.
Optional: If there is not enough space vertically, I want a scrollbar.

A: You need change items panel to WrapPanel
<ListBox x:Name="lbNames" Height="400" Width="400" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    <ListBox.ItemsPanel>
         <ItemsPanelTemplate>
              <WrapPanel/>
         </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding Element[Icon].Value}" />
                <TextBlock Text="{Binding Element[Name].Value}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

A: What you are describing is a WrapPanel. This element will place your TextBlock's in a Grid format, and if they exceed the width of the WrapPanel, then the next element will be forced onto a new line.
See this tutorial.

A: To make list horizontal, use
Orientation="Horizontal"

in stackpanel. And for vertical scrollbar if it goes higher than it should, use
ScrollViewer.VerticalScrollBarVisibility="Visible".


text:
Q: Spring - replace @Service bean in test In my spring boot application I have a service bean (with @Service annotation) and I want to mock this service in particular JUnit test (not in all tests). How can I replace this service bean for just one particular test?
Service declared as:
@Service
public class LocalizationServiceImpl implements LocalizationService {
   ...
}

App configuration class:
@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages="my.package")
@EntityScan

public class Application {
...
}

Test class:
@Transactional
@SpringApplicationConfiguration(classes = LocalizationServiceTest.LocalizationServiceTestConfig.class)
public class LocalizationServiceTest extends ESContextTest {

    @Autowired
    private LocalizationService locService;

    @Configuration
    public static class LocalizationServiceTestConfig {

        @Bean
        public LocalizationService localizationServiceImpl() {
            return mock(LocalizationService.class);
        }

    }
}

And test class parent:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public abstract class ESContextTest {
...
}

But this does not work. When I run the test then original LocalizationServiceImpl is used for autowired locService property. This appeared in log file:
    Skipping bean definition for [BeanMethod:name=localizationService,declaringClass=...LocalizationServiceTest$LocalizationServiceTestConfig]: a definition for bean 'localizationService' already exists. This top-level bean definition is considered as an override.
When I use different name for @Bean method in LocalizationServiceTestConfig e.g. localizationServiceMock() (to be different from original implementation classname) then spring throws
'No qualifying bean of type is defined: expected single matching bean but found 2: localizationServiceImpl,localizationServiceMock'

So I thought it is correct to use the same name.
Only working solution is to remove @Service annotation from LocalizationServiceImpl class and create configuration for normal (not test) app run  like
@Configuration
public class BeansConfig {
    @Bean
    public LocalizationService localizationServiceImpl() {
        return new LocalizationServiceImpl();
    }
}

Then in test run the correct mock implementation is autowired.
But it should be possible to do the same via @Service annotation, shouldn't?
Thanks for advice.

A: Found a solution by myself: rename localizationServiceImpl() e.g. to localizationServiceMock() in class LocalizationServiceTestConfig and annotate the method with @Primary.
But why simply redefining bean with the same 'id' doesn't work like via xml-config?


text:
Q: How do I update an element on my page with a callback? I have a element on my page that looks like this
Stopped

and I want to update it based on things that are going on in the code.
Take this example.. I have a button and that element, and when I click that button I want to start downloading a list of names. Once it's started I want the text inside that span to say "Started" rather than "Stopped" and than once the code finished running aka the list of names has been downloaded, I want it to say "Done" rather than "Started"
And I've been reading back and forth about how to do this and it seems as if I need to implement ajax somehow and I'm not sure how to.
I guess the button would invoke a asp-action="StartDownload" and then it would look something like this..
    public ActionResult StartDownload()
    {
       StartDownload();
       return View("WhereSpanIs");
    }

private void StartDownload()
{
   //Set span text to "Started" some how

   //Finished download

   //Set span text to "Done" some how
}

A: For manipulating HTML in the browser when requested by a controller method  as in your approach, you would need something like SignalR to enable communication between the server (i.e. controller) and client (i.e. browser).
As you already found out, it's easier using Ajax to update the text in this case (using JavaScript/JQuery). Like in the following example, you could set the text when the button has been clicked, and when the request is complete:
In the view:

In the (Home) controller:
public ActionResult StartDownload()
{
    // TODO: perform the download
    return Json(new {status = "OK"});
}

JSON is used to allow the result to be interpretable in JavaScript, although it is not used in this example.
See the Shopping Cart Tutorial for further information.


text:
Q: Can't trigger events inside an expanded DIV that is housed inside it's "trigger DIV" I have a div that I want to expand on click. Using either Bootstrap Collapse or AngularUI Collapse this works fine if I place a div inside the div I want to collapse. The code looks like this:

  Nærmeste skøyte

4,2 nm

{{Skoyte.Navn}}

8,9 nm

RS 160 Horn Rescue

8,9 nm

RS 160 Horn Rescue

      Skjul

The problem is that no events inside the collapsed DIV seems to respond. Not the data-toggle or the ng-click. If I put the DIV outside the "trigger DIV" all works fine. Is it something inside the "trigger DIV" that overrides or cancels all events fired inside it? How can I fix this?

A: With bootstrap (and angular but my example with bootstrap) you don't need to put the div inside the collapse div.
The key is to set the data-target to the id of the collapse div.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

<button data-toggle="collapse" data-target="#demo">Collapsible</button>

Lorem ipsum dolor text....


text:
Q: How can I prove equality of lists by induction? I'm very new to Coq. Suppose under some hypothesis I want to prove l1 = l2, both of which are lists. I wonder what is a general strategy if I want to prove it inductively.
I don't know of any way to do induction on l1 and l2 at the same time. If I do induction first on l1, then I'll end up having to prove l1 = l2 under hypothesis t1 = l2, where t1 is tail of l1, which is obviously false.

A: Usually it depends on what kind of hypothesis you have.
However, as a general principle, if you want to synchronise two lists when doing induction on one, you have to generalise over the other.
induction l in l' |- *.

or
revert l'.
induction l.

It might also be that you have some hypothesis on both l and l' on which you can do induction instead.
For instance, the Forall2 predicate synchronises the two lists:
Inductive Forall2 (A B : Type) (R : A -> B -> Prop) : list A -> list B -> Prop :=
| Forall2_nil : Forall2 R [] []
| Forall2_cons : forall (x : A) (y : B) (l : list A) (l' : list B), R x y -> Forall2 R l l' -> Forall2 R (x :: l) (y :: l')

If you do induction on this, it will destruct both lists at the same time.


text:
Q: SignalR Dynamic HubName I'm using an Azure Function to read messages off an Event Hub and post them to a SignalR instance.  I have frontend JavaScript that is connected to the SignalR instance and is receiving messages.  What I want is to dynamically set the "HubName" attribute in my Azure Function base off a value passed in.  Is this poissble?  I have included my Azure Function calls below.  In both methods, I would like to dynamically set the HubName value, which is hard coded to 'deviceMessages'
    public static SignalRConnectionInfo GetSignalRInfo(
        [HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequest req,
        [SignalRConnectionInfo(HubName = "deviceMessages")] SignalRConnectionInfo connectionInfo)
    {
        return connectionInfo;
    }

    public static Task SendMessage(
        [EventHubTrigger("{EventHubName}", Connection = "EventHubConnectionAppSetting")]string myEventHubMessage,
        [SignalR(HubName = "deviceMessages")] IAsyncCollector<SignalRMessage> signalRMessages)
    {
        return signalRMessages.AddAsync(
            new SignalRMessage
            {
                Target = "newMessage",
                Arguments = new[] { myEventHubMessage }
            });
    }

A: You can do binding the imperative way. Use IBinder binder in the signature of your function and you can create bindings at runtime.
var signalRAttribute = new SignalRAttribute(/* your settings here */));
var outputMessages = await binder.BindAsync<IAsyncCollector<SignalRMessage>>(signalRAttribute);

There are also good samples for this here:
How do I use Binder to perform dynamic bindings in my C# Function?
and here:
https://weblogs.asp.net/sfeldman/azure-functions-to-make-audit-queue-and-auditors-happy

A: I found a separate way around this issue, by using the UserId property of the SignalRConnectionInfo object.  I pass the id of the device I want to receive messages for in the 'negotiate' call using a custom header field, which returns a token for that id.  I then set that value in the SignalRMessage object when a message is received from the Event Hub.  This way, the device page that I'm on is only receiving message that that particular device is sending.
    [FunctionName("negotiate")]
    public static SignalRConnectionInfo GetSignalRInfo(
        [HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequest req,
        [SignalRConnectionInfo(HubName = "deviceMessages", UserId = "{headers.deviceId}")] SignalRConnectionInfo connectionInfo)
    {
        return connectionInfo;
    }

    [FunctionName("messages")]
    public static Task SendMessage(
        [EventHubTrigger("{EventHubName}", Connection = "EventHubConnectionAppSetting")]string myEventHubMessage,
        [SignalR(HubName = "deviceMessages")] IAsyncCollector<SignalRMessage> signalRMessages)
    {
        var dev = JToken.Parse(Convert.ToString(myEventHubMessage));
        DeviceMessage msg = dev.ToObject<DeviceMessage>();

        return signalRMessages.AddAsync(
            new SignalRMessage
            {
                UserId = msg.deviceId,
                Target = "newMessage",
                Arguments = new[] { myEventHubMessage }
            });
    }


text:
Q: Android Studio , some options like 'open an existing android studio project' are not showing and unable to start new project normal way Some options are missing and unable to start a new project.
Don't know what happened.
This is the current view

This is normal view

A: Try deleting Android Studio default setting.
Go to users[user_name], find folder .AndroidStudio and delete it.
This will reset all setting of Android Studio.


text:
Q: How does a shift reduce parser know what rule to apply? When writing a shift reduce parser, how does a shift reduce figure out what rule to apply efficiently? For example, if I have the following rules
S –> S + S
S –> id

How would the parser quickly determine the rule to apply in the following parse stacks?
$ id        # id -> S
$ S         # shift
$ S +       # shift
$ S + id    # id -> S
$ S + S     # S + S -> S
$ S

All the examples I've seen just pull the correct rule out of nowhere, but what is the code behind choosing a rule? Pseudocode would be appreciated.
I've taken the examples from here, but pretty much any shift reduce parsing articles I find online just magically know what rule to use and don't show how to choose them.

A: The rule number is in the parsing table. In other words, it was precomputed when the parsing table was created.
An LR state is a set of LR items, where each item is a production and an index into the production, usually written with a •. When you take a transition from one state to the next one, you move the • one symbol to the right in all the qualifying items. For a shift action, an item qualifies if the symbol following the • is the token being shifted, and for a goto action, which happens at the end of a reduction, an item qualifies if the symbol following the • is the non-terminal which was just reduced.
Normally not all the items in a state qualify, unless there is just one item in the state. But it can happen that there are two or more qualifying items; that's an indication that the grammar probably wasn't LL. Anyway, it doesn't matter. The parser generator takes all the qualifying items and uses them to create a new state (or look up an already constructed state). Newly constructed states are completed by "ε-closure", which is a fancy way of saying that you add all the productions for each non-terminal which follows the • in the new state. (Recursively, which is why it's called a closure.)
When the parser reaches a state where the • is at the end of an item, it can reduce that particular item, which is precisely the production which will be reduced. Reducing an item basically means backing up the parser until you reach the beginning of the item's production, which 8s what the parser stack is used for: each stack entry is a transition, do as you pop the stack you move backwards in the parse history. Once you reach the beginning of the item, you must be in a state which has a goto action on the production's non-terminal. That must be the case because an item with the • at the beginning was added during ε-closure, which only happens when some item(s) in the state have their • before that non-terminal. Then you take the goto action, which registers the fact that an instance of that non-terminal has just been recognised, and continue from there. So there's no magic.
Each reducible item has a lookahead set, which was also computed during table construction, consisting of the possible tokens which might come next. If the actual next token --the lookahead token-- is in that set, the reduction is allowed to happen. If the lookahead token follows the • in the current state, a shift action is allowed. If a state has both a possible reduction action and a possible shift action on the same token, the table has a parsing conflict and the grammar is not LR. The same if two different items are both reducible on that state on the same lookahead. For a grammar to be LR, every state can have at most one possible action for every different lookahead token. (If it has no possible action for the current lookahead, the parse fails and a syntax error is reported.)
In my opinion, you can't really learn this algorithm by reading about, although I've tried to write it. To see how it works, you need to construct (or borrow) a parsing table and play parser, armed with a whiteboard or a big pad of paper to keep track of the parsing stack. If you can find (or build) a parsing table where the items have not been deleted, you might find it easier to follow, although it takes up a lot more space. (G2G, like many "tutorials", deleted the items, possibly making it look like magic. But there are other resources, such as the infamous Dragon Book.)
The parser itself doesn't need to look at the items; all the relevant information has been summarised in the parsing table, which I suppose is why sites like G2G don't show them. And they do create a lot of clutter. Bison can produce Graphview source for an image of the parsing automaton; you need to supply the --report=all command-line option if you want to see the ε-closure in each state.


text:
Q: QGIS not showing CSV file when trying to join layers I am using QGIS 2.8.9 Wien, and trying to add data from a CSV file to an existing vector file.  At the "add vector join" stage the join layer drop down only shows the vector shapefile, so I find I can only able to add data from the shapefile to the CSV, not the other way round.  I would expect both files to appear on the drop down list so I could select the CSV file and go from there.
What am I doing wrong?

A: In order to add data from an external database (either in csv format or dbf format) to a shape file I ussualy do it as follows. Keep in mind that both the vector layer and the external attribute table must have a field with the same type of information.
1) Open the vector layer
2) Open the csv file with layer/ add delimited text layer. In the dialog box I make sure to select that "no geometry (attribute only table) is selected. Once you hit ok, the external database must be shown in the table of contents.
3) I select the shape file right click and select properties
4)I go to the join section
5)I select the green plus sign
6)In the dialog box the join layer section must show the external database you opened prevoiuosly
7) You have to select the join and target fields
8)Once you hit Ok the join is performed, but to see the result of the join you have to open the attribute table of the shape file.
Remember that the join is temporal, so in order to make it permanent you have to select the layer in the TOC, right click, choose save as and give a new name.
Hope it helps


text:
Q: Using :hover to change text displayed entirely? I have... Found no other forum I can ask for some input on this through. I've been editing the CSS of a webpage for a friend of mine, who wants the title's text to change when hovered over. The problem is, I've been having an absolute hell of a time trying to get :hover to work for the title. I'm not sure whether or not I should try and rip it up and re-code it, considering it was a "theme" she found, (which might prove even more of a headache) or if someone might know how to get the text to change.
What she wants is to be able to hover over her title, "Veoleth Dathgir," and have it change to a different word, but no amount of putzing around with it has given me the result needed.
I should add that I have no professional experience with this. I've learned through a few years worth of hobby. So considering this a learning experience- How should I effect the change I need to add? I've been searching and searching for a good hour or two through here, google, w3schools, etc, and... not really gotten anywhere.
Entire page's worth of code here, and some of the relevant lines here:
    .title {
  font-family:'apple chancery',uppercase; /*title font*/
  font-size:30px;
  padding-top:90px;
  text-shadow:0 0 10px rgba(0,0,0,.3);
}

.subheader {
  margin-top:10px;
}

.header {
  width:550px;
  height:200px;
  -webkit-transition:ease-in-out .5s;
  -moz-transition:ease-in-out .5s;
  -o-transition:ease-in-out .5s;
  transition:ease-in-out .5s;
  text-align:center;
  letter-spacing:1px;
  color:#271717;
  border-bottom:solid #381F1F 20px;
  background-color:#423535;
  background-image:url();
  background-position:center;
  background-size:100% auto;
}

.header:hover {
  letter-spacing:3px;
  text-shadow:0 0 30px rgba(255,255,255,.6);
}

and

Veoleth Dathgir

Spurned Ghosts

A: Yeah, you should use jQuery for that. Add this to the bottom of your body element in your HTML, just before the end to add jQuery to your site (if you don't already utilize it)...

Then I would add an ID to the title, something like this...

Veoleth Dathgir

Then your jQuery would look like this, you can add it right to your HTML, at the bottom of your body tag like so...

Working example: https://codepen.io/wade-labs/pen/QqNaMO, feel free to "export", the option is located in the lower right corner.


text:
Q: Binding an Image (as an encoded string) in UWP C# / Universal Windows Platform
I have an object that contains a property that contains an image as a base64 encoded string.  How would I bind this string to an image on the front end?  Currently I can convert the base64 string to an BitmapImage asynchronously, but cannot bind the resulting image to the front end because properties cannot contain asynchronous functions.  How would I go about doing this as all the solutions I have found thus far are not applicable to UWP.
Thank you for the help.

A: The first is convert the base64 to bit array.
You can use Convert.FromBase64String convert base64 to byte[]
var bytes = Convert.FromBase64String(base64);

But byte[] cant be stream that you should convert byte[] to buffer
 var buf=bytes.AsBuffer();

And you can change it to stream.
 var stream=buf.AsStream();

And you can use the stream for new BitmapDecoder
var image = stream.AsRandomAccessStream();

var decoder = await BitmapDecoder.CreateAsync(image);
image.Seek(0);

And you can use the WriteableBitmap that convert it  to ImageSource.
var output = new WriteableBitmap((int)decoder.PixelHeight, (int)decoder.PixelWidth);
await output.SetSourceAsync(image);
return output;

Then you can set the Image source to what you want to show.
See convert bitmap WriteableBitmap ,convert base64ToImage
If you want bind the imagesource to Image.Source that you should add a class that have a property.
    public ImageSource Source
    {
        get { return _source; }
        set { _source = value; OnPropertyChanged();}
    }

The OnPropertyChanged is INotifyPropertyChanged that you can use it in github
And you can use the convert base64 to image source and set the Source.
You can bind it to page and see the image show the base64.

A: Here's a code snippet for you to refer to. You can download the full solution here: code.msdn.
Write two properties in the viewmodel. When we set string value to encodedImage property, we call an async method to convert it to writeablebitmap type value and set the converted result to the other property selectedImage. Selected Image is the binding source of xaml Image control.
public class MainViewModel : INotifyPropertyChanged
{

    private string encodedImage;

    public string EncodedImage
    {
        get
        {
            return encodedImage;
        }
        set
        {
            encodedImage = value;
            // Convert source to writeblebitmap and set value to SelectedImage
            ConvertToImage(value);
            NotifyPropertyChanged("EncodedStream");
        }
    }

    private WriteableBitmap selectedImage;

    public WriteableBitmap SelectedImage
    {
        get { return selectedImage; }
        private set { selectedImage = value; NotifyPropertyChanged("SelectedImage"); }
    }

    /// <summary>
    /// Convert encoded string to writeblebitmap
    /// set result value to SelectedImage
    /// </summary>
    /// <param name="base64String"></param>
    public async void ConvertToImage(string base64String)
    {
        byte[] bytes = Convert.FromBase64String(base64String);

        InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
        await stream.WriteAsync(bytes.AsBuffer());
        stream.Seek(0);

        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
        WriteableBitmap writebleBitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
        await writebleBitmap.SetSourceAsync(stream);
        // When SelectedImage value is changed, it will notify the front end
        SelectedImage = writebleBitmap;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string propName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    }
}


text:
Q: PIL drawing an image then displaying it in wxpython I have an image drawn using PIL in python.
import Image
import ImageDraw
createCM():
   img = Image.new("RGB", (400,400), "white")
   draw = ImageDraw.Draw(img)

   coords = [(100,70), (220, 310), (200,200)]
   dotSize = 2

   for (x,y) in coords:
       draw.rectangle([x,y,x+dotSize-1,y+dotSize-1], fill="black")

Want i want to do now is show this on my wxpython panel.
I started off like this
CMchart = createCM(self)
self.vbox = wxBoxSizer(wx.VERTICAL)
self.vbox.Add(CMchart, 1, wx.LEFT | wx.TOP | wx.GROW)
self.vbox.AddSpacer(25)
self.SetSizer(self.vbox)
self.vbox.Fit(self)

This does't show anything. Just want to know where I am going wrong
Thank you

A: without knowing what createcM does it is really difficult to know how to help you. But the short of it is that to draw an Image you load the data from a wx.Image turn it into a wx.Bitmap and then draw it using a DeviceContext. Typically first draw it a wx.MemoryDC first the when you have finished all your drawing updates you then use a wx.PaintDC or a wx.ClientDC to draw it. Take a look it
http://wiki.wxpython.org/WorkingWithImages#PIL_.28Python_Imaging_Library.29
which gives you a good example of how to load images from PIL


text:
Q: How to edit /etc/resolv.conf on Ubuntu 12.04 I have two network interfaces configured via DHCP. As a result, /etc/resolv.conf is populated with information coming from the DHCP server.
How can I edit this file?
I know that if I add prepend domain-name-servers 127.0.0.1 to /etc/dhcp/dhclient.conf I can obtain nameserver 127.0.0.1 as the first (and only) line of /etc/resolv.conf.
What if I want 127.0.0.1 and only one of the two nameserver addresses provided via DHCP?

A: In Ubuntu 12.04 and later, /etc/resolv.conf is dynamically generated by the resolvconf utility. (Actually, resolvconf generates /run/resolvconf/resolv.conf and /etc/resolv.conf is a symbolic link to that. That's the default configuration; it is also possible to run with a static file at /etc/resolv.conf but that is non-standard.) Nameserver information (nameserver addresses and search domain names) gets registered with resolvconf by interface configurers (ifup, NetworkManager, dhclient, etc.). On the basis of what has been registered, resolvconf generates an up-to-date resolv.conf file.
Therefore, you can't edit the resolv.conf file directly. If you want to control what ends up in resolv.conf you will have to configure the resolvconf utility. Please see the resolvconf documentation for more information.
The answer to the specific question "What if I want 127.0.0.1 and only one of the two nameserver addresses provided via DHCP?" is:

*

*First, do not add prepend domain-name-servers 127.0.0.1 to /etc/dhcp/dhclient.conf.  The correct protocol is for local nameservers to register their local listen address(es) with resolvconf when they are ready to provide local name service; when they do this there is no need for DHCP clients to do so too. Dnsmasq does the right thing by default. In the case of BIND 9, you have to set RESOLVCONF=yes in /etc/default/bind9 to cause it to register the address 127.0.0.1 with resolvconf.

*Second, resolvconf by default truncates the list of nameservers after any loopback address such as 127.0.0.1. To disable this behavior, create a file /etc/default/resolvconf containing the line TRUNCATE_NAMESERVER_LIST_AFTER_LOOPBACK_ADDRESS=no.

*Third, resolvconf by default truncates the list of nameservers after three items. There is no point in including more addresses because the glibc resolver ignores any addresses after the first three. To cause resolvconf to truncate the list after two addresses you have to edit the script /etc/resolvconf/update.d/libc to replace this line
[ "$N" = 3 ] && return 0

by the following one.
    [ "$N" = 2 ] && return 0

A: It worked for my grandfather, it worked for my father and it works for me.
rm /etc/resolv.conf
vi /etc/resolv.conf

search yourdomain.com
nameserver 8.8.8.8
nameserver 8.8.4.4

EDIT:
rm removes the standard symbolic link.
vi creates an actual file in its place.

A: When I installed 12.04 this text helped me a lot: http://www.stgraber.org/2012/02/24/dns-in-ubuntu-12-04/

A: For the record, the official resolvconf documentation is here http://anonscm.debian.org/gitweb/?p=resolvconf/resolvconf.git;a=blob;f=README;hb=HEAD
"Editing" is as simple as using the resolvconf command line like an api.
e.g.
echo nameserver 8.8.8.8 | resolvconf -a eth0.goog

Here the . is a separator and the part after the interface is the name of the config for that interface.
And if you want to remove this name server just name the interface and configuration and use -d to delete
resolvconf -d eth0.goog

In a server/cloud scenario, this is all you need. For mobile, you will want to refer to the documentation.


text:
Q: How to prevent flattening of interactive fields in Pdf file using iText7 I have PDF file with interactive fields. I can change these fields manually without any problems.
I need change interactive fields in Pdf file using library iText7. I able change interactive fields using iText7, but when I open file after operation, I will able see that interactive fields were flatten, so I can't change fields values anymore in manual mode.
I created concise example, in that I only open and close pdf file. I have same result: after program work, all fields in PDF file were flattened.
Here this example.
string pdfReadPath = @"D:\IT\PROJECTS\PMIC\TASKS\PDF\TEMP\Read_Pdf.pdf";
string pdfWritePath = @"D:\IT\PROJECTS\PMIC\TASKS\PDF\TEMP\Write_Pdf.pdf";

//Initialize pdf document
PdfReader pdfReader = new PdfReader(pdfReadPath);
PdfWriter pdfWriter = new PdfWriter(pdfWritePath);

PdfDocument pdfDoc = new PdfDocument(pdfReader, pdfWriter);

pdfDoc.Close();

I don't want the interactive fields to flatten.
Does anybody know what way I can use if I want the interactive fields will not flatten after program work?

A: The fields in your output aren't flattened. You can check this by opening the PDF in any PDF viewer supporting interactive forms except Adobe Acrobat Reader, for example Foxit Reader.
Instead the problem is that your PDF contains a hybrid XFA/AcroForm form definition and a usage rights signature and that you in your code ignore this. Thus, your code invalidates said signature making Adobe Reader show you the form in a read-only mode.
By manipulating your PDF in append mode, you can fix this.
The problem in detail
Your PDF contains a hybrid XFA/AcroForm form definition and a usage rights signature.
The former means that the interactive form in your PDF is defined twice, once in the native PDF way (AcroForm) and once as a special XML riding piggyback in your PDF (XFA). XFA forms have been deprecated/obsoleted since 2017.
Only a few PDF processors support XFA forms. Adobe Acrobat and Adobe Acrobat Reader do. But Adobe Acrobat Reader only supports this if the PDF with the form has been generated by an Adobe product and only form fill-ins have been done since.
To check whether a PDF with a XFA form has been generated by an Adobe product, Adobe Acrobat Reader looks for a usage rights signature therein, a special kind of signature to mark PDFs generated by Adobe PDF generators to signal to the Adobe Reader that it shall extend its functionality.
But it does not only look for that signature but also validates it. As your code writes the PDF completely anew, though, the signature in your output PDF is broken. Adobe Acrobat Reader in such a case does not allow editing the form anymore but merely displays a read-only representation thereof which you incorrectly interpreted as flattened form.
Writing in append mode
To not invalidate the signature with iText 7, you have to keep the original PDF bytes as they are and only apply changes by appending them as incremental updates.
You do so by instantiating the PdfDocument with StampingProperties that have the AppendMode selected, so instead of
PdfDocument pdfDoc = new PdfDocument(pdfReader, pdfWriter);

use
PdfDocument pdfDoc = new PdfDocument(pdfReader, pdfWriter, new StampingProperties().UseAppendMode());

Beware, though: Validation does not only check whether the usage rights signature is valid, it also checks whether later incremental updates only contain allowed changes. Thus, make sure that you only change the form contents in your code.
An alternative fix
As you have a PDF with a hybrid form definition, not a pure XFA form definition, you can alternatively remove both the XFA form definition and the usage rights signature. Thereafter you can freely manipulate the PDF. This was proposed in this answer to a similar question with the difference that the PDF additionally was encrypted.


text:
Q: How do I get my SUV through that ring? If anyone has played "Crackdown", then you're aware of those purple, ring shaped "stunt markers" floating in various locations around the city.  If anyone is still familiar with the game, can you give me an idea of how to get to the one directly outside of, and above the tunnel leading from the Agency to the Corridor (Shai-Gen controlled zone)?
I've tried everything I can think of, with no luck.

A: You need a 4 star SUV, and you need to bunny hop after an S curve at the end of the tunnel.
Source (including video)


text:
Q: What's the difference between LSTM and Seq2Seq (M to 1) I want to ask the LSTM can be modeled as many-to-one.
However, Seq2Seq can also be modeled as many-to-one. (M to N, when N is one).
So, what is the difference?

A:
Long short-term memory (LSTM) is an artificial recurrent neural network (RNN) architecture used in the field of deep learning. Unlike standard feedforward neural networks, LSTM has feedback connections. It can not only process single data points (such as images), but also entire sequences of data (such as speech or video). For example, LSTM is applicable to tasks such as unsegmented, connected handwriting recognition, speech recognition and anomaly detection in network traffic or IDSs (intrusion detection systems).
(https://en.wikipedia.org/wiki/Long_short-term_memory)

Seq2seq is a family of machine learning approaches used for language processing. Applications include language translation, image captioning, conversational models and text summarization.
...
Seq2seq turns one sequence into another sequence. It does so by use of
a recurrent neural network (RNN) or more often LSTM or GRU to avoid
the problem of vanishing gradient.
(https://en.wikipedia.org/wiki/Seq2seq)

From my understanding, I guess Seq2Seq is a model which is optimized for NLP and uses an LSTM or GRU under the hood.