Setting a defaultValue for TimePicker using redux-form and materialUI?

Question: I can't make any version of setting a defaultValue (or defaultTime or even just value) work for initializing a TimePicker in redux-form from state. All other fields populate correctly, but date/time pickers don't respond to anything. Help is muuuuch appreciated!
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';

import moment from 'moment';

import { Field, reduxForm, FieldArray, formValueSelector } from 'redux-form';
import MenuItem from 'material-ui/MenuItem';
import {
  SelectField,
  TextField,
  DatePicker,
  TimePicker
} from 'redux-form-material-ui';

const selector = formValueSelector('myPantry');

let ServiceGroup = ({ service, index, fields, isAppointment, serviceDate }) =>

Service

    <button
      type="button"
      className="remove-button"
      onClick={() => fields.remove(index)}>Remove
    </button>

      <Field
        name={`${service}.day`}
        component={SelectField}
        floatingLabelText="Day of week"
        className="textfield">
          <MenuItem value={1} primaryText="Monday" />
          <MenuItem value={2} primaryText="Tuesday" />
      </Field>
      <Field
        name={`${service}.from_time`}
        component={TimePicker}
        value={null}
        floatingLabelText="From"
        className="textfield"
      />
      <Field
        name={`${service}.until_time`}
        component={TimePicker}
        value={null}
        floatingLabelText="To"
        className="textfield"
      />

      <Field
        name={`${service}.service_type`}
        component={SelectField}
        floatingLabelText="Service type"
        className="textfield">
        <MenuItem value={1} primaryText="First-come first-served" />
        <MenuItem value={2} primaryText="Appointment" />
      </Field>

    {isAppointment &&

        <Field
          name={`${service}.max_people`}
          type="number"
          component={TextField}
          label="Number of people per timeslot"
          className="textfield"
        />

    }

;

ServiceGroup = connect(
  (state, props) => ({
    isAppointment: selector(state, `${props.service}.service_type`) == 2,
    serviceDate: selector(state, `${props.service}.from_time`)
  })
)(ServiceGroup);

class MyPantry extends Component {
  static propTypes = {
    onSubmit: PropTypes.func.isRequired
  }

  constructor(props, context) {
    super(props, context);
  }

  renderGroups = ({ fields, meta: { touched, error } }) => {
    return (

        {fields.map((service, index) =>
          <ServiceGroup service={service} fields={fields} index={index} key={index} />
        )}
        <button
          type="button"
          className="action-button"
          onClick={() => fields.push({})}>Add Service
        </button>
        {touched && error && {error}}

    );
  }

  render() {
    const { handleSubmit } = this.props;
    return (
      <form onSubmit={handleSubmit}>

          <Field
            name="name"
            type="text"
            component={TextField}
            label="Pantry name"
            floatingLabelText="Pantry name"
            className="textfield full"
          />

            <Field
              name="address_street_1"
              type="text"
              component={TextField}
              label="Address"
              floatingLabelText="Address"
              className="textfield"
            />
            <Field
              name="address_street_2"
              type="text"
              component={TextField}
              label="Apartment, suite, etc."
              floatingLabelText="Apartment, suite, etc."
              className="textfield"
            />

Service Setup

          <FieldArray name="service_options" component={this.renderGroups} />

          <button type="submit" className="action-button">Save Pantry Details</button>

      </form>
    );
  }

}

MyPantry = reduxForm({
  form: 'myPantry'
})(MyPantry);

MyPantry = connect(
  state => ({
    initialValues: state.pantry.data
  })
)(MyPantry);

export default MyPantry;

Comment: My answer below is correct response, view if you need help with these.
Answer: To set default time of TimePicker:
<TimePicker hintText="Pick your time" defaultTime={new Date(2007, 11, 5, 8, 23, 17)} />

here is a working JSFiddle: https://jsfiddle.net/mu5r94m6/2/
Comment: It works outside of redux-form/redux-form-material-ui like your example, but the above version using redux-form won't register defaultTime.

Figured out in componentDidMount, can change (or just reaffirm) TimePicker values in the form state and cause the component to re-render correctly, but it just feels yucky AND can't get it to work for FieldArrays yet (where I need it), so not a totally viable solution. Example of changing normal field (not a field array):

    componentDidMount() {
        this.props.change('images', this.props.register.returnData.pantry.images);
      }
Answer: You're using this.props.pantry... inside your renderGroups().
You need to bind that function to be able to use this
add a constructor to the class and use bind on that function
constructor(props) {
    super(props);
    this.renderGroups = this.renderGroups.bind(this);
}

Comment: Not the issue, unfortunately - I can't even put in a hardcoded date object and it show up. It won't populate anything at all.
Comment: I don't think you can use defaultValue on a redux-form `Field`. They are all controlled. The only way to add a default value is to initialize the form with the default value in `initialValues` option or `fields.push({ fromTime: moment(...)})`. How are you adding items to the `FieldArray`?
Answer: Can now pass format={null} to Time and Date pickers for this. See thread/closed issue here: https://github.com/erikras/redux-form-material-ui/issues/37
and can view tweets that start here: https://twitter.com/megkadams/status/804363887428665345 and continue here: https://twitter.com/megkadams/status/804369699693793280
    <Field
      name={`${service}.from_time`}
      component={TimePicker}
      format={(value, name) => {
        if (fromTime) {
          return value === '' ? null : new Date(fromTime)
        } else {
          return null;
        }
      }}
      defaultValue={null}
      pedantic
      floatingLabelText="From"
      className="textfield"
    />


Criar uma planilha com nomes de pastas listadas de um diretório no excel

Question: Estou utilizando esse código para listar as pastas que contem alguns nomes que preciso planilhar.
Option Explicit

Sub CreateList()
    Application.ScreenUpdating = False
    Workbooks.Add    ' create a new workbook for the folder list
    ' add headers
    With Cells(1, 1)
        .Value = "Folder contents:"
        .Font.Bold = True
        .Font.Size = 12
    End With
    Cells(3, 1).Value = "Folder Path:"
    Cells(3, 2).Value = "Folder Name:"
    Cells(3, 3).Value = "Size:"
    Cells(3, 4).Value = "Subfolders:"
    Cells(3, 5).Value = "Files:"
    Cells(3, 6).Value = "Short Name:"
    Cells(3, 7).Value = "Short Path:"
    Range("A3:G3").Font.Bold = True
    ListFolders BrowseFolder, True
    Application.ScreenUpdating = True
End Sub

Sub ListFolders(SourceFolderName As String, IncludeSubfolders As Boolean)
    ' lists information about the folders in SourceFolder
    Dim FSO    As Scripting.FileSystemObject
    Dim SourceFolder As Scripting.Folder, SubFolder As Scripting.Folder
    Dim r      As Long
    Set FSO = New Scripting.FileSystemObject
    Set SourceFolder = FSO.GetFolder(SourceFolderName)
    ' display folder properties
    r = Cells(Rows.Count, 1).End(xlUp).Row + 1
    Cells(r, 1).Value = SourceFolder.Path
    Cells(r, 2).Value = SourceFolder.Name
    Cells(r, 3).Value = SourceFolder.Size
    Cells(r, 4).Value = SourceFolder.SubFolders.Count
    Cells(r, 5).Value = SourceFolder.Files.Count
    Cells(r, 6).Value = SourceFolder.ShortName
    Cells(r, 7).Value = SourceFolder.ShortPath
    If IncludeSubfolders Then
        For Each SubFolder In SourceFolder.SubFolders
            ListFolders SubFolder.Path, True
        Next SubFolder
        Set SubFolder = Nothing
    End If
    Columns("A:G").AutoFit
    Set SourceFolder = Nothing
    Set FSO = Nothing
    ActiveWorkbook.Saved = True

End Sub

O que eu gostaria é que toda vez que eu executasse o macro e por exemplo selecionasse a pasta "Julho" ele criasse uma nova planilha dentro da minha atual e listasse os nomes que estão dentro da pasta ( o que esse código já faz) mas gostaria que fosse em formato de planilha e que ele desse o nome da pasta pra planilha recém criada.

Então na tela inicial iria ficar o botão com o macro e o total de processos listados de todos os meses e de cada mês individual (o que eu ainda vou descobrir como fazer) e cada planilha vai ter seus processos listados com o nome do mês que ela pertence.
É possível fazer algo desse tipo ?
Answer: Bom dia!
Segue um exemplo, vai precisar de adaptações.
A ideia basicamente é verificar se existe uma planilha com o nome do mês, caso contrário, cria uma nova e renomeia em seguida.
Sub ListFolders(SourceFolderName As String, IncludeSubfolders As Boolean)
    ' lists information about the folders in SourceFolder
    Dim FSO    As Scripting.FileSystemObject
    Dim SourceFolder As Scripting.Folder, SubFolder As Scripting.Folder
    Dim r      As Long
    Set FSO = New Scripting.FileSystemObject
    Set SourceFolder = FSO.GetFolder(SourceFolderName)

    '========================================================================
    'Verifica se a plan existe, caso contrário, cria uma nova com o nome atual
    Dim qtd As Single
    Dim existe As Boolean

    For qtd = 1 To ActiveWorkbook.Sheets.Count
        If UCase(Sheets(qtd).Name) = "JANEIRO" Then
            existe = True
            Exit For
        End If

        If UCase(Sheets(qtd).Name) = "FEVEREIRO" Then
            existe = True
            Exit For
        End If

        'completar os demais meses

    Next

    'Cria a pasta caso não exista
    If Not existe Then
        Sheets.Add
        ActiveSheet.Name = SourceFolderName
    End If

    '========================================================================

    ' display folder properties
    r = Cells(Rows.Count, 1).End(xlUp).Row + 1
    Cells(r, 1).Value = SourceFolder.Path
    Cells(r, 2).Value = SourceFolder.Name
    Cells(r, 3).Value = SourceFolder.Size
    Cells(r, 4).Value = SourceFolder.SubFolders.Count
    Cells(r, 5).Value = SourceFolder.Files.Count
    Cells(r, 6).Value = SourceFolder.ShortName
    Cells(r, 7).Value = SourceFolder.ShortPath
    If IncludeSubfolders Then
        For Each SubFolder In SourceFolder.SubFolders
            ListFolders SubFolder.Path, True
        Next SubFolder
        Set SubFolder = Nothing
    End If
    Columns("A:G").AutoFit
    Set SourceFolder = Nothing
    Set FSO = Nothing
    ActiveWorkbook.Saved = True

End Sub

Answer: Pastas
Para criar uma planilha com o nome da Pasta e preencher na coluna A, utilize o seguinte código, em que a explicação está comentada no código:
Option Explicit
Sub Listar_Pastas()
    ''''''''''''''''''''
    '====  Pastas  ===='
    ''''''''''''''''''''
    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Dim xPath As String, xDir As String
    Dim xWs_pastas As Worksheet
    Dim fso As Object
    Dim fso_FOLDER As Object
    Dim fso_folders As Object
    Dim i As Long

    Set fso = CreateObject("Scripting.FileSystemObject")

    'Janela para escolher a pasta do diretório desejado
    With Application.FileDialog(msoFileDialogFolderPicker)
        .Title = "Escolha a pasta"
        .Show
    End With
    On Error Resume Next
    xPath = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1) & "\"

    If xPath = "" Then
        GoTo CleanExit                           'Se o caminho da pasta não existir
    End If
    'Define novo Objeto FSO GetFolder
    Set fso_FOLDER = fso.GetFolder(xPath)
    xDir = fso_FOLDER.Name
    'Apaga se houver planilha com mesmo nome existente
    CriarPlanilha (xDir)
    'Define nova planilha da pasta
    Set xWs_pastas = ThisWorkbook.Sheets(xDir)

    'https://stackoverflow.com/a/31428399/7690982
    'Encontra todos os Arquivos
    i = 1
    If fso_FOLDER.subFolders.Count > 0 Then
        'Loop em cada pasta do diretório escolhido
        For Each fso_folders In fso_FOLDER.subFolders
            With xWs_pastas
                'Preenche a coluna A com a lista de arquivos
                    .Cells(i, "A") = fso_folders.Name
            End With
            i = i + 1
        Next fso_folders
    Else
        MsgBox "Nenhuma pasta encontrada em " & xPath
        GoTo CleanExit
    End If

    'Sair do código
CleanExit:

    Set fso = Nothing
    Set fso_FOLDER = Nothing
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
    Application.EnableEvents = True
    If Err.Number <> 0 Then MsgBox "Ocorreu um erro em: " & Err.Number & " " & Err.Description
End Sub

Public Function CriarPlanilha(Name As String)
    Dim s As Worksheet, t As String
    Dim i As Long, k As Long
    Dim t_exists As Boolean
    k = ThisWorkbook.Sheets.Count
    t_exists = False
    'Verifica em todas as planilhas se o nome já existe
    For i = k To 1 Step -1
        t = ThisWorkbook.Sheets(i).Name
        If t = Name Then
            'Se existir, limpa o conteúdo
            t_exists = True
            Application.DisplayAlerts = False
            ThisWorkbook.Sheets(i).UsedRange.ClearContents
            Application.DisplayAlerts = True
        End If
    Next i
    'Se não existir, cria nova planilha
    If t_exists = False Then
            ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(k)).Name = Name
    End If
End Function

Subpastas e mais dados
Caso deseje também os subdiretórios e outros dados de diretório, utilize o seguinte código:
Option Explicit
Sub Listar_Subdir()
    ''''''''''''''''''''
    '====  Subdir  ===='
    ''''''''''''''''''''
    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Dim xDir As String, xDirName As String
    Dim xWs As Worksheet
    Dim ncell As Long
    Dim vaArray     As Variant
    Dim i As Long, j As Long
    Dim folder As Object, fso As Object

    'https://www.extendoffice.com/documents/excel/2994-excel-list-all-files-in-folder-and-subfolders.html
    'Updateby20150706
    Set folder = Application.FileDialog(msoFileDialogFolderPicker)
    Set fso = CreateObject("Scripting.FileSystemObject")
    'Escolher a pasta desejada
    With folder
        .Title = "Escolha a pasta"
    End With
    If folder.Show <> -1 Then GoTo CleanExit
    On Error Resume Next
    xDir = folder.SelectedItems(1) & "\"
    xDirName = fso.GetFolder(xDir).Name
    'Cria a planilha com o nome do Diretório
    SheetKiller (xDirName)
    ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(Sheets.Count)).Name = xDirName
    Set xWs = ThisWorkbook.Sheets(xDirName)
    'Cria a Lista de Subdiretórios na planilha xWs
    ListFilesInFolder xDir, True, xWs

    'Sair do código
CleanExit:
    Set fso = Nothing
    Set folder = Nothing
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
    Application.EnableEvents = True
    If Err.Number <> 0 Then MsgBox "Ocorreu um erro em: " & Err.Number & " " & Err.Description
End Sub

Public Sub ListFilesInFolder(ByVal xFolderName As String, ByVal xIsSubfolders As Boolean, xWs As Worksheet)
    Dim xFileSystemObject As Object
    Dim xFolder As Object
    Dim xSubFolder As Object
    Dim xFolderChild As Object
    Dim rowIndex As Long
    Set xFileSystemObject = CreateObject("Scripting.FileSystemObject")
    Set xFolder = xFileSystemObject.GetFolder(xFolderName)
    rowIndex = xWs.Range("A" & xWs.Rows.Count).End(xlUp).Row + 1
    For Each xSubFolder In xFolder.SubFolders
        With xWs
            .Cells(rowIndex, 1) = xSubFolder.Path
            .Cells(rowIndex, 2) = xSubFolder.Name
            .Cells(rowIndex, 3) = xSubFolder.Size
            .Cells(rowIndex, 4) = xSubFolder.ShortName
            .Cells(rowIndex, 5) = xSubFolder.ShortPath
            .Cells(rowIndex, 6) = xSubFolder.DateCreated
            .Cells(rowIndex, 7) = xSubFolder.DateLastAccessed
            .Cells(rowIndex, 8) = xSubFolder.DateLastModified
        End With
        rowIndex = rowIndex + 1
    Next xSubFolder
    If xIsSubfolders Then
        For Each xFolderChild In xFolder.SubFolders
            ListFilesInFolder xFolderChild.Path, True, xWs
        Next xFolderChild
    End If
    Set xSubFolder = Nothing
    Set xFolder = Nothing
    Set xFileSystemObject = Nothing
End Sub

Public Function SheetKiller(Name As String)
    Dim s As Worksheet, t As String
    Dim i As Long, k As Long
    k = ThisWorkbook.Sheets.Count

    For i = k To 1 Step -1
        t = ThisWorkbook.Sheets(i).Name
        If t = Name Then
            Application.DisplayAlerts = False
            ThisWorkbook.Sheets(i).Delete
            Application.DisplayAlerts = True
        End If
    Next i
End Function

Comment: Gostaria de saber como eu faço pra ele começar a listar a partir da linha A2, gostaria de colocar os títulos pra identificar na primeira linha. Gravei um macro pra ele criar uma planilha com esse dados e deixar bonitinho, mas tem que definir onde começa e onde termina e eu queria que ele criasse a planilha apenas até onde contem texto
Comment: @PauloCordeiro No primeiro código, mude de `i = 1` para `i = 2`, já no segundo você precisará ou adicionar o título pelo código na linha 1 ou criar uma condicional `if`, para verificar se não tiver nada preenchido, pular para a segunda linha.
Comment: Muito obrigado cara me ajudou bastante, depois dessas experiencias que tive com alguns programas VBA estou até pensando em cursar algo relacionado á área quando acabar o ensino médio
Comment: Desculpe voltar novamente aqui, mas tive que mudar algumas coisas na planilha e agora não consigo mais fazer ela funcionar, eu gostaria de mudar a ideia inicial de apagar a planilha caso ela já exista para limpar toda ela (exceto a celula G1), depois selecionar ela e listar normalmente, consegui alterar a função SheetKiller pra limpar porém não consigo fazer funcionar a partir dai pois sempre aparece um erro diferente, eu imagino que tenha que tirar a parte do Sheet.Add e mudar pra algum código que apenas leve você para a sheet escolhida
Comment: Isso tudo pq quando a planilha é apagada estraga uma tabela dinâmica que puxa um dado da linha G1, mesmo ela sendo criada novamente com o mesmo nome não dá certo, então se houver uma maneira de manter isso, o código original pode se manter também
Comment: @PauloCordeiro Veja o edit.


Can not record during calls

Question: I'm using React Native to implement an Android app that helps us record outgoing calls.
After the user types a phone number and clicks call, I start Recorder and then navigate the user to the phone screen to make a call.
The issue is that I only record voice before and after the user dials. nothing during the call.
I tested on a Nokia C31 (android 12)
here is my code.
import AudioRecorderPlayer, {
  AudioEncoderAndroidType,
  AudioSet,
  AudioSourceAndroidType,
} from 'react-native-audio-recorder-player';
import dayjs from 'dayjs';
import RNFetchBlob from 'rn-fetch-blob';
const dirs = RNFetchBlob.fs.dirs;

const audioSet: AudioSet = {
  AudioEncoderAndroid: AudioEncoderAndroidType.DEFAULT,
  AudioSourceAndroid: AudioSourceAndroidType.VOICE_COMMUNICATION,
};

export default function Dialer() {
  // other states...
  const audioRecorderPlayer = useRef(new AudioRecorderPlayer());

  const startRecording = async () => {
    const formattedDate = dayjs().format('DD-MMM-YYYY_hh-mm-ss-A');
    const fileName = `${dirs.CacheDir}/call-record_${formattedDate}.mp3`;
    console.log(fileName);
    setAudioPath(fileName);
    try {
      setIsRecording(true);
      const result = await audioRecorderPlayer.current.startRecorder(
        fileName,
        audioSet,
        true,
      );
      console.log('start recording', result);
    } catch (error) {
      console.error('Error starting recording:', error);
    }
  };

  const handleCall = () => {
    if (!isRecording) {
      startRecording();
      console.log('called');
      Linking.openURL(`tel:${number}`);
    }
  };
//...
}

permissions requested
const permissions = [
  PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
  PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
  PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
  PermissionsAndroid.PERMISSIONS.CALL_PHONE,
];

here is my manifest
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.CAPTURE_AUDIO_OUTPUT" />

I think I need to use the VOICE_CALL instead of VOICE_COMMUNICATION.
but VOICE_CALL needs android.permission.CAPTURE_AUDIO_OUTPUT.
according to the documentation:
This permission is reserved for use by system components and is not available to third-party applications.
when I use VOICE_CALL, I can not start the Recorder (get error)
Comment: I think this is why rooting was done
Comment: @FaysalB, no I can not root devices.
Answer: Only system apps can use VOICE_CALL.  This is for security reasons.  Android does not allow any app to get the audio of a call, except for preinstalled apps from the OEM.  The only way you can record a call as an app on Android is to use the normal microphone and hope the volume of the call is loud enough that it gets picked up.
Comment: Also, from my reading of that, it can receive audio input.  That means that it will allow you to process input from the mic, and would still need the special permission to receive call audio even as an accessibility service.  This seems mainly used to allow such services to process voice commands also sent to the app.  Although I haven't tested, so maybe it would attempt to allow it for transcription purposes.
Comment: I haven't.  But I can tell you that the Play Store will absolutely not allow you to use AccessibilityService to save calls for management.  If this is side loaded that's fine, but if it's downloaded from the Play Store it's going to be a blocker.
Comment: but according to [this documents](https://developer.android.com/guide/topics/media/platform/sharing-audio-input#voice_call_ordinary_app), if we create an AccessibilityService we can get the voice call audio, right?
Comment: If you're not actually providing accessibility, then you won't be allowed to use an AccessibilityService.  The Play store rejects any app that uses that permission inappropriately.
Comment: did you do this feature before? is there any other way to do that? I just want to save my agents's calls for management

Can not record during calls


Find an integer $N$ such that when $n≥N$, $ \left| U \left( \ln,P_n \right)-\int_1^2 {\ {\ln \left( x \right) }}\,dx \right|<ε\,\,? $

Question: With
$\,U \left( \ln,P_{{n}} \right) =\sum _{i=1}^{n}\ln  \left( 1+{\frac {i}{n}} \right) \frac {1}{n}
$
and
$\,L \left( \ln,P_{{n}} \right) =\sum _{i=1}^{n}\ln  \left( 1+{\frac {i-1}{n}} \right) \frac {1}{n}
$
I get
$$
U \left( \ln,P_{{n}} \right)-L \left( \ln,P_{{n}} \right)={\frac {\ln  \left( 2 \right) }{n}}.
$$
For all $ε>0$, and $\,U \left( \ln,P_{{n}} \right) =\sum _{i=1}^{n}\ln  \left( 1+{\frac {i}{n}} \right) \frac {1}{n}\,\,$, how do I proceed to show that there exists an integer $N$ such that when $n≥N$, when
$$
\left| U \left( \ln,P_n \right)-\int_1^2 {\ {\ln  \left( x \right) }}\,dx \right|<ε\,\,?
$$
All help appreciated
Answer: $\log(x)$ is a continuous and bounded function on the interval $(1,2)$, hence it is a Riemann integrable function and
$$ \lim_{n\to +\infty}\left|U(f,P_n)-\int_{1}^{2}\log(x)\,dx\right|=0$$
follows from the very definition of Riemann integrability. Explicit bounds can be derived from the Hermite-Hadamard inequality, since $\log(x)$ is a concave function on $[1,2]$. In particular:
$$\frac{1}{n}\left[\frac{1}{2}\log(1)+\log\left(1+\frac{1}{n}\right)+\ldots+\log\left(1+\frac{n-1}{n}\right)+\frac{1}{2}\log(2)\right]\leq \int_{1}^{2}\log(x)\,dx $$
and
$$ \int_{1}^{2}\log(x)\,dx \leq \frac{1}{n}\left[\log\left(1+\frac{1}{n}\right)+\ldots+\log\left(1+\frac{n-1}{n}\right)+\log(2)\right]$$
is trivial, hence $U(f,P_n)-\int_{1}^{2}\log(x)\,dx$ is bounded by $\frac{\log(2)}{2n}$ in absolute value.
Comment: DAurizio. After considering Your answer, which at first looked straight forward, I realize I don't fully understand it. Assume we know that $\,U \left( f,P_{{n}} \right) =\sum _{i=1}^{n}\ln  \left( 1+{\frac {i}{n}} \right) \frac {1}{n}$. Now, for $ε>0$, I want to show that there exist an integer $N$, such that when $n≥N$, then $\left| U \left( f,P_n \right)-\int_1^2 {\ {\ln  \left( x \right) }}\,dx \right|<ε\,\,$ holds. In Your answer You reach the conclusion that $U(f,P_n)-\int_{1}^{2}\log(x)\,dx$ is bounded by $\frac{\log(2)}{2n}$. Is that similar to say that $\frac{\log(2)}{2N}<ε\,$?
Comment: @Ludvig: for any $\epsilon>0$, as soon as $N$ is large enough, $\frac{\log 2}{2N}<\varepsilon$ holds.
Comment: why does everbody write $U(f,P_n)$ without mentioning that $f=\log$ you could just write $U(\log,P_n)$...
Answer: You were very close. Just recall that
$$L(f,P_n) \le \int _1^2 \ln x\, dx \le U(f,P_n).$$
This says $\int _1^2 \ln x\, dx$ lies in the interval $[L(f,P_n),U(f,P_n)].$ Thus the distance from $\int _1^2 \ln x\, dx$ to the upper end point – and this is what you are estimating – is bounded above by the length of the interval, which, as you found, is $(\ln 2)/n.$ Therefore any $N$ such that $\frac{\ln 2}{N} <\epsilon$ will work.


Unity C# error CS0411

Question: Estou tendo um erro em 4 códigos no qual eu não entendo o erro. O erro que está me retornado é este: error CS0411: The type arguments for method 'Component.GetComponent<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly.
E este erro também ao tenta colocar os Scripts no Objetos no jogo. Não sei se esses dois erro tem comum.
porem venho ate aqui procurar ajuda

Os códigos
using UnityEngine;

public class Bullet : MonoBehaviour
{
    void Start()
    {
        GetComponent().AddForce(transform.up * 350); // ---- erro da linha
    }

    public void KillOldBullet()
    {
        Destroy(gameObject, 2.0f);
    }

    void OnCollisionEnter(Collision collisionInfo)
    {
        Destroy(gameObject, 0.0f);
    }
}

-
using UnityEngine;

public class Gameplay : MonoBehaviour
{

    public GameObject asteroid;
    public GameObject rocket;
    private int _startLevelAsteroidsNum;
    private bool _allAsteroidsOffScreen;
    private int levelAsteroidNum;
    private Camera mainCam;
    private int asteroidLife;

    private void Start()
    {
        asteroid.SetActive(false);
        mainCam = Camera.main;
        _startLevelAsteroidsNum = 2;
        CreateAsteroids(_startLevelAsteroidsNum);
    }

    private void Update()
    {
        RenderSettings.skybox.SetFloat("_Rotation", Time.time * 0.8f);

        if (asteroidLife <= 0)
        {
            asteroidLife = 6;
            CreateAsteroids(1);
        }

        float sceneWidth = mainCam.orthographicSize * 2 * mainCam.aspect;
        float sceneHeight = mainCam.orthographicSize * 2;
        float sceneRightEdge = sceneWidth / 2;
        float sceneLeftEdge = sceneRightEdge * -1;
        float sceneTopEdge = sceneHeight / 2;
        float sceneBottomEdge = sceneTopEdge * -1;

        _allAsteroidsOffScreen = true;

    }

    private void CreateAsteroids(float asteroidsNum)
    {
        for (int i = 1; i <= asteroidsNum; i++)
        {
            GameObject AsteroidClone = Instantiate(asteroid, new Vector2(Random.Range(-10, 10), 6f), transform.rotation);
            AsteroidClone.GetComponent().SetGeneration(1); // ------ linha da erro
            AsteroidClone.SetActive(true);
        }
    }

    public void RocketFail()
    {
        Cursor.visible = true;
        print("GAME OVER");
    }

    public void asterodDestroyed()
    {
        asteroidLife--;
    }

    public int startLevelAsteroidsNum
    {
        get { return _startLevelAsteroidsNum; }
    }

    public bool allAsteroidsOffScreen
    {
        get { return _allAsteroidsOffScreen; }
    }

}

-
using UnityEngine;

public class Rocket : MonoBehaviour
{
    public GameObject bullet;
    private float thrust = 6f;
    private float rotationSpeed = 180f;
    private float MaxSpeed = 4.5f;
    private Camera mainCam;
    private Rigidbody rb;

    private void Start()
    {
        mainCam = Camera.main;
        rb = GameObject.Find("rb").GetComponent(); // ------ linha da erro
        bullet.SetActive(false);
    }

    private void FixedUpdate()
    {
        ControlRocket();
        CheckPosition();
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0) || Input.GetKeyDown("space"))
        {
            Shoot();
        }
    }

    private void ControlRocket()
    {
        transform.Rotate(0, 0, Input.GetAxis("Horizontal") * rotationSpeed * Time.deltaTime);
        rb.AddForce(transform.up * thrust * Input.GetAxis("Vertical"));
        rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -MaxSpeed, MaxSpeed), Mathf.Clamp(rb.velocity.y, -MaxSpeed, MaxSpeed));
    }

    private void CheckPosition()
    {

        float sceneWidth = mainCam.orthographicSize * 2 * mainCam.aspect;
        float sceneHeight = mainCam.orthographicSize * 2;

        float sceneRightEdge = sceneWidth / 2;
        float sceneLeftEdge = sceneRightEdge * -1;
        float sceneTopEdge = sceneHeight / 2;
        float sceneBottomEdge = sceneTopEdge * -1;

        if (transform.position.x > sceneRightEdge)
        {
            transform.position = new Vector2(sceneLeftEdge, transform.position.y);
        }
        if (transform.position.x < sceneLeftEdge) { transform.position = new Vector2(sceneRightEdge, transform.position.y); }
        if (transform.position.y > sceneTopEdge)
        {
            transform.position = new Vector2(transform.position.x, sceneBottomEdge);
        }
        if (transform.position.y < sceneBottomEdge)
        {
            transform.position = new Vector2(transform.position.x, sceneTopEdge);
        }
    }

    public void ResetRocket()
    {
        transform.position = new Vector2(0f, 0f);
        transform.eulerAngles = new Vector3(0, 180f, 0);
        rb.velocity = new Vector3(0f, 0f, 0f);
        rb.angularVelocity = new Vector3(0f, 0f, 0f);
    }

    void Shoot()
    {
        GameObject BulletClone = Instantiate(bullet, new Vector2(bullet.transform.position.x, bullet.transform.position.y), transform.rotation);
        BulletClone.SetActive(true);
        BulletClone.GetComponent().KillOldBullet(); // ------ linha da erro
        BulletClone.GetComponent().AddForce(transform.up * 350); // ------ linha da erro
    }
}

-
using UnityEngine;

public class Asteroid : MonoBehaviour
{

    public GameObject rock;
    public Gameplay gameplay;
    private float maxRotation;
    private float rotationX;
    private float rotationY;
    private float rotationZ;
    private Rigidbody rb;
    private Camera mainCam;
    private float maxSpeed;
    private int _generation;

    void Start()
    {

        mainCam = Camera.main;

        maxRotation = 25f;
        rotationX = Random.Range(-maxRotation, maxRotation);
        rotationY = Random.Range(-maxRotation, maxRotation);
        rotationZ = Random.Range(-maxRotation, maxRotation);

        rb = rock.GetComponent(); // ------ linha da erro

        float speedX = Random.Range(200f, 800f);
        int selectorX = Random.Range(0, 2);
        float dirX = 0;
        if (selectorX == 1) { dirX = -1; }
        else { dirX = 1; }
        float finalSpeedX = speedX * dirX;
        rb.AddForce(transform.right * finalSpeedX);

        float speedY = Random.Range(200f, 800f);
        int selectorY = Random.Range(0, 2);
        float dirY = 0;
        if (selectorY == 1) { dirY = -1; }
        else { dirY = 1; }
        float finalSpeedY = speedY * dirY;
        rb.AddForce(transform.up * finalSpeedY);

    }

    public void SetGeneration(int generation)
    {
        _generation = generation;
    }

    void Update()
    {
        rock.transform.Rotate(new Vector3(rotationX, rotationY, 0) * Time.deltaTime);
        CheckPosition();
        float dynamicMaxSpeed = 3f;
        rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -dynamicMaxSpeed, dynamicMaxSpeed), Mathf.Clamp(rb.velocity.y, -dynamicMaxSpeed, dynamicMaxSpeed));
    }

    void OnCollisionEnter(Collision collisionInfo)
    {
        if (collisionInfo.collider.name == "Bullet(Clone)")
        {
            if (_generation < 3)
            {
                CreateSmallAsteriods(2);
            }
            Destroy();
        }

        if (collisionInfo.collider.name == "Rocket")
        {
            gameplay.RocketFail();
        }
    }

    void CreateSmallAsteriods(int asteroidsNum)
    {
        int newGeneration = _generation + 1;
        for (int i = 1; i <= asteroidsNum; i++)
        {
            float scaleSize = 0.5f;
            GameObject AsteroidClone = Instantiate(rock, new Vector3(transform.position.x, transform.position.y, 0f), transform.rotation);
            AsteroidClone.transform.localScale = new Vector3(AsteroidClone.transform.localScale.x * scaleSize, AsteroidClone.transform.localScale.y * scaleSize, AsteroidClone.transform.localScale.z * scaleSize);
            AsteroidClone.GetComponent().SetGeneration(newGeneration); // ------ linha da erro
            AsteroidClone.SetActive(true);
        }
    }

    private void CheckPosition()
    {

        float sceneWidth = mainCam.orthographicSize * 2 * mainCam.aspect;
        float sceneHeight = mainCam.orthographicSize * 2;
        float sceneRightEdge = sceneWidth / 2;
        float sceneLeftEdge = sceneRightEdge * -1;
        float sceneTopEdge = sceneHeight / 2;
        float sceneBottomEdge = sceneTopEdge * -1;

        float rockOffset;
        if (gameplay.allAsteroidsOffScreen)
        {
            rockOffset = 1.0f;
            float reverseSpeed = 2000.1f;

            if (rock.transform.position.x > sceneRightEdge + rockOffset)
            {
                rock.transform.rotation = Quaternion.identity;
                rb.AddForce(transform.right * (reverseSpeed * (-1)));
            }

            if (rock.transform.position.x < sceneLeftEdge - rockOffset) { rock.transform.rotation = Quaternion.identity; rb.AddForce(transform.right * reverseSpeed); }
            if (rock.transform.position.y > sceneTopEdge + rockOffset)
            {
                rock.transform.rotation = Quaternion.identity;
                rb.AddForce(transform.up * (reverseSpeed * (-1)));
            }

            if (rock.transform.position.y < sceneBottomEdge - rockOffset) { rock.transform.rotation = Quaternion.identity; rb.AddForce(transform.up * reverseSpeed); }
        }
        else
        {
            rockOffset = 2.0f; if (rock.transform.position.x > sceneRightEdge + rockOffset)
            {
                rock.transform.position = new Vector2(sceneLeftEdge - rockOffset, rock.transform.position.y);
            }

            if (rock.transform.position.x < sceneLeftEdge - rockOffset) { rock.transform.position = new Vector2(sceneRightEdge + rockOffset, rock.transform.position.y); }
            if (rock.transform.position.y > sceneTopEdge + rockOffset)
            {
                rock.transform.position = new Vector2(rock.transform.position.x, sceneBottomEdge - rockOffset);
            }

            if (rock.transform.position.y < sceneBottomEdge - rockOffset)
            {
                rock.transform.position = new Vector2(rock.transform.position.x, sceneTopEdge + rockOffset);
            }
        }
    }

    public void Destroy()
    {
        gameplay.asterodDestroyed();
        Destroy(gameObject, 0.01f);
    }

    public void DestroySilent()
    {
        Destroy(gameObject, 0.00f);
    }

}

Comment: https://docs.unity3d.com/ScriptReference/Component.GetComponent.html pela documentação você precisa especifica o tipo do objeto: `rb = GameObject.Find("rb").GetComponent();`
Answer: Amigo o GetComponent precisa de um tipo de objeto para receber as informações, vou dar um exemplo em um dos seus códigos e você tenta em outros, como atividade mas caso tenha duvida eu posso te ajudar novamente:
public GameObject bullet;
private float thrust = 6f;
private float rotationSpeed = 180f;
private float MaxSpeed = 4.5f;
private Camera mainCam;
private Rigidbody rb;

private void Start()
{
    mainCam = Camera.main;
    rb = GameObject.Find("rb").GetComponent<RigidBody>(); // ------ Coloquei o tipo que o objeto e
    bullet.SetActive(false);
}

private void FixedUpdate()
{
    ControlRocket();
    CheckPosition();
}

private void Update()
{
    if (Input.GetMouseButtonDown(0) || Input.GetKeyDown("space"))
    {
        Shoot();
    }
}

private void ControlRocket()
{
    transform.Rotate(0, 0, Input.GetAxis("Horizontal") * rotationSpeed * Time.deltaTime);
    rb.AddForce(transform.up * thrust * Input.GetAxis("Vertical"));
    rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -MaxSpeed, MaxSpeed), Mathf.Clamp(rb.velocity.y, -MaxSpeed, MaxSpeed));
}

private void CheckPosition()
{

    float sceneWidth = mainCam.orthographicSize * 2 * mainCam.aspect;
    float sceneHeight = mainCam.orthographicSize * 2;

    float sceneRightEdge = sceneWidth / 2;
    float sceneLeftEdge = sceneRightEdge * -1;
    float sceneTopEdge = sceneHeight / 2;
    float sceneBottomEdge = sceneTopEdge * -1;

    if (transform.position.x > sceneRightEdge)
    {
        transform.position = new Vector2(sceneLeftEdge, transform.position.y);
    }
    if (transform.position.x < sceneLeftEdge) { transform.position = new Vector2(sceneRightEdge, transform.position.y); }
    if (transform.position.y > sceneTopEdge)
    {
        transform.position = new Vector2(transform.position.x, sceneBottomEdge);
    }
    if (transform.position.y < sceneBottomEdge)
    {
        transform.position = new Vector2(transform.position.x, sceneTopEdge);
    }
}

public void ResetRocket()
{
    transform.position = new Vector2(0f, 0f);
    transform.eulerAngles = new Vector3(0, 180f, 0);
    rb.velocity = new Vector3(0f, 0f, 0f);
    rb.angularVelocity = new Vector3(0f, 0f, 0f);
}

void Shoot()
{
    GameObject BulletClone = Instantiate(bullet, new Vector2(bullet.transform.position.x, bullet.transform.position.y), transform.rotation);
    BulletClone.SetActive(true);
    BulletClone.GetComponent<RigidBody>().KillOldBullet(); // ------ linha da erro
    BulletClone.GetComponent<RigidBody>().AddForce(transform.up * 350); // ------ linha da erro
}

Isso que te falei entra em conceitos de POO, mais especificamente em polimorfismo tipos genéricos, se você quiser seguir na área de programação, recomendo dar uma olhada. Mas é isso basicamente seu erro, você esqueceu de passar o tipo para GetComponent(); [este  é o tipo do objeto]

Unity C# error CS0411


Spatial data with duplicates and missing points

Question: I am analysing data from an egg survey. Data is available from different points in the North Sea, some stations are recorded double at different dates. The sea should be covered by 0.5 x 0.5 degree squares.
I have two questions for which I couldn't find any solution yet:

How do I replace the points with duplicated locations and different dates with a mean value? I know how to remove duplicates or how to replace them by max or min but couldn't find a way how to calculate a mean.
How do I calculate interpolated values for the missing points, based on neighbouring cells. Interpolated values should be calculated as long and only if at least two recorded points are neighbouring.

I tried with setting a grid, but did not come very far as I couldn't find a way how to tell R when to interpolate and when not.
Sample data:
egg_data <- structure(list(Latitude = c(54.25, 54.25, 54.25, 54.25, 54.25,
54.25, 54.25, 54.25, 54.25, 54.25, 54.25, 54.25, 54.25, 54.25,
55.25, 55.25, 55.25, 55.25, 55.25, 55.25, 55.25, 55.25, 55.25,
55.25, 55.25, 55.25, 55.25, 55.25, 55.25, 55.25, 55.25, 55.25,
55.25, 55.25, 55.25, 55.25, 55.25, 55.25, 55.25, 55.25, 55.25,
55.25, 55.25, 55.25, 54.25, 54.25, 54.25, 53.25, 58.25, 57.75,
57.25, 57.25, 57.25, 57.25, 57.25, 57.25, 57.25, 57.25, 56.75,
56.75, 56.75, 56.75, 56.75, 56.75, 56.75, 56.75, 56.75, 56.75,
56.75, 56.75, 56.75, 56.25, 56.25, 56.25, 56.25, 56.25, 56.25,
56.25, 56.25, 56.25, 56.25, 56.25, 56.25, 56.25, 56.25, 56.25,
56.25, 56.75, 56.75, 56.75), Longitude = c(6.25, 5.25, 5.25,
4.25, 4.25, 3.25, 3.25, 2.25, 2.25, 1.25, 1.25, 0.25, 0.25, 0.25,
0.25, 0.25, 0.25, 0.25, 1.25, 1.25, 2.25, 2.25, 3.25, 3.25, 4.25,
4.25, 5.25, 5.25, 5.25, 5.25, 4.25, 4.25, 3.25, 3.25, 2.25, 2.25,
1.25, 1.25, 0.25, 0.25, 0.25, 0.25, 1.25, 1.25, 0.25, 0.25, 0.25,
0.25, 3.25, 3.25, 3.25, 2.75, 2.25, 1.75, 1.25, 0.75, 0.25, 0.25,
0.25, 0.25, 0.75, 1.25, 1.75, 2.25, 2.75, 3.25, 3.75, 4.25, 4.75,
5.25, 5.75, 6.25, 5.75, 5.25, 4.75, 4.25, 3.75, 3.25, 2.25, 1.75,
1.25, 0.75, 0.25, 0.25, 0.75, 1.25, 1.75, 1.75, 1.25, 0.75),
    Eggs = c(9L, 6L, 4L, 20L, 57L, 14L, 35L, 18L, 4L, 1L, 3L,
    100L, 1L, 201L, 0L, 51L, 52L, 23L, 19L, 4L, 5L, 23L, 11L,
    18L, 7L, 7L, 14L, 6L, 3L, 4L, 20L, 13L, 19L, 5L, 16L, 23L,
    28L, 11L, 9L, 12L, 19L, 62L, 6L, 3L, 15L, 110L, 57L, 0L,
    14L, 3L, 3L, 8L, 94L, 62L, 7L, 19L, 511L, 59L, 283L, 308L,
    20L, 44L, 61L, 24L, 10L, 10L, 15L, 6L, 8L, 12L, 32L, 2L,
    5L, 10L, 21L, 4L, 1L, 19L, 3L, 4L, 4L, 17L, 51L, 108L, 1213L,
    132L, 4L, 0L, 0L, 0L)), .Names = c("Latitude", "Longitude",
"Eggs"), class = "data.frame", row.names = c("1", "2", "3", "4",
"5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15",
"16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26",
"27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37",
"38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48",
"49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59",
"60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70",
"71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81",
"82", "83", "84", "85", "86", "87", "88", "89", "90"))

Thank you very much!!
Answer: Add a factor for each location
egg_data <- within(egg_data,
  Location <- paste("(", Latitude, ", ", Longitude, ")", sep = "")
)
EDIT: There's no point in being fancy about this, since we want to reverse the process shortly.
egg_data <- within(egg_data,
  Location <- paste(Latitude, Longitude, sep = ",")
)

Then there are loads of ways of getting the mean.
means_by_location <- with(egg_data, tapply(Eggs, Location, mean))

or
library(plyr)
means_by_location2 <- ddply(egg_data, .(Location), summarise, Mean.eggs = mean(Eggs))

or
means_by_location3 <- aggregate(Eggs ~ Location, egg_data, mean)

or
means_by_location4 <- with(egg_data, by(Eggs, Location, mean))

EDIT: For the next bit, you want to hav the result in a data frame, so use method 2 or 3.
Add the latitude and longitude back in to your new dataset.  (Lots of ways of doing this.)
lat_long <- strsplit(means_by_location2$Location, ",")
means_by_location2$Latitude <- sapply(lat_long, function(x) x[1])
means_by_location2$Longitude <- sapply(lat_long, function(x) x[2])

This is your first question answered.

For the second question, you need to think a bit more.  Take a look a plot of eggs by location.
library(ggplot2)
(p <- ggplot(means_by_location2, aes(Longitude, Latitude, colour = log10(Mean.eggs  +1))) +
  geom_point() +
  scale_colour_gradient(low = "#FFFFFF", high = "#0000FF", space = "Lab")
)

Are you interpolating north to south, or east to west, or with all neighbouring points?  There are lots of different possibilities and they may have different answers.  It's a nontrivial task to say which interpolation is best.
Comment: Thank you very much for this fast response! I have to use a standard interpolation method they always used so I have to interpolate with all neighbouring points.


Maximum value of $|z|$ given $\lvert z-\frac 4z \rvert = 8$?

Question: The question is $$ \left|z-\frac 4z \right| = 8$$ Find the max value of $ |z|$
You know how the triangle inequality is:
$$ \bigg| | z_1 | - | z_2| \bigg| \leqq | z_1 \pm z_2 | \leqq | z_1 | + | z_2 | $$
The solutions used only the left hand side inequality, and also ignoring the absolute values outside of $ | z_1 | - | z_2 | $, i.e. they solved
$ | z |  - \left| \frac 4z \right| \leqq 8$ to obtain the answer $ | z |_{max} = 4 + 2 \sqrt{5} $
I am confused about this in two ways, firstly, the way they solved it aren't they assuming here that $| z | \geqq | \frac 4z |$ ? Also can you just ignore the right hand side inequality?
Comment: "aren't they assuming here that |z|≥|4z|"  No if $|z| < |\frac 4z|$ the $|z|-|\frac 4z| < 0 < 8$.  That's fine.  And if $|z|\ge |4z|$ then $|z|-|\frac 4z| = ||z|-|\frac 4z||$.  In any event $|z|-|\frac 4z| \le ||z|-|\frac 4z||$.  In fact $a\le |a|$ for all real numbers.  "Also can you just ignore the right hand side inequality?"  Of course.  If I told you to mow the lawn and I gave you a lawn mower and a pair of scissors and you use the lawn mower and not the pair of scissors can I yell at you and tell you "No, you were supposed to use *both*"
Answer: $|z|-|\frac  4 z| \leq |z-\frac 4 z| =8$ and solving this we get $|z| \leq 4 +2\sqrt 5$. This proves that any complex number such that  $|z-\frac 4 z| =8$ necessarily satisfies $|z| \leq 4+2\sqrt 5$ (whether or not $|z| \geq |\frac  4 z|$). Now we have to see that the value $4+2\sqrt 5$ is actually attained. To see this just take $z=4+2\sqrt 5$. This number satisfies the given equation. Hence the maximum  value is $4+2\sqrt 5$.
Comment: In my argument I did not use the inequality  $|z| \geq \frac 4 {|z|}$. So the upper bound $4+2 \sqrt 5$ works for any complex number satisfying the given equation. Since this upper bound is attained no further analysis is required. Getting inequalities like $|z| \geq -4+2\sqrt 5$ is of no use in finding the maximum value of $|z|$@Freddie
Comment: I still have $|z|\leq \frac  4 {|z|} +8$ which gives $|z| \leq 4 +2\sqrt 5$. Note that $|a-b| \geq |a| -|b|$ and $|a-b| \geq  |b|-|a|$ and I will choose the one that l find convenient. I don't have to consider both if I can show that the upper bound I get is actually attained at some point $z$.  @Freddie
Comment: You got $|z|\geq 4+2\sqrt 3$ OR $|z| \leq 4-2\sqrt 3$. If you had AND instead of OR the story would have been different. In that case $4-2\sqrt 3$ would have been an upper bound and that would have made my upper bound useless. @Freddie
Answer: Your equation is of the form $|z^2-4|=8|z|$, which is a punctured ellipse parallel to the axes centered on the real axis. Then the farthest point away, i.e. the maximium value of $|z|$ is on the major ellipse at $z= 4+2\sqrt{5}$.
Answer:
"aren't they assuming here that $|z|≥|\frac 4z|$"

No.
if $|z| < |\frac 4z|$ then $|z|-|\frac 4z| < 0 < 8$.  That's fine.
And if $|z|\ge |\frac 4z|$ then $|z|-|\frac 4z| = ||z|-|\frac 4z||$. That's fine too.
In any event $|z|-|\frac 4z| \le ||z|-|\frac 4z||$.  In fact $a\le |a|$ for all real numbers.   Becase if $a < 0$ then $a < 0 < |a|$.  And if $a \ge 0$ then $a=|a|$.  So $a \le |a|$.  Always.

"Also can you just ignore the right hand side inequality?"

Of course.
We can ignore both sides and watch a movie instead if we want to.
But  if I told you to mow the lawn and I gave you a lawn mower and a pair of scissors and you use the lawn mower and not the pair of scissors can I yell at you and tell you "No, you were supposed to use both"
We have $|z| -|\frac 4z| \le ||z| - |\frac 4z|| \le |z\pm \frac 4z| \le |z| +|\frac 4z|$.
That sentence contains NINE count them $9$ inequalities we can use.

$|z| -|\frac 4z|\le ||z| - |\frac 4z||$
$|z| -|\frac 4z|\le |z- \frac 4z|$
$|z| -|\frac 4z|\le |z+ \frac 4z|$
$|z| -|\frac 4z|\le |z| +|\frac 4z|$
$||z| - |\frac 4z|| \le |z- \frac 4z|$
$||z| - |\frac 4z|| \le |z+\frac 4z|$
$||z| - |\frac 4z||\le |z| +|\frac 4z|$
$|z -\frac 4z| \le |z| +|\frac 4z|$
$|z+\frac 4z| \le |z| + |\frac 4z|$.

Do we have to use all of them?  No.  We just need to use the ones that help us.
And they figured $|z| -|\frac 4z| \le |z -\frac 4z| = 8$ was the one that helps us.
=======
Okay..... let's go through this in detail.
$||z| -|\frac 4z|| \le |z-\frac 4z| = 8 \le |z| +|\frac z4|$.
Case 1: $|z| < |\frac 4z|$.
That means $|z|^2 < 4$ and $|z| < 2$.  We're looking for the maximum value of $|z|$ so whatever result we get here will not be useful if we later find that $|z|$ might be $\ge 2$ is some other cases.
But lets go on...
$-8 \le |z| - |\frac 4z|<0$
$0\le |z|^2 + 8|z| - 4< 8|z|$
$20 \le (|z|^2 + 8|x| + 16< 8|z| + 20$
$20 \le (|z|+4)^2 < 8|z|+20$
Now $|z|<2$ so $2\sqrt 5 \le 4+|z| < \sqrt{8|z|+20}$
$2\sqrt 5 - 4 \le |z| < \sqrt{8|z|+20}-4$
But we also have $|z| < 2$ so $2\sqrt 5-4\le |z| < \min(2,\sqrt{8|z|+20}-4)$.
As $\sqrt{8|z|+20}-4 \ge \sqrt{8(2\sqrt 5-4)+20}-4=2\sqrt{4\sqrt 5-3}> 2$ we hav $2\sqrt 5-4\le |z| < 2$.
Now all that work we did we the $\sqrt{8|z|+20}-4$ was wasted because we knew that $|z| < 2$.  And if discover that it is possible for $|z|\ge 2$ then all our work on case 1) will have been wasted.
Case 2:
$|z|\ge|\frac 4z|$  and so $|z| \ge 2$
$0 \le |z|-|\frac 4z| \le 8$
$-8|z| \le |z|^2 -8|z| -4 \le 0$
$-8|z|+20 \le |z|^2 - 8|z| +16 \le 20$
$\sqrt{\max(0,20-8|z|)}\le |z|-4\le 2\sqrt 5$
$4+ \sqrt{\max(0,20-8|z|)} \le |z| \le 4 +2\sqrt 5$.
Now we don't care about the LHS side indicates as we are looking for the maximum value of $|z|$ so doing that work was wasted.  Also as it is possible that $|z | < |\frac 4z|$ there wasn't any real reason to insiste $|z|$ MUST be $\ge |\frac 4z|$ so there was never any reason to do the LHS side at all in the first place.
And because can have $|z| \ge 2$ there was no reason to do case 1 at all and all that work was wasted.
And if $z= 4 + 2\sqrt 5$ then $z -\frac 4z=(4+2\sqrt 5) + \frac 4{4+2\sqrt 5}=$
$4+2 \sqrt 5 - \frac {4(1-\frac 12\sqrt 5)}{4(1+\frac 12\sqrt 5)(1-\frac 12\sqrt 5)}=$
$(4 + 2\sqrt 5) -\frac {4-2\sqrt 5}{4(1-\frac 54)}=$
$(4+2\sqrt 5) + (4 - 2\sqrt 5) = 8$.
Now let's go on and continue to so wasted work.
Let's deal with $|z -\frac z4| =8 \le |z| +|\frac z4|$
So
$0\le |z|^2 -8|z| + 4$ and $12 \le (|z|-4)^2$
$2\sqrt 3 \le ||z| - 4|$
Case 3:  $|z| < 4$ then
$2\sqrt 3 \le 4 - |z|$ and $|z|\le 4-2\sqrt 3$.
This was wasted work because we had already determined that $|z| = 4 + 2\sqrt 5$ was possible.
Case 4: $|z| \ge 4$ then
$2\sqrt 3 \le |z|-4$ and $|z| \ge 4+2\sqrt 3$.
Okay.... that's fine but we also proved that $|z| \le 4+2\sqrt 5$ so this result doesn't help us at all.
so all this was wasted.
====
.....
And that actually matters is that

$z = 4 + 2\sqrt 5$ is possible so $|z|=4+2\sqrt 5$ is possible.

$-\infty < |z| -|\frac 4z| \le ||z|-|\frac 4z|| < |z+\frac 4z| = 8$.

So $|z| \le 4+2\sqrt 5$.
All other conditions about $|z| \ge 2\sqrt 5-4$ or if $|z| \ge 4$ then $|z| \ge 4+2\sqrt 3$ don't matter.  They are true.  But they dont matter.
Comment: Okay but I thought if $|z|\lt |\frac 4z|$ then $-(|z|-|\frac 4z|) \le 8 $ $\implies |z| \le -4-2\sqrt5 $ or $|z|\ge -4+2\sqrt5 $ which are totally different numbers.
I don't understand what you said about "if $|z| < |\frac 4z|$ then $|z|-|\frac 4z| < 0 < 8$.  That's fine.".  If asked to solve $|a|\le8$ where $a<0$, you would do $-a\le8$ right?
Also if you use inequality 8 in your answer, ie $8 \le |z|+|\frac 4z| $ $\implies |z|\le 4-2\sqrt3 $ or $|z|\ge 4+2\sqrt3$ which are again totally different numbers, so that's why I was confused and I'm unfortunately still confused.
Comment: $|z|\sqrt -4-2\sqrt 5$ is not possible so you'd get $|z|\ge -4+2\sqrt 5$. But also $|z|<|\frac 4z|\le \frac 4{-4+2\sqrt 5}$.  If I were told $|a|\le 8$ then I would know that $a\le 8$ and I would know $-a\le 8$.  If the fact that $-a\le 8$ told me that there are mice in North America and $a\le 8$ Told me there plague ridden mice in San Francisco then in writing up my report I'd note $a\le 8\implies$ the plague ridden mice in San Francisco because that's a *stronger* result.  All those other inequalities are true but their results are weaker.
Answer: Redo:
We have three potential inequalities
$|z| - |\frac z4| \le ||z| - |\frac z4|| \le |z -\frac z 4|=8$ or

$|z| -|\frac z4| \le 8$.

$-|z| + |frac z4| \le ||z| - |\frac z4|| \le |z -\frac z 4|=8$ or

$|\frac z4| -|z| \le 8$.

$8=|z-\frac z4|\le |z| + |\frac z4|$ or

$|z| +|\frac z4| \ge 8$.

All three of these equations are true for any possible value of $z$ where $|z +\frac 4z| =8$.
The first yields $|z|\le 4 + 2\sqrt 5$ AND $|z|\ge 2\sqrt 5-4$ so $2\sqrt 5-4\le |z|\le 4+2\sqrt 5$.  That is always true.
The second yields $|z|\ge 2\sqrt 5-4$ OR that $|z|\le -4 -\sqrt 5$ but that is impossible.  So $|z|\ge 2\sqrt 5 -4$.  That is always true.
The third yields $|z| \ge  2\sqrt 3$ OR $|\le 4-2\sqrt 3$.
Putting these results together and noting that $2\sqrt 5-4 \le 4-2\sqrt 3 \iff \sqrt 5 + \sqrt 3 < 4 \iff 5+2\sqrt {15}+3 < 16\iff 8+2\sqrt {15}< 16=8+2\sqrt {16}$ which it is we get.
$2\sqrt 5 - 4\le |z| \le 4-2\sqrt 3$ or $4+2\sqrt 3 \le |z| \le 4+ 2\sqrt 5$
So $|z|_{max} = 4+2\sqrt 5$.
As we were only asked for the maximum value and we get that from inequality 1), inequality 1) is the only one we need to consider.


C# Performance Counter - How to watching W3WP / Active Request?

Question: I want to watch W3WP / Active Request with C#.NET, but W3WP / Active Request is invisible in the Visual Studio 2010 Ultimate's Performance Counter Object.
How can I watch the active request at real time with C#? Is there a different way?
Answer: As said here, the best way to follow Requests/sec at worker process level is to follow the Counter called Requests /Sec in category W3SVC_W3WP. Specify instance name following the pattern pid_apppool_name or _Total if you don't know Pid/AppPoolName.


List Drupal Revisions

Question: I just discovered the revisions function of Drupal. I tried it and the new revisions are stored in the database. I expected to get a list of revisions on the edit node page. But i don't see anything like this.
Is it possible to list and switch between revisions from within the UI?
Answer: If you are viewing a node that has revisions enabled, there will be a tab which will show all revisions of the current node.  If you want to see a list of all revisions on the site you could use Views to create a view of node revisions.  Then you can even add filters on content types, creation date, etc to customize your list.

List Drupal Revisions


Lilypond attaching postscript to a NoteHead

Question: I'm making a fingering chart for a 5-valve tuba, but having some troubles.

In the top line, I'm using lilypond's built in fingerings:
\relative bes,,{  <bes-0>   ... }

I guess this is fine, but I'd like to make it a bit more graphical.
In the second line, I am replacing the NoteHead with a note-head glyph and the postscript.  I love that it is close to the NoteHead, but I don't like the extended ledger lines.
\override NoteHead.stencil = #ly:text-interface::print
\override NoteHead.X-offset = 0.6
\relative bes,,{
  \once \override NoteHead.text = \markup{ \musicglyph "noteheads.s2" \postscript #open }
  bes
  \once \override NoteHead.text = \markup{ \musicglyph "noteheads.s2" \postscript #twofour }
  b
  ...
}

After failing to override LedgerLineSpanner nicely, I realized that manually re-drawing the whole NoteHead was probably not the right answer.  Instead, I tried to override fingering:
\override Fingering.parent-alignement-X = 1
\override Fingering.staff-padding = #'()
\override Fingering.direction = #LEFT
\relative bes,,{
  bes\finger \markup \postscript #open
  b\finger \markup \postscript #twofour
  ...
}

But I'm having trouble getting it to be right of the note head.  Any suggestions?
Here is the full *.ly:
\version "2.24.1"
\header{
  tagline=##f
}

open = #"
  0.15 setlinewidth
  2.5  3.9 moveto
  2.0  3.9 0.5 0 361 arc stroke
  2.5  2.8 0.5 0 361 arc stroke
  2.25 1.6 0.5 0 361 arc stroke
  2.0  0.4 0.5 0 361 arc stroke
  newpath
  0.25 2.5  moveto
  0.0  2.93 lineto
  0.43 3.18 lineto
  0.43 3.18 0.5 30 300 arcn
  closepath stroke
"

one = #"
  0.15 setlinewidth
  2.5  3.9 moveto
  2.0  3.9 0.6 0 361 arc fill
  2.5  2.8 0.5 0 361 arc stroke
  2.25 1.6 0.5 0 361 arc stroke
  2.0  0.4 0.5 0 361 arc stroke
  newpath
  0.25 2.5  moveto
  0.0  2.93 lineto
  0.43 3.18 lineto
  0.43 3.18 0.5 30 300 arcn
  closepath stroke
"

onetwo = #"
  0.15 setlinewidth
  2.5  3.9 moveto
  2.0  3.9 0.6 0 361 arc fill
  2.5  2.8 0.6 0 361 arc fill
  2.25 1.6 0.5 0 361 arc stroke
  2.0  0.4 0.5 0 361 arc stroke
  newpath
  0.25 2.5  moveto
  0.0  2.93 lineto
  0.43 3.18 lineto
  0.43 3.18 0.5 30 300 arcn
  closepath stroke
"

two = #"
  0.15 setlinewidth
  2.5  3.9 moveto
  2.0  3.9 0.5 0 361 arc stroke
  2.5  2.8 0.6 0 361 arc fill
  2.25 1.6 0.5 0 361 arc stroke
  2.0  0.4 0.5 0 361 arc stroke
  newpath
  0.25 2.5  moveto
  0.0  2.93 lineto
  0.43 3.18 lineto
  0.43 3.18 0.5 30 300 arcn
  closepath stroke
"

twothree = #"
  0.15 setlinewidth
  2.5  3.9 moveto
  2.0  3.9 0.5 0 361 arc stroke
  2.5  2.8 0.6 0 361 arc fill
  2.25 1.6 0.6 0 361 arc fill
  2.0  0.4 0.5 0 361 arc stroke
  newpath
  0.25 2.5  moveto
  0.0  2.93 lineto
  0.43 3.18 lineto
  0.43 3.18 0.5 30 300 arcn
  closepath stroke
"

twofour = #"
  0.15 setlinewidth
  2.5  3.9 moveto
  2.0  3.9 0.5 0 361 arc stroke
  2.5  2.8 0.6 0 361 arc fill
  2.25 1.6 0.5 0 361 arc stroke
  2.0  0.4 0.6 0 361 arc fill
  newpath
  0.25 2.5  moveto
  0.0  2.93 lineto
  0.43 3.18 lineto
  0.43 3.18 0.5 30 300 arcn
  closepath stroke
"

four = #"
  0.15 setlinewidth
  2.5  3.9 moveto
  2.0  3.9 0.5 0 361 arc stroke
  2.5  2.8 0.5 0 361 arc stroke
  2.25 1.6 0.5 0 361 arc stroke
  2.0  0.4 0.6 0 361 arc fill
  newpath
  0.25 2.5  moveto
  0.0  2.93 lineto
  0.43 3.18 lineto
  0.43 3.18 0.5 30 300 arcn
  closepath stroke
"

\new Staff = "main" {
  \omit Staff.TimeSignature
  \time 13/4
  \clef bass
  \set fingeringOrientations = #'(right)
  \relative bes,,{
    <bes-0>

    <c-13>
    <des-23>
    <d-12>
    <ees-1>
    <e-2>
    <f-0>
    <ges-23>
    <g-12>
    <aes-1>

    <bes-0>
  }\break

  \override NoteHead.stencil = #ly:text-interface::print
  \override NoteHead.X-offset = 0.6

  \relative bes,,{
    \once \override NoteHead.text = \markup{ \musicglyph "noteheads.s2" \postscript #open }
    bes
    \once \override NoteHead.text = \markup{ \musicglyph "noteheads.s2" \postscript #twofour }
    b
    \once \override NoteHead.text = \markup{ \musicglyph "noteheads.s2" \postscript #four }
    c
    \once \override NoteHead.text = \markup{ \musicglyph "noteheads.s2" \postscript #twothree }
    des
    \once \override NoteHead.text = \markup{ \musicglyph "noteheads.s2" \postscript #onetwo }
    d
    \once \override NoteHead.text = \markup{ \musicglyph "noteheads.s2" \postscript #one }
    ees
    \once \override NoteHead.text = \markup{ \musicglyph "noteheads.s2" \postscript #two }
    e
    \once \override NoteHead.text = \markup{ \musicglyph "noteheads.s2" \postscript #open }
    f
    \once \override NoteHead.text = \markup{ \musicglyph "noteheads.s2" \postscript #twothree }
    ges
    \once \override NoteHead.text = \markup{ \musicglyph "noteheads.s2" \postscript #onetwo }
    g
    \once \override NoteHead.text = \markup{ \musicglyph "noteheads.s2" \postscript #one }
    aes
    \once \override NoteHead.text = \markup{ \musicglyph "noteheads.s2" \postscript #two }
    a
    \once \override NoteHead.text = \markup{ \musicglyph "noteheads.s2" \postscript #open }
    bes
  }\break

  \revert NoteHead.stencil
  \revert NoteHead.X-offset

  \override Fingering.parent-alignment-X = 1
  \override Fingering.staff-padding = #'()
  \override Fingering.direction = #RIGHT

  \relative bes,,{
    bes\finger \markup \postscript #open
    b\finger \markup \postscript #twofour
    c\finger \markup \postscript #four
    des\finger \markup \postscript #twothree
    d\finger \markup \postscript #onetwo
    ees\finger \markup \postscript #one
    e\finger \markup \postscript #two
    f\finger \markup \postscript #open
    ges\finger \markup \postscript #twothree
    g\finger \markup \postscript #onetwo
    aes\finger \markup \postscript #one
    a\finger \markup \postscript #two
    bes\finger \markup \postscript #open
  }
}

\layout{
  indent = 0\cm
  \context {
    \Score
    \omit BarNumber
  }
}

Answer: I'm not sure where exactly the problem is — I don't know how to override the properties of Fingering to get the exact behavior you want. However, I know a simpler way of doing it (hopefully).
If you want the fingerings to be put into certain position with respect to the note (left/right/up/down), you should set fingeringOrientations like this:
\set fingeringOrientations = #'(left)

This will put all fingerings to the left of the notehead if and only if the note is a part of a chord (I have no idea why it's like this, but it's the official and well-documented behavior). So, if you write c4-1 d4-2 e4-3 etc., setting the fingeringOrientations will make no difference whatsoever! But if you make these notes into one-note chords like <c-1>4 <d-2> <e-3>, the fingerings will go to the left.
Throwing away your Fingering overrides, and replacing the code for the third line with this:
\set fingeringOrientations = #'(right)

\relative bes,,{
  <bes\finger \markup \postscript \open>

etc. will do the trick:
Comment: This behavior is in fact caused by the `Fingering_engraver`. This one  directly listens to fingering events, which does not work for Notes in chords (as here the articulations are not broadcasted). So the `Fingering_engraver` only handles fingerings like this `c\finger1` but not ``. We also have the more advanced `New_fingering_engraver`. But as both engravers are present the `Fingering_engraver` will handle the event, at which point it gets removed from the note event. Thus the other one does not see it, so we do not get two grobs.
Comment: But this also means that the `` is handled by the `New_fingering_engraver` which does use `fingeringOrientations` while `c\finger1` is handled by `Fingering_engraver`, which does not. Removing `Fingering_engraver` from the voice context will have both cases work the same.
Comment: Fantastic!  That's what I needed.  I couldn't figure out why `fingeringOrientations` wasn't working.  It was the chord behaviour.  I like this.
Comment: I also definitely would not have figured out the `\open` vs `#open` syntax on my own.
Comment: Thanks for the info @Lazy, I learned something.


What do I need to change in my date RegEx to account for leap years?

Question: I have separate input fields for month, day, and year. The current date regex does not account for leap years. I tried adding other regex to account for leap years but had no success. Your help is greatly appreciated.
var bmonth = Apperyio('register_birthdaymonth').val();
var bday = Apperyio('register_birthdayday').val();
var byear = Apperyio('register_birthdayyear').val();
var dateString = (bmonth + "/" + bday + "/" + byear)

var date_regex = /^(?:(0[1-9]|1[012])[\/.](0[1-9]|[12][0-9]|3[01])[\/.](18|19|20)[0-9]{2})$/;
if (!(date_regex.test(dateString)))
{
    errorMsg = errorMsg + "1";
    document.getElementById("bdayError").innerHTML = "Please enter your birthday.";
}

Comment: @John Thank you very much! This did the trick. It is working perfectly. I appreciate you taking the time to help.
Comment: Which date input fails for you ?
Comment: Leap years do not validate correctly. Example: It allows 02/29/1991.
Comment: Do you need a regex? You could use the date object. Like so: http://jsbin.com/kamebibena/3/edit?js,console,output In this way you could account for dates in the past fairly easily as well.
Comment: @timmyusa no problem!
Answer: Did you already look at this? Regular Expression | Leap Years and More
If not, try the following:
(02)[\/.]29[\/.](((18|19|20)(04|08|[2468][048]|[13579][26]))|2000)
Comment: When I replaced my current regex with the one you provided I received multiple errors including unexpected '/'

How would I go about resolving this?


VB.Net 2010 - Retrieve MemberValue from ComboBox

Question: I have been working on this for three days now and just can't find a simple answer. (It really can't be that hard to do surly). but now I can't see the trees for the forest anymore.
I populate a Combobox from an SQL database, this works fine and the data shows up fine in the Dataset Visualizer.
ComboList is called cmbStateList
Two Database fields
DisplayMember "State"
ValueMember "ID"
What I want to do is simply return the ValueMember of when an item is selected from the combobox.
When I use "cmbStateList.SelectedValue" in the cmbStateList_SelectedIndexChanged what is returned is the index or position of the item in the list, not the ValueMember ("ID") field of the data.
Here is the code I am using, really hope someone can help with this simple problem
Load the State List:
SQL = "Select * from State"
Command = New SqlCommand(SQL, CNN)
DA.SelectCommand = Command
DA.Fill(DS, "State")

Bind the ComboBox:
Me.cmbStateList.Items.Clear()
Me.cmbStateList.DataSource = DS.Tables("State")
Me.cmbStateList.DisplayMember = "State"
Me.cmbStateList.ValueMember = "ID"

Select the ComboBox (Have tried DropDownClosed and SelectedIndexChanged):
Private Sub cmbStateList_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cmbStateList.SelectedIndexChanged
     MsgBox(Me.cmbStateList.SelectedValue)
End Sub

Thanking you in advance
Chris
Answer: This is very slowly if you have arround 100000 records:
Me.cmbStateList.DataSource = Nothing
Me.cmbStateList.DataSource = DS.Tables("State")
Me.cmbStateList.DisplayMember = "State"
Me.cmbStateList.ValueMember = "ID"

This is fast, just changed the orders of commands:
Me.cmbStateList.DataSource = Nothing
Me.cmbStateList.DisplayMember = "State"
Me.cmbStateList.ValueMember = "ID"
Me.cmbStateList.DataSource = DS.Tables("State")

Answer: I'm not 100% sure if it will make a difference, but we always set our Members before the DataSource. I would try changing your code to the following:
Me.cmbStateList.DataSource = Nothing
Me.cmbStateList.DisplayMember = "State"
Me.cmbStateList.ValueMember = "ID"
Me.cmbStateList.DataSource = DS.Tables("State")

Comment: Thanks for your quick reply. I think you might have meant move the binding datasource to the end. I did this and then I get System.Data.DataRowView loaded in the combobox, no data. I realy cant belive it can be this hard to simply display the value..
Comment: You are welcome, and welcome to stackoverflow! Remember, if an answer solves or helps you solve your question, you should click the checkmark and up arrow next to the question so that future visitors know this is what helped you with your question.
Comment: Just did somthing Diffrent...

It seems to works if you use a DataTable
Does that mean you cant use a DataSource to bind to a combobox?
Comment: Does not work if the Combobox is Sorted.. this seems to be the issue
Answer: Try this:
Bind the combo box
Me.cmbStateList.Items.Clear()
Me.cmbStateList.DisplayMember = "State"
Me.cmbStateList.ValueMember = "ID"
Me.cmbStateList.DataSource = DS.Tables("State")
Me.cmbStateList.SelectedIndex = 0

Get selected value
To test add this on a button click event handeler.
MsgBox(Me.cmbStateList.SelectedValue.ToString())

Comment: 1 QLD
2 NSW
3 WA
4 SA
5 ACT
6 VIC
NULL NULL
Comment: It seems really strange because what is displayed is the position of the record in the combobox.
So if it is the 2nd item from the top it shows 2, 3rd item is 3 the first item is 1 (not zero as I would expect).

Below is the data from the database showing the states and ID number.
1         QLD
2 NSW
3 WA
4 SA
5 ACT
6 VIC

So it is pretty simple stuff.

Do you think that SelectedIndexChanged is the right area to check?
Honest been playing with this for three days straight, driving me mad.

Thanks for you time on helping
Comment: I am new to this forum, and it seems if you press the enter key to enter a new line it posts your comments.

I have learned to hold down the Shift key and press enter to start a new line.
Comment: Found the answer thanks to someone on VBWire.
Great forum and lots of answers.

The answer is for anyone who has the same problem you must sort the DataSet before you bind it to the Combobox.

DS being the Dataset

Dim Table As DataTable = DS.Tables("State")
Table.DefaultView.Sort = "State"

I would say .net (2010 anyway) is a major regression in fast and easy coding. Everything is so long winded and so un-intuitive... The days of quick and cost effective coding may be on it's last legs.

Thanks a lot to BizApps as being the only person to answer and I hope this helps someone else.
Comment: or you can add order by State on your select query


Problema para usar o click() do selenium em python

Question: Olá, estou começando a usar o selenium. Comecei tentando acessar o google e alguns comandos básicos. Entretanto não consigo usar o click(). Meu programa:
from selenium import webdriver

class Google(object):
    def __init__(self, driver):
        self.driver = driver
        self.url = 'http://google.com.br'
        self.search_bar = 'q'
        self.btn_search = 'btnK'
        self.btn_lucky = 'btnI'

    def navigate(self):
        self.driver.get(self.url)

    def search(self):
        self.pesquisa = 'sabonete'
        self.driver.find_element_by_name(self.search_bar).send_keys(self.pesquisa)
        self.driver.find_element_by_name('btnI').click()

gg = webdriver.Chrome()

g = Google(gg)

g.navigate()
g.search()

Erro:
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable
  (Session info: chrome=81.0.4044.138)

Answer: Segundo A edureka! Communinity - How do I resolve the ElementNotInteractableException in Selenium WebDriver, ElementNotInteractableException ocorre quando o elemento é encontrado, mas não pode-se interargir com o elemento, não podendo enviar um click. Isso pode acontecer devido a vários motivos:

elemento pode não estar visível na tela ou não é mostrado na tela
elemento está fora da tela
elemento está atrás de outro elemento
elemento html está escondido (hidden="true")
o javascript da página ainda está "montando" a página e o botão ainda não apareceu na tela.

Reproduzi o problema aqui, a solução foi colocar um tempo de espera antes de tentar clicar no botão.
Exemplo:
import time
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('https://www.google.com')
search_bar = driver.find_element_by_name('q')
search_bar.send_keys('texto da pesquisa')
btn_lucky  = driver.find_element_by_name('btnI')
time.sleep(1)  # Aguarda 1 segundo antes de clicar, foi o suficiente para resolver o erro.
btn_lucky.click()

Provavelmente isso é causado pela forma que o Google monta os elementos na página de forma dinâmica com javascript, quando o selenium tenta clicar o botão ainda não foi renderizado na tela.
Espero ter ajudado.
Answer: Realizei um teste e obtive o mesmo erro "element not interactable".
Verifiquei que isso ocorre porque você não fechou o seu driver com o driver.quit(), dai o Chrome continua carregado na memória quando seu programa sai, e na próxima vez que você tentar executar o programa ele lança mais uma instância do Chrome, provavelmente o driver se perde e se conecta na instância errada do Chrome e começa a dar esse erro. Você deve sempre fechar o driver no final do seu programa para evitar problemas.
Para resolver o erro:

Primeiro mate todas as instâncias do chrome da memória com o comando $ pkill chrome
Coloque o comando driver.quit() no final do seu programa.
Execute novamente seu programa, ele deverá funcionar corretamente sem erro.
Comment: Sim. Isso foi proposital, eu não executei o `driver.quit()`, de propósito para o cara poder ver o resultado em tela, e fechar manualmente após verificar que o comando foi executado com sucesso. Eu posso editar minha resposta e deixar essa informação explícita.
Answer: Nunca tentei interagir com uma página desta maneira, mas este erro que você está recebendo está dizendo que não é possível interagir com o elemento selecionado.
Uma maneira alternativa de conseguir o mesmo resultado é utilizando o elemento input da página inicial do google. Para isso basta pegar a classe css do elemento input da página.
Em meu exemplo utilizei o xpath para preencher os valores do input text e fazer o clique do botão pesquisa do Google
Segue um exemplo:
class Google(object):
    def __init__(self, driver):
        self.driver = driver
        self.url = 'http://google.com.br'

    def navigate(self):
        self.driver.get(self.url)

    def search(self):
        self.pesquisa = 'sabonete'
        self.driver.find_element_by_xpath('/html/body/div/div[3]/form/div[2]/div[1]/div[1]/div/div[2]/input').send_keys(self.pesquisa)
        self.driver.find_element_by_xpath('//*[@id="tsf"]/div[2]/div[1]/div[3]/center/input[1]').click()

gg = webdriver.Chrome()

g = Google(gg)

g.navigate()
g.search()

Se precisar de ajuda, pode falar aqui.


How to change default paths for Storybook and Storybook addons?

Question: Summary
I'm trying to run SB on a Next app running in a restricted Windows environment. I'm not sure what the function of node_modules/.cache/sb-manager is, but it's setting absolute Windows paths that can't be accessed in my environment. Like C:\USERS\USERNAME\DONT COME IN HERE! (see below)
What can instead be accessed is the git bash root path like ~/Documents/happy_path. I've got the app to work, and then not, so I'm not sure what it's doing that I'm missing. Do I have to remove all the addons? Error messages below.
We're running Node v20.8.1 with Storybook 7.6.17. React is version 18.2, Next is version 13.1.2.
Question: How to change the default path that addons and/or sb-manager is using?
Additional information
On npm run storybook:
The error message is Cannot read directory ../../../My Documents": Access is denied. Of course it is, that's the restricted part of the environment.
And then following from that a repeated panic: runtime error: invalid memory address or nil pointer dereference in... for every file in sb-manager
What it does:
Every file in sb-manager sets a path to 'c:/Users/XXXXX/Documents/XXXX/node_modules/@storybook/addon-whatever...'
What I want it to do:
It would be nice if that path could somehow instead be set to '~/Documents/XXXX/node_module/@storybook/addon-whatever...'
Error Message
On npm run storybook:
> firstname.lastname@example.com storybook
> storybook dev -p 6006

@storybook/cli v7.6.17

info => Serving static files from ./.\public at /
info => Starting manager..
X [ERROR] Cannot read directory "../../../My Documents": Access is denied.

X [ERROR] panic: runtime error: invalid memory address or nil pointer dereference (while parsing "../../../My Documents/XXX/XXX/node_modules/.cache/sb-manager/essentials-actions-2/manager-bundle.js")

  debug.Stack (runtime/debug/stack.go:24)
  helpers.PrettyPrintedStack (internal/helpers/stack.go:9)
  bundler.parseFile.func1 (internal/bundler/bundler.go:189)
  panic (runtime/panic.go:884)
  resolver.resolverQuery.tsConfigForDir (internal/resolver/resolver.go:977)
  resolver.resolverQuery.resolveWithoutSymlinks (internal/resolver/resolver.go:828)
  resolver.(*Resolver).Resolve (internal/resolver/resolver.go:577)
  bundler.RunOnResolvePlugins (internal/bundler/bundler.go:901)
  bundler.parseFile (internal/bundler/bundler.go:397)
  bundler.(*scanner).maybeParseFile (internal/bundler/bundler.go:1385)

X [ERROR] panic: runtime error: invalid memory address or nil pointer dereference (while parsing "../../../My Documents/XXX/XXX/node_modules/.cache/sb-manager/essentials-controls-1/manager-bundle.js")

  debug.Stack (runtime/debug/stack.go:24)
  helpers.PrettyPrintedStack (internal/helpers/stack.go:9)
  bundler.parseFile.func1 (internal/bundler/bundler.go:189)
  panic (runtime/panic.go:884)
  resolver.resolverQuery.tsConfigForDir (internal/resolver/resolver.go:977)
  resolver.resolverQuery.resolveWithoutSymlinks (internal/resolver/resolver.go:828)
  resolver.(*Resolver).Resolve (internal/resolver/resolver.go:577)
  bundler.RunOnResolvePlugins (internal/bundler/bundler.go:901)
  bundler.parseFile (internal/bundler/bundler.go:397)
  bundler.(*scanner).maybeParseFile (internal/bundler/bundler.go:1385)

Storybook Config
.storybook/main.js
/** @type { import('@storybook/nextjs').StorybookConfig } */
const config = {
    stories: [
        "../stories/**/*.mdx",
        ../stories/**/*.stories.@(js|jsx|mjs|ts|tsx),
        ../components/**/*.stories.@(js|ts),
    ],
    addons: [
        "@storybook/addon-links",
        "@storybook/addon-essentials",
        "@storybook/addon-onboarding",
        "@storybook/addon-interactions",
        "@storybook/addon-designs",
    ],
    framework: {
        name: "@storybook/nextjs",
        options: {},
    },
    core: {
        disableTelemetry: true,
    },
    docs: {
        autodocs: "tag",
    },
}
export default config

Comment: Can you provide your configuration for storybook?
Answer: What I found out so far is that the builder-manager wraps the manager entries like this:
export async function wrapManagerEntries(entrypoints: string[], uniqueId?: string) {
  return Promise.all(
    entrypoints.map(async (entry, i) => {
      const { name, dir } = parse(entry);
      const cacheLocation = resolvePathInStorybookCache('sb-manager', uniqueId);

      if (!cacheLocation) {
        throw new Error('Could not create/find cache directory');
      }

      const base = relative(process.cwd(), dir);
      const location = join(
        cacheLocation,
        sanitizeFinal(join(`${sanitizeBase(base)}-${i}`, `${sanitizeBase(name)}-bundle.js`))
      );

      await fs.ensureFile(location);
      await fs.writeFile(location, `import '${slash(entry)}';`);

      return location;
    })
  );
}

I think the problem lies in the resolvePathInStorybookCache function which looks like this:
/**
 * Get the path of the file or directory with input name inside the Storybook cache directory:
 *  - `node_modules/.cache/storybook/{directoryName}` in a Node.js project or npm package
 *  - `.cache/storybook/{directoryName}` otherwise
 *
 * @param fileOrDirectoryName {string} Name of the file or directory
 * @return {string} Absolute path to the file or directory
 */
export function resolvePathInStorybookCache(fileOrDirectoryName: string, sub = 'default'): string {
  let cacheDirectory = findCacheDirectory({ name: 'storybook' });
  cacheDirectory ||= path.join(process.cwd(), '.cache', 'storybook');

  return path.join(cacheDirectory, sub, fileOrDirectoryName);
}

Now my guess is that the poroblem lies in findCacheDirectory which resolves to absolute urls, but if we check the source code we can see that it uses CACHE_DIR environment variable that lets you specify the location.
So the solution would be to try to set something like CACHE_DIR=~/Documents/XXXX/node_modules/.cache (the correct path to the project).
Comment: Interesting...let me try that.
Comment: That was exactly it!  Kicking myself for not checking the source code.  Thanks @vl4d1m1r4!


Unit Vector Based on Angle with $XY-YZ-XZ$ Planes

Question: This may be a simple one but lets assume I have $3$ angles $(a,b,c)$ and I want to know what unit vector makes such angles with the $XY-YZ-XZ$ planes. Another question is that I wanna know if $a$, $b$ and $c$ are independent?
Answer: The angles $a$, $b$ and $c$ cannot be independent since the three angles are just determining a point on the surface of the unit sphere.
Comment: Yeah, same as what I expected. Any answers for the first part?
Comment: Do you know a parametrization for the unit sphere?
Comment: Yeah. I have derived some equations myself. Just wanna double check if they are correct. Lets assume I have (a,b,c) as the angles and (X,Y,Z) as the unit vector then: tan(a)=Y/Z, tan(b)=X/Z, tan(c)=X/Y. Does this make any sense? and the fact that X^2+Y^2+Z^2=1.
Comment: You can parmetrize the sphere with cos and sin of two angles
Comment: Ohh yes, I got myself confused with tangent! Thanks! Accepted as the answer.


How to check the stock count of an ubercart node

Question: I'm using a using a custom function to display child nodes of a taxonomy term while displaying the term page. Here is the function
function theme_name_child_terms($vid = 1) {
  if(arg(0) == 'taxonomy' && arg(1) == 'term') {
    $children = taxonomy_get_children(arg(2), $vid);
      if(!$children) {
        $custom_parent = taxonomy_get_parents(arg(2));
          $parent_tree = array();
          foreach ($custom_parent as $custom_child => $key) {
            $parent_tree = taxonomy_get_tree($vid, $key->tid);
          }
          $children = $parent_tree;
      }

    $output = '
';
    // Avoid unnecessary "Invalid foreach" errors showing up in the log:
    if (!empty($children)) {
        // If not empty, run the foreach loop:
        foreach ($children as $term) {
            // Then check to see if any nodes exist for that term id:
            $number_of_nodes = taxonomy_term_count_nodes($term->tid);
            // If there ARE nodes...
            if ($number_of_nodes > 0) {
              // ... then add them to the output:
              $output .= '
';
              $output .= l($term->name . ' (' . $number_of_nodes . ')', 'taxonomy/term/' . $term->tid);
              $output .= '
';
              }
        }
    }
    $output .= '
';

    return $output;
  }
}

This is the output: screen shot. You can can see that it's showing terms and node counts in brackets for items that are not in the 'jewellery' catalogue anymore as they are sold.
The problem I have is that the nodes i'm dealing with are products in an ubercart catalogue - - all items are unique as it's an antique trading site. The function above still counts 'sold' items as nodes associated with the term - a sold item is of course still tagged with a taxonomy term  .  - so, some terms are leading to blank pages, because I filter out nodes that are sold, from the taxonomy view.
Can another step be added to the function that checks each node associated with a term if it is a has stock level of 1 or above?
I've found the following function in uc_stock.module:
/**
 * Get the stock level of a particular product SKU.
 *
 * @param $sku
 *   The Ubercart product SKU of the stock level to return.
 * @return:
 *   The SKU's stock level, or FALSE if not active.
 */
function uc_stock_level($sku) {
  $stock = db_fetch_object(db_query("SELECT active, stock FROM {uc_product_stock} WHERE sku = '%s'", $sku));

  if ($stock && $stock->active) {
    return $stock->stock;
  }

  return FALSE;
}

I just can't figure out where or how to call this function in the original function. It needs to be passed the product 'sku', but i'm not sure how to give it that parameter.
I guess it should be something like:
$stock = uc_stock_level($sku);
  if ($stock > 0) {
    ...
  }

Any help much appreciated.
Answer: Note: here's a good page to have bookmarked when you use Ubercart with D6: http://www.ubercart.org/docs/api (as opposed to http://api.ubercart.me for when you use D7).
Also note: this ended up being a lot more in-depth than I anticipated, but I was already knee-deep in it so I figured I'd finish it up. ;) That said...

You're definitely on the right track... Like you said, you could just supply the function uc_stock_level($sku) with the value of $sku, but that might be a lot of SKUs and therefore kind of resource intensive.
Another alternative that should work would be something like this:
Change this part of your code:
$output = '
';
// Avoid unnecessary "Invalid foreach" errors showing up in the log:
if (!empty($children)) {
    // If not empty, run the foreach loop:
    foreach ($children as $term) {
        // Then check to see if any nodes exist for that term id:
        $number_of_nodes = taxonomy_term_count_nodes($term->tid);
        // If there ARE nodes...
        if ($number_of_nodes > 0) {
          // ... then add them to the output:
          $output .= '
';
          $output .= l($term->name . ' (' . $number_of_nodes . ')', 'taxonomy/term/' . $term->tid);
          $output .= '
';
          }
    }
}
$output .= '
';

To something like this:
$output = '
';
// Avoid unnecessary "Invalid foreach" errors showing up in the log:
if (!empty($children)) {
  // If not empty, run the foreach loop:
  foreach ($children as $term) {
    // Then check to see if any nodes exist for that term id:
    $number_of_nodes = taxonomy_term_count_nodes($term->tid);
    // And then check to see what the current stock level is:
    $stock_level = fetch_stock_level_from_termid($term->tid);
    // If there ARE nodes...
    if ($number_of_nodes > 0) {
      // And if the product is in stock...
      if ($stock_level > 0) {
        // ... then add them to the output:
        $output .= '
';
        $output .= l($term->name . ' (' . $number_of_nodes . ')', 'taxonomy/term/' . $term->tid);
        $output .= '
';
      }
    }
  }
}
$output .= '
';

You'll then need to add the function fetch_stock_level_from_termid() to your code as well:
function fetch_stock_level_from_termid($term_id) {
  $sql = "SELECT SUM( {uc_product_stock}.stock ) AS stock
          FROM {uc_product_stock}
          INNER JOIN {node} ON {uc_product_stock}.nid = {node}.nid
          INNER JOIN {term_node} ON {node}.vid = {term_node}.vid
          WHERE {term_node}.tid = %d
          AND {node}.status = 1";
  $stock_available = db_result(db_query($sql, $term_id));
  return $stock_available;
}

Hope that helps... :)
Comment: Wow! Thank you so much! Works perfectly. Really appreciate your time and effort coming up with an elegant solution. Saved me a lot of head scratching!
Comment: Hey no prob. Been there a few times so I know what it can be like sometimes... >_< OH and also, if you use path aliases you could change the line that reads `$output .= l($term->name . ' (' . $number_of_nodes . ')', 'taxonomy/term/' . $term->tid);` to something like this: `$output .= l($term->name . ' (' . $number_of_nodes . ')', drupal_get_path_alias('taxonomy/term/' . $term->tid));`


Manipulating images with .NET Core

Question: I have updated my project from .NET 4.5 to .NET Core (with ASP.NET Core). I had some very simple code in my previous version that used the bitmap object from System.Drawing to resize an image.
As I understand System.Drawing cannot be used in .NET Core because it is not cross platform, but what can be used instead?
I have googled this and cannot find anything.  The only thing I can find is this post, which has no code on it what so ever.
Comment: Add more facts to assist @Thomas [SkiaSharp can be dated back to 2012 as part of XobotOS](http://corefx.strikingly.com/). Xamarin made it available recently, so it can be used individually, or used as the basis for future 2D rendering framework (such as System.Drawing on SkiaSharp instead of GDI+/libgdiplus). .NET Core support is tracked in https://github.com/mono/SkiaSharp/issues/20
Comment: Updated link on this topic posted January 19, 2017 by Bertrand Le Roy

https://blogs.msdn.microsoft.com/dotnet/2017/01/19/net-core-image-processing/
Comment: Found [this](http://imageresizing.net/) on the github you linked. Helpful?
Comment: Possible duplicate of [Resize images with MVC 6 on Ubuntu running ASP.NET 5 on Mono](http://stackoverflow.com/questions/36643720/resize-images-with-mvc-6-on-ubuntu-running-asp-net-5-on-mono)
Comment: To my understanding the .NET (Core) team is still discussing this with the Xamarin team. Xamarin built a library called SkiaSharp which is a wrapper for the cross-platform Skia library which again is the graphic library of Google Chrome. It runs under Android, iOS, Linux, Windows, etc. which would make it a perfect match for .NET Core. But as of today, they have not finished it for .NET Core (https://blog.xamarin.com/cross-platform-2d-graphics-with-skiasharp/). My bets go, that this library will be the future story for .NET Core and drawing.
Comment: Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Comment: I'd be interested in advanced image manipulation like erode / dilate for core
Comment: Have you checked out [SkiaSharp](https://github.com/mono/SkiaSharp) ? Awesome library that I'm using in my project now.
Comment: Did you ever find a good solution for this? We mainly need it to convert between file formats and to get the image size and DPI.
Comment: I don't know about earlier versions of core but .NET 5 has System.Drawing integrated, it would appear. I was able to manipulate images from aspnetcore project.
Answer: Disclaimer: This is my software.
I'm working on a cross-platform 2D Graphics library that runs on .NET Core It's currently alpha but already supports a comprehensive feature set.
https://github.com/JimBobSquarePants/ImageSharp
Example usage.
using (FileStream stream = File.OpenRead("foo.jpg"))
using (FileStream output = File.OpenWrite("bar.jpg"))
{
    Image image = new Image(stream);
    image.Resize(image.Width / 2, image.Height / 2)
         .Greyscale()
         .Save(output);
}

Comment: Please note that ImageSharp changed their license and is PAID if your company makes more than 1M/year
Comment: Just perfect. Zero dependencies and full range of formats. Thanks!
Comment: @JamesSouth this is not relevant to the question, but this is relevant to the answer. It was posted in 2016 linking to an Apache-licensed library. Then the license has changed, but developers rarely pay attention when updating `nugets`. These things come up during legal audits later and can be very painful.
Comment: So what about drawing on a specific OS canvas? has anyone abstracted that away from the OS?
Comment: TK has a .Net Core library for graphics. I expect a UI lib eventually but it might wrap TK.
Comment: @IAbstract  TK, you got a link to share?
Comment: How is that relevant to the question?
Comment: Except that it's not. The question does not specify that OSI licenses are required and the answer does not specify that the library has an OSI license. This is a forum for technical QA and licensing discussions are explicitly off topic. https://stackoverflow.com/help/on-topic#:~:text=Legal%20questions%2C%20including%20questions%20about%20copyright%20or%20licensing%2C%20are%20off%2Dtopic%20for%20Stack%20Overflow.%20Open%20Source%20Stack%20Exchange%20or%20Law%20Stack%20Exchange%20may%20be%20suitable%20alternatives..
Answer: You can use now official (from Microsoft) System.Drawing.Common NuGet package.

Note that's it's Windows-only starting from .NET 6 (it used to be cross-platform for .NET Core and .NET 5). It will still work in .NET 6 with special switch on other platforms.
From Microsoft docs recommended action:
To use these APIs for cross-platform apps, migrate to one of the following libraries:

ImageSharp
SkiaSharp
Microsoft.Maui.Graphics

Alternatively, you can enable support for non-Windows platforms in .NET 6 by setting the System.Drawing.EnableUnixSupport runtime configuration switch to true in the runtimeconfig.json file:
{
   "configProperties": {
      "System.Drawing.EnableUnixSupport": true
   }
}

This configuration switch was added to give cross-platform apps that depend heavily on this package time to migrate to more modern libraries. However, non-Windows bugs will not be fixed. In addition, this switch has been removed in .NET 7.
Comment: @VadimOvchinnikov

System.Drawing.Common is unsupported on non Windows platforms as of .NET 6 https://learn.microsoft.com/en-us/dotnet/api/system.drawing?view=net-6.0#remarks
Comment: @JamesSouth I added information about .NET 6 non-Windows platforms in .NET 6. I'm grateful for your update, we didn't manage to migrate to .NET 6 so I didn't know about this.
Comment: @DougS No, it's cross platform. See discussion here https://github.com/dotnet/corefx/issues/20325
Comment: @DougS Yeah, I agree that headline is confusing.
Comment: See Scott Hanselman's blogg on how to use System.Drawing.Common: https://www.hanselman.com/blog/HowDoYouUseSystemDrawingInNETCore.aspx
Comment: This is bad solution due to dependencies and huge size. See @James South answer
Comment: @AlekDepler At the moment of writing answer (in 2018) library in James South answer was really buggy. I tested it and many alternatives back then. Probably it's not the best but at least I can recommend System.Drawing.Common library for enterprise solutions. It provides consistent and reliable results.
Answer: I've found an implementation of System.Drawing for .NET Core based on Mono's sources being maintained at:

https://github.com/CoreCompat/CoreCompat

The NuGet package is at:

https://www.nuget.org/packages/CoreCompat.System.Drawing

Which you can reference it in your .NET Core App's project.json with:
{
  "dependencies": {
    "CoreCompat.System.Drawing": "1.0.0-beta006",
    ...
  },
}

Comment: This is prerelease software, so make sure you have the "show prerelease" box ticked.
Comment: This package has been marked deprecated and has not received any updates since June 27, 2016.
Answer: Aspose.Drawing can manipulate images using API compatible with System.Drawing, fully managed and cross-platform with .NET Core 2.0+ support. (I'm one of the developers.)

Manipulating images with .NET Core