text:
Q: Install applications or software on Azure VM with ARM Template We're trying to install Kaspersky Network Agent on an Azure VM using ARM Template.
Also, we need to get the .exe or .msi file from VM storage using SAS token. I was searching for the Template examples to operate but couldn't come up with one that accomplishes the task. Do you know, if it's possible to do in this way?
If so,
Can you share a template that does a similar task?
Also, please explain how to modify the template for this case.
Thanks in advance

A: •   Yes, you can successfully install an application using the custom script extension in an ARM template in an Azure VM as follows. Kindly check the ARM template file as deployed by me for this purpose. Also, I have used the SAS token to download the application package in the Azure VM during deployment itself and have also used a powershell script to invoke the silent install of the concerned application.
ARM Template: -
I am using the default quickstart template for deploying an Azure VM through ARM template as given in this link : - https://learn.microsoft.com/en-us/azure/virtual-machines/windows/quick-create-template?toc=/azure/azure-resource-manager/templates/toc.json
In this template, I have added the below custom script extension installation content in 'resources' section in the above ARM template. Please check the formatting of the ARM template code correctly, i.e., commas, curly brackets, square brackets, etc. Also, ensure to open HTTPS port 443 inbound also as below: -
"securityRules": [
      {
        "name": "default-allow-3389",
        "properties": {
          "priority": 1000,
          "access": "Allow",
          "direction": "Inbound",
          "destinationPortRange": "3389",
          "protocol": "Tcp",
          "sourcePortRange": "*",
          "sourceAddressPrefix": "*",
          "destinationAddressPrefix": "*"
        }
      },
      {
        "name": "AllowHTTPSInBound",
        "properties": {
          "priority": 1010,
          "access": "Allow",
          "direction": "Inbound",
          "destinationPortRange": "443",
          "protocol": "Tcp",
          "sourcePortRange": "*",
          "sourceAddressPrefix": "*",
          "destinationAddressPrefix": "*"
        }
      }
  ]

Custom Script VM extension: -
 {
          "type": "Microsoft.Compute/virtualMachines/extensions",
          "apiVersion": "2021-04-01",
          "name": "[concat(parameters('vmName'),'/', 'InstallWebServer')]",
          "location": "[parameters('location')]",
          "dependsOn": [
            "[concat('Microsoft.Compute/virtualMachines/',parameters('vmName'))]"
          ],
        "properties": {
        "publisher": "Microsoft.Compute",
        "type": "CustomScriptExtension",
        "typeHandlerVersion": "1.7",
        "autoUpgradeMinorVersion": true,
        "protectedSettings": {
          "storageAccountName": "techtrix",
          "storageAccountKey": "EN6iUzOfVe8Ht0xvyxnqK/iXEGTEunznASsumuz0FR4SCvc2mFFHUJfbMy1/GSK7gXk0MB38MMo7+AStoKxC/w==",
          "fileUris": [
            "https://techtrix.blob.core.windows.net/executable/Testdemo2.ps1"
          ],
          "commandToExecute": "powershell.exe -ExecutionPolicy Unrestricted -File Testdemo2.ps1"
        }
      }
    }

Also, please note that you need to provision a storage account container already for storing the powershell script and the application package in it so that you can use that storage account's key, its name and the powershell script's blob URI in place of the same as requested above. Also, please change the name of the powershell script to be executed through the extension in 'commandToExecute' section.
Once the above has been done, please ensure the successful execution of silent installation commands for the application package to be installed locally so that they can be accordingly modified in the powershell script. I have used installed '7-zip' application here for demonstration purposes. Please find my powershell script as below. Ensure that this script and the application package is uploaded beforehand, and the access level of the container is set to 'Anonymous and public access': -
 Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
 Install-Module -Name Az.Storage -AllowClobber -Force
 Import-Module -Name Az.Storage -Force
 $StorageAccountName = "techtrix"
 $ContainerName = "executable"
 $Blob1Name = "7z2107-x64.exe"
 $TargetFolderPath = "C:\"
 $context = New-AzStorageContext -StorageAccountName $StorageAccountName -SASToken "sp=r&st=2022-02-10T08:40:34Z&se=2022-02-10T16:40:34Z&spr=https&sv=2020-08-04&sr=b&sig=DRDulljKTJiRbVPAXAJkTHi8QlnlbjPpVR3aueEf9xU%3D"
 Get-AzStorageBlobContent -Blob $Blob1Name -Container $ContainerName -Context $context -Destination $TargetFolderPath
 $arg="/S"
 Start-Process -FilePath "C:\7z2107-x64.exe" -ArgumentList $arg '

Then edit the parameters file with the desired values in 'adminUsername', 'adminPassword' and 'location' and save it in the same location where template file is stored. Now, execute the commands below from powershell console with elevated privileges locally, i.e., through the path where these ARM template files are stored by browsing to that path in powershell itself.
 az login
 az deployment group create -n <name of the deployment> -g <name of the resource group> --template-file "azuredeployVM.json" --parameters "azuredeployVM.parameters.json" '

After successful deployment, you will be able to see the application installed during the VM creation itself as below: -

In this way, you can install an '.exe' or '.msi' through the ARM template with custom script extension.

A: Installing .exe files requires elevated permissions to run as administrator.
Custom script is not working when it tries to run .exe file.


text:
Q: Problem with Denesting Radical Relations I was messing around with nested radicals, and I came up with $\sqrt[3]{6\sqrt[3]{2}-6}=\frac {2+\sqrt[3]{2}-\sqrt[3]{4}}{\sqrt[3]{3}}$.
The $\sqrt[3]{2}$ and $\sqrt[3]{4}$ seemed familiar to another nested radical exmaple: $\sqrt[3]{\sqrt[3]{2}-1}=\frac {1-\sqrt[3]{2}+\sqrt[3]{4}}{\sqrt[3]{9}}$.
So I decided to give it a try. I divided both sides of $\sqrt[3]{6\sqrt[3]{2}-6}$ by $\sqrt[3]{6}$ and got that $\sqrt[3]{\sqrt[3]{2}-1}=\frac {2+\sqrt[3]{2}-\sqrt[3]{4}}{\sqrt[3]{9}}$
But this isn't what Ramanujan had... Something went wrong. Any ideas?

A: Looks like you divided the right side by $\sqrt[3]3$.  The remaining $\sqrt[3]2$ should come from the numerator.
$$2+\sqrt[3]2-\sqrt[3]4=\sqrt[3]2(\sqrt[3]4+1-\sqrt[3]2)$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I prevent accessing my webpage outside my WIFI? I'm creating a web page that, briefly, connects business-clients. I want this to happen only when the client is inside the business facility. What I thought is to check if the client is connected to the business WIFI by the SSID, but then I realized that if you create your own WIFI network with the same SSID you can bypass this web's check.
Then I tryied to do it with the MAC Address, but unfortunately I couldn't manage it due to security reasons. Can anybody help me finding a work around or hack?
Thank you all!

A: Either host the website on a server inside your local network or, if you have to host on the public Internet, restrict access to the public facing IP addresses of your network (with a firewall by preference, but web server configuration is also an option).
Note you'll have to take additional steps if you want to deny access to people with VPN access to the network.

A: I figured out what I need. I can create a business's side local server which connects to my own webpage. So when someone scans the QR code, it connects to the local server (there I'll fix the main problem) and then the local server sends an API request to my own webpage and so on.


text:
Q: Pass value from gsp to controller I was using an export plugin for my grails app. How can I pass a list instance to the controller? I have this in my gsp:
    <g:set var="fruitInstanceList" name="fruitInstanceList" value="${fruitInstanceList}"/>
    <export:formats formats="['csv', 'excel', 'ods', 'pdf', 'rtf', 'xml']"/>

and in my controller:
    if(params?.format && params.format != "html"){
    response.contentType = grailsApplication.config.grails.mime.types[params.format]
    response.setHeader("Content-disposition", "attachment; filename=books.${params.extension}")
        exportService.export(params.format, response.outputStream,params.fruitInstanceList, [:], [:])
    }

The code doesnt work because the fruitInstanceList is not being pass to the controller. How can I do this? To pass the value from the gsp to controller using the above code?
Please help, thanks.

A: You don't have to pass your reporting data all the way back to the controller. You got this data (here 'fruitInstanceList') from the controller, maybe based on some filter options.
All you need to do is POST filter options again to the controller which will then fetch the same data (i.e. 'fruitInstanceList') and then export it to your desired format. The skelton code would look something like following:
reportFilter.gsp
<form name="fruitsFilterForm" action="fruitsReport" controller="report">
    <input type="text" name="search" value="${params.search}" />
    <input type="submit" value="Show Report" />
</form>

fruitsReport.gsp
<form name="reportExportForm" action="exportFruitsReport" controller="report">
    <input type="text" name="search" value="${params.search}" />
    <input type="hidden" name="format" value="${defaultFormat}" />
    <input type="submit" value="Export" />
</form>

ReportController.groovy
def reportService
def fruitsReport() {
    def fruitInstanceList = reportService.fetchFruitsList(params);
    [fruitInstanceList: fruitInstanceList, params: params, defaultFormat: "excel"]
}

def exportFruitsReport() {
    def fruitInstanceList = reportService.fetchFruitsList(params);

    /** All your code to export the fetched fruitInstanceList **/
}

ReportService.groovy
def fetchFruitsList(params) {
    return Fruit.findAll(/* your query based on the params */)
}

NOTE
If you still insist to pass the data from gsp to controller instead then you can still do it by POSTing your list with an ajax call. (but that would be a dirty approach)

A: This variable is only available to the page. you may to pass it using params
 <export:formats formats ="[]", params ="[fruitInstanceList:${fruitInstance}]"/>

A: You cannot pass list as parameter from views. Since, the params will go to controller as get, the parameter will concatenate to the URL and it will convert as string.
So what you want to do is, you need to do the logic in that action where you use export code.
i.e., How you are getting the list in controller and sending it to views? like the same way, here you have to do some business logic and get the list and then send it to export plugin.


text:
Q: Prevent non-ASCII characters from being captured in a UITextView I have a legacy database column which only supports the ASCII character set. I need a method which prevents non-ASCII characters from being typed or pasted into a UITextView. I need to filter out emojis and all other unicode characters.

A: There are two parts to this. Firstly, prevent non-ASCII characters from being typed in the first place by setting the keyboard type appropriately:
textView.keyboardType = UIKeyboardTypeASCIICapable;

Secondly, prevent non-ASCII characters being pasted in from another app by implementing this delegate method:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    // trim any non-ASCII characters
    NSString* s = [[text componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithRange:NSMakeRange(0, 128)].invertedSet] componentsJoinedByString:@""];

    // manually replace the range in the textView
    textView.text = [textView.text stringByReplacingCharactersInRange:range withString:s];

    // prevent auto-replacement
    return NO;
}

A: Swift 4 clean code solution
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return string.canBeConverted(to: .ascii)
}

A: This is what I am using for UITextField, just alternative solution, this works on default as well as custom keyboards and disables copy pasting of emojis. No need to set keyboard type to ascii as it only disables emojis of default iOS keyboard.
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
    //This is universal solution works on default as well as custom keyboards like SwiftKeyplus it will diallow pasting emoji
    if !string.canBeConvertedToEncoding(NSASCIIStringEncoding)
    {
        return false
    }

    return true
}


text:
Q: haskell Own version of Elem function using Foldl I'm trying to create my own version of elem function, which returns True or False based on if the element x is inside the given array.
elem' :: Eq(t)=>t->[t]->Bool
elem' x xs = or [foldl (\acc -> \a -> if a == x then True else False) [] xs]

What I'm trying to do here is to fill the array using foldl with True/False values and then make or function, which returns True if at least one of them is True (so what I want to get). However, this code results in the following compilation error:
main.hs:11:71: error:
    * Couldn't match expected type `Bool' with actual type `[a0]'
    * In the second argument of `foldl', namely `[]'
      In the expression:
        foldl (\ acc -> \ a -> if a == x then True else False) [] xs
      In the first argument of `or', namely
        `[foldl (\ acc -> \ a -> ...) [] xs]'
   |
11 | elem' x xs = or [foldl (\acc -> \a -> if a == x then True else False) [] xs]
   |

                                                       ^^

A: The idea of using a foldl is not to make a list of elements, and thus not to use or.
If you make use of foldl, then in case a == x fails, you look if the elem on the previous elements was succesful, so we return acc in that case. Furthermore you can not use [] as the "start value" for the accumulator, since the foldl is supposed to return a Bool, not a list:
elem' :: (Foldable f, Eq t) => t -> f t -> Bool
elem' x xs = foldl (\acc a -> if a == x then True else acc) False xs
Here it is however not a good idea to use foldl, since that means we will enumerate over the entire list. If we make use of foldr, we can stop from the moment we have found an element, so we can rewrite this to:
elem' :: (Foldable f, Eq t) => t -> f t -> Bool
elem' x = foldr (\e -> if x == e then const True else id) False
If we thus check:
elem' 1 ([1,4,2,5] ++ repeat 3)

It will return True for the foldr approach, whereas it will loop for the foldl approach.


text:
Q: Display text with a string in Textblock xaml I have a textblock, and I want to display a text with a defined string. How to do it?
The textblock:
 <TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Padding="6" VerticalAlignment="Center" Margin="45,0,0,0" Height="30" Width="386" Text="My Program ver. Version"/>

My string:
Public Version As String = "1.0a"

A: You can use StringFormat.
<TextBlock Text="{Binding Path=Version, StringFormat=My Program ver. {0}}" />

In your code- behind you must change Version to property (this property should be ReadOnly because it isn't change in runtime) and assign DataContext in constructor:
Class MainWindow

    Public Sub New()
        InitializeComponent()
        Me.DataContext = Me
    End Sub

    ReadOnly Property Version As String
        Get
            Return "1.0a"
        End Get
    End Property
End Class

A: If you want your TextBlock to update the version number every time you have a new version,
you can do it like this in C#. You can probably find out easily how to write this in VB.
This will update your TextBlock everytime you publish a new version of your program.
In XAML you bind a TextBlock text to "Version":
<TextBlock Text="{Binding Version, Mode=OneWay}" />`

And then in code-behind or in your view-model you can use a property for that Binding that you have in the XAML TextBlock:
    public string Version
    {
        get
        {
          return String.Format("VERSION: {0}",DeploymentInfo.Version.ToString());
        }
    }

Then you need to add a reference to "System.Deployment" in your project.
This will only work when you have done a "PUBLISH" of your project. When you start the debugger you will probably only see version number: 0.0.0.0

A: In XAML file:
First you should name your TextBlock i have gave tbWithNoName for example.
<TextBlock x:Name="tbWithNoName" HorizontalAlignment="Left" TextWrapping="Wrap" Padding="6" VerticalAlignment="Center" Margin="45,0,0,0" Height="30" Width="386" Text="My Program ver. Version"/>

Then add Loaded call on Window object.
<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
        Loaded="Window_Loaded">

Insert Window_Loaded function to your vb file.
Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)
    tbWithNoName.Text = tbWithNoName.Text + " " + Version
End Sub

This will change TextBlock's Text when Window loaded


text:
Q: How can I use spatialization in Web Audio API? Web Audio's PannerNode is supposed to allow placement of the sound source with the positionX, positionY and positionZ parameters, but I can't seem to get things to work consistently.
I've tested things using two different hardware setups: a four-speaker quadraphonic system (created with an aggregate device in Audio/MIDI Setup) and with AirPods Pro, which can mimic 11.1 surround. I've confirmed working surround sound using Dolby Atmos-enabled test videos and surround mixes created in Adobe Audition, so the speakers shouldn't be the problem. I'm using Safari 15.4 on macOS 11.6.4.
In the code below, which I've setup as a JSFiddle here, the sound starts centered but moving even slightly to the left or right moves it all the way to that side. In the quadraphonic setup, everything seems to come from the rear speakers no matter what the settings are. Moving along the Y axis seems to have no affect (expected with the quadraphonic setup, but it should come through on the AirPods).
I'm sure I'm missing something obvious, but I can't seem to figure it out. Can anyone tell me what I'm doing wrong?

var AudioContext = window.AudioContext || window.webkitAudioContext;
var ctx = new AudioContext();
// create a gain node to gate the sound on and off
var g = ctx.createGain();
g.connect(ctx.destination);
g.gain.setValueAtTime(0, ctx.currentTime);
// create a panner to handle sound location
var p = ctx.createPanner();
p.connect(g);
p.positionX.setValueAtTime(0, ctx.currentTime)
// create oscillator to generate the sound
var o = ctx.createOscillator();
o.type = 'sine';
o.frequency.setValueAtTime(440, ctx.currentTime);
o.connect(p);

function startOsc() {
  // start oscillator; we "play" the sound by turning volume up and down
  o.start(0);
}

function moveSound(x,y,z) {
  // move the sound by x, y, and z units
  // first, update displayed values (rounding is to avoid floating-point math)
  document.querySelector('#xVal').innerHTML = Math.round((p.positionX.value + x)*10)/10;
  document.querySelector('#yVal').innerHTML = Math.round((p.positionY.value + y)*10)/10;
  document.querySelector('#zVal').innerHTML = Math.round((p.positionZ.value + z)*10)/10;
  // now position the sound
    p.positionX.value = Math.round((p.positionX.value + x)*10)/10;
    p.positionY.value = Math.round((p.positionY.value + y)*10)/10;
    p.positionZ.value = Math.round((p.positionZ.value + z)*10)/10;
  // now turn volume up and then down 1/2 second later to make a tone
  g.gain.setTargetAtTime(1, ctx.currentTime, 0.02);
  g.gain.setTargetAtTime(0, ctx.currentTime+0.5, 0.02);
}
<button onclick="startOsc();">start</button>

<button onclick="moveSound(0,0,0);">play in current location</button>

<button onclick="moveSound(-0.1,0,0);">move left</button>

0

<button onclick="moveSound(0.1,0,0);">move right</button>

<button onclick="moveSound(0,-0.1,0);">move down</button>

0

<button onclick="moveSound(0,0.1,0);">move up</button>

<button onclick="moveSound(0,0,-0.1);">move backward</button>

0

<button onclick="moveSound(0,0,0.1);">move forward</button>

EDIT (3/28/22): After messing with this for a few days, it looks as though spatialization in Web Audio API doesn't actually do anything in a physical surround sound system; it just changes stereo panning and volume to account for the virtual geometry (in my example code above, I did notice that the volume starts to dip when any of the parameters gets as far out as 3 or 4 units). Seems like this could still be introduced at a browser or OS level (after all, Safari can play Dolby Atmos audio in an <audio> or <video> tag) but it doesn't look like it's there yet.
EDIT 2 (2/7/23): I eventually got this solved with my own class, which is available here if anyone is interested.


text:
Q: How can I make my setTimout functions run at the same speed? Preface: I have a demo of the problem on my personal site (I hope this is ok. If not, I can try to set it up on jsfiddle). I'm intending this question to be a little fun, while also trying to understand the time functions take in javascript.
I'm incrementing the value of progress bars on a timeout. Ideally (if functions run instantaneously) they should fill at the same speed, but in the real world, they do not. The code is this:
function setProgress(bar, myPer) {
bar.progressbar({ value: myPer })
    .children('.ui-progressbar-value')
        .html(myPer.toPrecision(3) + '%')
            .attr('align', 'center');
    myPer++;
    if(myPer == 100) { myPer = 0; }
 }

 function moveProgress(bar, myPer, inc, delay){
    setProgress(bar, myPer);
    if(myPer >= 100) { myPer = 0; }
    setTimeout(function() { moveProgress(bar, myPer+inc, inc, delay); }, delay);
 }

 $(function() {
   moveProgress($(".progressBar#bar1"), 0, 1, 500);
   moveProgress($(".progressBar#bar2"), 0, 1, 500);
   moveProgress($(".progressBar#bar3"), 0, .1, 50);
   moveProgress($(".progressBar#bar4"), 0, .01, 5);
 });

Naively, one would think should all run (fill the progress bar) at the same speed.
However, in the first two bars, (if we call "setting the progress bar" a single operation) I'm performing one operation every 500 ms for a total of 500 operations to fill the bar; in the third, I'm performing one operation every 50ms for a total of 5,000 operations to fill the bar; in the fourth, I'm performing one operation every 5ms for a total of 50,000 operations to fill the bar.
What part of my code is takes the longest, causes these speed differences, and could be altered in order to make them appear to function in the way that they do (the fourth bar gets smaller increments), but also run at the same speed?

A: The biggest problem with using setTimeout for things like this is that your code execution happens between timeouts and is not accounted for in the value sent to setTimeout.  If your delay is 5 ms and your code takes 5 ms to execute, you're essentially doubling your time.
Another factor is that once your timeout fires, if another piece of code is already executing, it will have to wait for that to finish, delaying execution.
This is very similar to problems people have when trying to use setTimeout for a clock or stopwatch.  The solution is to compare the current time with the time that the program started and calculate the time based on that.  You could do something similar.  Check how long it has been since you started and set the % based on that.

A: What causes the speed difference two things: first is the fact that you executing more code to fill the bottom bar (as you allude to in the 2nd to last paragraph). Also, every time you set a timeout, your browser queues it up... the actual delay may be longer than what you specify, depending on how much is in the queue (see MDN on window.setTimeout).

A: Love the question, i don't have a very precise answer but here are my 2 cents:
Javascript is a very fast language that deals very well with it's event loop and therefore eats setTimeouts and setIntervals for breakfast.
There are limits though, and they depend on a large number of factors, such as browser and computer speed, quantity of functions you have on the event loop, complexity of the code to execute and timeout values...
In this case, i think it's obvious that if you try to execute one function every 500ms, it is going to behave a lot better than executing it every 50ms, therefore a lot better than every 5ms. If you take into account that you are running them all on top of each other, you can predict that the performance will not be optimal.
You can try this exercise:
take the 500ms one, and run it alone. mark the total time it took to fill the bar (right here you will see that it's going to take a little longer than predicted).
try executing two 500ms timeouts at the same time, and see that the total time just got a bit longer.
If you add the 50ms to it, and then the 5ms one, you will see that you will lose performance everytime...


text:
Q: \center environment centers the whole document in LaTeX I have the following line between my \maketitle and my \begin{abstract}:
\center{ \textsc{Some text here} }

This seems to cause the ENTIRE DOCUMENT to be formatted as centered. Why is this and how should I get around it?

A: Try
\begin{center}
    \textsc{Some text here} }
 \end{center}

instead. center is an environment, meaning it needs to be used with \begin  and \end.
Furthermore there is the \centering command which turns on centered alignment for the rest of the block. I assume \center is a similar command from plain TeX.


text:
Q: No response to voice commands by Virtual Assistant I started making a virtual assistant program taking help from this YouTube video(https://www.youtube.com/watch?v=AGatX_8gaeM).
I made the basic speech recognition code but it isn't responding to voice inputs to both internal microphone and external microphone.
When I run the program
import speech_recognition as sr
from gtts import gTTS

def recordAudio():
   record=sr.Recognizer()

   with sr.Microphone() as source:
      print('Say something!')
      audio=record.listen(source)

   data=''

   try:
      data=record.recognize_google(audio)
      print('You said: {}'.format(data))

   except sr.UnknownValueError:
      print('Ran into some unknown error retry....')
      recordAudio()

   except sr.RequestError:
      print('Ran into request error retry....')
      recordAudio()

   except:
      print('Ran into something other than UnknownValueError or RequestError')

recordAudio()

but this happens:
ALSA lib pcm_dsnoop.c:641:(snd_pcm_dsnoop_open) unable to open slave
ALSA lib pcm_dmix.c:1089:(snd_pcm_dmix_open) unable to open slave
ALSA lib pcm.c:2642:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear
ALSA lib pcm.c:2642:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe
ALSA lib pcm.c:2642:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side
ALSA lib pcm_oss.c:377:(_snd_pcm_oss_open) Unknown field port
ALSA lib pcm_oss.c:377:(_snd_pcm_oss_open) Unknown field port
ALSA lib pcm_a52.c:823:(_snd_pcm_a52_open) a52 is only for playback
ALSA lib pcm_usb_stream.c:486:(_snd_pcm_usb_stream_open) Invalid type for card
ALSA lib pcm_usb_stream.c:486:(_snd_pcm_usb_stream_open) Invalid type for card
ALSA lib pcm_dmix.c:1089:(snd_pcm_dmix_open) unable to open slave
Say something!

And the command
import speech_recognitioin as sr
sr.Microphone.list_microphone_names()

returns this:
ALSA lib pcm_dsnoop.c:641:(snd_pcm_dsnoop_open) unable to open slave
ALSA lib pcm_dmix.c:1089:(snd_pcm_dmix_open) unable to open slave
ALSA lib pcm.c:2642:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear
ALSA lib pcm.c:2642:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe
ALSA lib pcm.c:2642:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side
ALSA lib pcm_oss.c:377:(_snd_pcm_oss_open) Unknown field port
ALSA lib pcm_oss.c:377:(_snd_pcm_oss_open) Unknown field port
ALSA lib pcm_a52.c:823:(_snd_pcm_a52_open) a52 is only for playback
ALSA lib pcm_usb_stream.c:486:(_snd_pcm_usb_stream_open) Invalid type for card
ALSA lib pcm_usb_stream.c:486:(_snd_pcm_usb_stream_open) Invalid type for card

ALSA lib pcm_dmix.c:1089:(snd_pcm_dmix_open) unable to open slave
['HD-Audio Generic: HDMI 0 (hw:0,3)', 'HD-Audio Generic: ALC236 Analog (hw:1,0)', 'hdmi',
'pulse', 'default']

Can somebody help me out with this.

A: You have to connect a microphone on your laptop or pc
Because for giving inputs through voice need microphone

A: Firts:
you need a microphone
Second
Check if EVERY bracket has a closing part and if it still doesn't work then start over from scratch


text:
Q: Bookmarks are associated with wrong page after some pages got deleted I used iTextSharp open source library.
I tried both PdfWriter and PdfStamper:
For PdfStamper I have code below (toDelegePageNumbers will be ",!4,!5" after code execution):
stamper.Outlines = bookmarks;
reader.SelectPages("1-" + reader.NumberOfPages + toDelegePageNumbers);
stamper.Outlines = bookmarks;
stamper.Close();

And alternatively for PdfWriter I used code below (w is PdfWriter):
foreach (int page in pageToKeep)
{
    doc.NewPage();
    w.DirectContent.AddTemplate(w.GetImportedPage(reader, page), 0, 0);
}
w.Outlines = bookmarks;
doc.Close();

In either scenario, bookmark originally point to Page 6 still point to Page 6 in the newly generated pdf file, which is wrong since page 4 and 5 have been deleted, original page 6 should be page 4 in the new document.
Is there any way we could preserve bookmarks without doing manual page number shifting? We have many existing bookmarks, and only need to delete two pages, it seems extra work for a simple operation.
Thank you very much.


text:
Q: How do I update pins on a MKMapView as a user moves I query a database for store information. I want stores to appear on screen within a certain radius around the user's current location. I want new stores to appear on screen as the user moves without the user having to manually refresh anything. What delegate method should I use to query for stores in and to place them on screen?

A: You can get the coordinates of the point at the center of the map using centerCoordinate
 var coord: CLLocationCoordinate2D = CLLocationCoordinate2DMake(map.centerCoordinate.latitude, map.centerCoordinate.longitude)

A: You can have a look at Tracking the User Location for MKMapView using its delegates.
For location update MKMapViewDelagate's
- mapView:didUpdateUserLocation:
To place them on screen remove the previous annotation and add new annotations fetched from your query.

A: you just need to implement only func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? and listen location changes with CLLocation Manager.Whenever new location appear query point of interests and append to mapview by addAnnotations.After than set mapview centerCoordinate property to reveal user current position in mapview


text:
Q: Warning: Invalid DOM property `for`. Did you mean `htmlFor`? El aviso de advertencia :

Warning: Invalid DOM property for. Did you mean htmlFor?

Me aparece al ejecutar la siguiente función:
listarPermisos(permisos){
    var myarra=[];
    if(permisos != undefined ){
        for(var obj in permisos){
            myarra.push(
                    <OnePermission
                        key={obj}
                        titulo={obj}
                        lista={permisos[obj]}
                        onChangePermission={this.onChangePermission}
                    />);
        }
    }else{
        console.log("Permisos no encontrados")
    }
    return myarra;
}

Aunque todo funciona sin problemas, me causa molestias al verlo en la consola del navegador. EL objeto que deseo recorrer es el siguiente:permisos

Dicho array tiende a crecer según vaya el avance del proyecto, razón por la cual lo recorro con un for.

¿Como recorrer las propiedades de un objeto con javascript-reactjs?

EDICION
Clase-component: OnePermission
const OnePermission = ({titulo,lista,onChangePermission})=>{
    return (

{titulo}

            {
                lista.map((el)=>(

                        <input type="checkbox" name={`check${el.id}`} id={`check${el.id}`} checked={el.check}  onChange={(e)=>onChangePermission(e,titulo,el.id)}/>
                        <label for={`check${el.id}`}>{el.display_name}

                ))
            }

        )
}

EL resultado es el siguiente:

A: Simplemente es cambiar el for a htmlFor en la etiqueta label:
De esto
<label for={`check${el.id}`}>{el.display_name}

A esto
<label htmlFor={`check${el.id}`}>{el.display_name}


text:
Q: Indy-node installation fails on Ubuntu I'm trying to install indy-node on a fresh Ubuntu 18.04 machine in order to create a small network with 4 nodes.
when following the installation instructions I get the following error:
localhost:~$ sudo apt-get install indy-node

The following packages have unmet dependencies:
 indy-node : Depends: indy-plenum (= 1.12.2) but it is not going to be installed
             Depends: libsodium18 but it is not installable
E: Unable to correct problems, you have held broken packages.

I've tried installing libsodium18 but I get the following error:
Package libsodium18 is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'libsodium18' has no installation candidate

Likewise, trying to install indy-plenum has a bunch of 'unmet dependency' errors.
**Note:* this is all happens with the following repo:
sudo bash -c 'echo "deb https://repo.sovrin.org/deb xenial stable" >> /etc/apt/sources.list'

when I try to add the packages for bionic instead of xenial, I get the following error:
repository 'https://repo.sovrin.org/deb bionic InRelease' doesn't have the component 'stable'

I have also tried to install indy-node via python + pip, but that doesn't seem to work either.
Has anyone successfully installed indy-node, and if so, can you share the secret?

A: We've generated Docker images for Indy-Node using Ubuntu 18.04, but had to build libsodium from source. You can see the source dockerfile here although there are git URLs that get replaced by the build script: https://github.com/PSPC-SPAC-buyandsell/von-image/blob/master/node-1.9/Dockerfile.ubuntu
The final images are at https://hub.docker.com/r/bcgovimages/von-image/tags (the node-* images, latest is bcgovimages/von-image:node-1.12-2)
I believe the Indy-Node team are shortly going to be updating to 20.04 for the image used in testing.

A: The solution in the end was to downgrade to Ubuntu 16.04


text:
Q: Pass username & password to an invisible Login Control to validate? In my master page, on the menu there is an icon which uses Jquery to slide, showing 2 textboxes (username, password) for users to enter & 1 submit button. My idea is that after submitting, I get values of these 2 fields to assigned it to an invisible Login Control in my MasterPage, then validate automatically.
I could get values and assign but problem is I don't know how to trigger the Login button in Login Control (how to force it to process information)? the DataBind() func doesn't work
Master.master

                            <asp:Login ID="Login2" runat="server" DestinationPageUrl="~/Index.aspx" LoginButtonStyle-CssClass="button_login"
                                TextBoxStyle-CssClass="input-name" Visible="false">
                            </asp:Login>
                            <asp:TextBox ID="inputUser" CssClass="input-name" Text="Username" runat="server"></asp:TextBox>
                            <asp:TextBox ID="inputPassword" CssClass="input-pass" Text="Password" runat="server"
                                TextMode="Password"></asp:TextBox>
                            <asp:Button ID="btn_login" CssClass="button_login" runat="server" OnClick="triggerLogin" />

Main.master.cs:
 protected void triggerLogin(object sender, EventArgs e)
        {
            Login2.UserNameLabelText = inputUser.Text;
            Login2.PasswordLabelText = inputPassword.Text;
            Login2.DataBind();
        }

Actually I already have a login page which processes individually, is it possible to pass information to that page to process?

A: You can add your username and password int o a session.
Something like:
  Session["user"] = inputUser.Text;
  Session["pass"] = inputPassword.Text;

By using that you can access the username,password in your pages.
 var myusername =  Session["user"].ToString();
 var mypassword=  Session["pass"].ToString();

Check this on MSDN:
ASP.NET State Management Overview
How to: Pass Values Between ASP.NET Web Pages
Regards

A: Yeah, I've found out the solution, without having to use Login Control. I can do it manually.
<asp:TextBox ID="inputUser" CssClass="input-name" Text="Username" runat="server"></asp:TextBox>
                            <asp:TextBox ID="inputPassword" CssClass="input-pass" Text="Password" runat="server"
                                TextMode="Password"></asp:TextBox>
                            <asp:Button ID="btn_login" CssClass="button_login" runat="server" OnClick="triggerLogin" />

Codebehind:
protected void triggerLogin(object sender, EventArgs e)
    {
        TextBox txtbxInputUser = (TextBox)Page.Master.FindControl("inputUser");
        TextBox txtbxInputPass = (TextBox)Page.Master.FindControl("inputPassword");

        Label samplelabel1 = (Label)Page.Master.FindControl("sampleLabel1");

        if (System.Web.Security.Membership.ValidateUser(txtbxInputUser.Text, txtbxInputPass.Text))
        {

            System.Web.Security.FormsAuthentication.SetAuthCookie(txtbxInputUser.Text, false);
        }
        else
        {
            Response.Redirect("Login.aspx?Attempt=wrong");
        }
    }


text:
Q: How to remove only minutes from UIDatePickerMode.DateAndTime Is there way to remove only minutes from UIDatePickerMode? I tried to search many posts and i still haven't find.
I see Date, Time , Date and Time, Count Down Timer from DatePicker Menu
The following image is got by choosing Date and Time.

But I need to do is like following image.

Any ideas, tips? Thank you!

A: As Christian mentioned, you can't edit the UIDatePicker. What you can do is use a UIPickerView. Implement the dataSource to return 3 components, 1 for each column. Then have an array for the possible options for month, day and hour time.
dataSource:
let monthsArray = ["august"..]
var daysArray = [1..31] //include logic for actual days of the month
let hoursArray = ["1pm"..]

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
   return 3
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
   switch component {
   case 1: return monthsArray.count
   case 2: return daysArray.count
   case 3: return hoursArray.count
   }
}

you also need to implement the delegate for knowing what the user has selected
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)


text:
Q: Ajustar el alto y el ancho máximo en gridster.js Estoy usando la librería Gridster para realizar un drag and drop, el caso es que la pantalla tiene que tener límite en alto y en ancho, he estado tratando de limitarlo añadiendo un máximo de columnas y filas pero sigue aumentando sin fin al arrastrar.
¿Es un problema de la librería?

$(document).ready(function () {

    $(function () {
    gridster = $(".gridster ul").gridster({
      widget_base_dimensions: [50, 50],
      widget_margins: [5, 5],
      shift_widgets_up: false,
      shift_larger_widgets_down: true,
      min_cols: 10,
      max_cols: 20,
      max_size_x: 20,
      min_rows: 10,
      resize: {
        enabled: true,
        max_size: [4, 4],
        min_size: [1, 1]
      }
    }).data('gridster');
  });
});
/*! gridster.js - v0.7.0 - 2017-03-27 - * https://dsmorse.github.io/gridster.js/ - Copyright (c) 2017 ducksboard; Licensed MIT */
.gridster {
    position: relative
}

.gridster > * {
    -webkit-transition: height .4s,width .4s;
    -moz-transition: height .4s,width .4s;
    -o-transition: height .4s,width .4s;
    -ms-transition: height .4s,width .4s;
    transition: height .4s,width .4s
}

.gridster .gs-w {
    z-index: 2;
    position: absolute;
    background: #61A9CF;
    cursor: pointer;
    -webkit-box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
    list-style-type: none
}

.gridster .preview-holder {
    z-index: 1;
    position: absolute;
    background-color: #000;
    border-color: #000;
    opacity: .3
}

.gridster .player-revert {
    z-index: 10 !important;
    -webkit-transition: left .3s,top .3s !important;
    -moz-transition: left .3s,top .3s !important;
    -o-transition: left .3s,top .3s !important;
    transition: left .3s,top .3s !important
}

.gridster.collapsed {
    height: auto !important
}

.gridster.collapsed .gs-w {
    position: static !important;
}

.ready .gs-w:not(.preview-holder), .ready .resize-preview-holder {
    -webkit-transition: opacity .3s,left .3s,top .3s,width .3s,height .3s;
    -moz-transition: opacity .3s,left .3s,top .3s,width .3s,height .3s;
    -o-transition: opacity .3s,left .3s,top .3s,width .3s,height .3s;
    transition: opacity .3s,left .3s,top .3s,width .3s,height .3s
}

.gridster .dragging, .gridster .resizing {
    z-index: 10 !important;
    -webkit-transition: all 0s !important;
    -moz-transition: all 0s !important;
    -o-transition: all 0s !important;
    transition: all 0s !important
}

.gs-resize-handle {
    position: absolute;
    z-index: 1
}

.gs-resize-handle-both {
    width: 20px;
    height: 20px;
    bottom: -8px;
    right: -8px;
    background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBzdGFuZGFsb25lPSJubyI/Pg08IS0tIEdlbmVyYXRvcjogQWRvYmUgRmlyZXdvcmtzIENTNiwgRXhwb3J0IFNWRyBFeHRlbnNpb24gYnkgQWFyb24gQmVhbGwgKGh0dHA6Ly9maXJld29ya3MuYWJlYWxsLmNvbSkgLiBWZXJzaW9uOiAwLjYuMSAgLS0+DTwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+DTxzdmcgaWQ9IlVudGl0bGVkLVBhZ2UlMjAxIiB2aWV3Qm94PSIwIDAgNiA2IiBzdHlsZT0iYmFja2dyb3VuZC1jb2xvcjojZmZmZmZmMDAiIHZlcnNpb249IjEuMSINCXhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHhtbDpzcGFjZT0icHJlc2VydmUiDQl4PSIwcHgiIHk9IjBweCIgd2lkdGg9IjZweCIgaGVpZ2h0PSI2cHgiDT4NCTxnIG9wYWNpdHk9IjAuMzAyIj4NCQk8cGF0aCBkPSJNIDYgNiBMIDAgNiBMIDAgNC4yIEwgNCA0LjIgTCA0LjIgNC4yIEwgNC4yIDAgTCA2IDAgTCA2IDYgTCA2IDYgWiIgZmlsbD0iIzAwMDAwMCIvPg0JPC9nPg08L3N2Zz4=);
    background-position: top left;
    background-repeat: no-repeat;
    cursor: se-resize;
    z-index: 20
}

.gs-resize-handle-x {
    top: 0;
    bottom: 13px;
    right: -5px;
    width: 10px;
    cursor: e-resize
}

.gs-resize-handle-y {
    left: 0;
    right: 13px;
    bottom: -5px;
    height: 10px;
    cursor: s-resize
}

.gs-w:hover .gs-resize-handle, .resizing .gs-resize-handle {
    opacity: 1
}

.gs-resize-handle, .gs-w.dragging .gs-resize-handle {
    opacity: 0
}

.gs-resize-disabled .gs-resize-handle, [data-max-sizex="1"] .gs-resize-handle-x, [data-max-sizey="1"] .gs-resize-handle-y, [data-max-sizey="1"][data-max-sizex="1"] .gs-resize-handle {
    display: none !important
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"/>

Como se puede apreciar, si arrastras hasta el limite, el objeto se queda ahi, pero es posible forzarlo con una segunda pieza y superar el limite.

A: El problema proviene de la librería, como se puede apreciar en la imagen, al arrastrar un cuadrado el otro item baja hasta superar el limite.

La mejor solución es buscar otra librería o construirlo por ti mismo, otra librería que puede ser útil es JQueryUI o Dragabilly.
También puedes realizarlo por ti mismo usando draggable.
En mi caso he usado un conjunto para realizar la misma función, dejo mi prueba para problemas similares.


text:
Q: What is the way to round of in TWIG? I need to round of numeric in my view. But there twig is used. What is the way to round of in TWIG?

A: You can use the format filter:
{{ '%.2f' | format(10.5555) }}
But note that it will round it to 10.56.
Can also use number_filter


text:
Q: Spring Batch skip policy not being called I have a situation where the first steps my job count the number of rows both in source and target databases, so I can present a live progress monitor during the job execution (which can take some days).
Due to a particularity of my inputs, the list of tables that feed the job may not correspond to the list of tables in fact present on both databases (my input can have tables that doesn't exist in the databases). Since most of the list should match the tables present in the databases, I thought using a fault tolerant step for dealing with this.
The pieces of my code that I believe are the most important in the context of this question follow:
(Step creation)
@Bean( "partitionedSourceRowsCounterStep" )
public Step partitionedSourceRowsCounterStep( @Qualifier( "sourceRowCounterStep" ) Step rowCounterStep,
                                          @Qualifier( "parallelTasksExecutor" ) TaskExecutor taskExecutor ) {

return stepBuilderFactory
            .get( "partitionedSourceRowsCounterStep" )
            .partitioner( "sourceRowCounterStep", new RowsCounterPartitioner(
this.model.getEntityNames() ) )
            .step( rowCounterStep )
            .taskExecutor( taskExecutor )
            .build();
}

@Bean( "sourceRowCounterStep" )
public Step rowCounterStep( SourceRowsCounterReader reader,
                        SourceRowsCounterInMemoryWriter writer,
                        @Qualifier( "parallelTasksExecutor" ) TaskExecutor taskExecutor ) {

return stepBuilderFactory
            .get( "sourceRowCounterStep" )
            .<Map<String, Object>, Map<String, Object>>chunk( this.config.getChunkSize() )
            .reader( reader )
            .writer( writer )
            .faultTolerant()
            .skipPolicy( new SkipPolicy() {

                @Override
                public boolean shouldSkip( Throwable t, int skipCount ) throws SkipLimitExceededException {
                    System.out.println( "SKIP_POLICY WAS CALLED" );
                    return false;
                }

            } )
            .taskExecutor( taskExecutor )
            .throttleLimit( 1 )
            .build();
}

(Rows counter reader)
@StepScope
@Slf4j
@Component
public class SourceRowsCounterReader extends AbstractCursorItemReader<Map<String, Object>> {

@Override
protected void openCursor( Connection con ) {
    try {
        String sql = getSql();

        log.debug( "Query string: '" + sql + "'" );

        if( isUseSharedExtendedConnection() ) {
            preparedStatement = con.prepareStatement( sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT );
        } else {
            preparedStatement = con.prepareStatement( sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY );
        }

        applyStatementSettings( preparedStatement );
        if( this.preparedStatementSetter != null ) {
            preparedStatementSetter.setValues( preparedStatement );
        }

        this.rs = preparedStatement.executeQuery(); // Exception happens here!

        handleWarnings( preparedStatement );
    } catch( SQLException se ) {
        close();
        throw getExceptionTranslator().translate("Executing query", getSql(), se);
    }

}

@Override
protected SQLExceptionTranslator getExceptionTranslator() {
    return this.customExceptionTranslator;
}

}

However, when the code runs I get the error:
org.springframework.batch.item.ItemStreamException: Failed to initialize the reader
at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.open(AbstractItemCountingItemStreamItemReader.java:153) ~[spring-batch-infrastructure-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader$$FastClassBySpringCGLIB$$ebb633d0.invoke(<generated>) ~[spring-batch-infrastructure-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771) ~[spring-aop-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) ~[spring-aop-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:136) ~[spring-aop-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:124) ~[spring-aop-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) ~[spring-aop-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691) ~[spring-aop-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at com.company.steps.SourceRowsCounterReader$$EnhancerBySpringCGLIB$$2dbb98e7.open(<generated>) ~[classes/:na]
at org.springframework.batch.item.support.CompositeItemStream.open(CompositeItemStream.java:103) ~[spring-batch-infrastructure-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.batch.core.step.item.ChunkMonitor.open(ChunkMonitor.java:114) ~[spring-batch-core-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.batch.item.support.CompositeItemStream.open(CompositeItemStream.java:103) ~[spring-batch-infrastructure-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.batch.core.step.tasklet.TaskletStep.open(TaskletStep.java:311) ~[spring-batch-core-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:205) ~[spring-batch-core-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.batch.core.partition.support.TaskExecutorPartitionHandler$1.call(TaskExecutorPartitionHandler.java:138) [spring-batch-core-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.batch.core.partition.support.TaskExecutorPartitionHandler$1.call(TaskExecutorPartitionHandler.java:135) [spring-batch-core-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_231]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_231]
Caused by: com.company.steps.jdbc.exception.TableOrViewDoesnExistException: Table doesn't exist; nested exception is java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist

at com.company.steps.jdbc.oracle.OracleExceptionTranslator.translate(OracleExceptionTranslator.java:18) ~[classes/:na]
at com.company.steps.SourceRowsCounterReader.openCursor(SourceRowsCounterReader.java:99) ~[classes/:na]
at org.springframework.batch.item.database.AbstractCursorItemReader.doOpen(AbstractCursorItemReader.java:428) ~[spring-batch-infrastructure-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.open(AbstractItemCountingItemStreamItemReader.java:150) ~[spring-batch-infrastructure-4.2.4.RELEASE.jar:4.2.4.RELEASE]
... 20 common frames omitted
Caused by: java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist

Besides, no "SKIP_POLICY WAS CALLED" is printed in the terminal, even I have a dozen failures due to the previous exception.
According to the docs exceptions should be handled regardless the point of the step chain they are thrown.
Does anyone can see any misconfiguration here?
Spring Boot v2.3.4.RELEASE
Spring Batch v4.2.4.RELEASE

A: According to your stacktrace, the exception happens while initializing the reader (SourceRowsCounterReader.openCursor), meaning that the step did not start yet at this point.
The skip policy will be called once the step starts correclty (ie the reader/writer are correctly initialized).


text:
Q: LINQ query with two joins that worked in EF 6 gives error in EF 7 I have a LINQ query that works in an EF 6 (Code First) project. Now I have migrated the code to EF 7, and this query now throws an exception: ArgumentException: Property 'Int32 ID' is not defined for type 'X.Models.Domain.MadeChoice'
The query:
var madeChoices = from res in X.Instance.Residence
                  join room in X.Instance.Room on res.ID equals room.Residence.ID
                  join madeChoice in X.Instance.MadeChoice on room.ID equals madeChoice.Room.ID
                  where res.ID == residence.ID
                  select room.MadeChoices;

The MadeChoice class:
public class MadeChoice
{
    public virtual int ID { get; set; }

    [Required]
    public virtual ChoiceGroup Choicegroup { get; set; }

    [Required]
    public virtual Room Room { get; set; }

    [Required]
    public virtual Item Item { get; set; }
}

The Room class:
public class Room
{
    public virtual int ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    public virtual Residence Residence { get; set; }
    public virtual RoomType RoomType { get; set; }
    public virtual List<MadeChoice> MadeChoices { get; set; }

    // Constructors:
    public Room()
    {
        this.MadeChoices = new List<MadeChoice>();
    }
}

The Residence class:
public class Residence
{
    public int ID { get; set; }
    public string ApartmentNumber { get; set; }

    public static IQueryable<List<MadeChoice>> GetMadeChoices(Residence residence)
    {
        var madeChoices = from res in X.Instance.Residence
                            join room in X.Instance.Room on res.ID equals room.Residence.ID
                            join madeChoice in X.Instance.MadeChoice on room.ID equals madeChoice.Room.ID
                            where res.ID == residence.ID
                            select room.MadeChoices;
        System.Diagnostics.Debug.Write("MadeChoices.Count: ");
        System.Diagnostics.Debug.WriteLine(madeChoices.Count());
        foreach (var madechoice in madeChoices)
        {
            System.Diagnostics.Debug.Write("MadeChoice.Count: ");
            System.Diagnostics.Debug.WriteLine(madechoice.Count());
        }
        return madeChoices;
    }

    // Navigational properties:
    public virtual List<Room> Rooms { get; set; }
    public virtual ResidenceType ResidenceType { get; set; }
    public virtual List<Tenant> Tenants { get; set; }
    public virtual List<PeriodResidenceDeadline> PeriodResidenceDeadline { get; set; }

    // Constructors:
    public Residence()
    {
        this.Rooms = new List<Room>();
        this.Tenants = new List<Tenant>();
        this.PeriodResidenceDeadline = new List<PeriodResidenceDeadline>();
    }
}

Originally, the ID was not virtual but it didn't affect the error. The database  looks as in EF 6. The relationships are one-to-many.
I use EF 7.0.0-rc1-final.
Any hints?
Thanks in advance,
Peter

A: As EF team said, EF Core RC1 doesn't handle complex sub-types (see their roadmap here https://github.com/aspnet/EntityFramework/wiki/Roadmap#in-progress for Query)
For querying, this will be handle in the EF Core 1.0 RTM version.
In the meantime, you can use one of the solution I enumerate here : EF Core fluent mapping to inner object properties (the problem is the same for mapping)


text:
Q: php session_start() ignores already created sessions I have set up a local webserver and put in a project I've been working on (the code was already working).
The problem I see is that session_start() ignores the already created sessions and keeps creating new ones (I can see a new file every time I click a link or refresh the page), even though the session variables get written into the file.
The sessions folder is owned by the http user (the default one in the php-fpm config).
This is the session config from php.ini:
session.save_handler = files
session.save_path = "/srv/http/sessions"
session.use_strict_mode = 1
session.use_cookies = 1
session.cookie_secure = 1
session.use_only_cookies = 1
session.name = PHPSESSID
session.auto_start = 0
session.cookie_lifetime = 0
session.cookie_path = /
session.cookie_domain =
session.cookie_httponly = 1
session.serialize_handler = php
session.gc_probability = 1
session.gc_divisor = 1000
session.gc_maxlifetime = 1440
session.referer_check =
session.cache_limiter = nocache
session.cache_expire = 180
session.use_trans_sid = 0
session.hash_function = 0
session.hash_bits_per_character = 5

Anyone knows what's going on?
This is the function that starts the session:
public static function sec_session_start() {
    if (ini_set('session.use_only_cookies', 1) === FALSE) {
        $session_error = 'Error: Cannot create new user session.';
        return $session_error;
    }
    else {
        $session_name   = 'session_id';
        $domain         = 'domain.com';
        $secure         = TRUE;
        $httpOnly       = TRUE;                         // prevents cookie theft

        // Get the current cookies params.
        $cookieParams = session_get_cookie_params();
        // Set the current cookies params.
        session_set_cookie_params($cookieParams['lifetime'], $cookieParams['path'], $domain, $secure, $httpOnly);

        // Sets the session name to the one set above.
        session_name($session_name);
        session_start();                                // Start the PHP session

        if (!isset($_SESSION['CREATED'])) {
            $_SESSION['CREATED'] = time();
        } else if ((time() - $_SESSION['CREATED']) > 1800) {
            // session started more than 30 minutes ago
            session_regenerate_id(TRUE);                // change session ID for the current session and invalidate old session ID
            $_SESSION['CREATED'] = time();              // update creation time
        }
/*
        $hasExpired = FALSE;

        if (isset($_SESSION['staff_id'], $_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY']) > 9999) {  // 300 (5 mins)
            // last request was more than 5 minutes ago
            $_SESSION = array();                        // unset $_SESSION variable for the run-time
            $params = session_get_cookie_params();      // Get session parameters
            setcookie(session_name(),                   // Delete the actual cookie
                      '',
                      time() - 3600,
                      $params["path"],
                      $params["domain"],
                      $params["secure"],
                      $params["httponly"]);
            session_destroy();                          // destroy session data in storage

            $hasExpired = TRUE;                         // now we know the user has lost his session for inactivity
        }

        $_SESSION['LAST_ACTIVITY'] = time();            // update last activity time stamp*/
    }

    //return $hasExpired;
}

A: My bad, forgot to add COOKIE to the variables_order directive:
variables_order = "GPCS"

So that means that the server needs to access the cookie to actually know if a current session (for the user) already exists, no way to know otherwise.


text:
Q: Several Port(8015,8016,8017) required by tomcat v8.0 are already in use Guys I am new to the eclipse, I have recently installed it and configured it with tomcat v8.0. From the last time I am receiving this error whenever I am trying to run any of my web application files on tomcat server.

I searched on internet and founds out that if I kill the processes which are using the required mentioned port or if I changes the port for tomcat and restarts the server then it will work but none of them is working for me.
Last time while trying I have tried by changing my port number that's why into image you can see my ports are 8015,8016,8017 instead of 8009,8080,8005. Please suggest me if I am doing something wrong.


text:
Q: In mgcv::gam(), what is the difference between s(x, by=cat) and s(x, cat, bs='fs')? In this comment about smooth-factor interactions, Gavin Simpson wrote:

s(x1, by = cat) doesn't create a "fs" class smooth

I understand that
y ~ s(x, by = cat) + cat             (a)
//cat is an unordered factor

creates a separate smooth for each level of the factor as shown in summary() and plot() with a confidence interval around each smooth (and that this model doesn't say anything about whether the smooths for those levels are different).
On the other hand, in
y ~ s(x, cat, bs = 'fs')             (b)

the summary shows one smooth, but the plot() shows two smooths and with no confidence intervals.
So my questions are:

*

*How should the fs smooth in (b) summary() be interpreted? Does the p-value say anything about whether the smooths for cat levels are different?

*Why does plot() in (b) shows two curves without confidence intervals?

*What is the exact difference between (a) and (b)? When should I use one instead of the other? And how does their interpretation differ?
Many thanks

A: Q3
The by smooth variant has a separate smoothness parameter for each level of cat. In one sense you can think of these smooths as creating entirely separate smooth functions (they're aren't quite, they share the same basis for example), hence you have nlevels(cat) entries in the summary() output.
fs smooths share a single smoothness parameter, and in that sense are a bit closer to the smooth equivalent of random slopes; all the smooths are being pulled towards 0 (null function), with the smooths for some levels of cat pulled more towards 0 than others.
Q1
You should just treat the fs smooth summary as some measure of overall importance of the set of smooth functions. If the fs smooth is the only one in the model where x is a covariate then you could say interpret this as a test of the amount of variation in the response that can be explained by smooth functions of x, against a null of no effect. It's like an omnibus test in the sense that it is over the set of smooths.
Put another way, it is a bit like a test for a variance term of random slopes in a mixed effects model; this would be on a single variance parameter and you get a single test over the entire "effect" even though it represents $m$ slopes.
Q2
Typically, one would use fs where there where nlevels(cat) was large and you aren't particularly interested in the specific levels, just like you might work with random effects in a mixed effects model.
As there could feasibly be a separate line for the many levels of the factor but we think of this as a single "smooth" you get a single plot with each smooth superimposed to get some idea of the variation within and between individual functions. It would get very messy it if also showed confidence bands for each smooth.
In the by case, because you conditioned on the observed set of levels (sensu fixed effects in a mixed model) it makes sense to view these are being of individual interest, hence a separate plot per level of cat.
Also note that this is just the default plot to get a quick look at the fitted functions.


text:
Q: How to pass functions from parent to any children and sub-children using Navigator and WithSecurityScreen in React Native? I am quite new in React Native and I am trying to understand how function written in a parent Component could be passed (inherited) to any children and sub-children. In particular I am using a library to internationalise my App using:
import * as RNLocalize from 'react-native-localize'
import i18n from 'i18n-js'

But I noticed that I have to implement the translate(...) function for each Component of the whole project and this seems to be exaggerated because it requires a lot of work to implement the translation feature (I followed this tutorial).
Please, note that I have a basic understanding how to pass a function or some data using this.props, so I am not asking how props works from a parent to a single child. What I am asking is: how to avoid to repeat the code from //BEGIN ... to //END... (please see WithSecurityScreen file) and to avoid to repeat the implementation of handleLocalizationChange, RNLocalize.addEventListener, RNLocalize.removeEventListener and translate.
Please also note that the translation library works, test is provided at following line of WithSecurityScreen:
const SecurityScreen = () => <View><Text>{translate('USER_SURNAME')}</Text></View>;

But I am not be able to pass translate(...) function to each components of the whole project.
The project structure is:

*

*App.js (wraps SecureApp.js)

*SecureApp.js (wrapped in App.js and runs WithSecurityScreen.js)

*WithSecurityScreen.js (wraps routes to views, e.g. Welcome.js)

*Welcome.js (main view)

App.js
import { withSecurityScreen } from './src/components/withSecurityScreen'

import App from "./SecureApp.js"

export default withSecurityScreen(App);

SecureApp.js
const MainNavigator = createStackNavigator({
    Home: {
        screen: Welcome,
        navigationOptions: {
            headerShown: false
        }
    },
    UserProfile: {
        screen: CoreApp,
        navigationOptions: {
            headerShown: false
        }
    },
    NumPad: {
        screen: NumPad,
        navigationOptions: {
            header: 'PIN Creation',
            headerShown: false
        }
    }, /* , navigationOptions: {headerLeft: () => null} */
    QrScan: {
        screen: QrScan, navigationOptions: {
            header: 'QR Scan',
            headerShown: false
        }
    },
    ...
});

export default createAppContainer(MainNavigator);

WithSecurityScreen.js
// START: https://heartbeat.fritz.ai/how-to-use-react-native-localize-in-react-native-apps-3bb3d510f801
import * as RNLocalize from 'react-native-localize'
import i18n from 'i18n-js'
import memoize from 'lodash.memoize'
const translationGetters = {
    en: () => require('./../../assets/locales/en/en.json'),
    it: () => require('./../../assets/locales/it/it.json')
};

const translate = memoize(
    (key, config) => i18n.t(key, config),
    (key, config) => (config ? key + JSON.stringify(config) : key)
)

const setI18nConfig = () => {
    const fallback = { languageTag: 'en' }
    const { languageTag } =
    RNLocalize.findBestAvailableLanguage(Object.keys(translationGetters)) ||
    fallback

    translate.cache.clear()

    i18n.translations = { [languageTag]: translationGetters[languageTag]() }
    i18n.locale = languageTag
}
// END: https://heartbeat.fritz.ai/how-to-use-react-native-localize-in-react-native-apps-3bb3d510f801

const SecurityScreen = () => <View><Text>{translate('USER_SURNAME')}</Text></View>;

const showSecurityScreenFromAppState = appState =>
    ['background', 'inactive'].includes(appState);

const withSecurityScreenIOS = Wrapped => {
    return class WithSecurityScreen extends React.Component {

        constructor(props) {
            super(props)
            setI18nConfig()
        }

        state = {
            showSecurityScreen: showSecurityScreenFromAppState(AppState.currentState)
        };

        componentDidMount() {
            AppState.addEventListener('change', this.onChangeAppState)
            RNLocalize.addEventListener('change', this.handleLocalizationChange)
        }

        componentWillUnmount() {
            AppState.removeEventListener('change', this.onChangeAppState)
            RNLocalize.removeEventListener('change', this.handleLocalizationChange)
        }

        handleLocalizationChange = () => {
            setI18nConfig()
                .then(() => this.forceUpdate())
                .catch(error => {
                    console.error(error)
                })
        }

        onChangeAppState = nextAppState => {
            const showSecurityScreen = showSecurityScreenFromAppState(nextAppState);

            this.setState({showSecurityScreen})
        };

        render() {
            return this.state.showSecurityScreen
                ? <SecurityScreen/>
                : <Wrapped {...this.props} />
        }
    }
};

const withSecurityScreenAndroid = Wrapped => Wrapped;

export const withSecurityScreen = Platform.OS === 'ios'
    ? withSecurityScreenIOS
    : withSecurityScreenAndroid;

Welcome.js
export default class Welcome extends Component {
    let username = 'UserName';
    render() {
        return (
            <View style={styles.container}>
                <LinearGradient colors={globalStyles.colors.gradientGreen} style={{flex: 1}}>
                    <View style={styles.upperView}><Text style={styles.upperViewText}>{this.props.translate('WELCOME_TEXT')}{this.username}</Text>
                    </View>

                </LinearGradient>
            </View>
        );
    }
}

I get following error:

A: First of all in your case you can declare translate function in separate js file locale.js and can declare all your translation logic in that file and export the functions translate and setI18nConfig
local.js
  import * as RNLocalize from 'react-native-localize'
    import i18n from 'i18n-js'
    import memoize from 'lodash.memoize'
    const translationGetters = {
        en: () => require('./../../assets/locales/en/en.json'),
        it: () => require('./../../assets/locales/it/it.json')
    };

   export const translate = memoize(
        (key, config) => i18n.t(key, config),
        (key, config) => (config ? key + JSON.stringify(config) : key)
    )

   export const setI18nConfig = () => {
        const fallback = { languageTag: 'en' }
        const { languageTag } =
        RNLocalize.findBestAvailableLanguage(Object.keys(translationGetters)) ||
        fallback

        translate.cache.clear()

        i18n.translations = { [languageTag]: translationGetters[languageTag]() }
        i18n.locale = languageTag
    }

and import this functions in your components where you want to use this like
App.js
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { setI18nConfig, translate } from './locale';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    setI18nConfig(); // This should be called only once through out the app at the time of changing locale.
    return (
      <View>
        <Text> translate ('key_from_json_to_label') </Text>
      </View>
    );
  }
}

For more details you can refer this repo where I have implemented the same.
Hope this will help.

A: i use import i18n from "i18next", for translation.
Here is the config file:

//config/i18n
import i18n from "i18next";
import { reactI18nextModule, initReactI18next } from "react-i18next";
import translationFR from '../translation/fr/translation.json';
import translationEN from '../translation/en/translation.json';
import DeviceInfo from 'react-native-device-info';

let locale = DeviceInfo.getDeviceLocale().substring(0, 2);
if (locale != 'fr') {
  locale = 'en';
}

// the translations
const resources = {
  en: translationEN,
  fr: translationFR,
};

i18n
  .use(reactI18nextModule) // passes i18n down to react-i18next
  .init({
    resources: resources,
    lng: locale,
    fallbackLng: ['en', 'fr'],
    keySeparator: false, // we do not use keys in form messages.welcome
    interpolation: {
      escapeValue: false // react already safes from xss
    }
  });

export default i18n;

One of the uses is to
import i18n from 'config/i18n'

and use translate in file like this
i18n.t('bottomTab:home_tab')

You can also wrap component with withNamespaces from 'react-i18next', like this:

export default withNamespaces([], {wait: true})(Welcome)

and then access translation with:

this.props.t('welcome_message')


text:
Q: Express / Node.js / WebStorm debugging is very slow I am trying to customize Node.js based web application: https://github.com/Mailtrain-org/mailtrain
I want to do debugging. I did some configuration for launching the app
 as you can see config in the following image:

But debugging is not working and its very slow to start. It take 5 min to start debugging.
/Users/Calm/.nvm/versions/node/v7.0.0/bin/node --debug-brk=50039
--nolazy index.js Debugger listening on 127.0.0.1:50039 info Using local auth  info sql Database check completed info Express WWW server listening on port 3000 verb UTC Updating timezone offsets Error: listen EADDRINUSE 127.0.0.1:50039
    at Object.exports._errnoException (util.js:1026:11)
    at exports._exceptionWithHostPort (util.js:1049:20)
    at Agent.Server._listen2 (net.js:1262:14)
    at listen (net.js:1298:10)
    at net.js:1397:7
    at _combinedTickCallback (internal/process/next_tick.js:77:11)
    at process._tickCallback (internal/process/next_tick.js:98:9)

Although it says port is already in using, but I didn't start any other debug process.
Would you like to help me to make this work?


text:
Q: Convert date format to mm-dd-yyyyy I am populating a list "results" with dates. In a query result I am getting a set of values .. where date value is in this format ..

20120510000000000

In my code, I am doing the following..
    query = service.GetData();
    List<String> results = new List<String>();
    foreach (var item in query)
    {
        results.Add(item.InDate);
        //This is in this format - 20120510000000000
        //Here I want to convert to mm-dd-yyyy
    }
    return results;

I would like to convert the above date format into "mm/dd/yyyy" and post it to "results" list.

A: query = service.GetData();
    List<String> results = new List<String>();
    foreach (var item in query)
    {
        var unformattedDate = item.InDate;
        var formattedDate = DateTime.ParseExact(unformattedDate,
                                    "yyyyMMddHHmmssfff",
                                    System.Globalization.CultureInfo.InvariantCulture)
        results.Add(formattedDate);
    }
    return results;

A: If the date is guaranteed to be in the [year][month][day][hour][minute][second][millisecond] format (looks like it), you can use a simple string manipulation:
var newDate = item.InDate.Substring(2, 2) + "-" +
              item.InDate.Substring(4, 2) + "-" +
              item.InDate.Substring(0, 4);

if you want it in a DateTime object, you can use the DateTime.ParseExact method:
var newDate = DateTime.ParseExact(indate, "yyyyMMddHHmmssfff", CultureInfo.InvariantCulture);

A: The answers provided above are correct. Better store the format of the date your expecting and the date format you are converting to display, store it in the config file or resource file. Its not good to hardcode.


text:
Q: Moving Linux install to a new computer I know that it can, in some circumstances, be difficult to move a Windows installation from one computer to another (physically move the hard drive), but how does that work on Linux? Aren't most of the driver modules loaded at bootup? So theoretically would it be that much of a hassle?
Obviously, xorg configs would change and proprietary ATI drivers and such would have to be recompiled (maybe?). Is there more to it than I'm thinking of?
Assume the two computers are from the same era, e.g. both i7s but slightly different hardware.
Update:
Thanks for the answers. This is mostly for my own curiosity. I have my Linux system up and running at work, but eventually I'd like to move to a computer that I can get dual video cards into so I can run more than two monitors. But not any time soon.

A: Indeed while under Windows it is almost impossible to move an installation to a new PC by just copying harddrive contents or switching the harddrive between the PCs, this works amazingly well under Linux. I switched from a Thinkpad R52 to a Thinkpad T400 by just copying the contents of my old harddrive to the new one (by putting the old one in an external closure connected via USB and copying everything under a Gparted-Live-CD). All I had to do after that was manually putting Grub into the MBR and boot. Everything still worked for me.
As Michael said, normally a new PC is a nice opportunity to get rid of the cruft accumulated over time, however sometimes you just have to get into work again really fast and then just copying the harddrive contents work great with Linux, as all drivers included in the kernel are available to the kernel without installation, nowadays the drivers are auto-loaded instead of manually listed in modprobe.conf and even xorg autoconfigures itself for me.
Only if you had to manually configure drivers on the old PC (e.g. Raid systems, proprietary graphic drivers etc) you might run into problems.

A: Moving or cloning a Linux installation is pretty easy, assuming the source and target processors are the same architecture (e.g. both x86, both x64, both arm…).
Moving
When moving, you have to take care of hardware dependencies. However most users won't encounter any difficulty other than xorg.conf (and even then modern distributions tend not to need it) and perhaps the bootloader.

*

*If the disk configuration is different, you may need to reconfigure the bootloader and filesystem tables (/etc/fstab, /etc/crypttab if you use cryptography, /etc/mdadm.conf if you use md RAID). For the bootloader, the easiest way is to pop the disk into the new machine, boot your distribution's live CD/USB and use its bootloader reparation tool.
Note that if you're copying the data rather than physically moving the disk (for example because one or both systems dual boot with Windows), it's faster and easier to copy whole partitions (with (G)Parted or dd).

*If you have an xorg.conf file to declare display-related options (e.g. in relation with a proprietary driver), it will need to be modified if the target system has a different graphics card or a different monitor setup. You should also install the proprietary driver for the target system's graphics card before moving, if applicable.

*If you've declared module options or blacklists in /etc/modprobe.d, they may need to be adjusted for the target system.
Cloning
Cloning an installation involves the same hardware-related issues as moving, but there are a few more things to take care of to give the new machine a new identity.

*

*Edit /etc/hostname to give the new machine a new name.
Search for other occurrences of the host name under /etc. Common locations are /etc/hosts (alias for 127.0.0.1) and /etc/mailname or other mail system configuration.

*Regenerate the ssh host key.

*Make any necessary change to the networking configuration (such as a static IP address).

*Change the UUID of RAID volumes (not necessary, but recommended to avoid confusion), e.g., mdadm -U uuid.
See also a step-by-step cloning guide targeted at Ubuntu.
My current desktop computer installation was cloned from its predecessor by unplugging one of two RAID-1 mirrored disks, moving it into the new computer, creating a RAID-1 volume on the already present disk, letting the mirror resynchronize, and making the changes outlined above where applicable.

A: I'm not sure if this answers your question, but typically you do the exact opposite -- you move your user folder and reinstall everything. In theory all your customization and individual configuration files should be in your user folder, so that's the only thing you really need to transfer.
Some package managers have a way to list all installed packages (Debian/Ubuntu have dpkg --list, Gentoo has /etc/world, etc.), so you can just:

*

*Install the base distro on a new system

*Tell it "install all the packages I had on the other computer"

*Copy your user folder

And you should end up with a functionally identical system.

A: I guess this will answer your question: https://wiki.debian.org/Wajig
From the page:

One slick trick: suppose you want to install all the packages on one system on a new system? Do:
$ wajig listinstalled > filename
where filename is now a file that lists all the installed packages. You perhaps want to use this line instead, so it excludes the lib files:
$ wajig listinstalled | grep -vP ^lib* > filename
You might want to edit this file to remove things you don't think you want anymore, etc.
Now move your file filename to the new machine and:
$ wajig install --fileinput filename

Install a fresh Linux, copy your home, and use wajig to reinstall all packages.

A: Outline
Recently, I moved an Arch Linux installation to another drive that was smaller than the original drive.
The original drive used only one partition which simplified things. If you have a boot partition separate from the root partition, here's an answer that might help you.
The steps were:

*Back up the data.

*Create a partition containing an ext4 filesystem on the target drive.

*Copy all data from the source partition to the target partition.

*Install GRUB as the bootloader on the target drive.

Hints
A hint before we start: To determine the paths of my connected devices (e.g. /dev/sdb) and generally keep an eye on the state of devices as well as partitions, I use watch combined with lsblk:
watch lsblk -o tran,name,model,fstype,label,mountpoints,fssize,fsavail,fsused,fsuse%

It updates every two seconds and produces output like this:
TRAN   NAME   MODEL                   FSTYPE LABEL        MOUNTPOINTS                FSSIZE FSAVAIL FSUSED FSUSE%
sata   sda    SanDisk SSD PLUS 1000GB
        ├─sda1                         ext4   VM partition /sda1                        108G     50G  53.4G    49%
        └─sda3                         ext4                /                            808G  561.3G 205.7G    25%
usb    sdb    SABRENT
        └─sdb1                         ext4   new_daedalus /run/media/me/new_daedalus  29.2G   25.3G   2.4G     8%
sata   sr0    MATSHITADVD-RAM UJ8A2

Since we're going to copy the contents of one partition to another, it's a good idea to get rid of cruft that takes up lots of space: Check the source partition with ncdu for directories that contain the most data and delete or move them if possible.
Another thing: I use SATA to USB adapters such as these to connect source and target drives to my computer.
Details
Assuming you've backed up your data and your target drive is at /dev/sdb, let's go into detail:

*

*Create a partition containing an ext4 filesystem on the target drive:

*

*Create a Linux partition (type 0x83 in the MBR):
sudo sfdisk /dev/sdb <<< "type=83"

*Create the file system on the new partition:
sudo mkfs.ext4 -L new_partition /dev/sdb1

*Copy all data from the source partition to the target partition:

*

*The following assumes both your old and new partition are mounted:
sudo rsync -a --hard-links --delete --progress --human-readable --stats /run/media/me/old_partition/ /run/media/me/new_partition/

*I used rsync here. You could also use good old cp to achieve the same:
sudo cp --recursive -a /run/media/me/old_partition/* /run/media/me/new_partition/

*Install GRUB as the bootloader on the target drive:

*

*Add the virtual file systems to your new partition which are needed to run grub-install:
sudo mount --bind /dev /run/media/me/new_partition/dev; sudo mount --bind /proc /run/media/me/new_partition/proc

*Make the root of your new partition the current root:
sudo chroot /run/media/me/new_partition/

*Install GRUB on the target drive (see this for more on what happens here):
grub-install /dev/sdb; grub-mkconfig -o /boot/grub/grub.cfg

*Exit chroot with Ctrl+d or exit

*Unmount virtual file systems and the partition itself:
sudo umount --recursive /run/media/me/new_partition

That's it, you should now be able to use your Linux install on new_partition residing on the drive /dev/sdb.


text:
Q: Why should copying luks headers with dd cause errors on the drive I am reading? Summary of the problem. I want to use a detached luks header for a luks-encrypted block device, /dev/nvme0n1p1, by making it into a USB flash drive partition, and afterwards erasing the keys that are on the header of the block device. I have limited details on how to do it, but my plan is to (1) set the size of the flash drive partition, /dev/sda3, to exactly the size of the header. Then (2) use dd if=/dev/nvme0n1p1 of=/dev/sda3 bs=4096 count=4096 to overwrite the space on the new partition with the header information. (3) Enter the header into the options of /etc/crypttab and generate new initramfs. I hoped this would work. But after I ran the dd-command (without yet editing crypttab) I tried to rebuild initramfs, but received the following error:
$ update-initramfs -u -k all
update-initramfs: Generating /boot/initrd.img-5.10.0-18-amd64
cryptsetup: ERROR: nvme0n1p1_crypt: Source mismatch
update-initramfs: Generating /boot/initrd.img-5.10.0-9-amd64
cryptsetup: ERROR: nvme0n1p1_crypt: Source mismatc

My questions are: (1) Why am I getting these errors? I don't understand why copying data should cause an error on the file system from which I am reading. (2) What's the right way to write the header to flash drive, if it is not with dd.
Details and any research.
I have searched google and stack exchange, and the seemingly most relevant thing was this. When I ran the command, I received the following information.
$ dmsetup info -c --noheadings -o devnos_used -- "nvme0n1p1_crypt"
259:1

Also this guide that I linked to above (in my opinion) seems to suggest that I should do it in this way.

A: When you bring up having to update the initramfs and crypttab, I presume this encrypted block device is part of your system's boot process? In which case, if you're going to be copying the header from the partition directly, the drive should be unmounted which would be ideal that you're performing all this from a USB Live-boot environment so that the drives aren't mounted, especially if the partition you're wanting to copy the header from is your primary system.
Assuming that is what you're doing, and you're currently attempting this from a USB Live boot environment (which would explain the error), make sure you've bind mounted the boot partition of the system you're trying to update the initramfs for as part of chrooting into the system to update it.
Buuuuuut....it should be noted that you wouldn't have any need to update your initramfs if you didn't make changes to crypttab yet, so I'm not sure I want to overload you with solutions that might not apply. So to back up a bit...
If you weren't trying this from a USB Live Boot environment, no worries, just follow option 2 of the guide you linked last where instead of using dd to copy the raw header directly, you can use cryptsetup to generate the backup header as a file, then write the file using dd to your USB flash drive partition as explained.
Whereas I've adopted their instructions to match your needs and added some notes in case anything was unclear (and identified each newline starting with a "$" to indicate it's the start of a new command:
 $ sudo -i
\\ just to ensure running everything below as root without a need to add sudo

$ mkdir /tmp/header_backup
$ mount -t tmpfs -o size=512m tmpfs /tmp/header_backup
\\ this user just took extra precaution by writing the backup header file to ramdisk
\\ which is unnecessary so u could just skip straight to the next step and designate
\\ somewhere normal like /home/USER/Documents if you wanted

$ cryptsetup luksHeaderBackup /dev/nvme0n1p1 --header-backup-file /tmp/header_backup/header.luks
$ dd if=/tmp/header_backup/header.luks of=/dev/sda3
$ umount /tmp/header_backup

\\ Then update crypttab, using your preferred text editor, here i use nano
\\ Here you're just appending the header option so if nvme0n1p1 is listed
\\ and shows as nvme0n1p1_crypt, then simply add it after the last option

$ nano /etc/crypttab

nvme0n1p1_crypt {UUID of /dev/nvme0n1p1} none luks,discard,header=/dev/sda3

\\ for nano, ctrl+x then Y then Enter & Enter again to exit and confirm saving
\\ At this point you're going to have 2 devices sharing the same UUID so
\\ you can address this by changing the one for the USB drive since it got
\\ changed when you copied the header to it, and saves you from updating fstab

$ cryptsetup luksUUID /dev/sda3 --uuid $(uuidgen)
\\ THEN you can run...

$ update-initramfs -u -k all

To be sure, /dev/nvme0n1p1 is the original LUKS drive and /dev/sda3 is the USB drive partition you want to store the header on.

Now, just to review your questions:

My questions are: (1) Why am I getting these errors? I don't
understand why copying data should cause an error on the file system
from which I am reading.

There's two possibilities I can think of that depend on specifically where you're running these commands from, as in, are you currently booted from a system that is located on nvme0n1p1? Or from a USB-Live Boot system where you are making the changes from a system totally separate from the one stored on nvme0n1p1? In the former, it's possible that /dev/sda3 was not unmounted before you wrote the header to that partition which would've changed the meta data of the USB partition while it's still mounted and confusing the system when running update-initramfs without any changes to the actual boot file settings or in the latter you didn't chroot into the system within nvme0n1p1 properly before running update-initramfs so it's reading the boot drive mounted in the Live-Boot and not the system you're updating. In either case, remember that crypttab refers to the mapped name of the partition, so whatever is in crypttab should match what is shown in your fstab as fstab is what mounts the drive by UUID and not by the device mappying name shown or used in crypttab
But, again, just remember that

(2) What's the right way to write the header to flash drive, if it is
not with dd.

Though there are other ways to write it, the way you're doing it is correct, it may just be a matter of what you're either not doing with that command (such as unmounting the partition before writing to it or if writing directly from another device that both devices are umounted)
If it helps, in following the last guide you linked that I modified the commands for above, bear in mind that your /dev/nvme0n1p1 is their /dev/sda4 and your /dev/sda3 is their /dev/sdb in the answer. Not to be confused with how in their question, it originally mentioned /dev/sda3 as their USB partition for the header as it was later changed when added an answer to their own question.


text:
Q: Remove words from permalink when saving post automatically? How can I automatically remove certain words from the automatically generated permalink (it uses %postname%).
For example: if a new post is created with the title:

How to remove certain words from the Wordpress permalink

I want to have an array of forbidden words like: certain, permalink
And then the slug would be saved automatically as as:
How-to-remove-words-from-the-wordpress
I don't want to affect old posts URLs just the new published ones.
I found plugins but they are too heavy, with millions of functions I just want to know how to modify the permalink while saving the post.

A: To update the slug of posts when they're published, hook to save_post action as in this answer. Also use sanitize_title() to perform the needed sensitization:
add_action( 'save_post', 'wpse325979_save_post_callback', 10, 2 );

function wpse325979_save_post_callback( $post_id, $post ) {

    // verify post is not a revision
    if ( ! wp_is_post_revision( $post_id ) ) {

        // unhook this function to prevent infinite looping
        remove_action( 'save_post', 'wpse325979_save_post_callback' );

        $title = $post->post_title;
        // remove forbidden keywords
        $forbidden = array('~certain~i', '~permalink~i'); //i modifier for case insensitive
        $title = preg_replace($forbidden, '', $title);

        // update the post slug
        $slug = sanitize_title($title);

        wp_update_post( array(
            'ID' => $post_id,
            'post_name' => $slug
        ));

        // re-hook this function
        add_action( 'save_post', 'wpse325979_save_post_callback' );

    }
}


text:
Q: Articulation point through non recursive DFS I wanted to find some way to find if root is an articulation point through non recursive approach. Through recursive approach we can recursively find number of non connected children of root. But I am not finding a way to do that without recursion.

A: I was able to write one algorithm that I thought might be working. Here it goes:
We have four states of any vertex. UNVISITED, VISITING, VISITED, REVISITING. We keep a dad array and an array that keeps count of unconnected children.

*

*We keep on adding vertices to stack starting from root but we dont pop the parent element. For example, we have root 1 connected to 2,3,6,7 then we push 1 to stack but dont pop it. Instead we push other children on top of it. And also we maintain dad for each element. For example, 2,3,6,7 have 1 as their dad.

*We mark nodes on the stack as VISITING if they were UNVISITED.

*If during any nodes adjacency list's traversal we find that some element is in VISITING state, we make its state REVISITING but only if this element is not its dad. For eg above all 2, 3 ,6, 7 are in VISITING state. Now if 7's adjacency list is 1, 3, 5, 10, 8, 12 then since 1 is its dad so we dont change state of 1. We go to 3 and see its state as VISITING and also its not 7's dad, we make its state as REVISITING. By now the stack is bottom to top as 1, 2, 3, 6, 7, 5, 10, 8, 12.

*Now if we come across any element in whose adjacency list there are no UNVISITED elements, if this element's state is VISITING state (not REVISITING) we add 1 to total count of its dad's children (initialized to 0). We ignore adding 1 to its dad's children number if it were in REVISITING state. Also we pop this element out of stack and make its state VISITED.

*Gradually popping elements we reach root's children (connected or unique). We check by step 4 to calculate number of unique unconnected children of the root. If its greater than 1 then root is an articulation point.
This algorithm seems bit complicated but seems to be working. Any suggestions or questions are welcome.


text:
Q: play2 java form binding - how to set field name to map to object? Say I have the below test case
I want to be able to bind camel case parameters:
anyData.put("my_id", "bob@gmail.com");

How can I get this test to pass??
public class FormBindingExampleTest {

    public static class FormBindingExampleModel {
        public String myid;
        public String email;

        public String getMyid() {
            return myid;
        }

        public void setMyid(String myid) {
            this.myid = myid;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }
    }

    @Test
    public void itShouldBindForm(){
        Form<FormBindingExampleModel> userForm = form(FormBindingExampleModel.class);

        Map<String,String> anyData = new HashMap();
        anyData.put("my_id", "bob@gmail.com");
        anyData.put("email", "secret");
        FormBindingExampleModel user = userForm.bind(anyData).get();

        System.out.println(user.myid);

        assert(user.myid.equals("bob@gmail.com"));
    }
}

A: Use form's fill() method inorder to populate the form with existing value.
@Test
public void itShouldBindForm(){
    Form<FormBindingExampleModel> userForm = form(FormBindingExampleModel.class);

    FormBindingExampleModel formModel = new FormBindingExampleModel();

    formModel.setMyid("bob@gmail.com");
    formModel.setEmail("secret");

    userForm.fill(formModel);

    FormBindingExampleModel user = userForm.get();

    System.out.println(user.getMyid);

    assert(user.getMyid.equals("bob@gmail.com"));
}

Documentation available here.


text:
Q: R Assign Same Value to Multiple Elements of a Vector I have trouble assigning the same value to the multiple elements of a vector. Here is my non-working example:
dog <- c()
year <- c(1980,1990)
for (i in 1:2){
     dog[(i*1):(i*12)]<- unique(year)[i]
}

I want the dog vector to have twelve 1980 and twelve 1990. But instead I get a 1980 and 1990 followed by 22 NAs. What's the next step?

A: If you unroll the loop, what you're doing is
dog <- c()
year <- c(1980,1990)
dog[1:12]<- unique(year)[1]
dog[2:24]<- unique(year)[2]

which is
 [1] 1980 1990 1990 1990 1990 1990 1990 1990 1990 1990
[11] 1990 1990 1990 1990 1990 1990 1990 1990 1990 1990
[21] 1990 1990 1990 1990

the second assignment pretty much overwrites everything. I'm not sure if you want the values to alternate or if you want the values grouped together, but you can easily create such a vector with
rep(year, each=12)
#  [1] 1980 1980 1980 1980 1980 1980 1980 1980 1980 1980
# [11] 1980 1980 1990 1990 1990 1990 1990 1990 1990 1990
# [21] 1990 1990 1990 1990

or
rep(year, times=12)
#  [1] 1980 1990 1980 1990 1980 1990 1980 1990 1980 1990
# [11] 1980 1990 1980 1990 1980 1990 1980 1990 1980 1990
# [21] 1980 1990 1980 1990