text:
Q: How Google play knows the country of app installation? How do Google play knows the country where the user in when installing application from Google Play Store ?
Edit:
But the location persimmons are not used in the application.

A: I guess they use the network location from where the download is started. I can't think of a better alternative.

A: While installing the application from play store, you need not to worry about permission used in application as google play uses its own permissions. And Google Play store used both i.e. network provider and GPS location to decide location of user. And based on that Google displays play store.
If you want to check play store for another country, you may use application like TunnelBear.


text:
Q: How to create/integrate a qml file into qt-widgets app? I have an application developed in Qt4, with current display window designed in xml design sheets. I want to create a new window for the application, using QML to design the interface. Is that possible? Does it require a Qt5 to integrate the new qml file into the existing qt-widgets app?

A: Assuming you already have some working QWidget based code:
auto* container = new QQuickWidget(QUrl(QStringLiteral("qrc:main.qml")));
container->setResizeMode(QQuickWidget::SizeRootObjectToView);

auto* layout = new QVBoxLayout(_ui->widget);
layout->addWidget(container);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python Neuron class - Name Error on a class property I've been working on my code since yesterday and maybe I'm just tired but I'm stuck at a Name error and I can't understand why.
What I'm trying to do is make a general neuran class and then a class for each type of neuron instantiated with an appropriate method for neuron type indicator.
I'm not very fluent with classes and inheritance, maybe there's a cleaner and more Pythonic way to do it? But first why the error?:
class _Neuron(number, function, forwards_to=[] ):
    def __init__(self, number, function, forwards_to):
        self.number = number
        self.function = function
        self.forwards_to = forwards_to
        self.current_state = 0 #neurons may have any numeric state representing the sum of inputs from other neurons
        self.output = 0

    #whenever ready call to use up current state to calculate function output and restet the current state
    def fire(self):
        self.output = function(self.current_state)
        self.current_state = 0

    #receices numeric values of outputs of other neurons and adds them to the sum of received signals
    def receive_signal(self, input_signal):
        self.current_state+=input_signal

    #adds a forward connection
    def add_connection(self, neuron_number):
        if neuron_number not in self.forwards_to:
            self.forwards_to.append(neuron_number)
    #add multiple forward paths
    def add_connections(self, **neuron_numbers):
            for neuron_number in neuron_numbers:
                self.add_connection(neuron_number)

    #remove a neuron connection
    def remove_connection(self, neuron_number):
        if neuron_number in self.forwards_to:
            self.forwars_to.remove(neuron_number)
    #remove multiple forward paths
    def remove_connections(self, **neuron_numbers):
            for neuron_number in neuron_numbers:
                self.remove_connection(neuron_number)

    def _make_deep(self):
        self.type = "deep"

    def _make_input(self):
        self.type = "input"

    def _make_output(self):
        self.type = "output"

    def get_number(self):
        return self.number

    def get_type(self):
        return self.type

    def get_connections(self):
        return self.forwards_to

    def get_current_state(self):
        return self.current_state

    def get_output(self):
        return self.output

#classes for declaring specific neuron types
#input neuron
class InputNeuron(_Neuron):
        def __init__(self, number, function, forwars_to=[]):
            super().__init__(number, function, forwars_to=[])
            self._make_input()

#output neuron
class OutputNeuron(_Neuron):
        def __init__(self, number, function, forwars_to=[]):
            super().__init__(number, function, forwars_to=[])
            self._make_output()

#deep neuron
class DeepNeuron(_Neuron):
        def __init__(self, number, function, forwars_to=[]):
            super().__init__(number, function, forwars_to=[])
            self._make_deep()

#tests
f = lambda x: 1/x
n1 = _Neuron(number=1, function=f)
n1._make_input()
n1.add_connections(1,2,3,4,5)
n1.receive_signal(100)
print(n1.get_type())
print(n1.get_number())
print(n1.get_connections())
print(n1.get_current_state())
print(n1.get_output())
n1.fire()
print(n1.get_connections())
print(n1.get_current_state())
print(n1.get_output())

A: I can see several errors:
the first to are in the init of your _Neuron class, should be something like this

*

*1: your initialization parameters you need to put them in the init not when you declare the class

*2 If you use a list as a default parameter you can have inspected result since this is declared when the class is read, and thus all instances will share the same list. Check this post for more info.
class _Neuron:
    def __init__(self, number, function, forwards_to=None):
        if not forwards_to:
            forwards_to = []
        self.number = number
        self.function = function
        self.forwards_to = forwards_to
        self.current_state = 0 #neurons may have any numeric state representing the sum of inputs from other neurons
        self.output = 0

*

*3 you are missing self.funtion in your method fire

     def fire(self):
        self.output = self.function(self.current_state)
        self.current_state = 0

*

*4 ** this operator is for unpacking mappers as a dictionary, you should use  a single * for list add_connections and remove_connections method

    def add_connections(self, *neuron_numbers):
            for neuron_number in neuron_numbers:
                self.add_connection(neuron_number)

5 - this is not an error but Is how I would recommend to do what you are trying. If I'm not wrong, you want to declare a base _Neuron class to inherit for the rest, that is call an abstract class, and you can use the module abc to do this. Check here to learn more about it. Note an abstract class cannot be instatiated.
from abc import ABC, abstractmethod

class _Neuron(ABC):
    def __init__(self, number, function, forwards_to=None):
        super().__init__()
        if not forwards_to:
            forwards_to = []
        self.number = number
        self.function = function
        self.forwards_to = forwards_to
        self.current_state = 0 #neurons may have any numeric state representing the sum of inputs from other neurons
        self.output = 0
        self._make_type()

    #whenever ready call to use up current state to calculate function output and restet the current state
    def fire(self):
        self.output = self.function(self.current_state)
        self.current_state = 0

    #receices numeric values of outputs of other neurons and adds them to the sum of received signals
    def receive_signal(self, input_signal):
        self.current_state+=input_signal

    #adds a forward connection
    def add_connection(self, neuron_number):
        if neuron_number not in self.forwards_to:
            self.forwards_to.append(neuron_number)
    #add multiple forward paths
    def add_connections(self, *neuron_numbers):
            for neuron_number in neuron_numbers:
                self.add_connection(neuron_number)

    #remove a neuron connection
    def remove_connection(self, neuron_number):
        if neuron_number in self.forwards_to:
            self.forwars_to.remove(neuron_number)
    #remove multiple forward paths
    def remove_connections(self, *neuron_numbers):
            for neuron_number in neuron_numbers:
                self.remove_connection(neuron_number)

    @abstractmethod
    def _make_type(self):
        self.type = "deep"

    def get_number(self):
        return self.number

    def get_type(self):
        return self.type

    def get_connections(self):
        return self.forwards_to

    def get_current_state(self):
        return self.current_state

    def get_output(self):
        return self.output

#classes for declaring specific neuron types
#input neuron
class InputNeuron(_Neuron):
        def __init__(self, number, function, forwards_to=None):
            super().__init__(number, function, forwards_to=forwards_to)

        def _make_type(self):
            self.type = "input"
#output neuron
class OutputNeuron(_Neuron):
        def __init__(self, number, function, forwards_to=None):
            super().__init__(number, function, forwards_to=forwards_to)

        def _make_type(self):
            self.type = "output"
#deep neuron
class DeepNeuron(_Neuron):
        def __init__(self, number, function, forwards_to=None):
            super().__init__(number, function, forwards_to=forwards_to)

        def _make_type(self):
            self.type = "deep"

#tests
f = lambda x: 1/x
n1 = InputNeuron(number=1, function=f)
n1.add_connections(1,2,3,4,5)
n1.receive_signal(100)
print(n1.get_type())
print(n1.get_number())
print(n1.get_connections())
print(n1.get_current_state())
print(n1.get_output())
n1.fire()
print(n1.get_connections())
print(n1.get_current_state())
print(n1.get_output())


text:
Q: Tendermint: why GasWanted, GasUsed and Fee appear in in DeliverTx/CheckTx response? The ABCI specs declare that results of DeliverTx and CheckTx contain the following information:
...
GasWanted (int64): Amount of gas requested for transaction.
GasUsed (int64): Amount of gas consumed by transaction.
...
Fee (cmn.KI64Pair): Fee paid for the transaction.

I'm not sure why these parameters should appear in the response.
How "actionable" are these to the Tendermint Core, if at all?

A: Feel free to ignore these for now. They are not used by Tendermint core.


text:
Q: How to handle the AuthenticityToken value using a HTTP POST request from a RoR application to another RoR application? I am using Ruby on Rails 3 and I would like to know how to handle the AuthenticityToken value using a HTTP POST request from a RoR application to another RoR application. In this case I aim to submit a sign in form and return the user information in JSON format if he\she provided correct email and password values.
I have a RoR application at this URL
pjtnam.com

and another RoR application at this URL
users.pjtname.com

If I make an HTTP POST request from the application pjtname.com to the application users.pjtname.com like this (in this example I use the Typhoeus gem)
response = Typhoeus::Request.post("http://users.pjtname.com/authentications",
             :params => {
               :new_authentication => {
                 :email    => email,
                 :password => password
               }
             }
           )

I get this response

  ActionController::InvalidAuthenticityToken
    in AuthenticationsController#create

ActionController::InvalidAuthenticityToken

So, how to handle the AuthenticityToken value in a safe approach\mode? I would like to know in both when applications are located on the same server and when they aren't.
At http://users.pjtname.com/authentications/new I have the following form for signing in users:
<%= form_for(:new_authentication) do |f| %>
  <%= f.label :email %>
  <%= f.label :password %>

  <%= f.submit "Sign in" %>
<% end %>

In the authentications_controller.rb I have
def create
  # Note ':authentication' symbol is different than ':new_authentication' seen in HTTP POST parameters and in the above form
  @authentication = Authentication.new(params[:authentication])

  @account = Account.sign_in_account(params[:new_authentication][:email], params[:new_authentication][:password])

  ...

  respond_to do |format|
    format.html {
      redirect_to @account
    }
    format.js {
      render(:update) { |page|
        page.redirect_to @account
      }
    }
    format.json {
      render :json => @account
    }
  end
end

In routes.rb I have
  resources :authentications do #, :path => "authentication" do
    member do
      get  'confirm_authentication'
      post 'confirm_authentication'
    end
  end

UPDATE for the @idlefingers answer

REQUEST
Typhoeus::Request.post("http://users.pjtname.com/authentications/new",
# or
# Typhoeus::Request.post("http://users.pjtname.com/authentications",
   :headers => {"Content-Type" => "application/json"},
   :params => { ... } # Same parameters as above
   }
 )

RESPONSE

  StandardError

Invalid JSON string

REQUEST
Typhoeus::Request.post("http://users.pjtname.com/authentications/new.json",
   :params => { ... } # Same parameters as above
   }
 )

RESPONSE

Routing Error

No route matches "/authentications/new.json"

A: It looks like it's not sending the request with the correct content type. Rails should skip the authenticity token check if the content-type is application/xml or application/json, so that it plays nice with APIs without having to disable the authenticity token altogether.
I don't know the Typhoeus gem, but it looks like you may need to just add ".json" or ".xml" to the url (depending on the API you've implemented), or may need to pass it in as options in the headers hash.


text:
Q: Sublimelinter-clang Пытаюсь добиться, чтобы Sublime Text 3 автоматически отмечал ошибки в С-коде.
Установил плагины Sublimelinter и SublimeLinter-contrib-clang.
Clang доступен из консоли командой clang-4.0, С файлы собирает и запускает.
Однако ошибок Sublime не отмечает, на нажатие кнопки "show errors" не реагирует, т.е. как будто и не ставил плагин.
Настройки SublimeLinter оставил стандартными.
В /usr/bin/ лежат символические ссылки clang-4.0 и clang-3.9.
Не понимаю, что может быть не так. Причем плагин не работает молча, никаких ошибок, что исправлять не понятно.

A: Добавил в PATH путь к исполняемому файлу clang, теперь Sublime делает что нужно для cpp файлов. Почему нельзя было добавить в usr/bin символическую ссылку, не понимаю. С .C файлами так и не работает.


text:
Q: Auto re-generate of Keys reflected in Azure Key Vault Secret I have managed to create auto re-generate process between 'key1' and 'key2' with a gap of 1 day.
I have Key1 as a connection string within the Key Vault as secret when the Key does auto re-generate how do I reflect that change within the Key Vault secret?
The Key Vault is used within the Data Factory Pipeline.
$servicePrincipal = Get-AzADServicePrincipal -ServicePrincipalName cfa8b339-82a2-471a-a3c9-0fc0be7a4093
New-AzRoleAssignment -ObjectId $servicePrincipal.Id -RoleDefinitionName 'Storage Account Key Operator Service Role' -Scope $storage.Id
$userPrincipalId = $(Get-AzADUser -SearchString 'Bob Johnson').Id
Set-AzKeyVaultAccessPolicy -VaultName 'AzureBlobVault' -ObjectId $userPrincipalId -PermissionsToStorage get, list, delete, set, update, regeneratekey, getsas, listsas, deletesas, setsas, recover, backup, restore, purge
$regenerationPeriod = [System.Timespan]::FromDays(1)
Add-AzKeyVaultManagedStorageAccount -VaultName 'AzureBlobVault' -StorageAccountName 'john' -AccountResourceId '/subscriptions/XXXXXXX-XXXX-XXXXXXXXXXXXXXXX/resourceGroups/myResourceGroup/providers/Microsoft.Storage/storageAccounts/John' -ActiveKeyName 'key1' -RegenerationPeriod $regenerationPeriod'

The Result:

Id                  : https://azurekeyvaultblob.vault.azure.net:443/storage/john
Vault Name          : AzureBlobVault
AccountName         : john
Account Resource Id : /subscriptions/XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX/resourceGroups/myResourceGroup/providers/Microsoft.Storage/storageAccounts/john
Active Key Name     : key1
Auto Regenerate Key : True
Regeneration Period : 1.00:00:00
Enabled             : True

A: According to my research, at the moment, we only can ask Key Vault to generate shared access signature tokens. If you want to do that, you can use the following the script
$sctx = New-AzStorageContext -StorageAccountName $storageAccountName -StorageAccountKey Key1
$start = [System.DateTime]::Now.AddDays(-1)
$end = [System.DateTime]::Now.AddDays(1)
$at = New-AzStorageAccountSasToken -Service blob,file,Table,Queue -ResourceType Service,Container,Object -Permission "racwdlup" -Protocol HttpsOnly -StartTime $start -ExpiryTime $end -Context $sctx
Set-AzKeyVaultManagedStorageSasDefinition -AccountName $storageAccount.StorageAccountName  -VaultName $keyVaultName -Name accountsas -TemplateUri $at -SasType 'account' -ValidityPeriod ([System.Timespan]::FromDays(1))

For more details, please refer to the document and the article
Besides, if you only want to use the connection string, I think you need to write code or script to manage it. For example, I use powershell script:
$name = "your account"
$password = "your passowrd"
$secpasswd = ConvertTo-SecureString $password -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ($name, $secpasswd)
Connect-AzAccount -Credential $mycreds

$accountName ="your storage account name"
$keyvaultNmae="your key vault name"
$secretNmae="your secret name"
$accoutGroupName="your storage account group name"

$key=(Get-AzStorageAccountKey -ResourceGroupName $accoutGroupName -Name $accountName)[0].Value
$string= 'DefaultEndpointsProtocol=https;AccountName=' + $accountName + ';AccountKey=' + $Key + ';EndpointSuffix=core.windows.net'

$secretVaule= $Secret = ConvertTo-SecureString -String $string -AsPlainText -Force
Set-AzKeyVaultSecret -VaultName $keyvaultNmae -Name $secretNmae -SecretValue  $secretVaule

$vaule= (Get-AzKeyVaultSecret -VaultName $keyvaultNmae -Name $secretNmae).SecretValueText

Write-Output $vaule

Then I host the PowerShell script on Azure Automation runbook and create a schedule to run it


text:
Q: Why does my regex not work? I have several lines of phrases like
The quick brown fox jumps over the lazy dog
quick brown fox jumps over the lazy dog
brown fox jumps over the lazy dog

Now I want to select the rest of each line after every first word. I.e. I want to mark everything starting from the end of the first word in a line.
My attempt was:
^(?:\w+).*

I'm using this in Notepad++.
Why does this select the entire line? What am I doing wrong?
Thanks for improving my Regex knowledge!

A: *

*Ctrl+H

*Find what: ^\S+\h+(.+)$

*Replace with: $1

*check Wrap around

*check Regular expression

*UNCHECK . matches newline

*Replace all
Explanation:
^           # beginning of line
  \S+       # 1 or more non space (you van use \w+ if you want to replace ONLY word characters)
  \h+       # 1 or more horizontal spaces
  (.+)      # group 1, 1 or more any character but newline
$           # end of line

Result for given example:
quick brown fox jumps over the lazy dog
brown fox jumps over the lazy dog
fox jumps over the lazy dog

Screen capture:

Here is an explanation of your regex:
^           # beginning of line
  (?:       # start non capture group
    \w+     # 1 or more word character
  )         # end group
  .*        # 0 or more any character

So, it matches a word and every thing after this word. The non capture group is useless here. A non capture group doesn't mean that will not match but only that will not be captured. It is strictly equivalent to: ^\w+.*

A: You could use a zero-width positive lookbehind with \K, e.g.:
^\w+[^\w]+\K.*

The \w+ would match the first word at the beginning of the line (The or quick), the following space character would be matched by [^\w]+ (one or more non-word characters). And \K.* matches everything after that, not including anything before the \K into the match.
It's described in the perl documentation: https://perldoc.perl.org/perlre.html#Lookaround-Assertions
You regex doesn't work, because you're matching the beginning of the line, followed by one or more word-characters (doesn't matter if you use the non-capturing group (?:…) here or not), followed by any characters. The problem is, that the word-characters at the beginning of the line ^(?:\w+) (same as ^\w+) are part of your match.


text:
Q: How do you append bytes onto a file inside of a zip file via Python 2.7? I am currently working on a piece of a larger puzzle. For my piece, I have a file object and the destination of the zip file. There is never a time that I am aware of the size of the file object. I only know I have one. There for the zip has to support zip64.
My goal is to take that file object(pointer to the file) and write it to the zip file without loading the entire file into memory. I would like to do this chunk by chunk(especially if the file object is really big).
Any ideas on how I can go about doing this?
import zipfile

zip_path = "/tmp/file.zip"
file_to_zip_path = "/home/ryanb58/Desktop/movie.mp4"

with zipfile.ZipFile(zip_path, mode="w", allowZip64=True) as zip:
    f = open(file_to_zip_path, 'rb')
    while True:
        data = f.read(1024)
        zip.writestr("file.mp4", data)
        if not data:
            break

My issue is that when I write the new bytes to the file inside the zip. Upon it finishing, I open the zip and it is just a huge list of small files with the same name, each about 1024bytes in size.  My code above ^^ I am kind of stuck, so any ideas or solutions would be great.

A: Following the advice that @J.F.Sebastian gave in his comment, I was able to write my file to a zip without bringing the full file into memory.
Here is my solution for the override.
import zipfile

BUFFER_SIZE = 1024 * 10000 # 10 megabytes.

class Zip(zipfile.ZipFile):

def write(self, fileobj, arcname=None, compress_type=None):
    """Put the bytes from file into the archive under the name
    arcname."""

    """CONST"""
    ZIP64_LIMIT = (1 << 31) - 1
    ZIP_DEFLATED = 8

    try:
        import zlib # We may need its compression method
        crc32 = zlib.crc32
    except ImportError:
        zlib = None
        crc32 = binascii.crc32

    if not self.fp:
        raise RuntimeError(
              "Attempt to write to ZIP archive that was already closed")

    st = os.stat(fileobj.name)
    isdir = stat.S_ISDIR(st.st_mode)
    mtime = time.localtime(st.st_mtime)
    date_time = mtime[0:6]

    # Create ZipInfo instance to store file information
    if arcname is None:
        arcname = "/temp.zip"
    arcname = os.path.normpath(os.path.splitdrive(arcname)[1])

    # Strips any leading forward or back slashes for files.
    while arcname[0] in (os.sep, os.altsep):
        arcname = arcname[1:]
    if isdir:
        arcname += '/'

    # Create the zipinfo.
    zinfo = zipfile.ZipInfo(arcname, date_time)
    zinfo.external_attr = (st.st_mode & 0xFFFF) << 16L      # Unix attributes

    if isdir:
        zinfo.compress_type = ZIP_STORED
    elif compress_type is None:
        zinfo.compress_type = self.compression
    else:
        zinfo.compress_type = compress_type

    zinfo.file_size = st.st_size
    zinfo.flag_bits = 0x00
    zinfo.header_offset = self.fp.tell()    # Start of header bytes

    self._writecheck(zinfo)
    self._didModify = True

    if isdir:
        zinfo.file_size = 0
        zinfo.compress_size = 0
        zinfo.CRC = 0
        zinfo.external_attr |= 0x10  # MS-DOS directory flag
        self.filelist.append(zinfo)
        self.NameToInfo[zinfo.filename] = zinfo
        self.fp.write(zinfo.FileHeader(False))
        return

    # Must overwrite CRC and sizes with correct data later
    zinfo.CRC = CRC = 0
    zinfo.compress_size = compress_size = 0
    # Compressed size can be larger than uncompressed size
    zip64 = self._allowZip64 and \
            zinfo.file_size * 1.05 > ZIP64_LIMIT
    self.fp.write(zinfo.FileHeader())
    if zinfo.compress_type == ZIP_DEFLATED:
        cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
             zlib.DEFLATED, -15)
    else:
        cmpr = None
    file_size = 0
    while 1:
        buf = fileobj.read(BUFFER_SIZE)
        if not buf:
            break
        file_size = file_size + len(buf)
        CRC = crc32(buf, CRC) & 0xffffffff
        if cmpr:
            buf = cmpr.compress(buf)
            compress_size = compress_size + len(buf)
        self.fp.write(buf)

    if cmpr:
        buf = cmpr.flush()
        compress_size = compress_size + len(buf)
        self.fp.write(buf)
        zinfo.compress_size = compress_size
    else:
        zinfo.compress_size = file_size
    zinfo.CRC = CRC
    zinfo.file_size = file_size
    if not zip64 and self._allowZip64:
        if file_size > ZIP64_LIMIT:
            raise RuntimeError('File size has increased during compressing')
        if compress_size > ZIP64_LIMIT:
            raise RuntimeError('Compressed size larger than uncompressed size')
    # Seek backwards and write file header (which will now include
    # correct CRC and file sizes)
    position = self.fp.tell()       # Preserve current position in file
    self.fp.seek(zinfo.header_offset, 0)
    self.fp.write(zinfo.FileHeader())
    self.fp.seek(position, 0)
    self.filelist.append(zinfo)
    self.NameToInfo[zinfo.filename] = zinfo

As you can see I can't pass in zip64 into the FileHeader methods because on the system the code runs, it only supports Python 2.7.2 Whereas to support the correct headers for zip64 files you will need Python 2.7.4 at the minimum.
https://github.com/python/cpython/blob/2e46376c8c10908afed56ace4c7f0f7c64e80c5e/Misc/NEWS#L189


text:
Q: Flex data binding re-bind when data model not change, possible? There is a common case that I bind a data model value to a GUI control, say, a TextInput. The data model is retrieve from backend.
If user change the value of the TextInput, then click refresh button to retrieve the data model from backend again, the GUI value will not change back. Re-binding not happen, Since the value of data model not changed, no propertyChanged event fired.
In this case, I must Programmatically set the model value to the GUI after data refreshing done.
I know bi-directional binding can solve this problem(when user change value on GUI, set the new value to data model immediately). But sometimes I cannot use bi-directional binding, for example, the data model is a int, but user input a non-int value, I cannot set the value to data model. So the value in data model do not change, when refresh data, rebinding still not happen.
This will make the data binding useless. How to resolve this?
I put pseudo-code here for now, I will put real code later:
1. retrieve a data model from server, via blazeds or something else.
2. bind the model to a TextInput on GUI.
3. user change the TextInput text.
4. User click a refresh button, triger retrieve the model value again.
5. Now since the model value do not change, no PropertyChanged event fired.
6. GUI value still is the user's input, not the value from the model.

I can clear the model value before set the velue back, make re-binding happen.(but sometimes you do not know how to clean the model value, take int for example, you may do not know the original value and happen set the same value). Or I can manually set the model value to GUI. But both are not good looking.
bi-directional binding not work since if user input a invalid value, I cannot set it to the model. Model value do not change, re-bind will not happen.

A: Bidirectional binding can be achieved in a variety of ways, not necessarily with the @-symbol. In your particular case you need to use the Binding-tag:
<fx:Binding source="parseInt(someNumberInput.text)"
    destination="someModel.someNumberValue"/>

<s:TextInput id="someNumberInput" text="{someModel.someNumberValue}"/>

It's very important not to forget to parseInt() the numeric value.

A: You can dispatch binding events whenever you want.  One way is to simply dispatch a PropertyChangeEvent on all properties you want to update, but another is to add your own binding event in addition to standard binding.
For instance, I think this will work:
[Bindable]
[Bindable (event="allChanged")]//make sure to dispatch this yourself when everything changes
public var myInt:int;

There is a possibility that the custom binding event might prevent Flex from generating the code in the background that does standard binding (I have never done the above, because if I am going to use custom events, I tend to not use the standard binding).
Flash Builder 4.5 has awesome code generation, so you can just convert a public variable to a getter and setter, and it will ask you if you want to fire a custom event for the property.  If you check that box, it will write the code for you.  Then you add the second metadata tag by hand.
The getter/setter method will perform better, because then each property will have its own event, rather than all of them firing on propertyChange and checking if the property is the correct one.  But the other one is less verbose and more maintainable, if it works.

A: Use a relevant editor to edit a numeric value. Flex can not guess what you want to do.


text:
Q: Ionic 2 - how to change tab name After you create new tabs template with Ionic 2, and you want to replace one of the tab names to something else, for example settings, is there a easy/fast way to do this without changing all instances and the files names, or creating new tab and to delete the other?

A: If you just want to change the text that appears as the tab link, then go to src/pages/tabs/tabs.html and in that file change the tabTitle to whatever text you would like to display.
For example <ion-tab [root]="tab1Root" tabTitle="Settings" tabIcon="list"></ion-tab>


text:
Q: Active Directory - Using GPO To Update Multiple Versions Of .NET OK, I have searched everywhere for this one.  I have all the MSI's and packages I need to deploy .Net 3.5 SP1, and 2.0 and 3.0 (which are prerequisites for 3.5).  I can't figure out how to install all of them at once via GPO.
Basically, the computers on the network do NOT have any version of .Net installed, and I need them to be at 3.5 SP1.  I know I can deploy each version via GPO, force reboot the client, then push the next one, force reboot, and so on.  Is there a way to streamline install all 3 at once via GPO?
Thanks

A: You only need to deploy the .NET Framework 3.5 via GPO.  Version 3.5 includes 3.0 and 2.0:

MSDN: "When you install the .NET Framework 3.5 SP1, you get the 2.0
  and 3.0 layers automatically."

Also, any updates to 3.5 will eventually install via Windows Update so no need to tack those on as additional installs.


text:
Q: How to calculate mean velocity of gas particles along some line of sight in a simulation? In a cosmological hydrodynamic zoom-in simulation, we happen to know both the position and 3d velocity of gas particles in the simulated volume. However, I am interested only in a column of gas along some line-of-sight which has a fixed square cross section. I want to calculate the mean velocity of all gas particles inside this column along the line-of-sight. How to do this analytically?

A: If you know the orientation of the column as a unit vector $\hat u = a \hat x + b \hat y + c\hat z$, then the velocity of a particle $i$ down the line of sight is $\vec v_i\cdot\hat u$. Compute this for each particle whose positions lie in the column, and find the mean. Depending on context, you may actually want to find the mean of $|\vec v_i\cdot\hat u|$; it is a question of whether or not you want to distinguish between particles moving "up" or "down" the column.


text:
Q: Can Eigen be used also for 1-vectors (scalars)? I am writing some routine which is formally identical for 2-vectors and also for scalars. I would like to write is as a template for Eigen::Matrix<double,N,1>, instantiating it for N=2 or N=1 (for scalars, wrapping scalar double d as Eigen::Map<Eigen::Matrix<double,1,1>>(&d).
Is Eigen designed with that special case in mind? Is it going to be efficient, e.g. internally calling abs(v1) for Eigen::Matrix<double,1,1>::norm(), v1*v1 for squaredNorm() or copysign(1,v1) for normalized()?

A: There is no explicit specializations for size=1, but thanks to explicit unrollers, most expression will generate scalar code. For instance, squaredNorm() will generate x*x, but norm will generate sqrt(x*x). Same for normalized().


text:
Q: Sample php code to programmatically check SOAP connection in Magento 2 I tried the below code though I am not sure whether these are the required set of scripts, but it didn't work and gives

SOAP-ERROR: Parsing WSDL: Couldn't load from  : Start tag expected,
  '<' not found

$wsdlUrl = 'http://localhost/magento20_0407/soap/default?wsdl_list=1';
$apiUser = 'testUser';
$apiKey = 'admin123';
$token = 'xioxnuuebn7tlh8ytu7781t14w7ftwmp';

$opts = array('http' => array('method' => "GET", 'header' => "Accept-language: en\r\nConnection: close\r\n"));
$context = stream_context_create($opts);
stream_context_set_option($context, "http", "protocol_version", 1.1);
fpassthru(fopen($wsdlUrl, 'r', false, $context));
$opts = array('http'=>array('header' => 'Authorization: Bearer '.$token));
$serviceArgs = array("id"=>1);

try{
    $context = stream_context_create($opts);
    $soapClient = new SoapClient($wsdlUrl, array('version' => SOAP_1_2, 'context' => $context));
    $soapResponse = $soapClient->customerCustomerAccountServiceV1($serviceArgs);
}catch(Exception $e){
    $e->getMessage();
}
    var_dump($soapResponse);exit;

Can anyone share the code to make SOAP connection in Magento2.x
In Magento1.x the below code works fine to connect SOAP
$apiUrl = 'http://localhost/magento_28_03/index.php/api/soap?wsdl';
$apiUser = 'testUser';
$apiKey = 'admin123';

ini_set("soap.wsdl_cache_enabled", "0");
try{
    $client = new SoapClient($apiUrl, array('cache_wsdl' => WSDL_CACHE_NONE));
} catch (SoapFault  $e) {
    echo 'Error in Soap Connection : '.$e->getMessage();
}
try {
    $session = $client->login($apiUser, $apiKey);
    if($session) echo 'SOAP Connection Successful.';
    else echo 'SOAP Connection Failed.';

} catch (SoapFault  $e) {
    echo 'Wrong Soap credentials : '.$e->getMessage();
}

But the above doesn't work for Magento1.x. Can anyone say, what changes the above code need to work fine for Magent2.x ?
I copied the view source code and pasted in a text file. Checked it thoroughly. There is no space at all.

A: <?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require('vendor/zendframework/zend-server/src/Client.php');
require('vendor/zendframework/zend-soap/src/Client.php');
require('vendor/zendframework/zend-soap/src/Client/Common.php');

$wsdlurl = 'http://10.16.16.190//magentoce27/index.php/soap/default?wsdl&services=customerCustomerRepositoryV1';

/*Token Generated from SYstem Integratio*/

$token = 'dx2x7pl5mxq9hp8jr8efcl5crv2pk699';

$opts = ['http' => ['header' => "Authorization: Bearer ".$token]];
$context = stream_context_create($opts);
//$arguments =
$serviceArgs = array('searchCriteria'=>
        array('filterGroups' =>
            array ('filters' =>
                array('field' =>'firstname',
                      'value' => 'Veronica' ,
                      'condition_type' => 'eq')
                )
         )
);
$soapClient = new \Zend\Soap\Client($wsdlurl);
$soapClient->setSoapVersion(SOAP_1_2);
$soapClient->setStreamContext($context);
$result = $soapClient->customerCustomerRepositoryV1GetList($serviceArgs);//array('searchCriteria' => $serviceArgs));
//$result = $soapClient->customerCustomerRepositoryV1GetById(array('customerId' => 1));
/*'search_criteria'=>
        array('filter_groups' =>
            array ('filters' =>
                array('field' =>'firstname',
                      'value' => 'Veronica' ,
                      'condition_type' => 'eq')
                )
         )
);*/
echo "<pre>"; print_r($result);
?>

This is test script for soap request so far I tried. You can do as per your need changing request and params


text:
Q: Short hand way of writing if statements using 13 OR comparison operators? Roulette.prototype.setColourToNumbers = function() {
  if (this.number == 2 || this.number == 4 || this.number == 6 || this.number == 8 || this.number == 10 || this.number == 11 || this.number == 13 || this.number == 15 || this.number == 17 || this.number == 20 || this.number == 22 || this.number == 24 || this.number == 26 || this.number == 29 || this.number == 28 || this.number == 29 || this.number == 31 || this.number == 33 || this.number == 35)
  { this.colour = 'black' }
 else if (this.number == 1 || this.number == 3 || this.number == 5 || this.number == 7 || this.number == 9 || this.number == 12 || this.number == 14 || this.number == 16 || this.number == 18 || this.number == 19 || this.number == 21 || this.number == 23 || this.number == 25 || this.number == 27 || this.number == 30 || this.number == 32 || this.number == 34 || this.number == 36)
{ this.colour = 'red'}
else
{ this.colour = null}
};

I'm writing a program in Javascript to make a board on Roulette. This code looks very messy to me and I was wondering if there was an cleaner and much shorter way of writing the above? Is there any way I can do it without specifying each number? Like having red numbers in an array? I'm stumped.
Appreciate the help!

A: I would suggest keeping a table of what maps where, and looking up values from that as you go. Like so:

var colorValues = {
  "red": [1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36],
  "black": [2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 25]
};

function getColor(value) {
  for (var f in colorValues) {
    if (colorValues.hasOwnProperty(f) && colorValues[f].indexOf(value) > -1) {
      return f;
    }
  }

  return null;
}

// Check a few
for (var i = 0; i < 40; ++i) {
  $("body").append("<div>" + i + " is " + getColor(i) + "</div>");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

This works by keeping each valid output as a key, with a list of values (I think that's the most obvious structure, given the data). When you receive a value, walk through the keys until you find the one containing that value. If none of them do, return null.

A: Check out How do I check if an array includes an object in JavaScript? for some options for Array contains functions.
I'd create an array using shorthand for numbers which resolve to black and a second array for numbers which resolve to red.
Shorthand to create the arrays is var redArray = [1, 3, 5, 7, ...]

A: I think you want a switch statement.
switch(this.number) {
  case 1,2,3,4,5,6,7: this.color = 'black'; break;
  case 8,9,10,11,12,13: this.color = 'red'; break;
}

UPDATE
This syntax will only match the last number of the series, so it's no good.
The switch version of this would be
switch(this.number) {
  case 1:
  case 2:
  case 3:
    this.color = red; break;
  case 4:
  case 5:
  case 6:
    this.color = black; break;
}

Which may be a little verbose for your use case.

A: Here you go:
Roulette.prototype.setColourToNumbers = function() {
    this.colour = null;
    var colors = {
        'red' : [2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 29, 28, 29, 31, 33, 35],
        'black' : [1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36]
    }

    for (var k in colors) {
        if (colors[k].indexOf(this.number) > 0) {
            this.colour = k;
        }
    }
    console.log(this.colour);
};

Beware of indexOf() not working in early IE.

A: You could also do the inverse of what @ssube suggests, having an array of numbers -> colors.  Note the use of comments to track numbers to colors in the source code.
//           0       1      2       3
var wheel= [null, "red", "black", "red", ...];

Then a simple lookup, color = wheel[this.number];
Frankly, I like ssube's idea slightly better, but presenting this as an alternative.  YMMV.

A: I've noticed that in your first if statment the this.number == 29 boolean clause is incorrectly duplicated.
PS: I am working on my solution now, which will include unit tests.

A: Whilst I was writing my answer I saw 'CmajSmith' had put up something pretty similar. The only difference being that I only define the arrays for red vs black lookup once and so I reduce the garbage collection overhead everytime the method runs. Not sure that this is important to you (i.e. performance) but I assumed that your method would be called quite frequently:
Roulette.prototype.setColourToNumbers = function() {
  var colour;
  if (!Roulette.prototype.setColourToNumbers.arrBlackNumbers) {
      Roulette.prototype.setColourToNumbers.arrBlackNumbers = [2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35];
      Roulette.prototype.setColourToNumbers.arrRedNumbers = [1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36];
  }
  colour = Roulette.prototype.setColourToNumbers.arrBlackNumbers.indexOf(this.number) > -1 ? "black" : Roulette.prototype.setColourToNumbers.arrRedNumbers.indexOf(this.number) > -1 ? "red" : null;
  this.colour = colour;
};
// *********************************************************
// U N I T    T E S T E D    M Y    A N S W E R    B E L O W
// *********************************************************
function Roulette(iNum) {
  this.number = iNum;
}
var num, roulette;
//First off unit test the 'black' numbers
num = 2, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'black'), "Expected \'black\' when number is: " + num );
num = 4, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'black'), "Expected \'black\' when number is: " + num);
num = 6, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'black'), "Expected \'black\' when number is: " + num);
num = 8, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'black'), "Expected \'black\' when number is: " + num );
num = 10, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'black'), "Expected \'black\' when number is: " + num);
num = 11, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'black'), "Expected \'black\' when number is: " + num);
num = 13, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'black'), "Expected \'black\' when number is: " + num );
num = 15, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'black'), "Expected \'black\' when number is: " + num);
num = 17, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'black'), "Expected \'black\' when number is: " + num);
num = 20, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'black'), "Expected \'black\' when number is: " + num );
num = 22, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'black'), "Expected \'black\' when number is: " + num);
num = 24, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'black'), "Expected \'black\' when number is: " + num);
num = 26, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'black'), "Expected \'black\' when number is: " + num );
num = 28, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'black'), "Expected \'black\' when number is: " + num);
num = 29, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'black'), "Expected \'black\' when number is: " + num);
num = 31, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'black'), "Expected \'black\' when number is: " + num );
num = 33, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'black'), "Expected \'black\' when number is: " + num);
num = 35, roulette = new Roulette(num);
//Now unit test the 'red' numbers
console.assert((roulette.setColourToNumbers(), roulette.colour === 'black'), "Expected \'black\' when number is: " + num);
num = 1, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'red'), "Expected \'red\' when number is: " + num);
num = 3, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'red'), "Expected \'red\' when number is: " + num);
num = 5, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'red'), "Expected \'red\' when number is: " + num);
num = 7, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'red'), "Expected \'red\' when number is: " + num);
num = 9, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'red'), "Expected \'red\' when number is: " + num);
num = 12, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'red'), "Expected \'red\' when number is: " + num);
num = 14, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'red'), "Expected \'red\' when number is: " + num);
num = 16, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'red'), "Expected \'red\' when number is: " + num);
num = 18, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'red'), "Expected \'red\' when number is: " + num);
num = 19, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'red'), "Expected \'red\' when number is: " + num);
num = 21, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'red'), "Expected \'red\' when number is: " + num);
num = 23, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'red'), "Expected \'red\' when number is: " + num);
num = 25, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'red'), "Expected \'red\' when number is: " + num);
num = 27, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'red'), "Expected \'red\' when number is: " + num);
num = 30, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'red'), "Expected \'red\' when number is: " + num);
num = 32, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'red'), "Expected \'red\' when number is: " + num);
num = 34, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'red'), "Expected \'red\' when number is: " + num);
num = 36, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === 'red'), "Expected \'red\' when number is: " + num);

//Finally unit test other numbers
num = -99, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === null), "Expected null when number is: " + num);
num = Number.POSITIVE_INFINITY, roulette = new Roulette(num);
console.assert((roulette.setColourToNumbers(), roulette.colour === null), "Expected null when number is: " + num);


text:
Q: How do I change the chain name of a pdb file? I want to rename the chains of a PDB file '6gch' - https://www.rcsb.org/structure/6GCH.
I have checked the Biopython manual and can't seem to find anything.
Any input would be of great help!

A: You can indeed just change the id attribute of the chain elements. After that you can use PDBIO to save the modified structure.
Note however, that this process modifies the PDB quite a bit. PDBIO does not store entries like REMARKs, SHEETs and SSBONDs. If you know that you need those, you must be careful.
Also this process moves the HETATMs at the end of the corresponding chain while the original PDB had them located at the end of the file.
As 6GCH has 3 chains, I am using the dictionary renames to configure the mapping of old to new chain name. If a chain name is not included in this dict, no renaming will be done.
from Bio.PDB import PDBList, PDBIO, PDBParser

pdbl = PDBList()

io = PDBIO()
parser = PDBParser()
pdbl.retrieve_pdb_file('6gch', pdir='.', file_format="pdb")

# pdb6gch.ent is the filename when retrieved by PDBList
structure = parser.get_structure('6gch', 'pdb6gch.ent')

renames = {
    "E": "A",
    "F": "B",
    "G": "C"
}

for model in structure:
    for chain in model:
        old_name = chain.get_id()
        new_name = renames.get(old_name)
        if new_name:
            print(f"renaming chain {old_name} to {new_name}")
            chain.id = new_name
        else:
            print(f"keeping chain name {old_name}")

io.set_structure(structure)
io.save('6gch_renamed.pdb')


text:
Q: Detecting keys pressed without events in UWP I am writing a simple 2D game engine for UWP. I have a code snippet taken from XNA, checking for if a certain key is pressed (see below), and I'm trying to do something similar.
Indeed, in my game engine I'd rather not use the dedicated event handlers (KeyDown etc), but instead simply check for pressed keys in my game loop - if this is possible to do. One reason for this is that I can then control for example how often a bullet fires if the key is continuously pressed (using a timer and mod). It would also let the keys be independent of each other, such as up and right arrow key gives diagonal movement for player 1, while another player (using the same keyboard) uses keys A and W to move his/her character in another direction, and they both occasionally fire their laser guns. Finally, I have always considered using the event handlers working separately from my the rest of my game code, resulting in lack of control. This is especially true for the KeyPress event, I think.
The code I have found looks like this:
 public void DrawHelp()
        {
            if (Keyboard.GetState().IsKeyDown(Keys.Tab))
            {

..and this is what I'm trying to use. However, the Keyboard class words don't come up in Intellisense for me (though the Windows.UI.Xaml.Input; using is attached by default).
What I'm thinking of is basically a series of if statements (the code is wrong - it's just to show what I want):
    int counter = 0;

    // Raised every tick while the DispatcherTimer is active.
    private void EachTick(object sender, object e)
    {
        TrackKeyboard();
        CalculateMoves();
        Physics.CollisionDetection();
        DrawGame();
    }

    private void TrackKeyboard()
    {
        if (Keyboard.GetState().IsKeyDown(Keys.P)) PauseGame();

        if (counter % 10 == 0) //control movements
        {
            if (Keyboard.GetState().IsKeyDown(Keys.Down)) AddSpeed("Player1", 0, -1);
            if (Keyboard.GetState().IsKeyDown(Keys.Left)) AddSpeed("Player1", -1, 0);
            if (Keyboard.GetState().IsKeyDown(Keys.Up)) AddSpeed("Player1", -1, 0);
            if (Keyboard.GetState().IsKeyDown(Keys.Right)) AddSpeed("Player1", 0, 1);
            if (Keyboard.GetState().IsKeyDown(Keys.W)) AddSpeed("Player2", -1, 0);
            if (Keyboard.GetState().IsKeyDown(Keys.D)) AddSpeed("Player2", 0, 1);
            if (Keyboard.GetState().IsKeyDown(Keys.S)) AddSpeed("Player2", -1, 0);
            if (Keyboard.GetState().IsKeyDown(Keys.A)) AddSpeed("Player2", 0, 1);
        }

        if (counter % 5 == 0) //fire
        {
            if (Keyboard.GetState().IsKeyDown(Keys.Space)) Fire("Player1");
            if (Keyboard.GetState().IsKeyDown(Keys.X)) Fire("Player2");
        }
    }

So, is it possible to write something like this in UWP, and if so: How?
I've done some searching on Bing and Google for this, but there is still very little info on UWP.
I have found a similar question on CodeProject (https://www.codeproject.com/Questions/1107441/How-do-I-register-events-from-two-players-in-UWP), but the answer is too difficult for me to follow, and in any case, I'd much rather include this code in the game loop, as described above.
(Also please let me know if the route I'm trying to take is stupid for some technical reason that I may not be aware of.)
Thanks so much and Happy New Year!
Petter

A: In UWP, you should check the key state from CoreWindow using these methods:
Window.Current.CoreWindow.GetKeyState(VirtualKey).HasFlag(CoreVirtualKeyStates);

You have to specify the key and state you want to get info about for example like this:
if(Window.Current.CoreWindow.GetKeyState(VirtualKey.Escape).HasFlag(CoreVirtualKeyStates.Down))
{
    // Escape key pressed
}

You should not only compare the value returned from the GetKeyState method like this:
Window.Current.CoreWindow.GetKeyState(VirtualKey) == CoreVirtualKeyStates.Down;

since it could return CoreVirtualKeyStates.Down | CoreVirtualKeyStates.Locked when the key is pressed and the condition will then be false.


text:
Q: $_GET is not passed in this form First of all, I can't use the action='' attribute. That's why I use on submit.
Here my code:
<form class="search" role="search" method="get" onsubmit="window.location.href='home.php?m=search&q='; return false;">
  <input type="text" placeholder="Rechercher..." name="s">
</form>

How can I get my input content after my onsubmit url ?
Can jQuery could get this content and put it in this address ? How do do this ?
Thanks.

A: I believe you want
window.location.href='home.php?m=search&q='+this.s.value; return false

Possibly even
window.location.href='home.php?m=search&q='+encodeURIComponent(this.s.value); return false

to be sure
To use the form action, you could do
onsubmit="this.action='home.php?m=search'"

and change name="s" to name="q"


text:
Q: scrape text from slideshare slides (for multiple presentations) Is there any method/package/framework to scrape text from slides on slideshare? The only method I could think of was to download slides as pdf and then run an OCR tool to extract text. I was wondering if there is a more elegant way to do this ? Ideally I would want to do this for multiple presentations and I am looking for a way to automate this process.
EDIT : Adding example
An example would be that say this slide has many elements. But below the comments we can get only the title of the slide. I was hoping that we can scrape the entire text off this slide.
This is what is shown below the comments
This is the entire slide


text:
Q: Flutter issue: Pass argument to Widget constructor as named parameter Flutter issue.  I'm trying to pass an argument to a Widget constructor as a named parameter, but I get the error: The named parameter 'uri' isn't defined.  The code where I define the class is below, followed by the code where I instantiate the Widget. I'm stuck. Any help is much appreciated!
//Code defining Widget

class VideoPlayerApp extends StatelessWidget {
  VideoPlayerApp({this.uri});
  final Text uri;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Video Player Demo',
      home: VideoPlayerScreen(),
    );
  }
}

//Code defining sURI and then instantiating Widget
Text sURI = Text(
        'https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4');

onPressed: () {
   Navigator.push(
      context,
      MaterialPageRoute(
         builder: (context) => VideoPlayerApp(uri: sURI),
      ),
   );
},

A: You should define uri as String, not Text.
Try this:
class VideoPlayerApp extends StatelessWidget {
  VideoPlayerApp({
    Key key,
    this.uri,
  }) : super(key: key);

  final String uri;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Video Player Demo',
      home: VideoPlayerScreen(),
    );
  }
}


text:
Q: Group concat limit 1 Here is my group concat query
GROUP_CONCAT(DISTINCT IF(catalog_product_entity_varchar.attribute_id = '134',catalog_product_entity_varchar.value,NULL)) AS 'Subtitle'

The table contains multiple rows with 134 as the attribute id.  Really all I want to do is pull the first catalog_product_entity_varchar.value WHERE catalog_product_entity_int.attribute_id=134
The full SQL is as follows
SELECT catalog_product_entity.sku AS SKU,
    IF(catalog_product_entity_decimal.attribute_id = '67',catalog_product_entity_decimal.value,NULL) AS 'Price',
    GROUP_CONCAT(DISTINCT IF(catalog_product_entity_int.attribute_id = '146',catalog_product_entity_int.value,NULL)) AS 'Brand',
    GROUP_CONCAT(DISTINCT IF(catalog_product_entity_varchar.attribute_id = '63',catalog_product_entity_varchar.value,NULL)) AS 'Name',
    GROUP_CONCAT(DISTINCT IF(catalog_product_entity_varchar.attribute_id = '134',catalog_product_entity_varchar.value,NULL)) AS 'Subtitle'
FROM catalog_product_entity
    JOIN catalog_product_entity_decimal ON catalog_product_entity_decimal.entity_id = catalog_product_entity.entity_id
    JOIN catalog_product_entity_int ON catalog_product_entity_int.entity_id = catalog_product_entity.entity_id
    JOIN catalog_product_entity_varchar ON catalog_product_entity_varchar.entity_id = catalog_product_entity.entity_id
WHERE catalog_product_entity.type_id='simple' AND catalog_product_entity.sku='30020262'
GROUP by catalog_product_entity.entity_id

Edit: An attempt to make things clearer.
I'm pulling off data for products.  To make things easier, try to ignore most of the query. We will concentrate only on the 'sku' and the 'subtitle'.
The first table catalog_product_entity.  We are pulling off the SKU for each product.  There is also a unique 'entity_id'.
We use the 'entity_id' when we want to pull off all associated details for this product from another table called catalog_product_entity_varchar.
The attribute id refers to which particular information you want. 134 is subtitle and 63 is the name.  There are other 'attributes' as well that each have an id.
I've used an IF statement to allow me to assign 134 to 'subtitle' and 63 to 'name'.  The table looks something like this.
entity_id   attribute_id   store_id   value
1                134         0        green, large
1                134         1        green, large
1                134         2        green, large
1                63          0        dakine day hiker bag
1                63          1        dakine day hiker bag
1                63          2        dakine day hiker bag

Notice how one product seems to have the same subtitle stored 3 times.  This is because the ecommerce platform I'm using (Magento) allows you to store a different subtitle for each store you having running (one Magento install allows multiple domains to share the same product database, but have separate subtitles/descriptions,etc)
I have used Group_Concat to grab the data and then DISTINCT to make sure I only grab one subtitle. However the problem I'm facing is that most of the time my subtitles and names are exactly the same across all stores (so Distinct works) but when there are different subtitles distinct will grab more than one subtitle.
To be honest I'm not great with MYSQL and feel I might somehow omit group_concat altogether, maybe using nested SQL statements.  Bear in mind we don't always know what store ids a product will use.
I don't really care which subtitle I grab, I just want one, the first one, the min one, the max one. Whatever.

A: You say:

The table contains multiple rows with 146 as the attribute id. Really all I want to do is pull the first catalog_product_entity_int.value WHERE catalog_product_entity_int.attribute_id=146.

What you say you want is implemented by:
SELECT Value
  FROM Catalog_Product_Entity_Int
 WHERE Attribute_ID = 146;

This might return multiple values, so you have to define what you mean by 'first'; it could be MIN, MAX, LIMIT 1, or some other criterion.
SELECT MIN(Value) AS Value
  FROM Catalog_Product_Entity_Int
 WHERE Attribute_ID = 146;

SELECT MAX(Value) AS Value
  FROM Catalog_Product_Entity_Int
 WHERE Attribute_ID = 146;

SELECT Value
  FROM Catalog_Product_Entity_Int
 WHERE Attribute_ID = 146
 LIMIT 1;

For what you say you want, I see no reason to join the other three tables or to use GROUP_CONCAT.
That leads me to suspect that you have not told us what you really want because the query shown is dramatic overkill for the stated requirement.


text:
Q: How to handle empty session cache when "no-store" in php? I am using:
session_cache_limiter('no-store');

Because I want when I go to the next page the previous page values remain the same and do not change. And this works fine for me.
But the problem is I have to empty one session before going to the next page.
I am empty the session like below:
    $_SESSION['abcde'] = "";

But the problem is when I return to the page where I use
session_cache_limiter('no-store');
$_SESSION['abcde'] = ""; // Here the session abcde still have the value and do not empty

Kindly suggest what I am doing wrong.
Thank You.

A: I really don't understand what you mean when you said "the problem is I have to empty one session"
but i can suggest you use
unset($_SESSION['abcde']); // for destroy session

or
$_SESSION['abcde'] = null; // for replace null instead of the previous value

i hope this is your solution.

A: make sure to call session_cache_limiter() before session_start()
I still think you should use 'nocache' instead of 'no-store' see possible values of session_cache_limiter https://www.php.net/manual/de/function.session-cache-limiter.php
When you go to next page and want to have previous values remain, it is doing in right.
First page (e.g. index.php) you set $_SESSION['foo'] = 'bar';
next page you have $_SESSION['foo'] == 'bar' remaining of the first page so you want to do something else?
Try make the session-array deeper, make a array-key for each page that was visited
page 1: index.php
session_cache_limiter('nocache');
session_start();
echo 'Session at the start:
' . print_r( $_SESSION, 1 ) . '
';
$_SESSION['index'] = array( 'foo' => 'bar');
echo 'Session now:
' . print_r( $_SESSION, 1 ) . '
';

page 2: page2.php
session_cache_limiter('nocache');
session_start();
// here $_SESSION contains index => array( 'foo' => 'bar' )
echo 'Session at the start:
' . print_r( $_SESSION, 1 ) . '
';
$_SESSION['page2'] = array( 'some' => 'value');
echo 'Session now:
' . print_r( $_SESSION, 1 ) . '
';


text:
Q: How to add data from controller to a blade file in laravel for table? I am trying to add data for a table from mysql to laravel blade file and the data is adding row by row, but i need the data to be entered in a single row.

Here is my vscode(oneway.blade.php) file.I used for each and if else to display the data to the table.
.
I used foreach to get the data from RatesController.php file..

I need to display the rates as a single row like this.
I tried to get all the data in a single row. But the data was adding one by one row wise. I used foreach to get the data from RatesController.php to my blade file oneway.blade.php file.
@foreach($rates as $rate)
@foreach($dummies as $dummy)

              if($dummy->passenger_category_name_start_value == $rate->passenger_category_name_start_value)

                {{$rate->places_id_start}}
                {{$rate->places_id_destination}}

                        @if ($rate->passenger_category_name_start_value == 1)

                          € {{$rate->rate}}

                        @elseif ($rate->passenger_category_name_end_value <= 3)

                          € {{$rate->rate}}

                        @endif

                  @if ($rate->passenger_category_name_start_value == 4)

                    € {{$rate->rate}}

                  @elseif ($rate->passenger_category_name_end_value <= 5)

                    €

                  @endif

                  @if ($rate->passenger_category_name_start_value == 5)

                    € {{$rate->rate}}

                  @elseif ($rate->passenger_category_name_end_value <= 6)

                    €

                  @endif

                  @if ($rate->passenger_category_name_start_value == 6)

                    € {{$rate->rate}}

                  @elseif ($rate->passenger_category_name_end_value <= 6)

                    €

                  @endif

                  @if ($rate->passenger_category_name_start_value == 7)

                    € {{$rate->rate}}

                  @elseif ($rate->passenger_category_name_end_value <= 7)

                    €

                  @endif

                  @if ($rate->passenger_category_name_start_value == 8)

                    € {{$rate->rate}}

                  @elseif ($rate->passenger_category_name_end_value <= 9)

                    €

                  @endif

                  @if ($rate->passenger_category_name_start_value == 9)

                    € {{$rate->rate}}

                  @elseif ($rate->passenger_category_name_end_value <= 10)

                    €

                  @endif

                @if ($rate->passenger_category_name_start_value == 10)

                  € {{$rate->rate}}

                @elseif ($rate->passenger_category_name_end_value <= 11)

                  €

                @endif

                @if ($rate->passenger_category_name_start_value == 11)

                  € {{$rate->rate}}

                @elseif ($rate->passenger_category_name_end_value <= 12)

                  €

                @endif

                @if ($rate->passenger_category_name_start_value == 12)

                  € {{$rate->rate}}

                @elseif ($rate->passenger_category_name_end_value <= 13)

                  €

                @endif

                @if ($rate->passenger_category_name_start_value == 13)

                  € {{$rate->rate}}

                @elseif ($rate->passenger_category_name_end_value <= 14)

                  €

                @endif

                @if ($rate->passenger_category_name_start_value == 14)

                  € {{$rate->rate}}

                @elseif ($rate->passenger_category_name_end_value <= 15)

                  €

                @endif

                @if ($rate->passenger_category_name_start_value == 15)

                  € {{$rate->rate}}

                @elseif ($rate->passenger_category_name_end_value <= 16)

                  €

                @endif

                @if ($rate->passenger_category_name_start_value == 16)

                  € {{$rate->rate}}

                @else

                  €

                @endif

            @endforeach
          @endforeach

I used for each in controller RatesController.php to get from my backend file.
<?php

namespace App\\Http\\Controllers\\Frontend;
use App\\Http\\Controllers\\Controller;

use App\\Models\\TourCategories;

use App\\Models\\PassengerCategories;

use App\\Models\\Rates;use App\\Models\\Place;

class RatesController extends Controller

{

    $rates =  Rates::where('deleted','=','0')->orderBy('rates.id')->get();

            // dd($rates);

            foreach($rates as $rate){

                $place = Place::where('id','=',$rate['places_id_start'])->first();
                $rate['places_id_start'] = $place['name'];
            }

            foreach($rates as $rate){

                $place = Place::where('id','=',$rate['places_id_destination'])->first();
                $rate['places_id_destination'] = $place['name'];
            }

            foreach($rates as $rate){

                $passenger_category = PassengerCategories::where('id','=',$rate['pasenger_categories_id'])->first();
                $rate['passenger_category_name_start_value'] = $passenger_category['start_value'];
            }
            foreach($rates as $rate){

                $passenger_category = PassengerCategories::where('id','=',$rate['pasenger_categories_id'])->first();
                $rate['passenger_category_name_end_value'] = $passenger_category['end_value'];
            }
            //dd($rates);
            //return $rates;

            $dummies =  Rates::where('deleted','=','0')->orderBy('rates.id')->get();

            // dd($rates);

            foreach($dummies as $dummy){

                $place = Place::where('id','=',$dummy['places_id_start'])->first();
                $dummy['places_id_start'] = $place['name'];
            }

            foreach($dummies as $dummy){

                $place = Place::where('id','=',$dummy['places_id_destination'])->first();
                $dummy['places_id_destination'] = $place['name'];
            }

            //dd($dummies);

            $tourCategories = TourCategories::where('active',1)->where('deleted',0)->get();
            return view('frontend.rates.oneway',compact('tourCategories','rates','dummies'));

            // dd($tourCategories);
        }
        public function paris(){
            $tourCategories = TourCategories::where('active',1)->where('deleted',0)->get();
            return view('frontend.transfers.paristransfers',compact('tourCategories'));
            //dd($tourCategories);
        }

A: In oneway.blade.php on line 57 you need to prepend the if statement with an @

A: Check this code:
@foreach($rates as $rate)
@foreach($dummies as $dummy)
          @if($dummy->passenger_category_name_start_value == $rate->passenger_category_name_start_value)

            {{$rate->places_id_start}}
            {{$rate->places_id_destination}}

                    @if ($rate->passenger_category_name_start_value == 1)

                      € {{$rate->rate}}

                    @elseif ($rate->passenger_category_name_end_value <= 3)

                      € {{$rate->rate}}

                    @endif

              @if ($rate->passenger_category_name_start_value == 4)

                € {{$rate->rate}}

              @elseif ($rate->passenger_category_name_end_value <= 5)

                €

              @endif

              @if ($rate->passenger_category_name_start_value == 5)

                € {{$rate->rate}}

              @elseif ($rate->passenger_category_name_end_value <= 6)

                €

              @endif

              @if ($rate->passenger_category_name_start_value == 6)

                € {{$rate->rate}}

              @elseif ($rate->passenger_category_name_end_value <= 6)

                €

              @endif

              @if ($rate->passenger_category_name_start_value == 7)

                € {{$rate->rate}}

              @elseif ($rate->passenger_category_name_end_value <= 7)

                €

              @endif

              @if ($rate->passenger_category_name_start_value == 8)

                € {{$rate->rate}}

              @elseif ($rate->passenger_category_name_end_value <= 9)

                €

              @endif

              @if ($rate->passenger_category_name_start_value == 9)

                € {{$rate->rate}}

              @elseif ($rate->passenger_category_name_end_value <= 10)

                €

              @endif

            @if ($rate->passenger_category_name_start_value == 10)

              € {{$rate->rate}}

            @elseif ($rate->passenger_category_name_end_value <= 11)

              €

            @endif

            @if ($rate->passenger_category_name_start_value == 11)

              € {{$rate->rate}}

            @elseif ($rate->passenger_category_name_end_value <= 12)

              €

            @endif

            @if ($rate->passenger_category_name_start_value == 12)

              € {{$rate->rate}}

            @elseif ($rate->passenger_category_name_end_value <= 13)

              €

            @endif

            @if ($rate->passenger_category_name_start_value == 13)

              € {{$rate->rate}}

            @elseif ($rate->passenger_category_name_end_value <= 14)

              €

            @endif

            @if ($rate->passenger_category_name_start_value == 14)

              € {{$rate->rate}}

            @elseif ($rate->passenger_category_name_end_value <= 15)

              €

            @endif

            @if ($rate->passenger_category_name_start_value == 15)

              € {{$rate->rate}}

            @elseif ($rate->passenger_category_name_end_value <= 16)

              €

            @endif

            @if ($rate->passenger_category_name_start_value == 16)

              € {{$rate->rate}}

            @else

              €

            @endif

        @endforeach
      @endforeach


text:
Q: Failed silent auth - Login required Auth0 I am trying to implement login with Auth0 and looking at Dashboard -> Monitoring -> Logs, I can see that login is failing because it says Failed silent auth - Login required.
What is the solution to fix failed logins?

A: Remove prompt: 'none' from the authParams you send.
In my case, I was using passwordless login with magic links and I was sending prompt: 'none' in the authParams of the body of the request to fetch auth0.com/passwordless/start.
I removed prompt: 'none' from the authParams and everything was good.


text:
Q: object and assign a concatenated string from two inputs We have a site that recommend website domain.
That get domains, site names and then create an Object with them.
For example :
If site names are "google,yahoo" and domain are "com,net,org" as inputs
Output should be :
 google: {com: "google.com", net: "google.net", org: "google.org"}
 yahoo: {com: "yahoo.com", net: "yahoo.net", org: "yahoo.org"}

This is really confused me. how can I create above object with given input with new method ?
any solution would be my pleasure

A: const sites = "google,yahoo"; const domains = "com,net,org";
const sitesArray = sites.split(',');
const domainsArray = domains.split(',');
let res = {};
sitesArray .forEach(siteKey => {
    res[siteKey] = {};
    domainsArray.forEach(domain => {
        res[siteKey][domain]= siteKey + "." + domain;
    })

})
// test
console.log(res);

A: even shorter you can do it using one array.map.

function RecommendDomain(address) {
    let domain = ["com", "org", "net", "me"];
    let keyValue =  domain.map((value) => {
        return [value, address + "." + value];
    });
  return Object.fromEntries(keyValue)
}

let a = RecommendDomain("google");
let b = RecommendDomain("yahoo");
console.log(a);
console.log(b);

A: You can do something like this

const sites = "google,yahoo".split(',')
const domains = "com,net,org".split(',')

const output = sites.reduce((res, site) => {
  return {
    ...res,
    [site]: domains.reduce((res, domain) => {
      return {
        ...res,
        [domain]: site + '.' + domain
      }
    }, {})
  }
}, {})

console.log(output)


text:
Q: Is incrementing and returning an integer in a thread atomic operation? Consider following posix thread code:
void *thr(void *arg)
{
    static int i = 0;

    return ++i;
}

I think that this is atomic and safe operation as it should translate in on assembly instruction inc i for change of value. However, I am not a great expert of internals of cpu and multithreading thus I am doubtful.
EDIT: Since it is not safe say I use mutex lock to make this safe then how much extra cost would it be in terms of time.
EDIT: I got my answer from Overhead of pthread mutexes for time cost. Thanks a bunch.

A: It's neither atomic nor safe for many reasons:

*

*No standard says it is. So if happens to be, it's only by luck and you'd be crazy to rely on that.

*Who says a single instruction is atomic? An increment requires a fetch, an add, and a store. On most CPUs, that's not atomic. (Why do you think x86 CPUs offer a LOCK prefix? If single instructions were already atomic, what purpose would it serve?)

*The compiler can optimize in all kinds of crazy ways.
But more importantly, you are making a very fundamental mistake. It is impossible to conclude that something is safe merely because you can't think of any way it can fail. This will never work and you should never, ever do it. If you don't have guarantees, and you don't in this case, it's not safe.

Since it is not safe say I use mutex lock to make this safe then how much extra cost would it be in terms of time.

Probably very little. On most platforms, acquiring an uncontested lock is roughly comparable in cost to an atomic increment. Since you need an atomic increment anyway, you have to pay this cost somehow.
In other words, in the uncontested case (where two threads don't try to increment at the same time), a lock/increment/unlock will perform about the same as an atomic increment on most platforms. However, if there's a lot of contention, the atomic increment will perform much better.
If you don't have to deal with contention super-effectively, just use a lock and be done with it. If you do, then you should be using some platform or library that provides effective ways to deal with contention, such as a C++ implementation with std::atomic, a library that provides inline assembly atomic operations, or a compiler with atomic intrinsics.

A: The operation is not atomic. It implies reading the variable from memory (it's a variable with static storage), incrementing it and then storing back in memory.


text:
Q: spring get properties difference Import properties
What are the three differences?

*

*Reading property files using PropertyPlaceholderConfigurer

*Reading property files using [context:property-placeholder]

*Reading properties file using [util: properties] and Spring EL

A: *

*PropertyPlaceholderConfigurer class pulls values from a properties file into bean definitions.

*<context:property-placeholder ... /> is a XML equivalent to the PropertyPlaceholderConfigurer.

*<util:properties/> is equivalent to java.util.Properties
Detailed information provided on this question here


text:
Q: Doubt about integration by change of variable I came across an example of an integral by change of variable that reads as follows
Find $$\int_a^{b} \frac{1}{\sqrt[2]{(x-a)(b-x)}}dx$$
What they do is to assume that $a<b$. They claim that the convenient change of variable consists of taking the interval $(-1,1)$ to the interval $(a,b)$ through a bijection of the type $g(t)=\alpha t+\beta$.
Thus, if we take $g(-1)=a, g(1)=b$ we have that $\alpha=\frac{b-a}{2}$ and $\beta=\frac{b+a}{2}$, then $x=g(t), dx=\frac{b-a}{2}dt, g(-1)=a$ and $g(1)=b$.
Then
$$\int_a^{b} \frac{1}{\sqrt[2]{(x-a)(b-x)}}dx=\int_{-1}^{1} \frac{dt}{\sqrt[2]{1-t^2}}=\pi$$
However, I do not understand the reason for several issues in this exercise. First of all because $dx=\frac{b-a}{2}dt$ was taken, then when replacing these values in the expression it is not very clear to me how they arrive to the final value of the integral.
Any help please?

A: The Assumption $a<b$:
Firstly, the assumption that $a<b$ is fairly natural considering that the bounds of the integral are, in fact, $(a,b)$. Consider a specific case if you want to see other weirdness erupt, say, $b:=2 < 3 =: a$;
$$\int_a^{b} \frac{1}{\sqrt[2]{(x-a)(b-x)}}\, \mathrm{d}x
\xrightarrow{(a,b)=(3,2)}
\int_3^{2} \frac{1}{\sqrt[2]{(x-3)(2-x)}}\, \mathrm{d}x$$
Notice how both factors in the radical are negative for $x \in (2,3)$. Accounting for that leads to simply replacing $x$ with $-x$, and then you get a situation in which the bounds are in the $a<b$ order again ($-3 < -2$):
$$
\int_3^{2} \frac{1}{\sqrt[2]{(x-3)(2-x)}}\, \mathrm{d}x
=
\int_{-3}^{-2} \frac{1}{\sqrt[2]{(3+x)(x+2)}}\, \mathrm{d}x
$$
This is just the integral if we took $(a,b) = (-3,-2)$; so there's no real reason to not assume $a<b$.

Constructing the (Right) Bijection:
Next, constructing a bijection $(a,b) \to (-1,1)$ is easy enough; you essentially need a function $g$ that:

*

*shifts $(a,b)$ to have left endpoint $0$, so $(a,b) \to (0,b-a)$

*then squishes that interval down to length $2$, so $(0,b-a) \to (0,2)$

*and then shifts that left one unit

Thus we:

*

*subtract $a$

*divide by $(b-a)/2$

*subtract $1$
This means that
$$g(t) = \frac{ t-a }{(b-a)/2} - 1 = \frac{-2t}{a-b}   + \frac{a+b}{a-b}$$
If we insist on the form $g(t) = \alpha t + \beta$, this means
$$\alpha = - \frac{2}{a-b} \qquad \beta = \frac{a+b}{a-b}$$

Possible Question: Wait, this is a bijection $(a,b) \to (-1,1)$, not the other way around. What gives?

What we're going to be doing is a $u$-substitution, or, in this case, $g$-substitution. If we want $g((a,b)) = (-1,1)$, this is what is necessary.
However, if we seek to replace $x$ in our integrand, we need the inverse of this, the backwards transformation. This is where the original transformation comes into play. It can be constructed similarly, and we have
$$g^{-1}(t) = \frac{t-\beta}{\alpha} =   \frac{b-a}{2} t + \frac{a+b}{2}$$

The Substitution & Subsequent Algebra:
So, letting $u=g(x)$ be our substitution, then:

*

*The bounds change from $(a,b)$ to $(-1,1)$

*$x$ becomes $g^{-1}(u)$

*$\displaystyle \, \mathrm{d}x = (g^{-1})'(t) \, \mathrm{d}t = \frac{b-a}{2} \, \, \mathrm{d}t$
In particular,
$$x-a \mapsto \frac{b-a}{2} t + \frac{a+b}{2} - a = \frac 1 2 (t+1)(b-a)$$
and
$$b-x \mapsto b - \frac{b-a}{2} t - \frac{a+b}{2} = \frac 1 2 (t-1)(a-b)$$
Consequently, multiplying the two and noting $(t^2 - 1) = -(1-t^2)$, and using that to reverse the order of subtraction in one of the factors, we
$$(x-a)(b-x) \mapsto \frac 1 4 (1-t^2)(b-a)^2$$
and
$$\sqrt{ \frac 1 4 (1-t^2)(b-a)^2 } = \frac{b-a}{2} \sqrt{1-t^2}$$
Thus, summarily,
$$\int_a^{b} \frac{1}{\sqrt[2]{(x-a)(b-x)}}\, \mathrm{d}x = \int_{-1}^1 \frac{1}{(b-a)/2} \frac{(b-a)/2}{\sqrt{1-t^2}} \, \, \mathrm{d}t = \int_{-1}^1 \frac{\, \mathrm{d}t}{\sqrt{1-t^2}} $$

Final Step:
And as
$$\frac{\mathrm{d}}{ \mathrm{d}x} \arcsin(t) = \frac{1}{\sqrt{1-t^2}}$$
we have
$$\int_{-1}^1 \frac{\, \mathrm{d}t}{\sqrt{1-t^2}}
= \arcsin(1) - \arcsin(-1) = \frac \pi 2 - \left( \frac \pi 2 \right) = \pi
$$
as desired.

A: Here provides a new aproach.
Note the identity$$\dfrac{x-a}{b-a}+\dfrac{b-x}{b-a}=1$$which inspires us to do this change of variable:$$\dfrac{x-a}{b-a}=\sin^{2}t,\ t\in(0,\dfrac{\pi}{2}).$$Now,$\dfrac{b-x}{b-a}=\cos^{2}t.$ Thus$$dx=2(b-a)\cos t\sin tdt.$$Hence,$$\int_{a}^{b}\dfrac{1}{\sqrt{(x-a)(b-x)}}dx=\int_{0}^{\frac{\pi}{2}}\dfrac{2(b-a)\cos t\sin t}{(b-a)\cos t\sin t}dt=\pi.$$

A: Like mio,
as we need $$a< x<b$$
$$\iff -\dfrac{b-a}2=a-\dfrac{a+b}2<x-\dfrac{a+b}2<b-\dfrac{a+b}2=\dfrac{b-a}2$$
WLOG $x-\dfrac{a+b}2=\dfrac{b-a}2\cdot\cos2t$ where $0<2t<\pi$
$$\iff2x= a+b+(b-a)\cos2t=b(2\cos^2t)+a(2\sin^2t)$$
$$\implies x=?$$

A: First of all, we treat the quadratic in the integrand by completing squares $$
\begin{aligned}
(x-a)(b-x) &=-\left[x^{2}-(a+b) x+a b\right] \\
&=\left(\frac{a+b}{2}\right)^{2}-a b -\left(x-\frac{a+b}{2}\right)^{2} \\
&=\left(\frac{b-a}{2}\right)^{2}-\left(x-\frac{a+b}{2}\right)^{2}
\end{aligned}
$$
WLOG, $a<b$,
letting
$$
\begin{aligned}
 & x-\frac{a+b}{2}=\frac{b-a}{2} \sin \theta \\
& d x=\frac{b-a}{2} \cos \theta d \theta \end{aligned}$$
yields
$$\begin{aligned}&I=\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} \frac{1}{\sqrt{\left(\frac{b-a}{2}\right)^{2}-\left(\frac{b-a}{2}\right)^{2} \sin ^{2} \theta} }\cdot \frac{b-a}{2} \cos \theta d \theta \\
& =\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} \frac{1}{\frac{b-a}{2} \cos \theta} \cdot \frac{b-a}{2} \cos \theta d \theta \\&=\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} 1d \theta  \\
&=\pi
\end{aligned}
$$
If $b<a$, then letting $x-\dfrac{a+b}{2}=\dfrac{a-b}{2} \sin \theta $ will yield the same result $\pi$.


text:
Q: nz-popover - nzPopoverPlacement, target another element for centering I was wondering if there was a way to get the nz-popover to center on another element.
I basically have a text input followed by two buttons in a div, I would like to center the popover on the div rather than on the button that triggers it.
I found that i could add the popover to the actual div and then use the nzVisible to trigger it but then i loose the ability to close the popup when the user leaves the area (prob when they hover over the mask or click it). I tried many ways to close it once the popover looses focus etc but that would cause the popover to close if the popover contains a menu or datepicker (when they are used).
Anyone got any ideas? (i used to use angular material and i believe they had something similar (think it was called target or something).
Thanks in advance,

A: For anyone who is interested in this, we have submitted a PR to provide this feature. You would be able to use this in 9.x (and future) versions.


text:
Q: How to use multiple models in one app? I have a django project with two applications, experiments and metadata and in one view I need to work with models from both these applications, so I have this:
from experiments.models import *
from metadata.models import *

Both my applications have a model with the same name; so how can I use two models in one app?

A: from experiments import models as exp_models
from metadata import models as meta_models

foo = exp_models.Foo.objects.all()
bar = meta_models.Bar.objects.all()

Btw. from module import * is considered as bad practice, it clutters your namespace.

A: Suppose in experiments/models.py you have:
class Foo(models.Model):
    name = models.CharField(max_length=200)

And in metadata/models.py you also have:
class Foo(models.Model):
    name = models.CharField(max_length=200)

Now you want to use both, you would import them like this:
from metadata.models import Foo as meta_foo
from experiments.models import Foo as experiment_foo


text:
Q: ImageMagick: Replace RGB channels with white, retain Alpha I have an image created in a Affinity Designer, which has the following channels:
R, G and B:

Alpha:

When I use this image in other places (Unreal Engine), I get small black artifacts on the edge of the shape due to the black part of the RGB channels. The only important information I need is the alpha channel.
How can I use ImageMagick to replace the RGB channels with white, while retaining the alpha channel?

A: Here is a simple way to do the in ImageMagick:
First, since you did not provide the actual image, I will reconstruct it from the rgb.png and alpha.png
convert rgb.png alpha.png -alpha off -compose copy_opacity -composite image.png

Now, to make the rgb part white, simply do:
convert image.png -fill white -colorize 100 result.png

Now to see that the rgb parts are fully white, we do:
identify -verbose result.png
.
.
.
 Channel statistics:
    Pixels: 512
    Gray:
      min: 255  (1)
      max: 255 (1)
      mean: 255 (1)
      standard deviation: 0 (0)
      kurtosis: -4.9152e+52
      skewness: 9.375e+35
      entropy: 0
    Alpha:
      min: 0  (0)
      max: 255 (1)
      mean: 187.152 (0.733931)
      standard deviation: 109.252 (0.42844)
      kurtosis: -0.822401
      skewness: -1.05578
      entropy: 0.336307

So the rgb components are a constant 255 (white) and the image is now white with an alpha component.

A: Try the following...
magick \( input.png -fill white -draw 'color 0,0 reset' \) \
       \( input.png -alpha extract \) \
       -compose Copy_Alpha -composite \
       output.png

I'm sure there's better ways to do the above. Reading the input.png twice, and extracting the alpha channel is bit redundant.
The first part replaces all RGB channels with white, but also clears the alpha channel.
input.png -fill white -draw 'color 0,0 reset'

The second part grabs the alpha channel.
input.png -alpha extract

Finally, we copy the extracted alpha values back over the white image's alpha channel.
-compose Copy_Alpha -composite

If your using ImageMagick-6, then replace magick with convert, and Copy_Alpha with Copy_Opacity.
Best of Luck!


text:
Q: How to know when scroller of the div reaches the bottom - JQuery How can I fire another event whenever the scroll of a div reaches its bottom.
I do not want to use jscroll.com or infinite-scroll.
Using $(window).bind("scroll", function (){} is not working for me.
Please suggest!!

A: Try this:
$('#div').bind('scroll', function() {
     if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight)
     {
         alert('bottom');
     }
});

A: You can use something like this....
$("#mydiv").scroll( function() {
if($(this)[0].scrollHeight - $(this).scrollTop() == $(this).outerHeight()) {
// what you want to do ...
}
});

A: somthing like this
$(window).scroll(function(){
    var window_height = $(window).height();
    var window_scroll = $(window).scrollTop();
    var document_height = $(document).height();

    if (window_height + window_scroll == document_height) {
       alert("bottom");
    }
});

example:
demo

A: Try this:

This will work for chrome, you may need to use other commands for other browsers.


text:
Q: JavaFX LineChart draw a red zone [javafx] [linechart] fx8+
is possible to plot a red region in my linechart... i will explain this better
..i would give to the user a visible "red zone" for understand that a value is to highter than a fixed (final) value, in this case 1000
i can place a screen but not code, or i will be fired XD

i spent about 2 hours for search a solution... any ideas?


text:
Q: Is it possible to pass a generic model to a JsonResult action from an ajax call? I'm creating a javascript function that will invoke ajax call to validate the model of a form.
function ValidateModel(formID) {
    $.ajax({
        url: '/Custom/ValidateModel',
        type: 'POST',
        data: $('#' + formID).serialize(),
        dataType: 'json',
        processData: false,
        success: function (data) {

        // code remove for brevity

        }
    });
}

That will be handled by this Action in the CustomController
[HttpPost]
    public ActionResult ValidateModel(CustomModel model)
    {
            if (!ModelState.IsValid)
            {
                 // code remove for brevity
            }
            return Json(customObject, JsonRequestBehavior.DenyGet);

    }

If I will pass a form with CustomModel object the auto binding works just fine. What I want to create is a generic handler on the server to validate the model. I want to achieve it with something like this:
public ActionResult ValidateModel(GenericModel model)
{

}

so that when I can pass different forms with different model types on the server.
thanks!

A: Could you use an interface that all your models implement and have
public ActionResult ValidateModel(IViewModel model)
{

}

You'd be able to pass any model that implements the IViewModel interface.
Or maybe you could use an abstract base class?


text:
Q: Calculate Cell height on basis of label text + image I have created a custom cell that have IMAGE view, and two label's the data of labels's are populated from a plist file, the data is populated properly but on front end the cell didn't show the data properly, the label cut's the data. I am using Uilabel view's.
Please have a view to my code, i have search over internet and followed some tutorial's as well but nothing work's.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    Customviewcell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
    UIImage * image = [UIImage imageNamed:justThumbs[indexPath.row]];
    cell.CustomTitle.text=justTitles[indexPath.row];

    cell.CustomTitle.numberOfLines =0;
    [cell.CustomTitle sizeToFit];
    cell.CustomDes.text=justDesc[indexPath.row];
    cell.CustomDes.numberOfLines=0;
      [cell.CustomDes sizeToFit];
    [cell.CustomTitle layoutIfNeeded];
    [cell.CustomDes layoutIfNeeded];
    [cell layoutIfNeeded];
    cell.Customimage.image=image;
    return cell;
}

Code for calculating the height as per stackoverflow different question's answer's.
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //Calculate Height Based on a cell
    if (!self.customcell) {
      self.customcell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
    }
    // Configure Cell
    UIImage * image = [UIImage imageNamed:justThumbs[indexPath.row]];
    self.customcell.CustomTitle.text=justTitles[indexPath.row];
    self.customcell.CustomTitle.numberOfLines=0;
    [self.customcell.CustomTitle sizeToFit];
    self.customcell.CustomDes.text=justDesc[indexPath.row];
    self.customcell.CustomDes.numberOfLines=0;
    [self.customcell.CustomDes sizeToFit];
    self.customcell.Customimage.image=image;

    //Layout Cell

    //Get Hieght for the cell

    if([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPhone)
    {

        if ([[UIScreen mainScreen] bounds].size.height == 568)
        {

            CGRect frame = [NSString setAttributeWithString:self.customcell.CustomTitle.text withLineSpacing:0.2 withSize:CGSizeMake(270, 999999999) withFont:self.customcell.CustomTitle.font withLabel:self.customcell.CustomTitle setLabelTextColor:self.customcell.CustomTitle.textColor setTextAlignment:self.customcell.CustomTitle.textAlignment];
            self.customcell.CustomTitle.height.constant = frame.size.height;
            frame = [NSString setAttributeWithString:self.customcell.CustomDes.text withLineSpacing:0.3 withSize:CGSizeMake(150, 999999999) withFont:self.customcell.CustomDes.font withLabel:self.customcell.CustomDes setLabelTextColor:self.customcell.CustomDes.textColor setTextAlignment:self.customcell.CustomDes.textAlignment];
            self.customcell.CustomDes.height.constant = frame.size.height;

        }
        else{

            CGRect frame = [NSString setAttributeWithString:self.customcell.CustomTitle.text withLineSpacing:1 withSize:CGSizeMake(337, 999999999) withFont:self.customcell.CustomTitle.font withLabel:self.customcell.CustomTitle setLabelTextColor:self.customcell.CustomTitle.textColor setTextAlignment:self.customcell.CustomTitle.textAlignment];
            self.customcell.CustomTitle.height.constant = frame.size.height;
            frame = [NSString setAttributeWithString:self.customcell.CustomDes.text withLineSpacing:1 withSize:CGSizeMake(227, 999999999) withFont:self.customcell.CustomDes.font withLabel:self.customcell.CustomDes setLabelTextColor:self.customcell.CustomDes.textColor setTextAlignment:self.customcell.CustomDes.textAlignment];
            self.customcell.CustomDes.height.constant = frame.size.height;

        }
    }
    [self.customcell layoutIfNeeded];

       // CGFloat height = self.customcell.CustomTitle.height.constant+self.customcell.CustomDes.height.constant+189;
    CGFloat height = [self.customcell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

    //Add padding of 1
    return height;
}

Used Github opensource library to solve the issue but didn't worked.
https://github.com/punchagency/line-height-tool
Issue still remain's, text of label's cut off, content hanging is at Required and Content is at 1000 horizontal + vertical..
Please help..
Thanks allot.

A: You can get the height of a string in certain bounds with the NSString method boundingRectWithSize, like
NSString* text = @"Test text";

CGRect textRect = [text boundingRectWithSize:CGSizeMake(300, CGFLOAT_MAX)
                                                     options:NSStringDrawingUsesLineFragmentOrigin
                                                  attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12]}
                                                     context:nil];
CGFloat textHeight = ceilf(textRect.size.height);

Use your own font and font size, and you can also add other attributes to the attributes dictionary if necessary.

A: Use following method to calculate your UILabel height:
add also use this method in your class.
- (CGFloat)getLabelHeight:(UILabel*)label{
CGSize constraint = CGSizeMake(label.frame.size.width, CGFLOAT_MAX);
CGSize size;

NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
CGSize boundingBox = [label.text boundingRectWithSize:constraint
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:@{NSFontAttributeName:label.font}
                                              context:context].size;

size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));

return size.height;}

Update your heightForRowAtIndexPath Method as per your requirement:
calculate all UI Height and return.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

Customviewcell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];

CGFloat totalHeight = 0;

cell.CustomTitle.text=justTitles[indexPath.row];
//get label Height
totalHeight += [Helper getLabelHeight:cell.CustomTitle];

cell.Customimage.image = [UIImage imageNamed:justThumbs[indexPath.row]];
CGFloat imageHeight = cell.Customimage.frame.size.height; //or Add image height here

totalHeight += imageHeight;

return totalHeight;}

A: In iOS8+ you can use self sizing cells:
http://www.appcoda.com/self-sizing-cells/

A: Auto Resizing of Cell is available in Ios 8.0, The issue my deployment target was ios 7.0, which is causing the layout issues.
Please refer to these articles:
http://www.appcoda.com/self-sizing-cells/
The Code is in swift but need to do same thing's in objective c as well.
This will also help's you.
http://useyourloaf.com/blog/self-sizing-table-view-cells.html


text:
Q: How to make rootfs read-only? I try to make my rootfs read-only.
I thought that I better use overlay filesystem for this purpose (I don't have other alternatives now).
Yet, after many trials and changing fstab, I can't manage to find any fstab which manage to start ubuntu with rootfs as readonly.
I also googled itm but found no examples.
This is what I tried, and I also tried many variations (options column), but still get error in overlay mount.
As you can see, the main changes are adding "ro" to the rootfs, and adding overlay for /etc /var and /home.
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
# / was on /dev/sda1 during installation
UUID=075d905c-5c56-4eae-9402-5a880d108a8c /               ext4    ro,errors=remount-ro 0       1

/dev/sdb /media/store ext4 defaults 1 1

# swap was on /dev/sda5 during installation
UUID=e190d8d1-5490-4ef5-9547-a38aefa44b3e none            swap    sw              0       0

/root/myswapfile               swap                    swap    defaults        0 0

overlay   /var    overlay   rw,noatime,lowerdir=/var,upperdir=/media/store /1,workdir=/media/store /11    0   2
overlay   /etc    overlay   rw,noatime,lowerdir=/etc,upperdir=/media/store /2,workdir=/media/store /22    0   2
overlay   /home    overlay  rw,noatime,lowerdir=/home,upperdir=/media/store /3,workdir=/media/store /33     0   2

Overlay is supported in my kernel, and things does works if I change my rootfs option in ftab from ro to writebale, but I need it read-only!
Thanks for any idea,
ranran

A: Check out the Protecting the Root Filesystem on Ubuntu with Overlayroot article about the creation of a read-only root FS.
It seems that you are running in the recurse issue with the temp fs.
Try booting the system with the / mounted read-only (no overlays!). This will lead to too many errors during the startup, but the system will boot. Then login as root and manually try to mount the overlays.