text:
Q: Generar .zip con archivos desde S3 Amazon con Python Estoy intentando descargarme un zip con archivos extraidos de S3 Amazon en Python pero me da error.
El código sería este:
   for id_file in files:
        chargeFile=ChargeFiles.objects.get(id=id_file)
        ...
        s3 = boto3.client('s3',aws_access_key_id=settings.AWS_ACCESS_KEY_ID,aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,region_name='eu-west-2')
        s3_response_object['Body'] = s3_response_object['Body'].read().decode("ISO-8859-1")
        s3_response_object['Key'] = settings.AWS_ACCESS_KEY_ID+'/'+settings.AWS_SECRET_ACCESS_KEY

        location = s3.get_bucket_location(Bucket=BUCKET_NAME)['LocationConstraint']
        url = "https://s3-%s.amazonaws.com/%s/%s" % (location, BUCKET_NAME, BUCKET_FILE_NAME)

        s3_response_object['URL'] = url
        s3_response_object=s3.get_object(Bucket=BUCKET_NAME,Key=BUCKET_FILE_NAME)
        ...
        //LA DESCARGA DEL ARCHIVO LA HACE CORRECTA
        resultFiles.append(s3_response_object)

    full_zip_in_memory = generate_zip(resultFiles)

    response = HttpResponse(full_zip_in_memory, content_type='application/force-download')
            response['Content-Disposition'] = 'attachment; filename="%s"' % 'documentacion_incidencias.zip'
            return response

Y la función generate_zip es la siguiente:
   def generate_zip(files):
      mem_zip = BytesIO()

      with zipfile.ZipFile(mem_zip, mode="w",compression=zipfile.ZIP_DEFLATED) as zf:
        for f in files:
          zf.writestr(f[0], f[1])

       return mem_zip.getvalue()

Me devuelve error con un 0 simplemente, en la fila zf.writestr(f[0], f[1])
    KeyError at /incidents/
     0
    Request Method: POST
    Request URL:    http://127.0.0.1:8000/incidents/
    Django Version: 2.2.1
    Exception Type: KeyError
    Exception Value:
    0
    Exception Location:  truckers/viewsAjax.py in generate_zip, line 1667
    Python Executable:  /usr/bin/python3
    Python Version: 3.6.9
    Python Path:
    [---]
  Server time:  Vie, 23 Abr 2021 08:38:34 +0200
 Traceback Switch to copy-and-paste view
  /home/miguel/.local/lib/python3.6/site-
  packages/django/core/handlers/exception.py in inner
        response = get_response(request) …
     ▶ Local vars
       /home/miguel/.local/lib/python3.6/site-
    packages/django/core/handlers/base.py in _get_response
            response = self.process_exception_by_middleware(e,
    request) …
    ▶ Local vars
     /home/miguel/.local/lib/python3.6/site-
        packages/django/core/handlers/base.py in _get_response
            response = wrapped_callback(request, *callback_args,
      **callback_kwargs) …
    ▶ Local vars
      /home/.local/lib/python3.6/site-
      packages/django/contrib/auth/decorators.py in _wrapped_view
            return view_func(request, *args, **kwargs) …
    ▶ Local vars /incidents/views.py in showIncidents
            full_zip_in_memory = generate_zip(resultFiles) …
    ▶ Local vars incidents/views.py in generate_zip
        zf.writestr(f[0], f[1])

¿Como puedo coger corréctamente el objeto que devuelve Amazon? ¿O Es correcta la función?
Gracias.

A: No es respuesta total ya que no podemos ver todo el código o un ejemplo mínimo [1]. También sería útil ver el error completo (puedes ver el output completo en tu cloudwatch), cual versión de python y que modulos estás usando. Es mejor que darnos el trabajo de asumir en base al poco código.
Dicho eso, pareces estar procesando varios archivos en un solo lambda (no has dicho tampoco de que tamaño son). Pero recuerda que un lambda tiene por default 128MB de RAM y 512MB de memoria "física". Pudiera ser que estas utilizando toda la memoria física si son muchos archivos, ya que aparte de ocupar el espacio de la descarga, también estás creando un nuevo archivo que, aun siendo compreso, está ocupando espacio en disco. Otro detalle es que la operación de ZIP ocupa memoria, talves tus archivos exigen más memoria de lo que una lambda puede hacer.  Todo es son suposiciones sin que dés los detalles necesarios (agrégalos a tu pregunta y a cualquier pregunta en el futuro).
Asumiendo que el límite del lamba sea el problema y no algo en el código que no se ve, sugiero que intentes otra estrategia. El problema de procesar archivos zip en lambda es relativamente común y la estratégia más usada es usar streams. Puedes combinar el uso de ese módulo con boto3 (que creo no estas usando pero sería el ideal) y procesar los archivos a como están llegando byte por byte.
Otra solución más rápida, pero quizás no la ideal, es simplemente aumentar la configuracion de tu lambda en cuestion de ambos memoria RAM y física.
Con más datos con gusto edito la respuesta. Suerte!
[1] https://es.stackoverflow.com/help/minimal-reproducible-example


text:
Q: Com Port data sending Issue i am sending data i.e 12345 to a LED display connected with my COM port,But it show 12344 instead of 12345 on LED.I have check it through Hyperterminal and found that there is no issue in LED Display.
My code is adding "4" at the end by itself.Need help in this issue
Mycode :
  With comPort

            '.ParityReplace = &H3B                    ' replace ";" when parity error occurs

            .BaudRate = 9600
            .Parity = IO.Ports.Parity.None
            .DataBits = 8
            .StopBits = IO.Ports.StopBits.One
            .Parity = IO.Ports.Parity.None
            '.Handshake = IO.Ports.Handshake.None
            '.RtsEnable = False
            '.ReceivedBytesThreshold = 1             'threshold: one byte in buffer > event is fired
            '.NewLine = vbCr         ' CR must be the last char in frame. This terminates the SerialPort.readLine
            '.ReadTimeout = 10000

        End With

        Try

            comPort.Close()
            If comPort.IsOpen = False Then
                comPort.Open()
            End If
            Dim a As String = ""
            For i As Integer = 0 To 4

                comPort.WriteLine("12345") ' & Char.Parse(32))
            Next

        Catch ex As Exception
            MsgBox("Error Open: " & ex.Message)
        End Try

redpajama_set_name: RedPajamaStackExchange


text:
Q: simple way to change the key value of an array element
Possible Duplicate:
In PHP, how do you change the key of an array element?

I am reading in a bunch of multi-dimensional arrays, and while digging through them I have noticed that some of the keys are incorrect.
For each incorrect key, I simply want to change it to zero:
from:
$array['bad_value']

to:
$array[0]

I want to retain the value of the array element, I just want to change what that individual key is.  Suggestions appreciated.
Cheers

A: if you change multiple keys to 0 you will overwrite the values...
you could do it this way
$badKey = 'bad_value';
$array[0] = $array[$badKey];
unset($array[$badKey]);

A: Bruteforce method:
$array[0] = $array['bad_value'];
unset($array['bad_value']);

A: $array['0'][] = $array['bad_value'];
unset( $array['bad_value'] );

Then it will be an array in $array['0'] with values of broken elements.

A: Well seeing as you said the keys can be changed to any numeric value how about this?
$bad_keys = array('bad_key_1', 'bad_key_2' ...);
$i = 0;
foreach($bad_keys as $bad_key) {
    $array[$i] = $array[$bad_key];
    unset($array[$bad_key]);
    $i++;
}

EDIT: The solution I gave was horrible and didn't really solve the problem as there are multiple bad keys, this should be better.


text:
Q: Thymeleaf Templating th:data=http://www.somesite.com || org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as assignation sequence Here is the template.
After I run the process function from the TemplateEngine, I receive this error org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as assignation sequence: "data=http://www.somesite.com" (template: "someFile.html" - line 5, col 2)
I've tried doing it a handful of different ways and keep getting the same result.

    <object class="someClass" type="application/pdf"
    th:data="'|${url}|'">

You don't have a PDF plugin for this browser.

                        Click here to download PDF file.

        </object>

A: You're tyring to pass a string to th: when it expect a expression.
Change this:
th:data="'|${url}|'"

To this:
th:data=${url}

Remember to change the other elements that are also as string.

A: You don't need most of the | characters (as using literal substitutions don't make a difference here.  The code you posted should look like this:

    <object class="someClass" type="application/pdf" th:data="${url}">

            You don't have a PDF plugin for this browser.
            Click here to download PDF file.

    </object>

That being said, the error you indicated usually comes with using th:with incorrectly, and since I don't see that anywhere in the code you've given us, I doubt you have located the root cause of the problem.


text:
Q:  Include name of person who uploaded file to SharePoint in e-mail I am using this Power Automate Flow.
I need the name of the person who uploaded the file, but don't see a way to include this through dynamic content. My plan is to add it to the body of the e-mail sent so that the recipient knows who uploaded the file.
Thanks!

A: You can get the user who has last modified the file by using another action which I have specified in the image below
Flow action
Hope this has solved your question
Regards
RT


text:
Q: Trying to remove ads in Gmail with Chrome Extension I'm experimenting with a Chrome extension that will remove the ads displayed in the right-hand pane in Gmail and instead put the information I want there.  (I haven't decided exactly what to put there yet; vacillating between several ideas, including external content and/or attachments.)
The ads are (usually) contained in a

 element.  But I can't seem to select that either in my extension or in the console.
I've tested my manifest.json settings by writing an extension that added a superfluous div to the top of the page, and that worked fine -- I just created a new element and
document.body.parentElement.insertBefore(new_el, document.body);

However, what I'm trying to do now is just rip out the ads and put in some dummy text, or just put the text above the ads.  This is the main function called in my content_script.js file.
function modifyPage(txt) {

    var container = document.getElementsByClassName('oM')[0];

    container.innerHTML = txt;

}

function modifyPage(txt) {
    var insert = document.createElement('div');
    insert.innerText = txt;

    var container = document.getElementsByClassName('oM')[0];

    document.body.parentElement.insertBefore(insert, container);

}

I've even tried to jQuery:
function modifyPage(txt) {
    $('.oM').html(txt);

}

Also, trying to retrieve the
 using the Chrome console returns nothing -- even though I can see it right there in the source.

A: Set a delay on the execution of your jquery selector. The Google Tubes are a bit more complicated than using static div classes on page load.

A: Rather than remove the ads with JS, just hide them with CSS:
.oM {
    display: none;
}

A: I'm using AdBlock + Chrome add-in(or extension).
It works very well it's a donation-ware, I'm guessing the author use jquery {display:none } to hide or remove the ads with a custom filter lists.


text:
Q: What might explain this nslookup error from Windows 10 using pihole for local DNS? The background is I am working through intermittent failures in pihole being used as a local DNS server, which I am running via Docker on my Macbook to enable my home lab of physical and virtual machines.
I encountered the following on a later tagged release of pihole Docker image, I believe one of v5.6 or v5.7. I really don't know if this is due to the pihole version, but I don't recall seeing an nslookup like this before; note the "DNS request timed out", but then it apparently succeeded. I believe I had rebooted the Windows 10 desktop just prior to trying this, after adding the local DNS entry "gitlab.m44zv82q.com" pointing to "192.168.50.211" in the pihole admin. I hadn't yet added a name for the DNS server in this case. Why does it show a "DNS request timed out" but then apparently succeed? I saw a similar issue from a separate Windows 10 laptop. BTW I pointed "m44zv82q.com" to "192.168.50.1".
C:\Users\iamuser>nslookup gitlab.m44zv82q.com
Server:  3400b21b6797
Address:  192.168.50.243

DNS request timed out.
    timeout was 2 seconds.
Name:    gitlab.m44zv82q.com
Address:  192.168.50.211

C:\Users\iamuser>

Switching back to v5.5.1 I get this, immediately after adding the local DNS entry in the pihole admin.
C:\Users\iamuser>nslookup gitlab.m44zv82q.com
Server:  iamuser-Macbook-Pro.m44zv82q.com
Address:  192.168.50.243

Name:    gitlab.m44zv82q.com
Address:  192.168.50.211

C:\Users\iamuser>

A:
Why does it show a "DNS request timed out" but then apparently succeed?

Because it does two DNS requests – one for AAAA records and another for A records (to retrieve IPv6 and IPv4 addresses respectively). The first timed out but the second returned one IP address.
Normally if a website doesn't support IPv6 and doesn't publish any AAAA records in DNS, the AAAA query will still succeed, just return zero records of the requested type.
However, some "network protection" software, as well as some VPN software, have the ill-advised feature of completely blocking queries for AAAA, such that they either return a fake SERVFAIL error, or don't return any response at all (forcing the client to wait until timeout). Make sure nothing like that is enabled.
Or, as Pi-Hole uses dnsmasq, it might also be the case that adding a local DNS entry no longer completely overrides all record types for that entry – that is, I'm suspecting that instead of directly returning "0 AAAA records", it ends up forwarding the AAAA query upstream (to your ISP's DNS servers) or something like that.
Take a look at Pi-Hole's recent DNS queries list to see what's happening.


text:
Q: Крестики-нолики проверка по диагонали class Board
{
    const MARK_0 = 0;
    const MARK_X = 1;

    /** @var int */
    private $sizeX;

    /** @var int */
    private $sizeY;

    /** @var int */
    private $requiredMarks;

    /** @var array */
    private $map = [];

    /**
     * @param int $sizeX
     * @param int $sizeY
     */
    public function __construct (int $sizeX = 3, int $sizeY = 3)
    {
        $this->sizeX = $sizeX;
        $this->sizeY = $sizeY;

        $this->requiredMarks = $sizeX;
    }

    /**
     * @return int
     */
    public function getSizeX() : int
    {
        return $this->sizeX;
    }

    /**
     * @return int
     */
    public function getSizeY() : int
    {
        return $this->sizeY;
    }

    /**
     * @return int
     */
    public function getRequiredMarks() : int
    {
        return $this->requiredMarks;
    }

    /**
     * @param int $count
     */
    public function setRequiredMarks (int $count) : void
    {
        $this->requiredMarks = $count;
    }

    /**
     * @param int $x
     * @param int $y
     * @param int $mark
     */
    public function setMark (int $x, int $y, int $mark) : void
    {
        $this->map[$x][$y] = $mark;
    }

    /**
     * @param int $x
     * @param int $y
     *
     * @return int|null
     */
    public function getMark (int $x, int $y) : ?int
    {
        return $this->map[$x][$y] ?? null;
    }

    /**
     * @return int|null
     */
    public function checkWin() : ?int
    {
        foreach([self::MARK_0, self::MARK_X] as $mark)
        {
            if(/* $this->checkLanes($mark) ||  */ $this->checkDiagonals($mark))
            {
                return $mark;
            }
        }

        return null;
    }

    /**
     * @param int $mark
     *
     * @return bool
     */
    private function checkDiagonals (int $mark) : bool
    {
        $sizeX = $this->getSizeX();
        $sizeY = $this->getSizeY();

        $required = $this->getRequiredMarks();

        $size = max($sizeX, $sizeY);

        for($k = $required - $size; $k <= ($size - $required); $k++)
        {
            $score1 = 0;
            $score2 = 0;

            $startI = max(0, $k);
            $endI = min($size, $size + $k);

            for($i = $startI; $i < $endI; $i++)
            {
                if($this->getMark($i, $k + $i) === $mark)
                {
                    if(++$score1 >= $required)
                    {
                        return true;
                    }
                }
                else
                {
                    $score1 = 0;
                }

                if($this->getMark($i, $size - 1 + $k - $i) === $mark)
                {
                    if(++$score2 >= $required)
                    {
                        return true;
                    }
                }
                else
                {
                    $score2 = 0;
                }
            }
        }

        return false;
    }
}

$b = new Board (4, 4);
$b->setRequiredMarks(3);

$b->setMark(0, 1, Board::MARK_X);
$b->setMark(1, 2, Board::MARK_X);
$b->setMark(2, 3, Board::MARK_X);

$winner = $b->checkWin();

if($winner === null)
{
    $winner = "nobody";
}
elseif($winner === Board::MARK_X)
{
    $winner = "X";
}
else
{
    $winner = "0";
}

var_dump($winner);

Как пофиксить функцию "checkDiagonals", чтобы она обрабатывала диагонали как на фото корректно и возвращала корректный результат?
Если делать проверку на диагоналях как на фото, то это работает корректно.
Я не могу придумать этот алгоритм, поэтому я взял его с этого ответа https://stackoverflow.com/a/34257658/10261980
Закомментированная функция "checkLanes" работает корректно, поэтому она удалена из кода.

A: private function checkDiagonals ($mark)
{
    $sizeX = $this->getSizeX();
    $sizeY = $this->getSizeY();

    $required = $this->getRequiredMarks();

    $lastPosition = 0;
    $newPosition = 0;
    $match = 0;
    for ($i = 0; $i < $sizeX; $i++) {
        for ($j = 0; $j < $sizeY; $j++) {
            $tmp[] = $_mark = $this->getMark($i, $j);

            if ( $_mark !== $mark ) {
                continue;
            }

            if ( $newPosition === 0 ) {
                $match++;
            }

            $newPosition = count($tmp) - 1;
            $delta = $newPosition - $lastPosition;

            if ( ($delta === $sizeX - 1 || $delta ===  $sizeX + 1) && $lastPosition !== 0 ) {
                    $match++;
            }

            $lastPosition = $newPosition;

            if ( $match === $required ) {
                return true;
            }
        }
    }

    return false;
}

Выполнить код
UPD
Функция для проверки всех направлений:
private function check ($mark)
{
    $sizeX = $this->getSizeX();
    $sizeY = $this->getSizeY();

    $required = $this->getRequiredMarks();

    $lastPosition = 0;
    $match = 0;
    $lastCheck = '';
    for ($i = 0; $i < $sizeX; $i++) {
        for ($j = 0; $j < $sizeY; $j++) {
            $tmp[] = $_mark = $this->getMark($i, $j);

            if ($_mark !== $mark) {
                continue;
            }

            $newPosition = count($tmp) - 1;

            $rules = [
                'upDiagonal' => $newPosition - $lastPosition === $sizeX - 1,
                'downDiagonal' => $newPosition - $lastPosition ===  $sizeX + 1,
                'cols' => $newPosition - $lastPosition ===  $sizeX,
                'rows' => $newPosition - $lastPosition ===  1,
            ];

            $newCheck = array_search(true, $rules);

            if ( $newCheck === $lastCheck || $lastCheck == '' ) {
                $match++;
            } else if ($newCheck !== $lastCheck) {
                $match = 2;
            }

            $lastPosition = $newPosition;

            if ( $match > 1 ) {
                $lastCheck = $newCheck;
            }

            if ( $match === $required ) {
                return true;
            }

        }
    }

    return false;
}

Код не протестирован!

A:
Если передать последний ход в метод checkWin, проверить условие выигрыша будет гораздо проще.

Продемонстрирую:
  private function checkWin($i, $j)
  {
    $player = $this->map[$j][$i];
    // Для каждого направления считаем количество совпадающих знаков в обе стороны:

    //  '—' direction
    $count = 1;
    for ($ci = $i - 1; $this->map[$j][$ci] === $player; $ci--) $count++;
    for ($ci = $i + 1; $this->map[$j][$ci] === $player; $ci++) $count++;
    if ($count >= $this->win) return true;

    //  '|' direction
    $count = 1;
    for ($cj = $j - 1; $this->map[$cj][$i] === $player; $cj--) $count++;
    for ($cj = $j + 1; $this->map[$cj][$i] === $player; $cj++) $count++;
    if ($count >= $this->win) return true;

    //  '\' direction
    $count = 1;
    for ($ci = $i - 1, $cj = $j - 1; $this->map[$cj][$ci] === $player; $ci--, $cj--) $count++;
    for ($ci = $i + 1, $cj = $j + 1; $this->map[$cj][$ci] === $player; $ci++, $cj++) $count++;
    if ($count >= $this->win) return true;

    //  '/' direction
    $count = 1;
    for ($ci = $i - 1, $cj = $j + 1; $this->map[$cj][$ci] === $player; $ci--, $cj++) $count++;
    for ($ci = $i + 1, $cj = $j - 1; $this->map[$cj][$ci] === $player; $ci++, $cj--) $count++;
    if ($count >= $this->win) return true;

    return false;
  }

Ради наглядности убрал из циклов проверки на достижение краёв карты. В принципе это можно решить даже добавлением кольца из null-ов вокруг карты в массиве.


text:
Q: Corupted keyboard layout When I try to add Persian keyboard layout on my Windows 7 x64, the keyboard doesn't show up in the language bar. For example, when I add English, Arabic, and Persian keyboard layouts as shown in the following figure,

the only available languages will be English and Arabic:

The properties for the Persian layout shows a blank keyboard:

I had installed a Persian accounting software with probably caused the problem. I've tried sfc /scannow to revert changes to system files, if any, but sfc didn't find any issues.

A: I had such an experience with installing custom keyboard layout using setup programs like "XP Farsi Keyboard".
This setup make similar dll to Kbdfa.dll in System32 folder: kbdfapsoft.dll
I resolve the problem using:
1- Search Windows folder for kbdfa.dll.
     I found these:
32 bit dlls:(6.50 KB)
 C:\Windows\System32\kbdfa.dll
 C:\Windows\winsxs\amd64_microsoft-windows-i..l-keyboard-00000429_31bf3856ad364e35_6.1.7600.16385_none_46c321d27ba117ab\kbdfa.dll

64 bit dlls:(6.00 KB)
 C:\Windows\SysWOW64\kbdfa.dll
 C:\Windows\winsxs\wow64_microsoft-windows-i..l-keyboard-00000429_31bf3856ad364e35_6.1.7600.16385_none_5117cc24b001d9a6\kbdfa.dll

2- Copy and paste kbdfa32.dll from winsxs folder to appropriate system32 or SysWOW64 Folders.
3- If you have files like kbdfa*.dll (ie: kbdfapsoft.dll) , Copy and replace appropriate kbdfa.dll to its location, ususally system32 folder with the same name(ie: kbdfapsoft.dll).
4- Copy and paste 32 bit dlls (kbdfa.dll and if you have kbdfa*.dll) into system32\dllcache
5- Remove Perian Keyboard and add it againg.
And its done.
It is better Idea to use standard windows layout.You can use ctrl+shift+2 to type zwnj (Zero Width None Joiner).
Some useful links:
The Microsoft Keyboard Layout Creator
traylayout-1.2.zip
for windows xp to mimic enhanced kbdfa.dll without actual replace of system files.


text:
Q: Can't mount newly generated Rails engine in an app I have a complex Rails app and I want to extract some core functionality into an engine so that I can reuse the models etc in other Rails apps.
I've been following the official documentation for engines (https://guides.rubyonrails.org/engines.html). I'm able to create a new engine inside the app and generate some test models
> rails plugin new testengine --mountable

testengine> rails generate model Test

This is the .gemspec
require_relative "lib/testengine/version"

Gem::Specification.new do |spec|
  spec.name        = "testengine"
  spec.version     = Testengine::VERSION
  spec.authors     = ["Me"]
  spec.summary     = "testengine"

  # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
  # to allow pushing to a single host or delete this section to allow pushing to any host.
  spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"

  spec.files = Dir["{app,config,db,lib}/**/*", "Rakefile", "README.md"]

  spec.add_dependency "rails", "~> 6.1.4"
end

I console into the test dummy rails app in testengine, and I can find my new model at Testengine::Test, no problem. So far so good.
Now I get to section 4.1 Mounting the Engine. I add the engine via the Gemfile file (in fact this is already done for me thanks to the rails generator above).
gem 'testengine', path: 'testengine'

Then I install my gems without problems.
> bundle install
...
Using testengine 0.1.0 from source at `testengine`
...

I console into the main app and I can find Testengine and Testengine::VERSION but not Testengine::Engine or Testengine::Test.
Reading a little further the docs say you need add this line to config/routes.rb
mount Testengine::Engine, at: "/testengine"

I do and now the rails app won't even start
config/routes.rb:3:in `block in <top (required)>': uninitialized constant Testengine::Engine (NameError)

What did I miss?

A: I will answer my question for the benefit of others who might make the same mistake I made. In my case, gem 'testengine', path: 'testengine' was buried inside a group of gems e.g. in
group :test do
    ...
end

I guess I was confused how rails loads gems from groups and missed the detail about group inclusion. It seems that while it'll show in the list during bundle install, and autoload some basic items, such as Testengine::VERSION it doesn't autoload everything unless you are running an environment as the same name as the group. In hindsight, this seems a bit obvious. Lesson learned.


text:
Q: Php - PDO - Parse error: syntax error, unexpected '.' I have this function.
public function selection($table, $condition_var,$condition_val)
    {
        if ($condition_var != '') {

           $stm = $this->dbh->prepare("SELECT * FROM " . $table . " WHERE " . $condition_var=.":".$condition_var. " ");
           $stm->bindParam(":".$condition_var, $condition_val);
          return $stm->execute();
        }

    }

I am getting here in this below line
$stm = $this->dbh->prepare("SELECT * FROM " . $table . " WHERE " . $condition_var=.":".$condition_var. " ");

dont know what I am doing wrong here. kindly please check

A: Please refer to this: http://php.net/manual/en/pdostatement.bindparam.php
$stm = $this->dbh->prepare("SELECT * FROM " . $table . " WHERE " . $condition_var."=:condition_val");
$stm->bindParam(":condition_val", $condition_val);

A: $stm = $this->dbh->prepare("SELECT * FROM " . $table . " WHERE " . $condition_var . " = :param");
$stm->bindParam(":param", $condition_val);


text:
Q: Tiling Problem Solutions for Various Size "Dominoes" I've got an interesting tiling problem,  I have a large square image (size 128k so 131072 squares) with dimensons 256x512... I want to fill this image with certain grain types (a 1x1 tile, a 1x2 strip, a 2x1 strip, and 2x2 square) and have no overlap, no holes, and no extension past the image boundary. Given some probability for each of these grain types, a list of the number required to be placed is generated for each.
Obviously an iterative/brute force method doesn't work well here if we just randomly place the pieces, instead a certain algorithm is required. 1) all 2x2 square grains are randomly placed until exhaustion. 2) 1x2 and 2x1 grains are randomly placed alternatively until exhaustion 3) the remaining 1x1 tiles are placed to fill in all holes.
It turns out this algorithm works pretty well for some cases and has no problem filling the entire image, however as you might guess, increasing the probability (and thus number) of 1x2 and 2x1 grains eventually causes the placement to stall (since there are too many holes created by the strips and not all them can be placed).
My approach to this solution has been as follows: 1) Create a mini-image of size 8x8 or 16x16. 2) Fill this image randomly and following the algorithm specified above so that the desired probability of the entire image is realized in the mini-image. 3) Create N of these mini-images and then randomly successively place them in the large image.
Unfortunately there are some downfalls to this simplification. 1) given the small size of the mini-images, nailing an exact probability for the entire image is not possible. Example if I want p(2x1)=P(1x2)=0.4, the mini image may only give 0.41 as the closes probability. 2) The mini-images create a pseudo boundary where no overlaps occur which isn't really descriptive of the model this is being used for. 3) There is only a fixed number of mini-images so i'm not sure how random this really is.
I'm really just looking to brainstorm about possible solutions to this. My main concern is really to nail down closer probabilities, now one might suggest I just increase the mini-image size. Well I have, and it turns out that in certain cases(p(1x2)=p(2x1)=0.5) the mini-image 16x16 isn't even iteratively solvable.. So it's pretty obvious how difficult it is to randomly solve this for anything greater than 8x8 sizes.. So I'd love to hear some ideas. Thanks

A: I had a similar problem recently, trying to find polyimino patterns that would fill a board.  A simple backgracking program worked quite well. Just place random tiles and backtrack when you cannot place and have not met the constraints.


text:
Q: Insert if not exists avoiding race condition How can I make sure following statements don't have a race condition?
IF NOT EXISTS (select col1 from Table1 where SomeId=@SomeId)
INSERT INTO Table1 values (@SomeId,...)

IF NOT EXISTS (select col1 from Table2 where SomeId=@SomeId)
INSERT INTO Table2 values (@SomeId,...)

Is this enough
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

BEGIN TRAN

IF NOT EXISTS (SELECT col1 FROM Table1 WITH (UPDLOCK) WHERE SomeId=@SomeId)
INSERT INTO Table1 VALUES (@SomeId,...)

COMMIT TRAN

BEGIN TRAN

IF NOT EXISTS (SELECT col1 FROM Table2 WITH (UPDLOCK) WHERE SomeId=@SomeId)
INSERT INTO Table2 VALUES (@SomeId,...)

COMMIT TRAN

A: Yes.  That is enough.  Setting the transaction isolation level to serializable will create key locks that cover SomeId=@SomeId when you run your select-- which will prevent other processes from inserting values with the same key (SomeId=@SomeId) while your transaction is running.
The WITH(UPDLOCK) hint will cause the SELECT to obtain an update lock on the selected row(s), if they exist.  This will prevent other transactions from modifying these rows (if they existed at the time of the select) while your transaction is running.
It doesn't look like you really need the WITH(UPDLOCK) hint, since you are committing the transaction right away if the record already exists.  If you wanted to do something else before committing if the record does exist, you might need this hint-- but as it is, it appears you do not.

A: A statement is a transaction
declare @v int = 11;
insert into iden (val)
select @v
where not exists (select 1 from iden with (UPDLOCK) where val = @v)


text:
Q: Targets of 0.1/0.9 instead of 0/1 in neural networks and other classification algorithms Rumelhart, Hinton and Williams (PDF) wrote in 1986 in the context of training a neural network (page 12):

One other feature of this activation function should be noted. The
  system can not actually reach its extreme values of 1 or 0 without
  infinitely large weights. Therefore, in a practical learning situation
  in which the desired outputs are binary {0, 1}, the system can never
  actually achieve these values. Therefore, we typically use the values
  of 0.1 and 0.9 as the targets, even though we will talk as if values
  of {0, 1} are sought.

I haven't seen this advice in any more recent paper, nor in any piece of code implementing a neural network. My questions:

*

*Is this advice still valid, or was it disproved as ineffective at some point?

*Was this advice used (historically) in other algorithms, e.g. logistic regression?

A: Coding the targets as $\{0.1, 0.9\}$ is an example of label smoothing. It's one of the tricks highlighted in this review and it appears to originate in "Rethinking the Inception Architecture for Computer Vision" by Christian Szegedy et al. as a certain kind of regularization. It's used as a regularization strategy to discourage a neural network from giving over-confident predictions in the outcome, because the predicted probabilities cannot be improved by becoming arbitrarily close to 1 for the true class; instead, the lowest loss value occurs at 0.9 for the true class.
The standard approach is to not use label smoothing.  When we estimate a logistic regression (a 0-hidden layer neural network with sigmoid activations on the last layer), we never do this; the problem is left "as is" for Newton's Method to solve. Provided that the usual conditions are satisfied (design matrix is full-rank, perfect separation is not present), we have no problem estimating the regression coefficients. Likewise, neural networks trained on binary problems proceed in the same way! Nonlinearities and multiple layers make the optimization more challenging, but the core concept is the same.
However, neural networks are more flexible models, and are able to find more complex relationships compared to logistic regression. This means that they are also more prone to giving uncalibrated outcomes (the predicted probabilities do not strongly correspond to the true probabilities), a trend that is remarked upon in  "Your classifier is secretly an energy-based model, and you should treat it like one" by Will Grathwohl, et al. (which also has citations to  other papers making similar observaitons).

A: I suspect the reasons they suggested this approach was that the magnitudes of the gradient descent steps in back-propagation are proportional to the derivative of the activation function. If you use a logistic activation function then the derivative is numerically zero before the output reaches 1 or 0.  As a result the optimization can never absolutely converge as the loss function has a very long trough in weight-space with a very shallow slope along the bottom.  Using these modified targets backpropagation is able to converge to a more definite minimum.  I used this technique a bit back in the very early 90s‡, and it doesn't really give much of a benefit in practice, especially if the modification to the targets is as large as that!
A more recent usage of this trick can be found in Platt Scaling, which is used to get estimates of the probability of class membership from support vector machines†.  In Platt Scaling, a logistic regression model is fitted to the (leave-one-out) scores outputted by the SVM, but with modified targets (as @Sycorax explains +1) as a regularisation method to avoid over-fitting.  However Platt adopts a much less heuristic (and less drastic) approach, and sets the targets to be
$y_+ = \frac{N_+ + 1}{N + 2} \qquad \mathrm{and} \qquad  y_- = \frac{N_- + 1}{N + 2}$
which is effectively a Bayesian regularisation based on the Laplace correction.
† Really - don't do this, if you want probabilities (and for most practical applications, you will), use a proper probabilistic classifier, such as kernel logistic regression or Gaussian process classifiers (if you like to be Bayesian).
‡ The PDP books were where I first learned about neural networks! (my copy is from 1989 ;o)


text:
Q: Cannot get NS records I currently have a PostgreSQL backed PowerDNS setup. The records table for a domain is currently set up somewhat like this:
 id | domain_id |        name         | type  |                             content                              | ttl | prio | change_date | disabled | ordername | auth
----+-----------+---------------------+-------+------------------------------------------------------------------+-----+------+-------------+----------+-----------+------
 16 |         2 | server1.abcd.me     | A     | 1.2.3.4                                                          | 300 |      |  1458164023 | f        |           | f
 17 |         2 | abcd.me             | CNAME | server1.abcd.me                                                  | 300 |      |  1458164023 | f        |           | f
 13 |         2 | abcd.me             | NS    | e.ns.buddyns.com                                                 | 300 |      |  1458165277 | f        |           | f
 15 |         2 | abcd.me             | NS    | ns3.abcd.me                                                      | 300 |      |  1458165277 | f        |           | f
 14 |         2 | abcd.me             | NS    | ns2.abcd.me                                                      | 300 |      |  1458165277 | f        |           | f
 12 |         2 | abcd.me             | SOA   | server1.abcd.me abcdef.ghijk@gmail.com 0 3600 3600 36000 300     | 300 |      |  1458165447 | f        |           | f
 18 |         2 | www.abcd.me         | CNAME | server1.abcd.me                                                  | 300 |      |  1458165629 | f        |           | f

However, for a dig @localhost abcd.me NS comes up with:
; <<>> DiG 9.9.5-11ubuntu1.3-Ubuntu <<>> @localhost abcd.me NS
; (2 servers found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 50639
;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 1, ADDITIONAL: 1
;; WARNING: recursion requested but not available

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1680
;; QUESTION SECTION:
;abcd.me.                     IN      NS

;; ANSWER SECTION:
abcd.me.              300     IN      CNAME   server1.abcd.me.

;; AUTHORITY SECTION:
abcd.me.              300     IN      SOA     server1.abcd.me. abcdef\.ghijk.gmail.com. 1458165629 3600 3600 36000 300

;; Query time: 2 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Wed Mar 16 23:01:02 CET 2016
;; MSG SIZE  rcvd: 120

I cannot seem to understand why the NS record do not show up, and any help would be very appreciated.
Thanks!

A: I just figured out why that hasn't been working.
As per RFC 1912 (correct me if I'm wrong), any record with a CNAME cannot have another type of record attached to the same name. Replacing the abcd.me CNAME with abcd.me A record solved it for me.


text:
Q: Linkedin share plugin not submitting form I am using LinkedIn share button on my site with the following html:
<script src="//platform.linkedin.com/in.js" type="text/javascript"> lang: en_US</script>

<script type="IN/Share" data-url="www.aidh.co.uk/blog/1506-exposure/default.html"></script>

The button brings up the Linkedin plug in with all of the content correct and options for sharing.
https://www.linkedin.com/cws/share?url=www.aidh.co.uk%2Fblog%2F1506-exposure%2Fdefault.html&original_referer=http%3A%2F%2Fwww.aidh.co.uk%2Fblog%2F1506-exposure%2Fdefault.html&token=&isFramed=false&lang=en_US&_ts=1432834994124.3257
However the share button on Linkedin's own page doesn't submit the information to Linkedin.
Can anyone help?

A: Read the documentation of LinkedIn plugin.
(https://developer.linkedin.com/docs/share-on-linkedin)

A: Take a look here: Official Microsoft LinkedIn Share API Documentation.  It seems like the only valid format is something in the following form...
https://www.linkedin.com/sharing/share-offsite/?url={url}

For example...
https://www.linkedin.com/sharing/share-offsite/?url=http%3A%2F%2Frevoltlib.com%2F

This means that you only have the url param to modify.
If you are interested in a regularly maintained github project that keeps track of this so you don't have to, check it out!  Social Share URLs


text:
Q: No wifi adapter found Ubuntu 20.04.1 LTS bcm4352/14e4:43b1 Solved and my brain melted
Chili555 you are my hero
the popup secure boot warning I thought getting passed that disabled secure boot
sudo systemctl reboot --firmware-setup

disabled secure boot and when the computer booted up it worked normally and I could connect to wifi like nothing was wrong
========================================================================
all I had done before I disabled secure boot. no clue if it made any difference:
I have an ROG G750JW and am completely new to Ubuntu.
I have followed numerous threads with no luck
I ran:sudo apt update && sudo apt upgrade
with no luck
and I followed:
Installing Broadcom Wireless Drivers
any help would be appreciated!
$ lshw -C network
WARNING: you should run this program as super-user.
  *-network
       description: Network controller
       product: BCM4352 802.11ac Wireless Network Adapter
       vendor: Broadcom Inc. and subsidiaries
       physical id: 0
       bus info: pci@0000:03:00.0
       version: 03
       width: 64 bits
       clock: 33MHz
       capabilities: bus_master cap_list
       configuration: driver=bcma-pci-bridge latency=0
       resources: irq:18 memory:dd400000-dd407fff memory:dd200000-dd3fffff
  *-network
       description: Ethernet interface
       product: QCA8171 Gigabit Ethernet
       vendor: Qualcomm Atheros
       physical id: 0
       bus info: pci@0000:04:00.0
       logical name: enp4s0
       version: 10
       serial: 74:d0:2b:1a:c8:c5
       size: 100Mbit/s
       capacity: 1Gbit/s
       width: 64 bits
       clock: 33MHz
       capabilities: bus_master cap_list ethernet physical tp 10bt 10bt-fd 100bt 100bt-fd 1000bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=alx duplex=full ip=192.168.0.197 latency=0 link=yes multicast=yes port=twisted pair speed=100Mbit/s
       resources: irq:19 memory:dd500000-dd53ffff ioport:d000(size=128)
WARNING: output may be incomplete or inaccurate, you should run this program as super-user.

output of lspci -knn | grep Net -A3:
lspci -knn | grep Net -A3
03:00.0 Network controller [0280]: Broadcom Inc. and subsidiaries BCM4352 802.11ac Wireless Network Adapter [14e4:43b1] (rev 03)
    Subsystem: AzureWave BCM4352 802.11ac Wireless Network Adapter [1a3b:2123]
    Kernel driver in use: bcma-pci-bridge
    Kernel modules: bcma
04:00.0 Ethernet controller [0200]: Qualcomm Atheros QCA8171 Gigabit Ethernet [1969:10a1] (rev 10)

output of lspci -nn:
00:01.0 PCI bridge [0604]: Intel Corporation Xeon E3-1200 v3/4th Gen Core Processor PCI Express x16 Controller [8086:0c01] (rev 06)
00:14.0 USB controller [0c03]: Intel Corporation 8 Series/C220 Series Chipset Family USB xHCI [8086:8c31] (rev 04)
00:16.0 Communication controller [0780]: Intel Corporation 8 Series/C220 Series Chipset Family MEI Controller #1 [8086:8c3a] (rev 04)
00:1a.0 USB controller [0c03]: Intel Corporation 8 Series/C220 Series Chipset Family USB EHCI #2 [8086:8c2d] (rev 04)
00:1b.0 Audio device [0403]: Intel Corporation 8 Series/C220 Series Chipset High Definition Audio Controller [8086:8c20] (rev 04)
00:1c.0 PCI bridge [0604]: Intel Corporation 8 Series/C220 Series Chipset Family PCI Express Root Port #1 [8086:8c10] (rev d4)
00:1c.2 PCI bridge [0604]: Intel Corporation 8 Series/C220 Series Chipset Family PCI Express Root Port #3 [8086:8c14] (rev d4)
00:1c.3 PCI bridge [0604]: Intel Corporation 8 Series/C220 Series Chipset Family PCI Express Root Port #4 [8086:8c16] (rev d4)
00:1c.4 PCI bridge [0604]: Intel Corporation 8 Series/C220 Series Chipset Family PCI Express Root Port #5 [8086:8c18] (rev d4)
00:1d.0 USB controller [0c03]: Intel Corporation 8 Series/C220 Series Chipset Family USB EHCI #1 [8086:8c26] (rev 04)
00:1f.0 ISA bridge [0601]: Intel Corporation HM87 Express LPC Controller [8086:8c4b] (rev 04)
00:1f.2 SATA controller [0106]: Intel Corporation 8 Series/C220 Series Chipset Family 6-port SATA Controller 1 [AHCI mode] [8086:8c03] (rev 04)
00:1f.3 SMBus [0c05]: Intel Corporation 8 Series/C220 Series Chipset Family SMBus Controller [8086:8c22] (rev 04)
01:00.0 VGA compatible controller [0300]: NVIDIA Corporation GK106M [GeForce GTX 765M] [10de:11e2] (rev a1)
01:00.1 Audio device [0403]: NVIDIA Corporation GK106 HDMI Audio Controller [10de:0e0b] (rev a1)
03:00.0 Network controller [0280]: Broadcom Inc. and subsidiaries BCM4352 802.11ac Wireless Network Adapter [14e4:43b1] (rev 03)
04:00.0 Ethernet controller [0200]: Qualcomm Atheros QCA8171 Gigabit Ethernet [1969:10a1] (rev 10)

after running:sudo apt-get install bcmwl-kernel-source
I get back
sudo apt-get install bcmwl-kernel-source
[sudo] password for zainen:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
  libdrm2:i386 libexpat1:i386 libfprint-2-tod1 libglapi-mesa:i386
  libglvnd0:i386 libx11-xcb1:i386 libxcb-dri2-0:i386 libxcb-dri3-0:i386
  libxcb-glx0:i386 libxcb-present0:i386 libxcb-sync1:i386 libxdamage1:i386
  libxfixes3:i386 libxshmfence1:i386 libxxf86vm1:i386
Use 'sudo apt autoremove' to remove them.
The following NEW packages will be installed:
  bcmwl-kernel-source
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 0 B/1,544 kB of archives.
After this operation, 8,068 kB of additional disk space will be used.
Media change: please insert the disc labeled
 'Ubuntu 20.04.1 LTS _Focal Fossa_ - Release amd64 (20200731)'
in the drive '/media/cdrom/' and press [Enter]
sudo sed -i '/cdrom/d' /etc/apt/sources.list
Ign:1 cdrom://Ubuntu 20.04.1 LTS _Focal Fossa_ - Release amd64 (20200731) focal/restricted amd64 bcmwl-kernel-source amd64 6.30.223.271+bdcom-0ubuntu5
Get:1 cdrom://Ubuntu 20.04.1 LTS _Focal Fossa_ - Release amd64 (20200731) focal/restricted amd64 bcmwl-kernel-source amd64 6.30.223.271+bdcom-0ubuntu5 [1,544 kB]
Selecting previously unselected package bcmwl-kernel-source.
(Reading database ... 187968 files and directories currently installed.)
Preparing to unpack .../bcmwl-kernel-source_6.30.223.271+bdcom-0ubuntu5_amd64.deb ...
Unpacking bcmwl-kernel-source (6.30.223.271+bdcom-0ubuntu5) ...
Setting up bcmwl-kernel-source (6.30.223.271+bdcom-0ubuntu5) ...
Loading new bcmwl-6.30.223.271+bdcom DKMS files...
Building for 5.4.0-51-generic
Building for architecture x86_64
Building initial module for 5.4.0-51-generic
Done.

wl.ko:
Running module version sanity check.
 - Original module
   - No original module exists within this kernel
 - Installation
   - Installing to /lib/modules/5.4.0-51-generic/updates/dkms/

depmod........

DKMS: install completed.
modprobe: ERROR: could not insert 'wl': Operation not permitted
update-initramfs: deferring update (trigger activated)
Processing triggers for initramfs-tools (0.136ubuntu6.3) ...
update-initramfs: Generating /boot/initrd.img-5.4.0-51-generic

I also put in sudo sed -i '/cdrom/d' /etc/apt/sources.list to get past the cdrom request
Trying to work with ndiswrapper I cant seem to get the windows driver to work
sudo ndiswrapper -i bcmwl63.inf
couldn't open bcmwl63.inf: No such file or directory at /usr/sbin/ndiswrapper line 162.


text:
Q: HTML / iFrames: IFrame в IFrame не отображается (Dynamics CRM) Добрый день!
Я пытаюсь средствами HTML отобразить IFrame в IFrame.
var iFrameAuth = $('#InlineDialog_Iframe', window.parent.document).contents().find('#iFrameAuth');
    iFrameAuth.css("display","block")
    iFrameAuth.width(w);
    iFrameAuth.height(h);
    iFrameAuth.src = url;

Итог:

Там ничего не отображается, хотя я указываю валидный src (окрывал в отдельной вкладке)
Подскажите, пожалуйста, как все-таки отобразить во втором iframe старницу?

A:  iFrameAuth[0].src = url;

решило вопрос


text:
Q: Notepad class in Java I'd like to achieve the following:
A resizable JFrame class that has a panel of buttons on top and a JTextArea on the rest of the JFrame. It should look much like Notepad with buttons instead of drop down menus. So far I was able to write this, but the JTextArea resizes incorrectly.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class TestDialog extends JDialog implements ActionListener {

    public TestDialog(JFrame parent, String title, String message) {
        super(parent, title, true);
        JPanel buttonPanel = new JPanel();
        JButton buttonOK = new JButton("OK");
        buttonPanel.add(buttonOK);
        buttonOK.addActionListener(this);
        //Listing 2 goes here
        add(buttonPanel, BorderLayout.NORTH);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        JTextArea myTextArea = new JTextArea();
        myTextArea.setText(message);
        myTextArea.setName(title);

        myTextArea.setLineWrap(true);
        myTextArea.setWrapStyleWord(true);

        JScrollPane myScrollBar = new JScrollPane(myTextArea,
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        add(myScrollBar, BorderLayout.SOUTH);
        setPreferredSize(new Dimension(1100, 800));
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        setVisible(false);
        dispose();
    }
}

These are two closest hits: (JTextArea on JPanel inside JScrollPane does not resize properly) and (http://www1.cs.columbia.edu/~swapneel/1007/Notepad.java) However, in the first case the JTextArea resizes only to fit all text, not all available JFrame space. The second version version of Notepad doesn't have a scroll bar. As a result it doesn't work with large files.
Also, I have a lot of "overridable method calls in the constructor". I know this is bad. What should I do about it?

A: This app seems to behave as you described. https://docs.oracle.com/javase/tutorial/displayCode.html?code=https://docs.oracle.com/javase/tutorial/uiswing/examples/components/TextDemoProject/src/components/TextDemo.java
You should ask a new question regarding the warnings that you see, because it is a separate topic, imho.


text:
Q: can I include a file with class in another class? file.php

class file{
    function include_file($file_name){
        include($file_name);
    }
}

$file = new file;
$file->include_file('content.php');

----------------------------------
content.php

include('content_class.php');
$content = new content;
switch($option){
    case 'a':
        $content->table_list($option);
    break;
}

----------------------------------
content_class.php
class content{
    function table_list($option){
        echo 'table list for option : '.$option;
    }
}

I've tested those code and it give the result
// table list for option : a
but i want to know are those class above run in valid way of OOP class ? since class content running inside class file because it was included via content.php
i'm still new with OOP.
Thanks in advance.

A: I believe that in content.php, assuming that $option is set in previous lines of code, that the switch block should look like this:
switch ($option) {
    case 'a':
        $content->table_list($option);
        break;
}

Since table_list is a member of the class content. otherwise, I believe that the classes as declared above are valid. I am not sure about including files in the middle of a class in file.php, though. If nothing else, it probably isn't doing you any favors.

A: To answer the question in your title:  Yes, classes can be defined in basically any scope, and includes can be nested inside functions.  So, defining the content class where you have done it is perfectly valid.
That said, three things about the code:
1) You are referencing table_list as a variable* ($table_list) instead of method on the content object:
switch($option){
    case 'a':
        $content->table_list($option);
    break;
}

2) When you include a file from inside a method (in this case, the $file->include_file method), the execution is in the scope of that method.  That means that $option in the line switch($option) will be undefined (since it isn't defined anywhere in this script).  You may need to pull it in from a superglobal, from a parameter passed to the original method, or using the global keyword:
global $option;
switch($option){ ...

3): If you are just going to pass $option to the method, you probably don't need the switch statement, though maybe your example is just oversimplified.
global $option;
$content->table_list($option);

Lastly, the examples are obviously very simple classes, so I can't really judge whether they are good objects, but right now they aren't serving any purpose as objects since they have no members.  (Therefore, they are the same as plain old functions, right now — in other words, they don't need any object scope.)

* Note that in PHP this is not a syntax error.  Instead, it evaluates the value of $table_list and then tries to call a function by that name.  If $table_list contained "a", it would try to call a().


text:
Q: How to check conversion from C++ string to unsigned int I need to:
1) Find what is the maximum unsigned int value on my current system. I didn't find it on limits.h. Is it safe to write unsigned int maxUnsInt = 0 - 1;? I also tried unsigned int maxUnsInt = MAX_INT * 2 + 1 that returns the correct value but the compiler shows a warning about int overflow operation.
2) Once found, check if a C++ string (that I know it is composed only by digits) exceeded the maximum unsigned int value on my system.
My final objective is to convert the string to a unsigned int using atoi if and only if it is a valid unsigned int. I would prefer to use only the standard library.

A: There should be a #define UINT_MAX in <limits.h>; I'd be
very surprised if there wasn't.  Otherwise, it's guaranteed
that:
unsigned int u = -1;

will result in the maximum value.  In C++, you can also use
std::numeric_limits<unsigned int>::max(), but until C++11,
that wasn't an integral constant expression (which may or may
not be a problem).
unsigned int u = 2 * MAX_INT + 1;

is not guaranteed to be anything (on at least one system,
MAX_INT == UMAX_INT).
With regards to checking a string, the simplest solution would
be to use strtoul, then verify errno and the return value:
bool
isLegalUInt( std::string const& input )
{
    char const* end;
    errno = 0;
    unsigned long v = strtoul( input.c_str(), &end, 10 );
    return errno == 0 && *end == '\0' && end != input.c_str() && v <= UINT_MAX;
}

If you're using C++11, you could also use std::stoul, which
throws an std::out_of_range exception in case of overflow.

A: numeric_limits has limits for various numeric types:
unsigned int maxUnsInt = std::numeric_limits<unsigned int>::max();

stringstream can read a string into any type that supports operator>> and tell you whether it failed:
std::stringstream ss("1234567890123456789012345678901234567890");

unsigned int value;
ss >> value;

bool successful = !ss.fail();

A: According to this you do not need to calculate it, just use appropriate constant, which it this case should be UINT_MAX.
Few notes.
This seems more of a c way in contrast to c++ but since you say you want to use atol I stick with it. c++ would be using numeric_limits as Joachim suggested. However the c++ standard also defines the c-like macros/definitions, so it should be safe to use.
Also if you want it to be c++-way, it would probably be preferred to use stringstream (which is a part of standard c++ library) for conversion.
Lastly I deliberately don't post explicit code solution, 'cause it looks like homework, and you should be good to go from here now.


text:
Q: How to take user input and add to array in Javascript? I've got a page im trying to develop which will take user input and then add it to an array and then take that array and make a select and option list out of it as such.
<!DOCTYPE>
<html>
<head>
<script>
 var option_list = [];
   // for loop at thats option_list to select select tag
 for (var i = 0; i < option_list.length; i++){
  var opt = option_list[i];
  var option = document.createElement("option");
  var select = document.getElementById("select");
  option.setAttribute("id", opt); //Adding ID to the option list
  option.setAttribute("class", "intersect-option"); // adds classes to option
  option.value(opt); // adds value to option list
  select.appendChild(option); // Adds option to the list.

}
function add_option(name){
var name = document.getElementById("name").value;
name.push(option_list());
}
</script>
</head>
<body>
 <input type="text" id="name" value="">
 <input type="button" onclick="add_option()" value="add person">
 <select id="select">
</select>

</body>
</html>

The issue i am having is that it says when i try and input the information i get back-

Uncaught TypeError: option_list is not a function
at add_option (selectTest.html:19)
at HTMLInputElement.onclick (selectTest.html:25)

I am unsure what i am doing wrong and any help would be greatly appreciated.

A: You should push name into option_list array. The correct syntax is option_list.push(name);
function add_option(){
    var name = document.getElementById("name").value;
    option_list.push(name);
}

A: Pushing elements into array works the other way:
option_list.push(name);

http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

A: name.push(option_list());

As it says, option_list is not a function, and balanced parentheses after an identifier designate a function call in C family languages, so option_list() is not a valid expression.
Additionally, did you really intend to loop from zero up to the length of an empty array (which is equally zero)?

A:

    <!DOCTYPE>
    <html>
    <head>

    </head>
    <body>
     <input type="text" id="name" value="">
     <input type="button" onclick="add_option()" value="add person">
     <select id="select">
    </select>
    <script>
     var option_list = [];
       // for loop at thats option_list to select select tag

      var select = document.getElementById("select");

    function add_option(name){
    var name = document.getElementById("name").value;
     var option = document.createElement("option");
      var label = document.createTextNode(name);
      option.setAttribute("id", name); //Adding ID to the option list
      option.setAttribute("class", "intersect-option"); // adds classes to option
      option.value = name; // adds value to option list

      option.appendChild(label);
      select.appendChild(option); // Adds option to the list.
    }

    </script>
    </body>
    </html>


text:
Q: How to show output in HTML instead of text enter image description hereI am using a jquery script to show the page content on a scroll of page, which is working fine but I'm facing issues in output content.
It is showing my all loops data in text form, not in HTML

The above script I have used to use scroll effect to page content, but out is displaying all HTML tags along with content

A: You are using jQuery.text() method to output the contents.
$p.text(p + (block === -1 ? '(No More Events)' : '...'));

Try using jQuery.html() instead


text:
Q: Issue: Multithread bulkinsert I tried to do a bulkinsert with many threads. After using linq to read 1000 rows of one dataTable (called 'dt'), it made a new dataTable and did the bulkinsert into the database.
There is the code to initialize the threads:
        ManualResetEvent[] doneEvents = new ManualResetEvent[10];
        BancoDAO[] fibArray = new BancoDAO[10];

         for (int i = 0; i < 10; i++)
        {
            doneEvents[i] = new ManualResetEvent(false);
            BancoDAO bd = new BancoDAO()
            {
                _doneEvent = doneEvents[i],
                dataTable = (dt.AsEnumerable()
                    .Skip(i * 1000)
                    .Take(1000)
                    ).CopyToDataTable<DataRow>()
            };
            fibArray[i] = bd;
            ThreadPool.QueueUserWorkItem(bd.ThreadPoolCallback, i);
        }

        WaitHandle.WaitAll(doneEvents);

As you can see, the insert occurs on BancoDAO class. Here is the code:
    public DataTable dataTable = new DataTable();
    public ManualResetEvent _doneEvent;

    public void ThreadPoolCallback(Object threadContext)
    {
        int threadIndex = (int)threadContext;
        GravaTabelaThread(dataTable);
        _doneEvent.Set();
    }

    public static void GravaTabelaThread(DataTable dt)
    {
            OracleConnection cteste = new OracleConnection(ConfigurationManager.ConnectionStrings["TesteUpload"].ToString());
            cteste.Open();
            OracleBulkCopy bcp = new OracleBulkCopy(cteste);
            bcp.DestinationTableName = "MAG_T_SORTIMENTO2";

            foreach (KeyValuePair<string, string> k in ColumnMappings())
            {
                bcp.ColumnMappings.Add(k.Key, k.Value);
            }
            try
            {
                bcp.WriteToServer(dt);
                bcp.Dispose();
            }
            catch (Exception ex)
            {
            }
            cteste.Close();
            //Now I open and close the connection everytime after doing the bulkinsert in the database.
            //I'm not using anymore the same connection.
    }

The problem is: some threads inserts the values on database...some times this exception blows (I'll translate the oracle message from portuguese into english, so, please keep in mind this is a "free translation"):
{Oracle.DataAccess.Client.OracleException Error in row '1' column '1'
ORA-39776:  API fatal error, wrong directoty way when loading the table USR_TRANSF.MAG_T_SORTIMENTO2
ORA-39781: Loads of direct path stream are not allowed after another context loading the same table was to be terminated  in Oracle.DataAccess.Client.OracleBulkCopy.PerformBulkCopy()
   in Oracle.DataAccess.Client.OracleBulkCopy.WriteDataSourceToServer()
   in Oracle.DataAccess.Client.OracleBulkCopy.WriteToServer(DataTable table, DataRowState rowState)
   in Oracle.DataAccess.Client.OracleBulkCopy.WriteToServer(DataTable table)
   in UploadArquivo.BancoDAO.GravaTabelaThread(DataTable dt) at c:\Users\Rafael.pinho\Desktop\UploadArquivo\UploadArquivo\UploadArquivo\BancoDAO.cs:linha 49}

A: It appears from the ODP.Net Developer's Guide that OracleBulkCopy class does a direct-path load.  If that's the case, then it is not really compatible with a multi-threaded application.  Only one session can be doing a direct-path load on a particular object at any point in time.  I suppose that you could serialize your threads so that only one thread has an open transaction at any point in time but it seems highly likely that this would defeat the purpose of multithreading on the client.  On the other hand, since a direct path insert is the most efficient way to load data, you should basically be able to load data as quickly as you can pump it over the network (assuming, of course, your database can process data that quickly but I would assume that it could).


text:
Q: Finitely Many Extensions of Fixed Degree of a Local Field How does one show that there are only finitely many degree $n$ extensions of a local field? I understand how this follows from class field theory in the Abelian case but don't understand how to do the non-Abelian case.

A: In my comment, I said there was an argument from compactness, but on thinking a little more, I realized that since the set of irreducible polynomials over the ring of integers $\mathfrak o$ of your field is not closed, that approach would be a little trickier than I hoped.
Instead, let's do it piecemeal; I'm sure there's a quicker argument than what I give below, but I'm not recalling it now.
It's not Class Field Theory, it's Kummer Theory mostly. I'll give a proof for extensions of $\Bbb Q_p$, and there will be necessary modifications for the function-field case. I'll show that there are only finitely many Galois extensions of degree $n$; the general case follows from this. First, notice that there is only one unramified extension of degreee $n$, so I can concentrate on totally ramified extensions.
In case we're talking about degree $n$ prime to $p$, then Ramification Theory says that the Galois group is injected into $\kappa^*$, where $\kappa$ is the residue field; in particular, the Galois group is cyclic. Now extend the base from your original $p$-adic field $k$ to the field $k'$ you get by adjoining the $n$-th roots of unity. Now you're talking about a cyclic extension of degree $n'$ dividing $n$, and these are in one-to-one correspondence with the subgroups of ${k'}^*/({k'}^*)^{n'}$, only finitely many 'cause the $n$-th power map is open (here is one of the places where the fact that the field is local gets used).
Now for the case that the extension is of degree $p^m$ for some $m$. Just as before, I'll pass to the situation where the base field $k$ has $p$-th roots of unity. You have a $p$-group, so a composition series where each factor is $C_p$, cyclic of order $p$. Kummer theory again, the number of extensions of degree $p$ is finite, each of these has only finitely many extensions of degree $p$, etc. Finitely many in all.
Those are the arguments for the separate layers. I only need to say that the maximal tamely ramified extension in your general extension of degree $n$ is Galois over the base, and it all works out.
Maybe somebody else has a slicker proof; I would welcome it.

A: About questions I have seen on the "explicit" number of extensions of fixed degree of a local field k : Krasner has shown complete (and ugly) formulae in the book "Tendances géométriques en Algèbre et Théorie des Nombres", ed. CNRS, Paris 1966, 143-169 ; a much more elegant "mass formula" has been given by Serre, Comptes Rendus Acad. Sciences Paris, 286 (1976), 1031-1036 .
As for the same problem for Galois extensions with a given Galois group G, the answer is also known when G is a p-group: if k does not contain the group of p-th roots of 1, see Safarevic, Amer. Math. Soc. Transl., 4 (1956), 59-72 ; if k does, see Yamagishi, Proc. Amer. Math. Soc., 123 (1995), 2373-2380.   ¤


text:
Q: Glyphicon on dynamic button I'm trying to add a glyphicon to my dynamically created button in my javascript file.
I can add it in the actual html file but I can't figure out how to add it from javascript
function createRemoveIcon(){
    var icon = document.createElement("span");

    icon.className ="glyphicon glyphicon-remove-circle";

    alert("test" + icon);
}

Or this is how I was originally trying to create it
function createRemoveRowButton(attendeeArrayIndex) {
    var removeIcon = document.getElementById("removeIcon");

    var removeRowButton = document.createElement("BUTTON");
    var icon = document.createTextNode(removeIcon);
    removeRowButton.appendChild(icon);
    removeRowButton.onclick = function() {
        deleteRow(attendeeArrayIndex);
    };
    return removeRowButton;
}

A: I hope I understand your problem correctly. You want to add a button via javascript and then add an icon to that button.
This example adds a button to the DOM and when you click the button; it appends the icon to itself.
JSFiddle: http://jsfiddle.net/e9f2M/1/
function createRemoveIcon(){
    var button = document.createElement("button");
    button.setAttribute('class', 'btn btn-default');
    button.innerHTML = 'click me';
    button.onclick = function(){
        var icon = document.createElement("span");

        icon.className ="glyphicon glyphicon-remove-circle";
        this.appendChild(icon);
    }
    document.getElementById("container").appendChild(button);
}

A:             var p=document.createElement("p")
          var ActiveBtn = document.createElement("button");
          var sp1 = document.createElement("span");

           sp1.style.color = "green";
           sp1.setAttribute("class", "glyphicon glyphicon-off");
           sp1.setAttribute("class", "glyphicon glyphicon-ok-circle");
            ActiveBtn.appendChild(sp1);

p.appendChild(ActiveBtn)


text:
Q: Do you need to use API key for google maps API for client-side applications? They allow only 2,500 requests per key, so I must use client-side and use user's IP for requests. Do I need to use API key for google maps API for client-side applications? What if I don't and they found out? Would my domain get banned?

A: To answer your first question, no you do not need a key on the client-side if you expect your application to make less than 25,000 map loads per day. If you don't have a key, and you reach the limit for 90 consecutive days - they will contact you about it and ask you to purchase a license (not shut their services down from your site). For more info read Usage Limits and Billing from the API docs.


text:
Q: C# ошибка CS1525 Делаю метод который принимает на вход строку и, если первая буква не заглавная, возвращает перевернутый вариант исходной строки.
class App
{
    // BEGIN (write your solution here)
    public static string ConvertString(string word)
    {
        var check = char.IsUpper(word[0]);
        if (check == false)
        {
            return Functions.StringReverse(word);
        }
        else if (word == "")
        {
            return "";
        }
        else (check == true)
        {
            return word;
        }
    }
    // END
}

В итоге выдаёт ошибку:
(16,8): error CS1525: Unexpected symbol `{'

Что делать?
Functions.StringReverse() – переворот строки
char.IsUpper() – проверка символа на верхний регистр

A: В исправленном коде проблема не воспроизводится, однако он содержит ошибку: сначала происходит обращение к первому символу, а потом только проверка, является ли строка пустой.
Также код можно упростить при помощи тернарного оператора:
public static string ConvertString(string word)
{
    return word == "" || !char.IsUpper(word[0]) ? word : Functions.StringReverse(word);
}


text:
Q: I made a Javascript slider and i'm having some serious trouble with the CSS. So I made a Javascript Slider. The problem is that the Image is like pushing down my next/prev divs when the image loads and its not sitting in the container I have for the slider right either. I'm not sure whats going on Here is my code:
I can post a link to my site if you need to see it.
  HTML

CSS
#sliderFrame{
margin-top: 10px;
width:100%;
height:350px;
border: 2px solid #003E66;
background:#CAE9FF;

}
#prev{
z-index:99;
display:block;
float:left;
height:100%;
width:5px;
background-color:#8F8F8F;
opacity: 0.2;
width:10%;
position:relative;
}
#prev:hover{
opacity: 0.4;
}
#next{
z-index:99;
display:block;
float:right;
height:100%;
width:10px;
background-color:#8F8F8F;
opacity: 0.2;
width:10%;
position:relative;
}
#next:hover{
opacity: 0.4;
}

JavaScript
var Image = new Array("img/CS-GO-Test.jpg", "img/CS-GO-Test2.jpg", "img/test.jpg");
var ImageNum = 0;
var ImageLength = Image.length -1;

function swapImage(num){
  ImageNum = ImageNum + num;

  if(ImageNum > ImageLength){
    ImageNum = 0;
  }

  if(ImageNum < 0){
    ImageNum = ImageLength;
  }

 document.slider.src = Image[ImageNum];
}

A: To place the next and prev divs above sliderFrame use absolute positioning instead of relative positioning for the #prev and #next elements.
Here is how I would do it:
#sliderFrame {
margin-top: 10px;
width: 100%;
height: 350px;
border: 2px solid #003E66;
background: #CAE9FF;
position:relative; /*add this so that divs inside can be placed relative to THIS div*/
}
#prev {
z-index: 99;
display: block;
height: 100%;
width: 10px;
background-color: #8F8F8F;
opacity: 0.2;
width: 10%;
position: absolute; /*needed for placement relative to the parent element (sliderFrame) and for overlapping elements*/
top: 0; /*place on top*/
}
#next {
z-index: 99;
display: block;
height: 100%;
width: 10px;
background-color: #8F8F8F;
opacity: 0.2;
width: 10%;
position: absolute; /*absolute positioning to place relative to parent element (sliderFrame) */
right: 0; /*instead of floats use right for positioning*/
top: 0; /*place on top*/
}

To sum it up, make sure that the parent container (sliderFrame) is set the position to relative and use absolute positioning for the inside elements that need to be positioned over the parent element.
Check out this link to learn more about absolute and relative positioning:
http://css-tricks.com/absolute-positioning-inside-relative-positioning/


text:
Q: Select containing row based on CSS and content I know how to deal with CSS, so I could create custom filter to block some post's name from some websites with a chrome extension called "stylish".
However, as CSS3 selector not allow to search inverted way, I want to enhance my custom filter using Tampermonkey in Chrome with jQuery or javascript.
What I want is an effect like below with javascript (which doesn't work with CSS3 yet.)
.wordbreak[content="USER_NAME"] < a < tr {display:none!important}

What I meant to do is; find classes named wordbreak also which contains the text 'USER_NAME' for the first, and then set their styles to "display:none" if the "tr" sibling tree is formed as; tr > a > .wordbreak + the inner text is "USER_NAME"
I've look through greasemonkey.org to find something like this one, but I couldn't any clue to how to make it work though. help would be grateful !

Link of the page I want to modify
List of the posts and I want to hide the line of authored by "LibereQ:

The first shot :
// ==UserScript==
// @name         Black list
// @match        https://cafe.naver.com/MyCafeIntro*
// @match        https://cafe.naver.com/jssct*
// @match        https://cafe.naver.com/jssct
// ==/UserScript==

document.querySelectorAll('tr > td > div > table > tbody > tr > td > a > .wordbreak').forEach(wordbreak => {
  if (wordbreak.textContent.includes('LiberaQ')) wordbreak.style.display = 'none';
}, 1000);

A: That script has 3 main problems:

*

*The target pages are AJAX (javascript) driven so you must use AJAX-aware techniques such as MutationObserver or waitForKeyElements.

*The selector is overly complicated -- which means:
  (a) you must get it EXACTLY right and missing tds (for example) are deal-breakers
  (b) The script becomes much more brittle (likely to fail on some pages, or in the future).

*The @match list is wrong.  The actual content you appear to be targeting is in an iframe with an address like: cafe.naver.com/ArticleList.nhn?search....

The content you want is conveniently marked with a wordbreak class. That is the ideal selector by itself (based on what you've shown). Keep it simple.
Also keeping the @match simple, but you might be okay with the alternate.
Here's a complete script that illustrates the process:
// ==UserScript==
// @name        Black list
// @match       https://cafe.naver.com/*
// @require     https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require     https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant       GM_addStyle
// @grant       GM.getValue
// ==/UserScript==
//- The @grant directives are needed to restore the proper sandbox.

//Possible alternate match:
// @match       https://cafe.naver.com/ArticleList*

waitForKeyElements (".wordbreak", hideBlackListedNode);

function hideBlackListedNode (jNode) {
    if (jNode.text ().includes ('LiberaQ') ) {
        //jNode.hide ();                             // Hide just the node
        //jNode.closest ("tr").hide ();              // Hide the containing row
        /* Hide the containing row of the containing table
           The .parent() is needed due to a quirk of .closest().
        */
        jNode.closest ("tr").parent ().closest ("tr").hide ();
    }
}

A: Select all .wordbreaks that match the selector string, and check their textContent. If it includes USER_NAME, set the element's display property:
document.querySelectorAll('tr > a > .wordbreak').forEach(wordbreak => {
  if (wordbreak.textContent.includes('USER_NAME')) {
    wordbreak.style.display = 'none';
  }
});

(But are you sure you have an a which is a direct descendant from a tr? If it's valid HTML you should see a td there instead, and probably use something more like tr > td > a > .wordbreak)


text:
Q: Is there a way to break into the debugger when an AngularJS expression is running? If I have this select: <select name="custType" ng-model="vm.custType" ng-options="c.name.toUpperCase() as c.name for c in vm.customers"...>
Is there a way to break into the devtools debugger when the expression inside ng-options starts to run?
Different reasons:
 - I would like to know when the expression runs during the lifecycle of the web page.
 - I would like to know the current values of c.name and vm.customers at
   a point of time during the expression lifecycle.
  - I also want to know if vm.customers is being used before it gets loaded with data.

A: find ng-options directive at angular src code and place a breakpoint.
ng-options

A: Have a try using the following:
HTML
 <select name="custType"
         ng-model="vm.custType"
         ng-options="c.name.toUpperCase() as c.name for debugCustomer(c) in vm.customers"
  ... ></select>

JS
...

$scope.debugCustomer = function (customer) {
  console.log(customer);
  debugger;
  return customer;
}

...


text:
Q: new activity from AsyncTask not starting My Async task runs as it is supposed to and I want to pass an object of arraylists through an intent into the next activity which will update the screen and build some views.
I have my constructor:
Async(BigDecimal balance, Date SD, Integer Years, BigDecimal CPY, Date fPayDate, BigDecimal Nom, String PF, Context context) {

    this.balance = balance;
    this.SD = SD;
    this.Years = Years;
    this.CPY = CPY;
    this.fPayDate = fPayDate;
    this.Nom = Nom;
    this.PF = PF;
    this.context = context;
}

I try to pass the intent and start the activity:
@Override
protected void onPostExecute(arWrapper wrapper) {
    super.onPostExecute(wrapper);

   this.balAr = wrapper.balAr;
   this.payAr = wrapper.payAr;
   this.intAr = wrapper.intAr;
   this.dateAr = wrapper.dateAr;
   this.prinAr = wrapper.prinAr;

    Intent intent = new Intent(context,scrollTable.class)
            .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra("balance", new myParcelable(balAr, intAr, dateAr, prinAr, payAr));
    context.startActivity(intent);

}

I then try to start the following activity to create a dynamic table layout:
public class scrollTable extends Activity
{

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        myParcelable object = getIntent().getParcelableExtra("balance");
        ArrayList<BigDecimal> balAr = object.balAr;
        ArrayList<BigDecimal> intAr = object.intAr;
        ArrayList<Calendar> dateAr = object.dateAr;
        ArrayList<BigDecimal> prinAr = object.prinAr;
        ArrayList<BigDecimal> payAr = object.payAr;

        String[] column = { "Payment", "Interest", "Principal",
                "Balance"
        };
        int rl=balAr.size();
        int cl=column.length;

        ScrollView sv = new ScrollView(this);
        TableLayout tableLayout = createTableLayout(dateAr, column,rl, cl, payAr, intAr, prinAr, balAr);
        HorizontalScrollView hsv = new HorizontalScrollView(this);

        hsv.addView(tableLayout);
        sv.addView(hsv);
        setContentView(sv);

    }

    private TableLayout createTableLayout(ArrayList rv, String [] cv,int rowCount, int columnCount, ArrayList pay, ArrayList intr, ArrayList prin, ArrayList bal)
    {
        // 1) Create a tableLayout and its params
        TableLayout.LayoutParams tableLayoutParams = new TableLayout.LayoutParams();
        TableLayout tableLayout = new TableLayout(this);
        tableLayout.setBackgroundColor(Color.BLACK);

        // 2) create tableRow params
        TableRow.LayoutParams tableRowParams = new TableRow.LayoutParams();
        tableRowParams.setMargins(1, 1, 1, 1);
        tableRowParams.weight = 1;

        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.US);

        for (int i = 0; i < rowCount; i++)
        {
            // 3) create tableRow
            TableRow tableRow = new TableRow(this);
            tableRow.setBackgroundColor(Color.BLACK);

            for (int j= 0; j < columnCount; j++)
            {
                // 4) create textView
                TextView textView = new TextView(this);
                //  textView.setText(String.valueOf(j));
                textView.setBackgroundColor(Color.WHITE);
                textView.setGravity(Gravity.CENTER);

                if (i ==0 && j==0)
                {
                    textView.setText("Date");
                }
                else if(i==0)
                {
                    Log.d("TAG", "set Column Headers");
                    textView.setText(cv[j-1]);
                }
                else if( j==0)
                {
                    //set up for dates
                    Log.d("TAG", "Set Row Headers");
                    textView.setText(rv.get(i).toString());
                }
                else if (j == 1)
                {
                    textView.setText(pay.get(i).toString());

                }
                else if (j == 2)
                {
                    textView.setText(intr.get(i).toString());

                }
                else if (j == 3)
                {
                    textView.setText(prin.get(i).toString());

                }
                else if (j == 4)
                {
                    textView.setText(bal.get(i).toString());

                }

                // 5) add textView to tableRow
                tableRow.addView(textView, tableRowParams);
            }

            // 6) add tableRow to tableLayout
            tableLayout.addView(tableRow, tableLayoutParams);
        }

        return tableLayout;
    }
}

Why doesn't the start activity work properly? I don't get any error message and the debug frames just stop as soon as it hits the new activity. I'm also not sure if the main thread can handle all the dynamic creating of the table layout. In addition to why this won't work is there a way to break up the rendering computations?
Edit, there was a log of the events - Logcat:
01-30 13:30:14.462 32279-32279/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 21866747 , only wrote 21713760
01-30 13:30:16.385 32360-516/? I/ActivityManager: START u0 {flg=0x10000000 cmp=dcash.loanschedulecalculator/.scrollTable (has extras)} from uid 10095
01-30 13:30:16.440 9711-9711/dcash.loanschedulecalculator I/Choreographer: Skipped 298 frames!  The application may be doing too much work on its main thread.
01-30 13:30:16.461 32360-410/? E/JavaBinder: !!! FAILED BINDER TRANSACTION !!!  (parcel size = 743720)
01-30 13:30:16.462 32360-410/? W/ActivityManager: Exception when starting activity dcash.loanschedulecalculator/.scrollTable
                                                  android.os.TransactionTooLargeException: data parcel size 743720 bytes
                                                      at android.os.BinderProxy.transactNative(Native Method)
                                                      at android.os.BinderProxy.transact(Binder.java:748)
                                                      at android.app.IApplicationThread$Stub$Proxy.scheduleLaunchActivity(IApplicationThread.java:1230)
                                                      at com.android.server.am.ActivityStackSupervisor.realStartActivityLocked(ActivityStackSupervisor.java:1467)
                                                      at com.android.server.am.ActivityStackSupervisor.startSpecificActivityLocked(ActivityStackSupervisor.java:1571)
                                                      at com.android.server.am.ActivityStack.resumeTopActivityInnerLocked(ActivityStack.java:2663)
                                                      at com.android.server.am.ActivityStack.resumeTopActivityUncheckedLocked(ActivityStack.java:2215)
                                                      at com.android.server.am.ActivityStackSupervisor.resumeFocusedStackTopActivityLocked(ActivityStackSupervisor.java:2062)
                                                      at com.android.server.am.ActivityStack.completePauseLocked(ActivityStack.java:1449)
                                                      at com.android.server.am.ActivityStack.activityPausedLocked(ActivityStack.java:1375)
                                                      at com.android.server.am.ActivityManagerService.activityPaused(ActivityManagerService.java:7251)
                                                      at android.app.IActivityManager$Stub.onTransact(IActivityManager.java:317)
                                                      at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:2935)
                                                      at android.os.Binder.execTransact(Binder.java:674)
01-30 13:30:16.463 32360-410/? W/ActivityManager: Force removing ActivityRecord{2aa6505 u0 dcash.loanschedulecalculator/.AmortizationSchedule t144}: app died, no saved state
01-30 13:30:16.477 32360-410/? I/ActivityManager: Start proc 9753:dcash.loanschedulecalculator/u0a95 for activity dcash.loanschedulecalculator/.scrollTable
01-30 13:30:16.480 9753-9753/? I/zygote: Not late-enabling -Xcheck:jni (already on)
01-30 13:30:16.507 9753-9753/? W/zygote: Unexpected CPU variant for X86 using defaults: x86
01-30 13:30:16.530 32360-419/? E/JavaBinder: !!! FAILED BINDER TRANSACTION !!!  (parcel size = 743720)
01-30 13:30:16.531 32360-419/? E/ActivityManager: Second failure launching dcash.loanschedulecalculator/.scrollTable, giving up
                                                  android.os.TransactionTooLargeException: data parcel size 743720 bytes
                                                      at android.os.BinderProxy.transactNative(Native Method)
                                                      at android.os.BinderProxy.transact(Binder.java:748)
                                                      at android.app.IApplicationThread$Stub$Proxy.scheduleLaunchActivity(IApplicationThread.java:1230)
                                                      at com.android.server.am.ActivityStackSupervisor.realStartActivityLocked(ActivityStackSupervisor.java:1467)
                                                      at com.android.server.am.ActivityStackSupervisor.attachApplicationLocked(ActivityStackSupervisor.java:972)
                                                      at com.android.server.am.ActivityManagerService.attachApplicationLocked(ActivityManagerService.java:6958)
                                                      at com.android.server.am.ActivityManagerService.attachApplication(ActivityManagerService.java:7025)
                                                      at android.app.IActivityManager$Stub.onTransact(IActivityManager.java:291)
                                                      at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:2935)
                                                      at android.os.Binder.execTransact(Binder.java:674)
01-30 13:30:16.531 32360-419/? I/ActivityManager: Process dcash.loanschedulecalculator (pid 9753) has died: fore TOP
01-30 13:30:16.545 32360-419/? I/ActivityManager: Start proc 9767:dcash.loanschedulecalculator/u0a95 for activity dcash.loanschedulecalculator/.scrollTable
01-30 13:30:16.567 32360-32483/? W/InputDispatcher: channel '88672e0 dcash.loanschedulecalculator/dcash.loanschedulecalculator.AmortizationSchedule (server)' ~ Consumer closed input channel or an error occurred.  events=0x9
01-30 13:30:16.567 32360-32483/? E/InputDispatcher: channel '88672e0 dcash.loanschedulecalculator/dcash.loanschedulecalculator.AmortizationSchedule (server)' ~ Channel is unrecoverably broken and will be disposed!
01-30 13:30:16.572 9767-9767/? I/zygote: Not late-enabling -Xcheck:jni (already on)
01-30 13:30:16.599 9767-9767/? W/zygote: Unexpected CPU variant for X86 using defaults: x86
01-30 13:30:16.605 32360-32706/? I/WindowManager: WIN DEATH: Window{88672e0 u0 dcash.loanschedulecalculator/dcash.loanschedulecalculator.AmortizationSchedule}
01-30 13:30:16.605 32360-32706/? W/InputDispatcher: Attempted to unregister already unregistered input channel '88672e0 dcash.loanschedulecalculator/dcash.loanschedulecalculator.AmortizationSchedule (server)'
01-30 13:30:16.627 1395-1395/? D/gralloc_ranchu: gralloc_alloc: Creating ashmem region of size 8298496
01-30 13:30:16.642 32360-419/? W/ActivityManager: Slow operation: 125ms so far, now at attachApplicationLocked: after mServices.attachApplicationLocked
01-30 13:30:16.653 32360-419/? W/ActivityManager: Slow operation: 136ms so far, now at attachApplicationLocked: after updateOomAdjLocked
01-30 13:30:16.665 32360-32407/? E/ViewRootImpl[loanschedulecalculator]: Attempting to destroy the window while drawing!
                                                                           window=android.view.ViewRootImpl@9617e17, title=Splash Screen dcash.loanschedulecalculator
01-30 13:30:16.718 1395-1395/? D/gralloc_ranchu: gralloc_alloc: Creating ashmem region of size 8298496
01-30 13:30:16.725 32360-304/? W/ActivityManager: Slow operation: 59ms so far, now at attachApplicationLocked: after mServices.attachApplicationLocked
01-30 13:30:16.727 32360-304/? W/ActivityManager: Slow operation: 62ms so far, now at attachApplicationLocked: after updateOomAdjLocked
01-30 13:30:16.729 32360-32388/? W/Looper: Dispatch took 204ms on android.ui, h=Handler (com.android.server.am.ActivityManagerService$UiHandler) {452b573} cb=null msg=53
01-30 13:30:16.730 32360-32407/? W/ActivityManager: setHasOverlayUi called on unknown pid: 9711
01-30 13:30:16.752 1395-1395/? D/gralloc_ranchu: gralloc_alloc: Creating ashmem region of size 8298496
01-30 13:30:16.808 1413-1879/? E/BufferQueueProducer: [Splash Screen dcash.loanschedulecalculator#0] queueBuffer: BufferQueue has been abandoned
01-30 13:30:16.808 32360-32467/? E/Surface: queueBuffer: error queuing buffer to SurfaceTexture, -19
01-30 13:30:16.808 32360-32467/? E/Surface: queueBuffer (handle=0x898a4a00) failed (No such device)
01-30 13:30:16.809 1395-1395/? D/gralloc_ranchu: gralloc_alloc: Creating ashmem region of size 8298496
01-30 13:30:16.811 32360-32467/? E/ViewRootImpl[loanschedulecalculator]: Could not unlock surface
                                                                         java.lang.IllegalArgumentException
                                                                             at android.view.Surface.nativeUnlockCanvasAndPost(Native Method)
                                                                             at android.view.Surface.unlockSwCanvasAndPost(Surface.java:351)
                                                                             at android.view.Surface.unlockCanvasAndPost(Surface.java:332)
                                                                             at android.view.ViewRootImpl.drawSoftware(ViewRootImpl.java:3104)
                                                                             at android.view.ViewRootImpl.draw(ViewRootImpl.java:3007)
                                                                             at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2794)
                                                                             at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2347)
                                                                             at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1386)
                                                                             at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6733)
                                                                             at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911)
                                                                             at android.view.Choreographer.doCallbacks(Choreographer.java:723)
                                                                             at android.view.Choreographer.doFrame(Choreographer.java:658)
                                                                             at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
                                                                             at android.os.Handler.handleCallback(Handler.java:789)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                             at android.os.Looper.loop(Looper.java:164)
                                                                             at android.os.HandlerThread.run(HandlerThread.java:65)
                                                                             at com.android.server.ServiceThread.run(ServiceThread.java:46)


text:
Q: Custom column filter on a formatted column I need help using a custom column filter for handling JS objects.
I have a slickgrid table where the values in one column are JS object:
[
  { id: "1234", text: "Batman"},
  { id: "2345", text: "Robin"}
]

I use a custom formatter to smash the object into a string:
// convert [{id:string, text:string}...] to string
const optionFormatter: Formatter = (row, cell, value, columnDef, dataContext: any) =>
  value ? value.map(o => o.text).join(', ') : '';

Which displays in slickgrid as
Batman, Robin

my slickgrid options use gridmenu and enables column filtering:
 this.gridOptions = {
  enableGridMenu: true,
  enableFiltering: true,
  enableAutoResize: true,
  enableColumnReorder: true
};

My columnDef enables filtering for this column:
{
  id: 'owners',
  name: 'Owners',
  field: 'owners',
  sortable: false,
  formatter: optionFormatter,
  filterable: true
}

Everything works if the value in the cell is a string, but the filter doesn't work if the cell is an object.  I assume the filter is searching the pre-formatted value.
Is there a way to provide the column with a custom filter function that knows how to search the JS object for the query string?  For example if I could just search the JSON.stringify(value), that would be good enough.
Alternatively, this answer describes how I could use the formatter to store the formatted text as a different string property in dataContext.  If I do that, how do I specify which property to filter, seeing as it is a different property than the column field?

A: I found a workaround.
preprocess my data, calling JSON.stringify on all values that are objects:
flattenFeature(f: Feature): any{
  var res = {};
  for (var prop in f) {
    res[prop] = (typeof f[prop] === 'object') ? JSON.stringify(f[prop]) : f[prop];
  }
  return res;
}

Then in my formatter, I parse the json, before formatting:
// convert [{id:string, text:string}...] to string
const optionFormatter: Formatter = (row, cell, value, columnDef, dataContext) =>
  value ? JSON.parse(value).map(o => o.text).join(', ') : '';

This allows the standard string filter to search the stringify'd JSON


text:
Q: curl query from external domain Hello dear stackoverflow's sons , I have a problem a very hard problem for me , ok my problem is like this I have a domain name example.com and that domain has a query string that query datas from database , and I have another domain name example2.com that will query and echo datas from domain name example.com but when I want to use mysql_connect('') on the domain example2.com using database mysql of domain example.com it gives me this error "access denied for user(db_user) ... (using password : yes) I tried with many things and I didn't fix it yet, and I was thinking if I can use curl to query datas from example.com/?dataid=1 in the domain example2.com and thanks in advance please I don't want some answers that says contact your hosting provider in order for them to enable remote mysql because they didn't want to :'( and thanks in advance for your help <3

A: you need to create a user on mysql in example.com like 'youruser@example2.com' with all privileges and look at your server if external connections is enabled.


text:
Q: Autofac can inject property like @Resource in Spring? Im using .Net6 with Autofac, now I have a controller and two service:
public class TestController {
    public ITestService TestService { get; set; }

    public string Test() => TestService.Test();
}

public interface ITestService {
    string Test();
}

public class TestService1 : ITestService {
    public string Test() => "Test1";
}

public class TestService2 : ITestService {
    public string Test() => "Test2";
}

I register them in Module:
public class AutofacModule : Autofac.Module {
    // use assembly scanning to register: https://autofac.readthedocs.io/en/latest/register/scanning.html
    protected override void Load(ContainerBuilder builder) {
        builder.RegisterControllers().PropertiesAutowired().AsSelf();

        builder.RegisterServices().AsImplementedInterfaces();
    }
}

Now TestController.Get() will return "Test1" because TestService1 was injected. If I want to get TestService2(or other implemented instances), I need use constructor to take it.
In Spring, @Resource("beanName") can specify which instance will be inject, so I want to use an attribute to match instance`s name and inject it like Spring:
public class TestController {
    [Resource("TestService2")]
    public ITestService TestService { get; set; }

    // return "Test2"
    public string Test() => TestService.Test();
}

How can I do about that?

A: Autofac.Annotation sloved it.
In short, it used AutowiredAttribute (extend ParameterFilterAttribute) and pipeline phases, the pseudo-code like this:
// Autofac.Module
protected override void Load(ContainerBuilder builder) {
    // get all components that has `[Component]` attribute in process;
    List<Type> components = GetComponents();
    foreach (Type c in components) {
        // register as self
        var registration = builder.RegisterType(c).WithAttributeFiltering();

        // get properties that has `[Autowired]` attribute
        List<PropertyInfo> properties = GetProperties(c);
        registration.ConfigurePipeline(pb =>
            pb.Use(PipelinePhase.Activation, MiddlewareInsertionMode.StartOfPhase,
                   // the callback will be execute when components was resolved
                   (context, next) => {
                       next(context);
                       object instance = context.Instance;
                       foreach (PropertyInfo info in properties) {
                           // get component from container by `Autowired`'s options
                           context.TryResolveService(..., out object obj);
                           info.SetValue(intance, obj);
                       }
                   }
            )
        );
    }
}


text:
Q: How do I change which application is controlled by the audio controll keys? I'm sorry if this is an obvious question. When I have a video open in my browser and an mp3 file playing in VLC, how do I change which application is controlled by the play/pause and forward/backward keys?
Intuitively I would expect the last application to be used to be controlled by these keys, but that doesn't seem to be the case. For me, the browser video is tied to the shortcuts, even if I've been using VLC last.
Thanks you all!