text:
Q: Rangy - Module 'WrappedSelection' Not Supported I am trying to use Rangy in my Google Chrome extension, but I keep on receiving the error "Module 'WrappedSelection' not supported". This is a bare-bones extension so I have not implemented any code in this project other then Rangy.
Does anyone know if Rangy is compatible with a Google Chrome extension?

A: I'm no expert in Google Chrome extensions but I don't believe there's any reason why Rangy couldn't be used in one. I believe it's done using content scripts. A project called Feltipen uses Rangy in a Chrome extension.


text:
Q: How to align 3 columns that span 4 in 16 columns grid I have a grid layout with 16 columns. And for news i need to have 3 columns, each of them span on 4 columns of the grid container. How can i align those 3 columns with space evenly? - like on design

Because in this case justify-content doesnt seem to work as we have 16 columns. Please help me how to do this layout
Codepen is here: https://codepen.io/oleksiukmary/pen/BqGQdg
@supports ( grid-area: auto ) {
      display: grid;
      grid-template-columns: repeat(16, 1fr);
      grid-column-gap: 16px;
      justify-content: space-evenly;
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where should I place my custom javascript object? Let's say I have the following script
<script type="text/javascript">
  $(function($, d) {
    var custom = {
      settings: { news: $('div.news') },
      init: function() { this.settings.news.html('new'); }
    }
  }(jQuery, $(document)))
</script>

You can assume that the object has more functionality, but my question is where should I place it?
I know two approaches:

*

*Place the script in the <head> tag. That way I will have to make sure the object is called only after document.ready, so the settings jQuery objects ($('div.news')) won't be empty.

*The second way is less semantically correct in my opinion, but I can give up the document.ready function: I can just "physically" place the script after the html.
What solution would you prefer and why? Thanks from advance!

A: Any script that doesn't assist in rendering the layout of the page should be placed at the bottom of the body, preferrably as a reference to a script file (not the script itself). This allows the CSS + HTML to render the page visually, and then the JavaScript (or jQuery, in your case) is applied to the rendered elements.
It does not increase the performance of the page perse, but it does speed up the visual rendering, appearing to provide a faster experience for the end user.
See here for more details.

A: I place my code like this just before the closing body tag, and run init():
var custom: {
    settings: { news: null },
    init: function() {
        this.settings.news = $('#news');
        this.settings.news.html('new');
    }
}

custom.init();

Something like that.
Edited to reflect Anthony's comment.


text:
Q: Exception message in xunit includes parameter so my test fails I am trying to check that an exception that I throw gives the correct error message.
I have a method in a class that withdraws (substracts) from a value. If the value is less than 0, I throw an exception.
if (amount < 0)
{
    throw new System.ArgumentOutOfRangeException("amount", AmountLessThanZeroMessage);
}

This is my error message:
public const string AmountLessThanZeroMessage = "Amount is less than zero";

However, when I try to write a unit test to see if I get the correct message, it fails because of the parameter. This is the test:
[Fact]
public void CannotWithdrawLessThanZero()
{
    // Arrange
    var account = new Account("User", 23);

    // Act
    account.DepositCash(100);
    var thrownException = Assert.Throws<ArgumentOutOfRangeException>(() => account.WithdrawCash(-10));

    // Assert
    Assert.Equal(Account.AmountLessThanZeroMessage, thrownException.Message);
}

The result includes the parameter in the end, resulting in a failed test:

It seems the actual message includes which parameter it refers to. How do I correct this message? Should I just add the line (Parameter 'amount') to the expected string, or are there any better options?

A: You can create the exact same exception and use its message property. Like the code below
[Fact]
public void CannotWithdrawLessThanZero()
{
    // Arrange
    var account = new Account("User", 23);
    var expectedException = new System.ArgumentOutOfRangeException("amount", AmountLessThanZeroMessage);

    // Act
    account.DepositCash(100);
    var thrownException = Assert.Throws<ArgumentOutOfRangeException>(() => account.WithdrawCash(-10));

    // Assert
    Assert.Equal(expectedException.Message, thrownException.Message);
}

A: Messages changes often, message can be localized, so testing message equality will make tests more fragile.
Instead you can test that correct exception type was thrown, or even better and create domain specific exception to be sure that exception have been thrown for correct reasons.
public class WithdrawOfNegativeAmountNotAllowedException : Exception
{
    public WithdrawOfNegativeAmountNotAllowedException(int amount)
        : base($"Amount is less than zero ({amount})")
    {
    }
}

[Fact]
public void Cannot_withdraw_less_than_zero()
{
    var account = new Account("User", 23);
    account.DepositCash(100);

    Action withdraw = () => account.WithdrawCash(-10);

    withdraw.Should().Throw<WithdrawOfNegativeAmountNotAllowedException>();
}

In case you still want to test for correct message. Assertions of strings can be done in multiple ways, I would suggest to make assertion as loose as possible.
Test for part of the message which unlikely will change. For example test that message starts with some text or contain critical value.
[Fact]
public void Cannot_withdraw_less_than_zero()
{
    var account = new Account("User", 23);
    account.DepositCash(100);

    Action withdraw = () => account.WithdrawCash(-10);

    withdraw.Should()
        .Throw<WithdrawOfNegativeAmountNotAllowedException>()
        .And
        .Message.Should().ContainEquivalentOf("Amount is less than zero");
}


text:
Q: Properly creating a SalesOrder in Dynamics 365 I am trying to write a Dynamics 365 CRM plugin in which I want to create a new "salesorder".
I have the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;

// Microsoft Dynamics CRM namespace(s)
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;

namespace Microsoft.Crm.Sdk.Samples
{
    public class OrderTest : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            // Obtain the execution context from the service provider.
            Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
                serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));

            // The InputParameters collection contains all the data passed in the message request.
            if (context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is Entity)
            {
                // Obtain the target entity from the input parameters.
                Entity entity = (Entity)context.InputParameters["Target"];

                if (entity.LogicalName != "salesorder")
                    return;

                try
                {
                    Entity salesorder = new Entity("salesorder");

                    salesorder["name"] = "order test";

                    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
                    tracingService.Trace("OrderTestPlugin: Creating the order test.");
                    Guid orderId = service.Create(salesorder);

                }
                catch (FaultException<OrganizationServiceFault> ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred in the OrderTest plug-in.", ex);
                }
                //</snippetFollowupPlugin3>

                catch (Exception ex)
                {
                    tracingService.Trace("OrderTestPlugin: {0}", ex.ToString());
                    throw;
                }

            }
        }
    }
}

My problem is that it fails creating the salesorder. The error message I get is useless. It says: Download the details and load with Plug-in Profiler. followed by a long token. I don't understand how to create the "salesorder" and how to get a more understandable error message.

A: The code you have written is for creating salesorder in another execution pipeline using plugin. And you registered this plugin step to run on creation of salesorder entity record itself.
Hence this code will go on loops, to avoid that you can use depth property to stop the deadlock.
For your learning purpose, register this plugin step on some other entity & test it.


text:
Q: How to avoid chaining parameter as input and output in RxJava I don't have solid concepts on ReactiveX yet. What I'm trying to do is to download new files from an FTP server.
The sequence that I'm currently thinking of is connect -> list files from FTP -> filter out files that are already in local path -> download new files.
How to do this on a ReactiveX way, without having to pass the FTP connection as a parameter and returning it as an output for the next operator?
I don't think having something like this is the correct way:
fun listFilesFromFTP(ftpConnection : Connection) : Pair<Connection, List<Files>>

connectionObservable.flapMap(::listFilesFromFTP).flapMap(::filterLocalFiles).flatMap(::downloadFiles)  ... and so on...

A: If you want to do that in a pure functional way, without depending any data other than the function parameters, then you can define a FileDownloadContext with all connection and file info in it. Then all your functions can receive FileDownloadContext, edits it and then pass to the next function.
Or you can do it in a stateful way via encapsulating those functions in a class. So functions can reach to the class state. This is similar to Closure concept. Of course for each new file download request you need to create an new state object not to mix states.


text:
Q: Copying range without excluding autofiltered rows I am trying to copy a specific range from a protected sheet that has an autofilter with a few rows in the range filtered out.
When using the following code, only the visible rows in the range get copied:
origWB.Sheets("some data").Range("D3:LB77").Copy
targetWS.Cells(3, 4).PasteSpecial xlValues

As I said, the sheet is protected (and for various reasons I can't unprotect it within the macro), so I can't use commands that would normally solve the problem like this:
origWB.Sheets("some data").Range("D3:LB77").EntireRow.Hidden = False

I've been able to cancel the filter:
origWB.Sheets("some data").AutoFilterMode = False

This enables me to copy all the lines but then I can't figure out how to get the filter working again (as I need to leave the sheet exactly the way I found it) without getting blocked by the sheet protection.
I would appreciate either a solution that temporarily removes the filter and resumes it after the copy, or a solution that enables me to copy all the range including the hidden/filtered rows without messing with the filter itself.

A: I am not sure if it is possible to copy invisible cells by "copy". As far as i know it is not possible.
However, it is possible to read each cell value / styling properties cell by cell.
It should do the work fine for smaller ranges, but it is really slow when we have more cells (it trying to read each value instead copying entire range and this is time consuming).
Option Explicit

Sub code()
'a little performence boost
Application.ScreenUpdating = False

Dim source_cols As Integer
Dim source_rows As Integer
Dim source_range As Range
Set source_range = Sheets("SourceSheet").Range("a1:LB77")
Dim destination_range As Range
Set destination_range = Sheets("targetSheet").Range("a1")
source_cols = source_range.Columns.Count
source_rows = source_range.Rows.Count

Dim col As Integer
Dim row As Integer
For row = 1 To source_rows
    For col = 1 To source_cols
        'Copy value
        destination_range.Offset(row - 1, col - 1).Value = source_range.Cells(row, col).Value

        'Copy some extra styling if needed
        destination_range.Offset(row - 1, col - 1).Interior.Color = source_range.Cells(row, col).Interior.Color
        destination_range.Offset(row - 1, col - 1).Font.Color = source_range.Cells(row, col).Font.Color
        destination_range.Offset(row - 1, col - 1).Font.Bold = source_range.Cells(row, col).Font.Bold

    Next col
Next row

Application.ScreenUpdating = True
End Sub

However, I am recommending copy file (or worksheet at least) to remove filter, copy entire range and delete file/sheet that you just copied.

A: The following code adds a new worksheet and copies the entire range to the new spreadsheet where you can then copy and paste where you like

I have directed the copy to be below the existing filtered data but this can be redirected

Sub CopyFilteredData()
    Dim wsDst As Worksheet, tblDst As Range

    Dim wb As Workbook: Set wb = ThisWorkbook
    Dim wsSrc As Worksheet: Set wsSrc = wb.Worksheets("some data")
    Dim tblSrc As Range: Set tblSrc = wsSrc.Range("D3:LB77")

    Set wsDst = wb.Worksheets.Add
    Set tblDst = wsDst.Range(tblSrc.Address)
    tblDst = "='" & wsSrc.Name & "'!" & tblSrc.Address
    tblDst.Copy
    tblSrc.Offset(tblSrc.Rows.Count + 1, 0).PasteSpecial xlPasteValues

    Application.DisplayAlerts = False
    wsDst.Delete
    Application.DisplayAlerts = True

End Sub


text:
Q: Android problems when import library project using IntelliJ I am not sure why I cannot import the android.support.v7.app.ActionBarActivity class. I looked at and followed the steps described in this question to change the jar file of the project. However in the solution the first step was to delete the jar file that was already there, I however did not have that file. I am not using gradle.
This is code I got from the android tutorial.
    package com.example.myapp;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActvity;

public class DisplayMessageActivity extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_display_message);

        }
}

The error that comes up first is
Error:(5, 30) java: package android.support.v7.app does not exist

In the manifest also wrote this line.
<uses-sdk android:minSdkVersion="7"/>

I assume this is okay because I would need to make sure that v7 stuff is supported. As mentioned in the title I am using IntelliJ.

A: Add this in build.gradle in dependencies
compile 'com.android.support:appcompat-v7:21.0.0'

A: If you are using IntelliJ IDEA and not Android Studio (gradle based), you
should add the library by going to File > Project Structure
then go to your module, tab Dependencies, and add the jar file from there.
Jar files in libs are not automatically added in IntelliJ, you have to manually add them as dependencies.


text:
Q: postgresql json_build_object property LIKE I have a table with a column named "data" that contains json object of telemetry data.
The telemetry data is recieved from devices, where some of the devices has received a firmware upgrade. After the upgrade some of the properties has received a "namespace" (e.g. ""propertyname"" is now ""dsns:propertyname""), and there is also a few of the properties which is suddenly camelcased (e.g. ""propertyname"" is now ""propertyName"".
Neither the meaning of the properties or the number of properties has changed.
When querying the table, I do not want to get the whole "data", as the json is quite large. I only want the properties that are needed.
For now I have simply used a json_build_object such as:
select json_build_object('requestedproperty',"data"-> 'requestedproperty','anotherrequestedproperty',"data"-> 'anotherrequestedproperty') as "data"
from device_data
where id ='f4ddf01fcb6f322f5f118100ea9a81432'
and timestamp >= '2020-01-01 08:36:59.698' and timestamp <= '2022-02-16 08:36:59.698'
order by timestamp desc

But it does not work for fetching data from after the firmware upgrade for the devices that has received it.
It still works for querying data from before the upgrade, and I would like to have only one query for this if possible.
Are there some easy way to "ignore" namespaces and be case insensitive through json_build_object?
I'm obviously no postgresql expert, and would love all the help I can get.

A: This kind of insanity is exactly why device developers should not ever be allowed anywhere near a keyboard :-)
This is not an easy fix, but so long as you know the variations on the key names, you can use coalesce() to accomplish your goal and update your query with each new release:
json_build_object(
  'requestedproperty', coalesce(
                         data->'requestedproperty',
                         data->'dsns:requestedproperty',
                         data->'requestedProperty'),
  'anotherrequestedproperty', coalesce(data-> 'anotherrequestedproperty',
                                       data-> 'dsns:anotherrequestedproperty',
                                       data-> 'anotherRequestedProperty')
) as "data"

Edit to add:  You can also use jsonb_each_text(), treat key-value pairs as rows, and then use lower() and a regex split to doctor key names more generally, but I bet that the kinds of scatterbrains behind the inconsistencies you already see will eventually lead to a misspelled key name someday.


text:
Q: Updating a controller's scope using a directive's method How can I use a method in a directive to update a variable in the controller's scope?
I am using: Dropzone.js and angular-dropzone.js.
One of Dropzone's methods is .getQueuedFiles(). I would like to use this method to update a variable in the controller scope, but it isn't working. I would like to be able to update controller scope so I can show and hide things and pass the number of files to the next step in the form.
Here is the angular:
.controller('ImagesCtrl', function($scope) {

  $scope.queuedFiles = 0;

  $scope.dropzoneConfig = {
    init: function() {
      this.on("addedfile", function(file) {
        $scope.queuedFiles = $scope.dropzone.getQueuedFiles().length;
      });
    }
  };

})

And here is the html:
<form class="dropzone clear"
    method="post"
    enctype="multipart/form-data"
    ng-dropzone
    dropzone="dropzone"
    dropzone-config="dropzoneConfig">
</form>

Queued Files: {{queuedFiles}}

A: This is the correct code
var app = angular.module('myApp', ['ui.router', 'myApp.controllers']).
    config(['$stateProvider', '$urlRouterProvider',
    function ($stateProvider, $urlRouterProvider) {
        $urlRouterProvider.otherwise('/');

        $stateProvider
        .state('app', {
            url: '/',
            templateUrl: 'admin.html',
            onEnter: function ($stateParams) {
                console.log("Entered Admin route");
            }
            //controller: 'myController'
        })
        .state('sitebinding', {
            url: '/sitebinding',
            templateUrl: 'sitebinding.html'
        })
        .state('scrum', {
            url: '/scrum',
            templateUrl: 'scrum.html'
        });

    }
]);

angular.module('myApp.controllers', []).
controller('myController', function ($scope) {
    $scope.models = {
        helloAngular: 'I work!'
    };

    $scope.$on('$stateChangeStart', function (evt, toState, toParams, fromState, fromParams) {
        console.log('In state change start');
    })
});

This is the problem: when you write angular.module('myApp', []) specifying dependencies the second time to define your controllers, you override the original module.
If you want to add new stuff the an existing module you don't need to pass the dependencies array
angular.module('myModule').controller('MyCtrl', function....


text:
Q: Is it possible to launch a console app from an Office Add-In (C#) I think the subject says it all, I'm trying to open a console (really just for debugging, to write object properties) from an Outlook Addin I wrote in C#.  If so, how would you go about it? I tried starting a new console project just to see how it did it, but can't really see an easy way about it.
any thoughts are much appreciated! Thanks

A: If my understanding is correct in your Outlook addin cant you have some code like
System.Diagnostics.Process.Start(filename);

The above code is to invoke the appropriate file for opening. If the file name is of an exe then i guess it should open your console app.
UPDATE:
You can include an console app that has the Main method as follows:
static void Main(string args[])
{
     Console.Write(args[0].ToString());
     Console.Read();
}

And now in your Load method of the outlook addin :
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
      System.Diagnostics.Process.Start(filename, "hello test");
}

Now when your addin loads the console app should fire up and then print "hello test" in the console.


text:
Q: Actionsript 3.0 control multiple Instances of a class using a single function Hey I'm new to Flash AS 3.0 and I am having trouble with creating instances of classes and want to Control them using a single function for all of them.
import flash.display.MovieClip;
import flash.events.*;
stage.addEventListener (KeyboardEvent.KEY_DOWN, movestuff);

var newsymbol:MovieClip;
newsymbol = new Symbol1;
addChild(newsymbol);
newsymbol.x = 200
newsymbol.y = 200
addChild(newsymbol);

function movestuff (event:KeyboardEvent):void
{

newsymbol.x + 100
}

Symbol1 is a class from the library that I am trying to move, and I want to add multiple instances of it but control all of them using the function movestuff

A: Keep the instances in an array:
var penguinArray:Array = [];

function addPenguin(){
    var newPenguin:Penguin = new Penguin();
    //do stuff
    penguinArray.push(newPenguin);
}

function moveStuff(){
    for(var i in penguinArray){
        penguinArray[i].x += 10;
    }
}

A: Is your movement that uniform between all of them (do you want to move them all by the same x and y)? If so, put them all inside one parent movie clip and only move that.


text:
Q: cant find element on website with selenium i want search five-stars hotels in the near of Stuttgart (Germany) automatically on hotelstars.eu and wrote a python script with the selenium framework. I looked for similar questions but nothing worked.
Here are my browser-Driver code in a seperate file (browserDriver.py):
#-*-coding:utf-8-*-
import os

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument('--incognito')

chromedriver = r"\Users\simon\Documents\chromedriver_win32\chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver)

And the searchAutomattecally_hotelstars_eu.py - file:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select

import browserDriver as bd
import time

val_land = 'Germany'
val_city = 'Stuttgart'
val_radius = '100'
val_stars = '5'

bd.driver.get('https://www.hotelstars.eu/de/deutschland/service/hotelsuche/')

bd.driver.implicitly_wait(10)

# accept Cookies
bd.driver.find_element(By.ID, '564').click()

print('- - - Status: Cookies accepted')

element_land =bd.driver.find_element(By.NAME, 'country')
print(element_land.text)

all_options = element_land.find_elements(By.TAG_NAME, 'option')
for option in all_options:
    if option == val_land:
        select_land = Select(option)
        print('- - - Status: Geeeeeeeeeht')
print('- - - Status: if-Bedingung beendet')

select_land.select(By.Value, val_land)
print('- - - Status: ', select_land)

element_stadt = bd.driver.find_element(By.ID, 'city')
element_stadt.send_keys(val_city)

element_radius = bd.driver.find_element(By.ID, 'radius')
select_radius = Select(bd.driver.find_element_by_name('radius'))
select_radius.select_by_value(val_radius)

element_stars = bd.driver.find_element(By.ID, 'stars')
select_stars = Select(bd.driver.find_element(By.NAME, 'stars'))
select_stars.select_by_value(val_stars)

bd.driver.find_element_by_id("sendbtn").click()

link of the site hotelstars.eu
Here the error message:
Traceback (most recent call last):

File "...\searchAutomatecally_hotelstars_eu.py", line 28, in <module>
    element_land =bd.driver.find_element(By.NAME, 'country')

File "...\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "...\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "...\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response

raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[name="country"]"}
  (Session info: chrome=93.0.4577.63)

Can someone help??

A: Cause the desired element is in this iframe :
<iframe id="searchIframe" scrolling="no" src="/fileadmin/bsdist/theme/modules/hotelstars_search/?L=1" width="100%" height="200px" frameborder="0" style="border: 0px; height: 250px;" allowfullscreen=""></iframe>

so you have to switch to this iframe first and then you can interact with the desired element.
bd.switch_to.frame(bd.find_element_by_xpath("//iframe[@id='searchIframe']"))

and then interact with country drop down like this :-
element_land = bd.driver.find_element(By.NAME, 'country')


text:
Q: No se encuentra la 'variable' Firebase Android Studio / Firebase Tengo el siguiente codigo
public class NombreClase extends android.app.Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Firebase.setAndroidContext(this);
    }
}

Firebase tira el error

Cannot resolve Symbol 'Firebase'.

A: Hay que agregar la dependencia en el archivo build.gradle del proyecto.
compile 'com.firebase:firebase-client-android:2.5.2+'

Sincronizan de nuevo y ya.
Así podràn importar la clase Firebase.

A: Depende del uso que quieras hacer de Firebase. Te recomiendo que sigas los pasos de la documentación de
Firebase
Para registro de usuarios:

compile 'com.google.firebase:firebase-auth:9.6.1

Para usar base de datos:
compile 'com.google.firebase:firebase-database:9.6.1'

Para almacenar archivos (imágenes, videos, audio):
compile 'com.google.firebase:firebase-storage:9.6.1'


text:
Q: symfony vichupload cashe:clear Expected to find class "App\Message\EventSubscriber" After a redeployment of a website that I created with symfony 5, I have an error when I do a clear cache:
Expected to find class "App\Message\EventSubscriber" in file "/home/nduqhkrs/cineconde/src/Message/EventSubscriber.php" while importing services from resource "../src/", but it was not found! Check the namespace prefix used with the resource.
I tried to import class App\Message\EventSubscriber, but still not work.here is the EventSubscriber file :
    namespace App\EventSubscriber;

use App\Message\RemoveProductImageMessage;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Messenger\MessageBusInterface;
use Vich\UploaderBundle\Event\Event;
use Vich\UploaderBundle\Event\Events;

class RemoveFileEventSubscriber implements EventSubscriberInterface

{

private $messageBus;

public function __construct(MessageBusInterface $messageBus)
{
    $this->messageBus = $messageBus;
}

public static function getSubscribedEvents(): array
{
    return [
        Events::PRE_REMOVE => ['onPreRemove'],
    ];
}

public function onPreRemove(Event $event): void
{
    $mapping = $event->getMapping();
    $mappingName = $mapping->getMappingName();

    if ('product_image' === $mappingName) {
        $this->dispatch(RemoveProductImageMessage::class, $event);
    }
}

private function dispatch(string $messageClass, Event $event): void
{
    $event->cancel();

    $object = $event->getObject();

    $mapping = $event->getMapping();
    $filename = $mapping->getFileName($object);

    $message = new $messageClass($filename);
    $this->messageBus->dispatch($message);
}
}

I tried to dump the autoloader but I still have the problem. The class is not present in the services.yaml :
parameters:
locale: 'en'

services:
# default configuration for services in *this* file
_defaults:
autowire: true      # Automatically injects dependencies in your            services.
autoconfigure: true # Automatically registers your services as commands,  event subscribers, etc.

# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
resource: '../src/*'

exclude:
    - '../src/DependencyInjection/'
    - '../src/Entity/'
    - '../src/Kernel.php'
    - '../src/Tests/'

# controllers are imported separately to make sure services can be injected
# as action arguments even if you don't extend any base controller class

App\Controller\:
resource: '../src/Controller/'
tags: ['controller.service_arguments']

# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones

Thanks for helping...

A: You are showing the code to a class that isn't the problem. The problem in the error is in App\Message\EventSubscriber. Symfony cannot find that class. You are showing code for App\EventSubscriber\RemoveFileEventSubscriber which is the wrong place to look.
There are several reasons this can happen.

*

*Sometimes this is a result of not clearing the cache. Since the error is occurring when you do this, probably this is not the reason in this case.

*Did you dump the composer autoloader again? Depending on how you've set up your composer, you may need to dump the autoloader again: composer dumpautoload

*Is autoloading set up properly for that directory? See your config/services.yaml file. Under the services:App\: key be sure the file falls into the resource category and is not under the exclude directories.

*Is the class actually present? Is the file properly named and properly located by namespace? check for typos, missed capitalization, etc.


text:
Q: C program int to ascii conversion in certain range A given question asks to write a C program "snippet" that converts a whole positive integer in the range from 0 to 10 000 stored as int dnum to the appropriate number of ASCII characters in an array of 5 characters. "Unused characters should NULL (ASCII 0). Note that "9" = ASCII 57(10) = 39 (H). The character array is BCDchar.
I started writing the snippet, but not sure how to continue. Thank you in advance. (The question given is really confusing, that's why I don't quite understand what it really wants.)
#include <stdio.h>

int main(void) {

int range = 0;
int dnum = 0;
char BCDchar[5]; //ASCII

if(range >= 0 && range <= 10000) {

   }
}

A: ASCII stands for American Standard Code for Information Interchange and is a character encoding standard. Each character has a code in the ASCII table and the question asks you to convert a given int to its ASCII representation.
Check this table and look for number 9: its decimal code is 57 which stands for 39 in Hex and that is what the hint is trying to tell you.
The result should be stored in BCDchar with a maximum length of 5 because the highest number that you can treat in this example would be 10000 which stands for 49 48 48 48 48 in ASCII format, you can use this to verify your solution.
Finally, if a conversion needs only 4 bytes you just put 0 for the last byte in BCDchar.
This is only trying to help you understand the question, implementing this in C should be fairly easy.

A: What i think you need is the number xxxx to convert to a string "xxxx\0"
Store the digits of the number in an array.
int arr[5];
int n=dnum;    //assuming dnum is the number you want to convert
int i,no_of_digits;
for (i=0; i<5; i++){
    arr[i]=n%10;
    n=n/10;
    if(num==0){
        no_of_digits=i+1;
}
//now convert each digit to the respective ascii value
char *str=(char*) malloc((no_of_digits+1)*sizeof(char));
str[no_of_digits]='\0';
for (i=0; i<no_of_digits; i++){
    str[no_of_digits-i+1]=(char) arr[i]+48;
}
//str is the required string


text:
Q: How can I use overflow-text ellipses for flex-box children? I'm working on a flexbox with flex-direction: column and a fixed height. One of the flex items has flex: 1 to fit the remaining available space in the flexbox when necessary. My issue is that sometimes this flex item has text content that (if my language is correct) vertically overflows its container.
What I want to have happen is that the text content is truncated the way that text-overflow: ellipses usually does it, but I'm not finding a way that I'm able to make this happen.
You can see a demo I set up on Codepen where you can click the swap text button to swap between short an long text, where the long text does not use ellipses when overflowing. I've made an effort to separate out the important CSS to the issue and the visual aids to show what's happening on this demo.
Any help would be greatly appreciated! Thanks so much.


text:
Q: Response.End () doesn't abort current thread Anybody know why ASP.NET might not abort the current thread with a Response.End()?
Update: Reason being that there is code, albeit not well written, that is getting executed after Response.End().  I've never seen a case where Response.End () didn't stop the current thread from executing.

protected void Page_Load(object sender, EventArgs e)
{
        Response.Clear();
        Response.Redirect("somewhere", true);
        Response.End();

        //Some other code get's executed here
}

A: As you've pointed out, the method Response.End is defined as:
public void End()
{
  if (this._context.IsInCancellablePeriod) {
    InternalSecurityPermissions.ControlThread.Assert();
    Thread.CurrentThread.Abort(new HttpApplication.CancelModuleException(false));
  }
  else if (!this._flushing)
  {
    this.Flush();
    this._ended = true;
    if (this._context.ApplicationInstance != null) {
      this._context.ApplicationInstance.CompleteRequest();
    }
  }
}

Debugging a fairly simple web app with a break point in the Page_Load method, I can see the call stack includes the line:

System.Web.dll! System.Web.HttpApplication.ExecuteStep(System.Web.HttpApplication.IExecutionStep step = {System.Web.HttpApplication.CallHandlerExecutionStep}, ref bool completedSynchronously = true) + 0x4c bytes

Reflecting into CallHandlerExecutionStep I can see that the property IsCancellable is defined as:
bool HttpApplication.IExecutionStep.IsCancellable {
  get {
    return !(this._application.Context.Handler is IHttpAsyncHandler);
  }
}

The default handler for .aspx pages is the output from the PageHandlerFactory which implement IHttpHandler, not IHttpAsyncHandler - which would result in IsCancellable returning true (as indeed it does in my test app).
Have you configured a different HttpHandler in either your root web.config or one further up the stack to use an Async Handler instead? Are you using Update Panels with Partial Postbacks for example?

A: You don't have it in a try block do you?  That would throw a ThreadAbortException.

A: According to Community comment on http://msdn.microsoft.com/en-us/library/a8wa7sdt(VS.80).aspx  (select .NET framework 2.0) the current thread is not cancellable in Global.asax:
"Careful!! If you pass true, Response.Redirect() calls Response.End(), however there are certain circumstances where Response.End() does not raise the ThreadAbortException and instead sets a couple of flags and returns. One such situation is when you're in Global.asax, but it would occur more generically in any execution step that was not cancellable. I'll add details on Response.End(), but in a page you'd be fine, but in Global.asax processing will continue even if you pass true as the second parm."
I actually noticed this behaviour in one of my projects.

A: I could be mistaken, but I believe for one thing the threads that are used are background threads that belong to a thread pool and are recycled so it doesn't kill the thread.
Response.End(), terminates the Response, but it doesn't return from the function.
protected void Page_Load(object sender, EventArgs e)
{
        If(sometingBad)
        {
        Response.Clear();
        Response.Redirect("somewhere", true);
        Response.End();
        return;
        }

        //Some other code get's executed here
}


text:
Q: Print string with ' in python I have an array of strings a that I would like to print like e.g.
'a1','a2','a3'

where a1 = a[0], a2 = a[1], a3 = a[2].
For some reason
printformat = ''
for i in range(3):
    printformat+=a[i]+"',"

prints instead
"a1',a2',a3',"

A: a = ['a1', 'a2', 'a3']

print(','.join(f"'{i}'" for i in a))

Output:
'a1','a2','a3'

A: With loop:
printformat = "'"
for i in range(3):
    printformat += a[i] + "',"
printformat = printformat[:-1]  # Remove trailing comma
print(printformat)

You were exactly adding together three elements, each followed by a quote and a comma. The outer (double) quotes come from interpreter, probably, if you're doing it in REPL.
With more convenient methods:
printformat = ','.join(f"'{x}'" for x in a)
print(printformat)


text:
Q: Continuity of multivariable functions when "component functions" are continuous Given topological spaces $X_1, X_2, \dotsc, X_n, Y$, consider a multivariable function $f : \prod_{i = 1}^nX_i \to Y$ such that for any $(x_1, x_2, \dotsc, x_n) \in \prod_{i = 1}^nX_i$, the functions in the family $\{x \mapsto f(x_1, \dotsc, x_{i - 1}, x, x_{i + 1}, \dotsc, x_n)\}_{i = 1}^n$ are all continuous. Must $f$ itself be continuous? It seems to be true, so is there a Theorem that proves this?

A: The answer is "Yes" if you give the product $\prod X_i$ the slice (or sometimes called "cross topology").
The answer is "No" if you give the product $\prod X_i$ the usual product topology. In this case, $f$ is "separately continuous" but not necessarily continuous. The standard example is the function $f:\mathbb{R}\times \mathbb{R}\to \mathbb{R}$ defined by $f(x,y)=\frac{2xy}{x^2+y^2}$ for $(x,y)\neq (0,0)$ and $f(0,0)=(0,0)$. This function is continuous everywhere except $(0,0)$ but is continuous in each variable.


text:
Q: Promise.all in Node.js not blocking in function call using map and async calls I wrote a small module to talk to Zookeeper to obtain a list of service endpoints.
Everything work fine except for the part that return that list of endpoint. In the module, I expose a function that should return an array of endpoints obtain by calling getData (from module node-zookeeper-client) as many time as there's children in a specific path on Zookeeper. I tried to combine array map and Promise.all to call the getData x times but my function return before the Promise.all resolve ending with an "undefined" variable on the caller side. Here my code snippet:
zookeeper.js
...
const getData = (entry) => {
  return new Promise(function(resolve, reject) {
    client.getData(
      "/application/agent/" + entry,
      function (error, data, stat) {
        if (error) {
          console.log(error);
          reject(error);
        } else {
          console.log('getData resolve %s',data.toString('utf8'));
          resolve(data.toString('utf8'));
        }
      });
  });
};
...
function agentsEndpoint() {
  console.log('Begin agentsEndpoint...');
  var requests = agentList.map(getData);
  console.log('requests: %s', requests);
  var results = Promise.all(requests);
  console.log('results: %s', results);
  results.then((endpoints) => {
    return endpoints;
  });
  console.log('...agentsEndpoint return.');
}

module.exports = { agentsEndpoint };

main.js
...
const zk = require('./zookeeper.js');
zk.client.connect();

setInterval(listEndpoints,5000, zk);
function listEndpoints(zk) {
  console.log('Calling agentsEndpoint: %s',zk.agentsEndpoint());
}
...

And here the console output:
Begin agentsEndpoint...
requests: [object Promise],[object Promise]
results: [object Promise]
...agentsEndpoint return.
Calling agentsEndpoint: undefined
getData resolve 10.0.0.8/getEndpoint
getData resolve 10.0.0.10/getEndpoint

My expected behavior was that the function should have wait at the line results.then((endpoints) => { for the resulting Promise to resolve but as you can see in the console output, it resolve much later.
What I am missing here?!?!

A: The heart of the problem you are having is that agentsEndpoint is doing asynchronous things, but it is not returning anything. In order to know when the async parts of the function are done you need to return a promise from this function too, just like getData. Then the caller will receive the promise and can use it when it resolves. The basic idea without the console.logs will look like this:
In zookeeper.js ==>
const agentsEndpoint = () => Promise.all(agentList.map(getData));

In main.js ==>
function listEndpoints(zk) {
    zk.agentsEndpoint()
    .then(elements => console.log('Calling agentsEndpoint: %s', elements))
  }

A: console.log('Calling agentsEndpoint: %s',zk.agentsEndpoint());

You function don't return anything.
function agentsEndpoint() {
  ...
  console.log('...agentsEndpoint return.');
}

So Calling agentsEndpoint: undefined is valid answer.
You should  work with agentsEndpoint as async.
You may use callback, promise or async/await for it.
See example:
function agentsEndpoint() {
    console.log('Begin agentsEndpoint...');
    var requests = agentList.map(getData);
    console.log('requests: %s', requests);
    var results = Promise.all(requests);
    console.log('results: %s', results);
    return results;
}

function listEndpoints(zk) {
 zk.agentsEndpoint().then(endpoints => console.log('Calling agentsEndpoint: %s', endpoints);
}


text:
Q: How to perform BigInteger multiplication on char vectors? I'm implementing a BigInt in c++ and am trying to overload the multiplication operator. I'm storing large integers in a char vector.
vector<char> storage;

Here is what I did to implement operator*(int)
BigInt BigInt::operator*(int x)
{
int extra = 0;
int dec_mod = pow(10, this->storage.size());

for (auto & g : storage) {
    g = g * x + extra;
    int mod_g = g % dec_mod;
    extra = g / dec_mod;
    g = mod_g;
}

while (extra > 0) {
    storage.push_back(extra % dec_mod);
    extra /= dec_mod;
}

return *this;
}

The operator*(bigInt) function returns wrong answers. For example, 33 * 4 returns 1212 and not 132.This was my attempt at writing the overloaded operator* which takes a bigint object:
BigInt BigInt::operator*(BigInt bigN) {
int carry = 0;

for (int i = bigN.storage.size()-1; i >= 0; i--) {

    for (int j = this->storage.size()-1; j >= 0; j--) {

        int val = (this->storage.at(i) * bigN.storage.at(j)) + carry;
        this->storage.push_back(val % 10);
        carry = val / 10;
    }

}
return *this;
}

It looks like the logic in the carry is flawed, but i'm not sure how to fix it.

A: I'm not sure how you're trying to do this, but here is a walkthrough of why you're getting the result 1212 instead of 132:
BigInt operator*(int x)// x is 4
    {
        // Let's say storage holds 33, that's
        // {3, 3} in your char vector;
        int extra = 0;
        int dec_mod = pow(10, this->storage.size()); // dec_mod may be 100

        for (auto & g : storage)
        {
            g = g * x + extra;  // same as g = 3 * 4 + 0, g = 12
            int mod_g = g % dec_mod; // same as mod_g = 12 % 100 = 12
            extra = g / dec_mod; // same as 12 / 100 = 0
            g = mod_g;  // g = 12
        }
        // Exact same thing happens on the second iteration, your storage vector
        // ends up as {12, 12};
        // That's why your result is 1212

        while (extra > 0) {
            storage.push_back(extra % dec_mod);
            extra /= dec_mod;
        }
        return *this;
    }

I'm not sure how you are trying to do it, but here's my attempt, it's just as one would do it on paper:
#include <iostream>
#include <string>
#include <vector>

using namespace std;

struct BigInt
{
    BigInt(std::string num) { for (auto &i : num) storage.push_back(i - 48); }
    BigInt(std::vector<char> numVect) : storage(numVect) {}

    vector<char> storage;

    string getAsString()
    { string str; for (auto& i : storage) str += i + 48; return str; }
    // Add 48 to turn 0 - 9 to ascii string.

    vector<char> add(vector<char>& lhs, vector<char>& rhs)
    // Add function only needed if number is multiplied by more than one digit.
    {
        // Fill with zeros to make both vectors same length.
        int sizeDiff = (int)lhs.size() - (int)rhs.size();
        if (sizeDiff < 0)
            lhs.insert(lhs.begin(), abs(sizeDiff), 0);
        else if (sizeDiff > 0)
            rhs.insert(rhs.begin(), abs(sizeDiff), 0);

        vector<char> resultVect;
        int carry = 0;
        for (int i = lhs.size() - 1; i >= 0; --i)
        {
            int result = lhs[i] + rhs[i] + carry;
            carry = result / 10;
            result %= 10;
            resultVect.insert(resultVect.begin(), result);
        }
        if (carry != 0) resultVect.insert(resultVect.begin(), carry);

        return resultVect;
    }

    BigInt operator*(BigInt rhs)
    {
        int unitPlace = 0; // Keeps track of how many zeros to add in subsequent results
        vector<char> totalVect; // Accumulated value after each addition
        vector<char> resultVect; // Result of this particular multiplication

        for (int i = rhs.storage.size() - 1; i >= 0; --i, unitPlace++)
        {
            int carry = 0;
            for (int k = 0; k < unitPlace; ++k) resultVect.push_back(0);

            for (int j = storage.size() - 1; j >= 0; j--)
            {
                int result = rhs.storage[i] * storage[j] + carry;
                carry = result / 10;
                result %= 10;

                resultVect.insert(resultVect.begin(), result);
            }
            resultVect.insert(resultVect.begin(), carry);
            totalVect = add(totalVect, resultVect); // Add sub-result
            resultVect.clear();
        }

        // Strip leading zeros
        for (int i = 0; i < totalVect.size(); ++i) {
            if (totalVect[i] == 0) totalVect.erase(totalVect.begin() + i);
            else break;
        }

        return BigInt{ totalVect };
    }
};

int main()
{
    BigInt a{ "335467" };
    BigInt b{ "1019737" };

    BigInt c = a * b;

    std::cout << c.getAsString() << '\n';

    cin.ignore();
    return 0;
}


text:
Q: What is the best programming language and regression method for this private equity investment dataset? The excel (can be csv) dataset I want to work with has thousands of company names, and for each company, a few rounds of investment. This means many mentions of the same company but with different numbers over time. As a fake example with incorrect numbers:
(Company name, round name, round number, investment amount, post-investment valuation, date)

*

*Facebook, Seed, 1, $5,000,000, $20,000,000, 01-01-05

*Facebook, Series A, 2, $10,000,000, $50,000,000, 05-11-07

*AirBnB, Seed, 1, $200,000, $5,000,000, 10-08-10

and so on...
Usually each company has a single-digit amount of rounds (1-7 for the majority). There are many other columns that I also have more gathered info on each company, such as investors, amount raised to date, and debt round. I also have some derived columns from the given info, such as change in value from previous round, change in amount raised from previous round, normalized value (given an equation I developed), and other derived yes/no columns.
What I would like to do is be able to use all of these variables to make predictions for:

*

*Next round post-investment valuation

*Next round amount raised

*Next round deal date

*Whether a company fits a high-growth company identification model (to be created)

A: On the one hand, the data have panel format. They have two dimensions: company & time. Therefore, the ideas of classic panel data approaches, like mixed effects models, would be helpful here... Stata and R are the best packages for panel data.
On the other hand, if the data have 10,000+ companies (better 100,000+ companies) you can employ non-linear and non-parametric methods of machine learning: gradient boosting, random forest, support vector machine, etc. Arguably, R is the best language for that.
All in all, you may benefit from combining the panel data and machine learning approaches. So R wins.


text:
Q: Entity Framework Migrations: Prevent dropping column or table If EF migration decides to rename a column (or a table), it fulfills this by dropping the (old) column and then adding a column with the new name. This clearly leads to data loss.
Is there any way to prevent EF migration from dropping a column and force it to use RenameColumn instead?

A: Well, I didn't find a clear and straightforward solution.
My solution is hiding DbMigration class which every migration that was generated using code-based migration is derived from. I do this by introducing a new class with the same name (DbMigration). Then I put it inside the same assembly and same namespace where code files reside. This way, any reference of code files to the original DbMigration resolves to the new DbMigration type. Then, I can switch dropping a column ON or Off:
namespace MyProject.DAL.Migrations
{

    /// <summary>
    /// Customized DbMigration which protects columns to be dropped accidentally
    /// </summary>
    public abstract class DbMigration : global::System.Data.Entity.Migrations.DbMigration
    {
        public bool AlloDropColumn { get; set; }
        protected internal new void DropColumn(string table, string name, object anonymousArguments = null)
        {
            if (!AlloDropColumn)
                throw new Exception("MyProject: Dropping a column while updating database is prohibited. If you really want to drop column(s), set property 'AllowDropColumn' true.");
        }
    }
}

And in a code file:
public partial class _1 : DbMigration
    {
        public override void Up()
        {
            AlloDropColumn = true; // To allow column drop
            AddColumn("driver.TruckDriver", "FullName2", c => c.String());
            DropColumn("driver.TruckDriver", "FullName");
        }

        public override void Down()
        {
            AddColumn("driver.TruckDriver", "FullName", c => c.String());
            DropColumn("driver.TruckDriver", "FullName2");
        }
    }


text:
Q: Select iframe using Python + Selenium So, I was absolutely baffled as to how to do this in Selenium, and couldn't find the answer anywhere, so I'm sharing my experience.
I was trying to select an iframe and having no luck (or not repeatably anyway). The HTML is:

Blah Blah

The Python code (using the selenium library) was trying to find this iframe using this:
    @timed(650)
def test_pedometer(self):
    sel = self.selenium
    ...
    time.sleep(10)
    for i in range(5):
        try:
            if sel.select_frame("css=#upload_file_frame"): break
        except: pass
        time.sleep(10)
    else: self.fail("Cannot find upload_file_frame, the iframe for the device upload image buttons")

Repeated fails with every combination of Selenium commands I could find.
The occasional success would not be reproducible, so perhaps it was some sort of race condition or something? Never did find the right way to get it in selenium proper.

A: This worked for me with Python (v. 2.7), webdriver & Selenium when testing with iframes and trying to insert data within an iframe:
self.driver = webdriver.Firefox()

## Give time for iframe to load ##
time.sleep(3)
## You have to switch to the iframe like so: ##
driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))
## Insert text via xpath ##
elem = driver.find_element_by_xpath("/html/body/p")
elem.send_keys("Lorem Ipsum")
## Switch back to the "default content" (that is, out of the iframes) ##
driver.switch_to.default_content()

A: You don't need to use JavascriptExecutor.  All you needed to do was switch into the frame and then switch back out, like so:
// do stuff on main window
driver.switch_to.frame(frame_reference)
// then do stuff in the frame
driver.switch_to.default_content()
// then do stuff on main window again

As long as you are careful with this, you will never have a problem.   The only time I always use a JavascriptExecutor is to get window focus since I think using Javascript is more reliable in that case.

A: To shift Selenium's focus within the  you can use either of the following Locator Strategies:

*

*Using ID:
driver.switch_to.frame("upload_file_frame")

*Using CSS_SELECTOR:
driver.switch_to.frame(driver.find_element(By.CSS_SELECTOR, "iframe#upload_file_frame"))

*Using XPATH:
driver.switch_to.frame(driver.find_element(By.XPATH, "//iframe[@id='upload_file_frame']"))

Ideally, you have to induce WebDriverWait for the desired frame to be available and switch to it and you can use either of the following Locator Strategies:

*

*Using ID:
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.ID,"upload_file_frame")))

*Using CSS_SELECTOR:
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe#upload_file_frame")))

*Using XPATH:
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='upload_file_frame']")))

*Note : You have to add the following imports :
 from selenium.webdriver.support.ui import WebDriverWait
 from selenium.webdriver.common.by import By
 from selenium.webdriver.support import expected_conditions as EC

Reference
You can find a couple of relevant discussions in:

*

*Ways to deal with #document under iframe

*Switch to an iframe through Selenium and python

A: If iframe is dynamic node, it's also possible to wait for iframe appearence explicitly and then switch to it using ExpectedConditions:
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as wait

driver = webdriver.Chrome()
driver.get(URL)
wait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it("iframe_name_or_id"))

If iframe doesn't have @id or @name it can be found as common WebElement using driver.find_element_by_xpath(), driver.find_element_by_tag_name(), etc..:
wait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it(driver.find_element_by_xpath("//iframe[@class='iframe_class']")))

To switch back from iframe:
driver.switch_to.default_content()

A: Selenium's selectFrame command accepts all the standard locators like css=, but it also has a an extra set of locators that work specifically with FRAME and IFRAME elements.
As the doc says:

selectFrame ( locator )  Selects a frame within the current window.
  (You may invoke this command multiple times to select nested frames.)
  To select the parent frame, use "relative=parent" as a locator; to
  select the top frame, use "relative=top". You can also select a frame
  by its 0-based index number; select the first frame with "index=0", or
  the third frame with "index=2".
You may also use a DOM expression to identify the frame you want
  directly, like this: dom=frames["main"].frames["subframe"]
Arguments: locator - an element locator identifying a frame or iframe

In general, you'll have better luck using the specialized locators, especially if you establish the right context first (e.g., select_frame("relative=top"); select_frame("id=upload_file_frame");).

A: What finally worked for me was:
        sel.run_script("$('#upload_file_frame').contents().find('img[alt=\"Humana\"]').click();")

Basically, don't use selenium to find the link in the iframe and click on it; use jQuery.  Selenium has the capability to run an arbitrary piece of javascript apparently (this is python-selenium, I am guessing the original selenium command is runScript or something), and once I can use jQuery I can do something like this: Selecting a form which is in an iframe using jQuery

A: you can use this simple code to look for the iframe using xpath
sample use
set_iframe("/html/body/div[2]/table/")
def set_iframe(xpath):
    print('set_iframe')
    driver.switch_to.default_content()
    seq = driver.find_elements_by_tag_name('iframe')
    for x in range(0, len(seq)):
        driver.switch_to.default_content()
        print ("iframe-"+str(x))
        try:
            driver.switch_to.frame(int(x))
            driver.find_element_by_xpath(xpath)
            return str(x)
        except:
            continue


text:
Q: Convert PHP's dot concatenation of a binary part + string part to C# I'm working on rewriting a piece of PHP code to C#. This code is used for password hashing. In the first step it produces a string like "password{salt}", than hashes it via sha512 hash algorithm. After that a loop is hashing the combination of the first hash and the salt again for 5000 iterations.
The PHP Code looks like this:
<?php
$password = 'abc';
$salt = 'def';
$salted = $password.'{'.$salt.'}';
$digest = hash('sha512', $salted, true);

for ($i=1; $i<5000; $i++) {
    $digest = hash('sha512', $digest.$salted, true);
}

$encodedPassword = base64_encode($digest);

//$encodedPassword contains the final hash code

I was able to get it working without the loop (with just the first hash() call). So the main hashing and base64 encoding is done correctly. I found out that this part is what I cannot manage to rewrite in C#:
$digest.$salted

$digest seems to be a binary representation since PHP's hash() function was used with "true" as the last parameter (see PHP hash - manual). $salted is a string. Both get somehow magically combined by PHP's dot / concat operator. I guess there will be some sort of standard conversion from binary to string under the hood when using the dot operator with a non-string operand.
This is my code so far:
void Main()
{
    string password = "abc";
    string salt = "def";
    string salted = String.Format("{0}{{{1}}}", password, salt);
    byte[] digest = hash(salted);

    for(int i = 1; i < 1; i++)
    {
        digest = hash(String.Format("{0}{1}", System.Text.Encoding.UTF8.GetString(digest), salted));
    }
    var encodedPassword = System.Convert.ToBase64String(digest);
    //$encodedPassword should contain the final hash code
}

static byte[] hash(string toHash)
{
    System.Security.Cryptography.SHA512 sha512 = new System.Security.Cryptography.SHA512Managed();
    return sha512.ComputeHash(System.Text.Encoding.UTF8.GetBytes(toHash));
}

As you see I tried to convert the hash bytes back to a string with System.Text.Encoding.UTF8.GetString() and then append the salt but that doesn't produce the same output as the PHP code.
I would be very happy if someone could help me on this. Thank you very much.

A: In the PHP version you loop 4999 times, while in the C# version 0. The second problem is that the returned bytes from hash() have no encoding at all.
This should give you the same result as the PHP version:
    System.Security.Cryptography.SHA512 sha512 = new System.Security.Cryptography.SHA512Managed();
    var saltedUtf8Bytes = System.Text.Encoding.UTF8.GetBytes(salted);

    for(int i = 1; i < 5000; i++)
    {
        digest = sha512.ComputeHash(digest.Concat(saltedUtf8Bytes).ToArray());
    }


text: Q: Передача базы данных в приложение есть готовая база данных sqlite на сервере (порядка 40000 строк), каким образом лучше всего передать все данные из нее в android приложение, в котором тоже лежит база данных отображающая эту? формировать огромный json?


text:
Q: Передача параметров на другую страницу уважаемые форумчане!
Имеется страница с таблицей иностранных слов:

   {% for word in word_list %}

        {{ forloop.counter }}
        {{word.russian_word}}
        {{word.foreign_word}}
        {{word.context}}
        Редактировать

    {% endfor %}

Соответственно страница с иностранным словом находится по адресу: "/edit/?id=21".
Есть еще вариант с передачей параметра через строку запроса "/edit/21".
Отсюда два вопроса:

*

*какая принципиальная разница между "/edit/?id=21" и "/edit/21". Какой способ предпочтительнее использовать в данном случае?

*это нормальная практика светить id записи?

A: *

*/edit/?id=21 - передаётся как GET параметр, а в /edit/21 - 21 это часть самой ссылки, лично я бы использовал второй вариант. Но решать вам, как вам будет удобнее реализовать и как вы это видите.

*Да, конечно, что такого в том чтобы засветить id записи? Конечно, если это не конфиденциальная информация, как например: номер карты или номер транзакции.


text:
Q: How to Populate value in Text Field from Picklist in Salesforce? I want to populate values in TEXT field automatically while selecting values from picklist. I need to do this task using :

*

*Formula Field

*Workflows

*Triggers

A: You can do this using easily using any of the above three methods.

*

*Formula
Create formula field and do TEXT(Picklist__c)

*Workflow Crate a Wf created and Edited and on Field Update select your text field and then update this TEXT(Picklist__c)

*Trigger Create a before insert, before update trigger and do simply
for(Object a : trigger.new)
       a.YourTextField__c = a.Picklist__c;


text:
Q: How to use python to login to a page and retrieve the redirected link? I've tried the following:
How to use Python to login to a webpage and retrieve cookies for later usage?
However this requires
resp = opener.open('http://www.example.com/hiddenpage.php')

I can't know the hiddenpage link since it changes with every login and every refresh.
The page is a simple HTTP one and
I used WireShark to know the input fields and they are as follows
HTML Form URL Encoded: application/x-www-form-urlencoded
Form item: "mode" = "451"
Form item: "json" = "{"username":"test1,"password":"dragon","testtest":"1","browser":"Chrome_57"}"
Form item: "__RequestType" = "ajax"
Form item: "t" = "Sat Apr 22 2017 15:05:41 GMT 0530 (India Standard Time)"

Do I have to include all the form items in the script or are they provided by default by the request library? As a user visiting the website I only provide username and password, though rest of the fields are editable as well.
This is how login page looks if it helps

A: You can use request.session. You can login using a POST request. After that, session will automatically follow the login link as if you're logging in from a browser.
from request import session

Session = session()

payload = {
    "username": test1,
    "password": "dragon",
    "testtest": "1",
    "browser": "Chrome_57"
    }

result = Session.post("http://example.com/",data=payload).content.decode() #Session.get for get request

print(result) #page after logging in.


text:
Q: Database table constraints query Can a relational table have constraints related to another table? If yes, please provide an example also

A: Yes, think of foreign key constraint. Foreign key constraint is related to another table.
For example, consider following table

*

*Address (Addressid (PK), AddressLine1, City, State_cd (FK))

*State (State_cd(PK), State_name)

Note here that State_cd which is in Address table is related to another table (State).
Hope this is clear


text:
Q: Изменить заголовок(ссылку) на textbox Добрый день! Вопрос немного странный, но пришлось и с ним столкнуться. Есть обычный текст, я хочу при нажатии на кнопку изменить содержимое этого текста. Это реализовано в codepen (скрин ниже). Код там мне не ясен, помогите разобраться как решить вопрос грамотно. Спасибо!

A: В codepen это сделано путем подмены тега  на тег
т.е. когда я нажимаю на карандаш у тега  накидывается класс со стелем "display: none", а у тега  наоборот уберется
надеюсь на js добавление класса при нажатии сможете реализовать


text:
Q: Angular 2/4 Variables in animations I'm trying to use Angular animations with variables and I've made some mistakes I can't figure out,
what I would like to accomplish is to "move" a "tab" on the "li" elements of my sidebar. here is my HTML:

                  {{menuItem.icon}}

{{menuItem.title}}

        {{icon}}

{{title}}

I've Angular 4.3.3 and I've tried to use the variables in animations here the sidebar.componet.ts:
import { Component, OnInit, ElementRef } from '@angular/core';
import { ROUTES } from './sidebar-routes.config';
import { animate,  transition} from '@angular/animations';

import {movingTabAnimation, movingTab} from './moving-tab-animation';

@Component({
  selector: 'sidebar-cmp',
  moduleId: module.id,
  templateUrl: './sidebar.component.html',

  animations: [movingTab]

})
export class SidebarComponent implements OnInit {

  public movTabVar = {

    value: 'inactive',
    params: {translate3d: 'translate3d(0, 20px, 0)'},

  }

  public menuItems;
  public icon: String;
  public title: String;

  constructor() {

  this.movTabVar.value = "inactive";
  this.movTabVar.params.translate3d = "translate3d(0, 380px, 0)";
  this.icon = 'home';
  this.title = 'Home';

  }

  ngOnInit() {

    this.menuItems = ROUTES.filter(menuItem => menuItem);

  }

  navMenuToggle(value, _icon: String, _title: String){

    this.movTabVar.value =(this.movTabVar.value === 'active' ? 'inactive' : 'active');
    this.icon = _icon;
    this.title = _title;
    let  tmp = value.srcElement.parentElement.getBoundingClientRect().top-80;
    this.movTabVar.params.translate3d="translate3d(0," +String(tmp)+"px,0)";

    //
    console.log(this.movTabVar.value);
    console.log("the icon is "+this.icon+" the Title is "+this.title);
    console.log("position "+ (this.movTabVar.params.translate3d));

  }

}

and here is my animation:
import {
  animate,
  animateChild,
  animation,
  state,
  style,
  transition,
  trigger,
  useAnimation
} from '@angular/animations';

export const movingTabAnimation = animation([
  style({
    transform: '{{translate3d}}'
  }),
animate('0.9s cubic-bezier(0.29, 1.42, 0.79, 1)')
], { params: { translate3d: 'translate3d(0, 20px, 0)' } });

export const movingTab = trigger(
  'moving-tab',
  [
    transition(
      'inactive <=> active',
      [
        useAnimation(movingTabAnimation)
      ],
      { params: { translate3d: 'translate3d(0, 380px, 0)' } }
    )
  ]
);

I don't get any error on console but the tab is fixed in the same position,
thanks in advance for your help.


text:
Q: Trouble installing application I'm trying to install Timeshift (.deb file) on Raspbian 9.4 and I used
sudo apt install ./fileName.deb

which produced
Reading package lists... Done
Building dependency tree
Reading state information... Done
Note, selecting 'timeshift:i386' instead of './timeshift-v18.4-i386.deb'
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 timeshift:i386 : Depends: libc6:i386 (>= 2.4) but it is not installable
              Depends: libcairo2:i386 (>= 1.2.4) but it is not installable
              Depends: libgdk-pixbuf2.0-0:i386 (>= 2.22.0) but it is not installable
              Depends: libgee-0.8-2:i386 (>= 0.8.3) but it is not installable
              Depends: libglib2.0-0:i386 (>= 2.35.9) but it is not installable
              Depends: libgtk-3-0:i386 (>= 3.16.2) but it is not installable
              Depends: libjson-glib-1.0-0:i386 (>= 0.13.2) but it is not installable
              Depends: libvte-2.91-0:i386 but it is not installable
E: Unable to correct problems, you have held broken packages.

The Timeshift website says that "you may need to install packages for the following dependencies libgee json-glib rsync". I assume those are separate packages that I will need to install first but how would I do that? The same way I attempted to install the .deb file? Thanks so much in advance.

A: I'm guessing you downloaded the package from the Timeshift releases page. That only provides binary releases for amd64 and i386, neither of which can be used on your Raspberry Pi (which is armhf).
You'll need to build Timeshift from source; Raspbian 9.4 has all the necessary build dependencies. You can use the enclosed build-deb.sh script, after editing it to change xenial to stretch:
git clone https://github.com/teejee2008/timeshift.git
cd timeshift
sed -i s/xenial/stretch/g build-deb.sh
./build-deb.sh armhf

This will tell you what programs to install.


text:
Q: How not to miss the elimination of Optical Audio Output from 3rd to 4th gen Apple TV I speculate that the audio signal at the Optical Audio Out of the 3rd generation Apple TV is always the same audio signal within the HDMI output.
I further speculate that that's the reason behind eliminating the Optical Audio Out connector in the 4th generation Apple TV.
Hence one does not need to worry about losing Optical-Out when replacing an ATV3 with an ATV4 provided that either:

*

*the TV has Audio Return Channel (ARC), which would take the audio signal from HDMI and pass it onto the receiver. (Here I'm thinking of a user who never uses the audio amplifier on the TV and who always switches the receiver on, even when watching TV.) ARC is important since you wouldn't want to keep the TV on during all the time you're just listening to music.

*the receiver has HDMI input (older receivers don't). If the receiver has HDMI input/output, then the ATV4's HDMI would connect to the receiver and from there to the TV. Hence, again, the TV can remain off while you're listening to music.

Is my understanding correct? Am I missing something?
Here is the setup I have in mind:

As you can see, there is no "return" involved here. So the feature that I'm looking for could more plausibly be called "audio pass-through". This audio pass-through works fine when a TV is on (by necessity!). The question then is what guarantees there are for it to continue working when a TV is off.

A: The understanding in the question is correct.
With a very recent somewhat-high-end LG TV, I have been unable to find or to activate a feature that functions like Active Return Channel, nor one that is called a synonym of ARC or "pass through".
The conclusion is that when Apple omitted Optical Audio Out on the most recent Apple TV 4, they were basically assuming that those using an ATV4 to listen to music will upgrade their receiver and buy one centered on HDMI connections. Given the expected lifetime (and price) of nicer receivers, this is not necessarily a good thing, and so you may be better off with an ATV3 than an ATV4, until you're ready to upgrade your receiver.
But there is one caveat. If you stream your lossless audio files through AirPlay to an Apple TV (either 3 or 4) from your iphone, iPad, or Mac, you are not listening to lossless files on your sound system. This is fairly easy to confirm by a listening test. Presumably Apple designed things that way to conserve bandwidth (strangely, since a quick calculation will reveal that there is more than enough WiFi bandwidth to spare to transmit an audio stream with no further compression). It may even be the case that mp3 (or other lossy) files go through a compression-decompression cycle when they are sent from iOS/OS X to an Apple TV. I haven't been able to confirm this conclusively one way or the other.
Hence if you do listen to Apple-lossless files, you would not want to use AirPlay anyway (and there is no other way to go through the Apple TV). You then need a (dedicated?) iOS/OS X device hooked-by-wire to your receiver, and then it's a moot point whether your TV has ARC. It's even a moot point whether you chose Apple TV over the competition. There is of course a (significant) advantage in using a Mac rather than an iPhone/iPad since Macs provide an optical digital signal out. Using an iOS device (which would anyway be scarce on storage and would introduce its own problems if you hook additional storage) would indeed send a lossless file, but you'd still be losing by using whichever D/A converter Apple uses in their iOS devices. Whether this would be perceptible will vary from one setup to another.
Sequel question: how are things like on the Roku, Amazon Fire TV, and Google Chromecast? Do any of these make it possible to transmit/receive lossless files (perhaps in the non-Apple-centric FLAC) from some device (Android, Linux, Windows, or Mac) without going through a compress-decompress cycle?


text:
Q: When i run same c++ programm by terminal and same programm in ide (CLion) output is different why? using namespace std;

void print(vector<string>str) {

    vector<string>::iterator it=str.begin();
     while (it!=str.end()) {
         cout<<*it<<endl;
         it=it+1;
    }
}

void collectWord(vector<string>&str,string line) {

    const char* delim=" ,.-";
    char* l =new char[line.length()+1];
    strcpy(l,line.c_str());
    char *pch;
    pch=strtok(l,delim);

    while (pch!=NULL) {

       // cout<<pch<<endl;
        str.push_back(pch);
        pch=strtok(NULL,delim);
    }

    delete[] l;

}

int main() {

    string line;
    vector<string>spam;

    ifstream spamfile("spam.txt");
    if (spamfile.is_open()) {
        while (getline(spamfile,line)) {
            collectWord(spam,line);
        }
        spamfile.close();
    }
    else{
        cout<<"Unable to open file"<<endl;
    }

    print(spam);

    return 0;

}

When i run this programm in terminal output is ok but when i run it into ide(Clion(c/c++)) output is different

A: ifstream spamfile("spam.txt");
This opens the file spam.txt relative to the "Current Working Directory" (CWD). CLion runs your executable from a different folder than when you run it from command line, so the CWD is different.
You need to make sure that spam.txt exists in the directory where CLion is building your executable.
edit: alternatively I think CLion will allow you to choose which CWD to run the executable from, or you could give a fully-specified path for the file (like C:\MyStuff\spam.txt)


text:
Q: The class ..$Proxy$_$$_WeldClientProxy' does not have the property '...' So I am struggling with getting a sample app to work. I'm using Primefaces 3.3M4-SNAPSHOT, JBOSS 7 web profile (CDI and JSF Mojarra).
I have my backing bean:
@Named
@ViewScoped
@URLMapping(id = "viewEditor", pattern = "/editor/e", viewId = "/editor/editor.jsf")
public class ViewEditor implements Serializable {

public void deleteNode() {
    selectedNode.getChildren().clear();
    selectedNode.getParent().getChildren().remove(selectedNode);
    selectedNode.setParent(null);

    selectedNode = null;

}
}

My xhtml:
        <p:contextMenu for="docs">
            <p:menuitem value="View" update="documentPanel"
                icon="ui-icon ui-icon-search" oncomplete="documentDialog.show()" />
            <p:menuitem value="Delete"
                actionListener="#{viewEditor.deleteNode}" update="docs"
                icon="ui-icon ui-icon-close" />
        </p:contextMenu>

When I run my app, this is the exception I get:
javax.el.ELException: /editor/editor.xhtml: The class 'application.ViewEditor$Proxy$_$$_WeldClientProxy' does not have the property 'deleteNode'.
    com.sun.faces.facelets.compiler.AttributeInstruction.write(AttributeInstruction.java:94)
    com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:82)
    com.sun.faces.facelets.compiler.UILeaf.encodeAll(UILeaf.java:183)
    javax.faces.render.Renderer.encodeChildren(Renderer.java:168)

Did anyone come across the same issue as I did?

A: Okay got the answer. It turns out that the namespace for primefaces has changed from
xmlns:p="http://primefaces.prime.com.tr/ui"

to
xmlns:p="http://primefaces.org/ui"

By changing the namespace everything worked. Wow that was an elusive thing to track down.

A: In my case the reason was completely different.
I copied a class including serialVersionUID field:
private static final long serialVersionUID = 5443351151396868724L;

so I had two different classes and objects with the same serialVersionUID and this was the clue of the problem.


text:
Q: script to check cpu utilization in linux I want a bash script that show the CPU consumption every minute and save it in a file.
The output would be like this:
11/09/2015 10:00: CPU: 60%
11/09/2015 10:01: CPU: 72%
11/09/2015 10:02: CPU: 32%

And so on... Can somebody help me ?
I can do it with # sar >> Result.txt but it shows the result every 15 minutes instead of every minute. Does anyone know how to fix this?

A: Put this into a bash script somewhere on your system (/opt for example):
#!/bin/bash

CPU_USAGE=$(top -b -n2 -p 1 | fgrep "Cpu(s)" | tail -1 | awk -F'id,' -v prefix="$prefix" '{ split($1, vs, ","); v=vs[length(vs)]; sub("%", "", v); printf "%s%.1f%%\n", prefix, 100 - v }')

DATE=$(date "+%Y-%m-%d %H:%M:")

CPU_USAGE="$DATE CPU: $CPU_USAGE"

echo $CPU_USAGE >> /opt/cpu_usage.out

Then create a file called cpu_usage under /etc/cron.d/ with the following in:
*/1 * * * * root /opt/your_script.sh

This should execute the script once per minute, and output the CPU usage in a percentage format on a new line within the specified file.

A: */1 * * * * prstat -Z|head -18|tail -1|awk '{print$7}'>filename.txt


text:
Q: Boolean Algebra equivalency Which Boolean algebra laws are required to show that
$$(\lnot y \land  \lnot z) \lor  (x \land  ((\lnot y \land  z) \lor  (y \land \lnot z))) = (\lnot y \land \lnot z) \lor (x\land (\lnot (y \land z)))$$
I don't want to solve by computing for all possible values. No luck for me with distributive properties, absorption, idempotence, or DeMorgan's.

A: Sorry to disappoint, but if you want to "algebraically" prove the equivalence, you are going to need to use distributivity and DeMorgan's, and a couple more identities.
Since each side of the equivalence has the term $\;(\lnot y \land \lnot z) \lor,\;$
we can first focus on:
$$x \land  ((\lnot y \land  z) \lor  (y \land \lnot z))) \equiv x\land (\lnot (y \land z)))$$
And now you see each side has an equivalent conjunct: $x \land\;$
Indeed, to prove: $$(\lnot y \land  \lnot z) \lor  (x  \land   (\lnot y \land  z) \lor  (y \land \lnot z))) \equiv (\lnot y \land \lnot z) \lor (x \land (\lnot (y \land z)))$$
we first focus on the following to check for equivalence:
$$\lnot (y \land z) \equiv^? (\lnot y \land  z) \lor  (y \land \lnot z)$$
There is no getting around using the distributive properties, absorption, and DeMorgan's, etc. but this breaks it down so as to make such applications relatively transparent.
$$\lnot (y \land z)\; \equiv^? \;(\lnot y \land  z) \lor  (y \land \lnot z)$$
$$\equiv\; [(\lnot y \land z) \lor y] \land [(\lnot y \land z )\lor \lnot z]\tag{distributivity}$$
$$\equiv [(\lnot y \lor y) \land (z \lor y)] \land [(\lnot y \lor \lnot z) \land (z \lor \lnot z)]\tag{?}$$
$$ \equiv T \land (z \lor y) \land (\lnot y \lor \lnot z) \land T\tag{?}$$
$$\equiv (z \lor y) \land (\lnot y \lor \lnot z)\tag{?}$$
$$ \vdots$$
$$ \vdots$$
Don't forget that each side of the original equivalence is also also true whenever $\lnot y \land \lnot z \equiv \lnot (y \lor z)$ is true, as it is a disjunct to the expressions on each side, so if it holds, the equivalence holds.
So, e.g., if $x$ is false, then the expressions on the RHS and LHS are equivalent because then, the truth values of each expression is equivalent to the truth value of $\lnot p \land \lnot q$: i.e., each side evaluates to the equivalent truth value.

To prove algebraically, just keep the "disjunct" and $x \land$ "riding along" (operating only as you would above) until you can safely eliminate $x$ and/or make use of $\lnot p \land \lnot q$ to establish the equivalence.

Final Note Using the "$=$"-sign isn't really appropriate in logic. I have used the symbol for logical equivalence: "$\equiv$", which means (equivalently) $\iff$: "if and only if". It can be viewed as a logical connective in its own right. I'll include the truth-table displaying its truth-functional definition:

A: $$(\lnot y \land  \lnot z) \lor  (x \land  ((\lnot y \land  z) \lor  (y \land \lnot z)))$$
try to make it a disjunction of conjunctions (same idea as multiply out brackets of a polynomial)
$$(\lnot y \land  \lnot z) \lor (x \land  \lnot y \land  z) \lor  (x \land  y \land \lnot z)$$

and the other side is
$$(\lnot y \land \lnot z) \lor (x\land (\lnot (y \land z)))$$
push negation in
$$(\lnot y \land \lnot z) \lor (x\land (\lnot y \lor \lnot z))$$
try to make it a disjunction of conjunctions
$$(\lnot y \land \lnot z) \lor (x\land \lnot y) \lor (x\land \lnot z)$$

to make the two terms equal we can use $a\lor b = a \lor (\lnot a \land b)$.

note $\lnot (\lnot y \land \lnot z) = y \lor z$ so we can make the LHS
$$(\lnot y \land \lnot z) \lor ((y \lor z) \land x\land \lnot y) \lor ((y \lor z) \land x\land \lnot z)$$
which simplifies to
$$(\lnot y \land \lnot z) \lor (z \land x\land \lnot y) \lor (y \land x\land \lnot z)$$
which is easily equal to the other side.


text:
Q: Upgrading to Nodejs 8 and "error: failed to commit transaction" I am trying to upgrade my nodejs 6 to 8 in my arch linux. So I did:
$ sudo pacman -S nodejs npm

Result:
resolving dependencies...
looking for conflicting packages...

Packages (3) openssl-1.0-1.0.2.l-1  nodejs-8.1.3-1  npm-4.6.1-1

Total Installed Size:  39.22 MiB
Net Upgrade Size:       6.79 MiB

:: Proceed with installation? [Y/n] y
(3/3) checking keys in keyring                                                                                [####################################################################] 100%
(3/3) checking package integrity                                                                                [####################################################################] 100%
(3/3) loading package files                                                                                [####################################################################] 100%
(3/3) checking for file conflicts                                                                                [####################################################################] 100%
error: failed to commit transaction (conflicting files)
openssl-1.0: /usr/lib/libcrypto.so.1.0.0 exists in filesystem
openssl-1.0: /usr/lib/libssl.so.1.0.0 exists in filesystem
Errors occurred, no packages were upgraded.

And now my nodejs is broken I think!
$ node --version
node: error while loading shared libraries: libhttp_parser.so.2.7.1: cannot open shared object file: No such file or directory

Any ideas what should I do now?

A: I had same problem and this is how I solve it :
sudo pacman -S nodejs npm --force

Option --force will upgrade your package even if you get warning with existing files.
After this you need to install http-parser with pacman so :
sudo pacman -S http-parser --force

Finally, node -v will give you this error :

error while loading shared libraries: libicui18n.so.59: cannot open shared object file: No such file or directory

To fix it, install icu lib from pacman :
sudo pacman -S icu --force

Here we go, your node version is now v8.4.0.
Edited 17/01: --force was deprecated. Please use --overwrite


text:
Q: Expressão regular start, end Tenho duas expressões regulares:
$exp1 = '/^abc.*\_20150430.txt$/'
$exp2 = '/^def.*\_20150430.txt$/'

Deve retornar true para arquivos começados por abc na primeira e def na segunda. As nas duas expressões a string deve terminar por _20150430.txt. Para o que preciso devo executar:
if(preg_match($exp1, $str) || preg_match($exp2, $str)) {
    // Do something
}

Como faço isso em uma única expressão regular?

A: Você deve usar uma subpatern (grupo delimitado com parênteses) com alternation (caractere | ou pipe) conforme descrito no manual (sem tradução).
Dessa maneira a expressão regular fica assim:
'/^(abc|def).*_20150430\.txt$/'
Vi que você escapou o underline (\_), mas esse não é um caractere especial dentro da expressão regular, então não precisa de escape.
O ponto da extensão no nome do arquivo (430.txt) deve ser escapado, conforme apontado pelo @wryel, por se tratar de um curinga

A: O que poderia ser feito também, e é muito praticado pelos novatos é:

*

*Formas as diferentes REGEX

*

*/^abc.*_20150430\.txt$/

*/^def.*_20150430\.txt$/

*uni-las pelo ou

*

*^abc.*_20150430\.txt$|^def.*_20150430\.txt$
Note que ele interpreta como sendo duas validações distinta, contudo na mesma validação.
Seja funcionando no regex101
Mas com o tempo se pega as reduções das regex e os atalhos, assim como na resposta do @Sanção.


text:
Q: warning: invalid memory pointer passed to a callee: What does it mean and how to fix I am trying to analyze some data. For one set of my data the code I have written works well, i.e there are no errors, results are as expected. However, if I use the same code on another set of similar data, I get this error:
 Generating stack trace...
 0x00007f46964680a0 in cling::IncrementalExecutor::executeWrapper(llvm::StringRef, cling::Value*) const + 0x380 from /home/cucip/builddir/lib/libCling.so
 0x00007f46963fae77 in cling::Interpreter::RunFunction(clang::FunctionDecl const*, cling::Value*) + 0xa7 from /home/cucip/builddir/lib/libCling.so
 0x00007f46963fc4df in cling::Interpreter::EvaluateInternal(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, cling::CompilationOptions, cling::Value*, cling::Transaction**, unsigned long) + 0x1df from /home/cucip/builddir/lib/libCling.so
 0x00007f46964c61f1 in cling::MetaSema::actOnxCommand(llvm::StringRef, llvm::StringRef, cling::Value*) + 0x591 from /home/cucip/builddir/lib/libCling.so
 0x00007f46964d6084 in cling::MetaParser::isXCommand(cling::MetaSema::ActionResult&, cling::Value*) + 0x194 from /home/cucip/builddir/lib/libCling.so
 0x00007f46964d7476 in cling::MetaParser::isCommand(cling::MetaSema::ActionResult&, cling::Value*) + 0xa6 from /home/cucip/builddir/lib/libCling.so
 0x00007f46964bf64b in cling::MetaProcessor::process(llvm::StringRef, cling::Interpreter::CompilationResult&, cling::Value*, bool) + 0x10b from /home/cucip/builddir/lib/libCling.so
 0x00007f469637b68e in <unknown> from /home/cucip/builddir/lib/libCling.so
 0x00007f469638fe72 in <unknown> from /home/cucip/builddir/lib/libCling.so
 0x00007f4696384537 in <unknown> from /home/cucip/builddir/lib/libCling.so
 0x00007f469bb12908 in TApplication::ExecuteFile(char const*, int*, bool) at /home/cucip/root-6.18.04/core/base/src/TApplication.cxx:1156 from /home/cucip/builddir/lib/libCore.so
 0x00007f469bb120ac in TApplication::ProcessLine(char const*, bool, int*) at /home/cucip/root-6.18.04/core/base/src/TApplication.cxx:1007 from /home/cucip/builddir/lib/libCore.so
 0x00007f469bfe18e2 in TRint::ProcessLineNr(char const*, char const*, int*) at /home/cucip/root-6.18.04/core/rint/src/TRint.cxx:762 from /home/cucip/builddir/lib/libRint.so
 0x00007f469bfe1cd4 in TRint::HandleTermInput() at /home/cucip/root-6.18.04/core/rint/src/TRint.cxx:613 from /home/cucip/builddir/lib/libRint.so
 0x00007f469bc66600 in TUnixSystem::CheckDescriptors() at /home/cucip/root-6.18.04/core/unix/src/TUnixSystem.cxx:1309 from /home/cucip/builddir/lib/libCore.so
 0x00007f469bc67f98 in TUnixSystem::DispatchOneEvent(bool) at /home/cucip/root-6.18.04/core/unix/src/TUnixSystem.cxx:1065 from /home/cucip/builddir/lib/libCore.so
 0x00007f469bb7cd81 in TSystem::Run() at /home/cucip/root-6.18.04/core/base/src/TSystem.cxx:412 from /home/cucip/builddir/lib/libCore.so
 0x00007f469bb0fc7f in TApplication::Run(bool) at /home/cucip/root-6.18.04/core/base/src/TApplication.cxx:1179 from /home/cucip/builddir/lib/libCore.so
 0x00007f469bfe32d1 in TRint::Run(bool) at /home/cucip/root-6.18.04/core/rint/src/TRint.cxx:463 from /home/cucip/builddir/lib/libRint.so
 0x00007f469c800a0c in <unknown> from /home/cucip/builddir/bin/root.exe
 0x00007f469af71b97 in __libc_start_main + 0xe7 from /lib/x86_64-linux-gnu/libc.so.6
 0x00007f469c800a6a in _start + 0x2a from /home/cucip/builddir/bin/root.exe
Error in <HandleInterpreterException>: Trying to access a pointer that points to an invalid memory address..
Execution of your code was aborted.
In file included from input_line_776:1:
/mnt/c/1/MG5_aMC_v2_6_6/Delphes/examples/HZZXT.C:167:5: warning: invalid memory pointer passed to a callee:
 if(muon1->PT < 20 | muon2->PT < 20 | abs(muon1->Eta) > 2.5 | abs(muon2->Eta) > 2.5) continue;

What does this error mean? And how can I fix it?
Please let me know if more information or code is needed.


text:
Q: ref does not work in this reactjs component I want to change the css class of a span element whenever an anchor  is clicked
I will modify the css class in the onclick callback
class Button extends Component {
  handleCallback() {
    this.icon.className = this.icon.className + ' wiggle'
  }
  render() {
    return (

        {this.props.summary}

           this.icon = c} className='icon-up'>

    );
  }
}

To do so I need to be able to refer the component. That's why I use the ref attribute in the span class.
However when the callback is called, I got this error:
Uncaught TypeError: Cannot read property 'icon' of null

Why the ref does not work here?

A: You're missing a few things here
First off, you're writing an ES6 component class and when using ES6 together with React, React no longer features auto binding of this making your call to handleCallback refer to a this which will be null.
this.handleCallback.bind(this) or declare your callback with an arrow function handleCallback = () => {} will take care of that problem.
And secondly, the way you're trying to set the className is not allowed, React only updates the tree (i.e., what you see) when re-rendering and React will never flush the changes you made 'inline' back into the DOM so you would have to utilize this.setState() or this.forceUpdate() in order to be able to see, but since your changes are inline they will never persist on a subsequent render.
Below is a very verbose Component to illustrate how to do it
class Button extends React.Component {
  constructor() {
    super();
    this.state = {
      shouldWiggle: false
    };
  }
  handleCallback() {
    this.setState({shouldWiggle: !this.state.shouldWiggle});
  }
  render() {
    let cls = this.state.shouldWiggle ? 'icon-up wiggle': 'icon-up';
    return (

        {this.props.summary}

           this.icon = c} className={cls}>ad

    );
  }
}


text:
Q: Remove row based on sum of numpy array within each entry in df column I feel I'm making this harder than it should be: what I have is a dataframe with some columns whose entries each contain numpy arrays (the names of the columns containing these arrays is in an array called names_of_cols_that_contain_arrays). What I want to do is filter out rows for which these numpy arrays have a sum value of zero. This is a similar question on which my code is based, but it doesn't seem to work with the iterator over rows in each column.
What I have currently in my code is
for col_name in names_of_cols_that_contain_arrays:
  for i in range(len(df[col_name])):
    df = df[df[col_name][i].sum() > 0.0]

which doesn't seem that efficient but is a first attempt that explictly goes through what I thought would be the correct method. But this appears to return a boolean, i.e.
Traceback
...
KeyError: True

In fact in most cases to the code above I get some error associated with a boolean being returned. Any pointers would be appreciated, thanks in advance!

A: IIUC:
You can try:
df=df.loc[df['names_of_cols_that_contain_arrays'].map(sum)>0]
#OR
df=df.loc[df['names_of_cols_that_contain_arrays'].map(np.sum).gt(0)]

Sample dataframe used:
from numpy import array

d={'names_of_cols_that_contain_arrays': {0: array([-1,  0, -8]),
  1: array([-1, -2,  5])}}

df=pd.DataFrame(d)


text:
Q: Cant play a song using MediaPlayer Im having some problems playing a simple song (stored in the external SD) using MediaPlayer API. I really dont know what Im doing wrong, cause I havent seen the code error in any other questions and using the developer I havent found it either.
The error Im getting is this:
08-25 00:20:49.514: D/MediaPlayer(26764): mPlayerID = 94
08-25 00:20:49.519: E/MediaPlayer(26764): error (1, -2147483648)
08-25 00:20:49.597: E/MediaPlayer(26764): Error (1,-2147483648)

AudioActivity.java
public class AudioActivity extends Activity{

    Audio audioPlayer;

    public AudioActivity(){

        audioPlayer = new Audio();

    }

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        //Set of view where videos and the listView (is there is any) will appear
        setContentView(R.layout.audio_player);

        Button play = (Button)findViewById(R.id.playButton);

        play.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                String path = Environment.getExternalStorageDirectory() + "/" + "song";
                audioPlayer.loadFile(path);
                audioPlayer.prepare();
                audioPlayer.play();
            }
        });

        Button pauseResume = (Button)findViewById(R.id.pauseButton);

        pauseResume.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                audioPlayer.pause();
            }
        });

        Button stop = (Button)findViewById(R.id.stopButton);

        stop.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                audioPlayer.stop();
            }
        });
    }
}

Audio.class
public class Audio {

    MediaPlayer mediaPlayer;
    String pathSong;

    public Audio(){

        mediaPlayer = new MediaPlayer();

        mediaPlayer.setOnErrorListener(new OnErrorListener() {

            public boolean onError(MediaPlayer arg0, int arg1, int arg2) {

                Log.d("Error", "Arg1: " + arg1 + ".Arg2: " + arg2);
                mediaPlayer.reset();
                return false;
            }

        });
    }

    public void loadFile(String path){

        try {
            mediaPlayer.setDataSource(path);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void prepare(){
        try {
            mediaPlayer.prepareAsync();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void play(){

        mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mediaPlayer.start();
            }
        });
    }

    public void stop(){

        mediaPlayer.stop();
    }

    public void pause(){

        mediaPlayer.pause();
    }

    public int getDuration(){

        return mediaPlayer.getDuration();
    }

    public MediaPlayer getMediaPlayer(){

        return mediaPlayer;
    }

    public TrackInfo[] getTrackInfo(){

        return mediaPlayer.getTrackInfo();
    }
}

Any idea? Why the code (1, -2147483648) doesnt appear anywhere? Thanks!


text:
Q: Create reusable concourse pipelines I have a bunch of applications that follow the same basic pattern so I'm trying to create a pipeline that would act as a reusable library.  So far it's working pretty good by doing something like:
fly -t TARGET set-pipeline /n /c Pipelines\WindowsApp.yml ^
    /l ..\Secrets\config.yml /p %PRODUCT%-%BRANCH% ^
    --var productname=%PRODUCT% --var branch=%BRANCH%

It's working great so far but one thing I don't see is  what if I want to execute a step for one scenario but not another.   Is there a way to apply a condition to a step?  I am able to pass the variables into my run steps and act upon them in a shell script but that seems to defeat the purpose of using resources and steps if I go down that road.

A: There is no way to do conditional resources or steps in a pipeline configuration.
The best practice is to create a text template that generates the final pipeline configuration you'd like to set. For example, some teams have used ERB (Embedded Ruby) to add conditionals and logic.


text:
Q: Canvas not supported by browser when using GoJS I'm using GoJS and trying to setup a simple diagram on page using:
 const $ = go.GraphObject.make;  // for conciseness in defining templates
const myDiagram =
  $(go.Diagram, "myDiagramDiv",  // create a Diagram for the DIV HTML element
    { // enable undo & redo
      "undoManager.isEnabled": true
    });

// define a simple Node template
myDiagram.nodeTemplate =
  $(go.Node, "Auto",  // the Shape will go around the TextBlock
    $(go.Shape, "RoundedRectangle",
      { strokeWidth: 0, fill: "white" },  // default fill is white
      // Shape.fill is bound to Node.data.color
      new go.Binding("fill", "color")),
    $(go.TextBlock,
      { margin: 8 },  // some room around the text
      // TextBlock.text is bound to Node.data.key
      new go.Binding("text", "key"))
  );

// but use the default Link template, by not setting Diagram.linkTemplate

// create the model data that will be represented by Nodes and Links
myDiagram.model = new go.GraphLinksModel(
[
  { key: "Alpha", color: "lightblue" },
  { key: "Beta", color: "orange" },
  { key: "Gamma", color: "lightgreen" },
  { key: "Delta", color: "pink" }
],
[
  { from: "Alpha", to: "Beta" },
  { from: "Alpha", to: "Gamma" },
  { from: "Beta", to: "Beta" },
  { from: "Gamma", to: "Delta" },
  { from: "Delta", to: "Alpha" }
]);

And when rendered I have:

This text is displayed if your browser does not support the Canvas HTML element.

Inside canvas tag. That's very odd since I have the latest vesrion of Chrome, Firefox and Edge (I tried them all) and they support canvas.
And using simple canvas with simple shapes without GoJS renders correct result.
What can be the problem?

A: That's the right behaviour of canvas HTML element, not GoJS problem.
As documentation said, the canvas element is "used to draw graphics on a web page". You cannot inspect elements in it.
If you want to inspect nodes and links from GoJS diagram, you can type diagram.model.nodeDataArray or diagram.model.linkDataArray to browser console.