text:
Q: R - plot reactive subset with plotly I want to make a plot based on a reactive subset, it works to display my table but i am not able to take the columns of the subset in order to plot that.

structure(list(WEG = c(0, 0.01, 0.02, 0.02, 0.03, 0.04), VERTIKAL_KRAFT_FY = c(358.77,
358.78, 358.78, 358.79, 358.79, 358.8), VERSCHIEBEKRAFT_FX = c(0,
0, 0, 0, 0, 0), HD = c(-9.39, -9.39, -9.41, -9.36, -9.36, -9.38
), PROBE_NR = c(6812L, 6812L, 6812L, 6812L, 6812L, 6812L), ZYKLUS = c(101L,
101L, 101L, 101L, 101L, 101L)), row.names = c(NA, 6L), class = "data.frame")

ui <- fluidPage(
  selectInput("Select1","Select Test",unique(d$PROBE_NR)),
  selectInput("Select2","Select Cycle",choices = NULL)

  mainPanel(
    tableOutput("view"),
    plotlyOutput('plot'),
  )

)

server <- function(input, output,session) {

  observeEvent(input$Select1,{
    updateSelectInput(session,'Select2',
                      choices=unique(d$ZYKLUS[d$PROBE_NR==input$Select1]))
  })

  newData <- reactive({
    t <- subset(d, d$PROBE_NR == input$Select1 & d$ZYKLUS %in% input$Select2) #subset
    return(t)
  })

  output$view <- renderTable({ newData() })

  output$plot <- renderPlotly({

    data = newData()
    plot<-plot_ly(data, color = ~source, x = ~WEG, y = ~HD, mode = "lines", type = "scatter") %>%
      layout( xaxis = list( title=input$Selectx),
              yaxis = list( title=input$Selecty ), title = "Plot1" )
    plot
  })

}

shinyApp(ui = ui, server = server)

I would like to take some columns of the subset t in order to plot them.

A: The column source specified as plotly's color argument doesn't exist in your data.frame. Please check the following:
library(shiny)
library(plotly)

d <- structure(
  list(
    WEG = c(0, 0.01, 0.02, 0.02, 0.03, 0.04),
    VERTIKAL_KRAFT_FY = c(358.77,
                          358.78, 358.78, 358.79, 358.79, 358.8),
    VERSCHIEBEKRAFT_FX = c(0,
                           0, 0, 0, 0, 0),
    HD = c(-9.39, -9.39, -9.41, -9.36, -9.36, -9.38),
    PROBE_NR = c(6812L, 6812L, 6812L, 6812L, 6812L, 6812L),
    ZYKLUS = c(101L,
               101L, 101L, 101L, 101L, 101L)
  ),
  row.names = c(NA, 6L),
  class = "data.frame"
)

ui <- fluidPage(
  selectInput("Select1", "Select Test", unique(d$PROBE_NR)),
  selectInput("Select2", "Select Cycle", choices = NULL),
  mainPanel(tableOutput("view"),
            plotlyOutput("plot"))
)

server <- function(input, output, session) {
  observeEvent(input$Select1, {
    updateSelectInput(session, 'Select2',
                      choices = unique(d$ZYKLUS[d$PROBE_NR == input$Select1]))
  })

  newData <- reactive({
    subset(d, d$PROBE_NR == input$Select1 & d$ZYKLUS %in% input$Select2)
  })

  output$view <- renderTable({
    newData()
  })

  output$plot <- renderPlotly({
    plot_ly(
      data = newData(),
      # color = ~ source,
      x = ~ WEG,
      y = ~ HD,
      mode = "lines",
      type = "scatter"
    ) %>%
      layout(
        xaxis = list(title = input$Selectx),
        yaxis = list(title = input$Selecty),
        title = "Plot1"
      )
  })

}

shinyApp(ui = ui, server = server)


text:
Q: Module parse failed error Unexpected token } - Webpack I'm not sure why I'm getting this error
ERROR in ./login/loginController.js
Module parse failed: /Users/leon/Projects/admin/login/loginController.js Line 66: Unexpected token }
You may need an appropriate loader to handle this file type.
|             console.log('login failed!');
|         }
|     }
| }
|
 @ ./entry.js 16:22-59

This is my entry.js file
Here is the loginController (line 66 is the last closing } in the code below:
var loginController = angular
    .module('loginController', [])
    .controller('LoginCtrl', LoginCtrl);

LoginCtrl.$inject = [
    '$rootScope',
    '$scope',
    '$location',
    '$timeout',
    'ApiFactory',
    'AUTH_EVENTS',
    'AuthFactory'];

function LoginCtrl(
    $rootScope,
    $scope,
    $location,
    $timeout,
    ApiFactory,
    AUTH_EVENTS,
    AuthFactory) {

    /** Init LoginCtrl scope */
    /** --------------------------------------------------------------------- */
    var vs = $scope;
        vs.login = login;

    $rootScope.$broadcast(AUTH_EVENTS.loginSuccess);

    $rootScope.$on(AUTH_EVENTS.notAuthenticated, function (event, data) {
        $rootScope.currentUser = null;
        $scope.currentUser     = null;
        AuthFactory.logout();
        $location.path('/login');
    });

    function login(credentials) {
        console.log('credentials',credentials);
        AuthFactory.login(credentials).then(function (user) {
            $rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
            $scope.setCurrentUser(user);

            if (user.password_reset) {
                $location.path('/password');
            } else {
                $location.path('/tickers');
            }
        }, function () {
            // $scope.loginData.message = "Invalid Username/Password";
            $rootScope.$broadcast(AUTH_EVENTS.loginFailed);
            console.log('login failed!');
        }
    }
}

module.exports = loginController;

A: I think your issue is AuthFactory.login(credentials).then(function (user) {, it doesn't look like there's a ) closing off this method call.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "we need a password" or "we need the password"? Suppose you and your friend are trying to log in someone else's computer (you are trying to hack someone else's computer) and the screen prompts you to enter password.
Would you say "we need a password" or "we need the password" to your friend?
In the series Archer one character says "we need a password" while trying to log in someone else's computer. Is this correct?

A: They're kind of interchangeable, but "the" would be more accurate in the way that you're using it because it's more specific. You don't just need any password, "a" password. You need the right one, in which case you should use "the".

*

*A: "I need a password."

*B: "My bank password? My phone password?"

*A: "The bank password."

Source

A: "I need a password" implies that one password may open multiple areas. "The password" implies that it is needed to open one area.


text:
Q: Writing a function to check if a relational statement is true or false Here is the function (I hope the logic is fairly obvious).
Let x be one of the '<' or '>' operators
and a and b are the terms.
int rationalCheck(x, a, b){

    if ( x == '<' && a < b && b < a ){
        printf( "a is less than b\n" );
    }

    if ( x != '>' && a > b && b > a ){
        printf( " a is greater than b\n" );
    }

    return 0;
}

The input into the function would be
(4 < 4) > (3 > 3)

This would evaluate to
(4 < 4) > (3 > 3) is false

Or input into the function would be
(4 < 6) > (2 > 1)

This would evaluate to
(4 < 6) > (2 > 1) is true

A: You can't pass operators/operations to functions in C. I suggest considering Haskell.
Alternatively, you can pass operations to macros, so this can be implemented as a macro, hence the definition of the assert macro being something like:
#include <stdio.h>

#define assert(cond) if (!(cond) && printf("Assertion failed: " # cond " at " __FILE__ ":%d\n", __LINE__) != 0) abort()

int main(void) {
    assert(1 > 1);
}

Perhaps you want something like:
#include <stdio.h>

#define rational_check(cond) printf(# cond " is %s\n", (cond) == 0 ? "false" : "true")

int main(void) {
    rational_check((4 > 4) > (3 > 3));
    rational_check((4 < 6) > (2 > 1)); // (4 < 6) > (2 > 1) is 1 > 1, by the way... false
}

I can't be certain, however, whether this suits your needs. A function pointer can't be derived from rational_check, and it can't work with strings that represent expressions formed during runtime; You'd need to write a translator for any use cases that require those... Otherwise, this should be suitable.

A: This works for me. I was over thinking it.
int rationalCheck(x, a, b){

if ( x == '<')
{
    if (a >= b)
    {
        return 99;
    }

    if (b <= a) {
        return 99;
    }
}

if (x == '>')
{
    if (a <= b)
    {
        return 99;

    }
    if (b >= a)
    {
        return 99;
    }

}

return 1;
}

Thanks for everyone's input.


text:
Q: cannot compile wxwidgets project on mac OSX mavericks I'm working on porting across an application to the MAC OSX (Mavericks). I have installed wxWidgets and the following two commands successfully return output from the terminal.
wx-config --libs

Gives the following output.
-L/usr/local/lib   -framework IOKit -framework Carbon -framework Cocoa -framework AudioToolbox -framework System -framework OpenGL /usr/local/lib/libwx_osx_cocoau-3.0.a -framework WebKit -lwxregexu-3.0 -lwxtiff-3.0 -lwxjpeg-3.0 -lwxpng-3.0 -lz -lpthread -liconv

and
wx-config --cxxflags

Gives the following output.
-I/usr/local/lib/wx/include/osx_cocoa-unicode-static-3.0 -I/usr/local/include/wx-3.0 -D_FILE_OFFSET_BITS=64 -D__WXMAC__ -D__WXOSX__ -D__WXOSX_COCOA__

However, I tried to compile a basic wxWigets project using code blocks and netbeans. I followed numerous tutorials, but every time I build my project I get the following compile error.
"fatal error: 'wx/setup.h' file not found
I have added the following settings to the code blocks (and tried netbeans) IDE:

*

*Compiler Settings -> Other options == wx-config --cxxflags

*Linker Settings -> Other linker settings == wx-config --libs
but I just can't get my widgets project to build :(
can anyone please help
Thanks in advance

A: I see only two possible explanations:

*

*You didn't install wxWidgets using make install, i.e. there is no actual wx/setup.h under the directory output by your wx-config --cxxflags.

*Your IDE doesn't run commands in its settings (BTW, I assume you did put wx-config --cxxflags inside the backticks). In this case you need to copy and paste the actual output instead of using wx-config directly.


text:
Q: Getting properties from JSON object I'm receiving a JSON object and need to select a property out of it, but the key is split with a "."
metrics: {
    site.hardware: {
      values: []
    }
}

When selecting metrics.site.hardware.values I'm getting a cannot read properties error. This make sense to me as it is looking for the hardware value within site. How do I select values within the site.hardware property?


text:
Q: How to do page load in jQuery? I have this menu in HTML / CSS:
HTML:

King Kong

Table

CSS:
#inner {
    background-color: #547980;
    width: 130px;
    margin-left: 8px;
}
#inner:first-child {
    background-color: #547980;
    width: 130px;
    margin-left: 8px;
    margin-top: 8px;
}
div {
    border-radius: 5px;
    border: 2px solid black;
}

and I want load page in jQuery.

*

*It can be like printer, after click on link from menu it should start from margin-left position 140 and printing to margin-right position 20 or

*Loading like book when you go to another page.

But I don't know how to do it. Any advice please?

A: With jQuery you can use this script:

$('body').on('click', 'a', function(event) {
  event.preventDefault();
  var href = $(this).attr('href');
  $('.result').load(href);
});

Menu Link


text:
Q: keycloak:javax.ws.rs.BadRequestException: HTTP 400 Bad Request while creating a new realm i am trying to create a new realm from master realm using keycoak-admin-client here is my code
val keyclaok = KeycloakBuilder.builder()
          .serverUrl("http://0.0.0.0:8080/auth")
          .realm("master")
          .username("admin")
          .password("admin")
          .clientId("admin-cli")
          .resteasyClient(
            new ResteasyClientBuilder()
              .connectionPoolSize(10).build()
          ).build()
val realm = new RealmRepresentation
        realm.setRealm("testrealm")
        keyclaok.realms().create(realm)

i am getting
javax.ws.rs.BadRequestException: HTTP 400 Bad Request
    at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.handleErrorStatus(ClientInvocation.java:219)
    at org.jboss.resteasy.client.jaxrs.internal.proxy.extractors.DefaultEntityExtractorFactory$3.extractEntity(DefaultEntityExtractorFactory.java:50)
    at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invokeSync(ClientInvoker.java:151)
    at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invoke(ClientInvoker.java:112)
    at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientProxy.invoke(ClientProxy.java:76)
    at com.sun.proxy.$Proxy33.create(Unknown Source)
    at com.lufz.authentication.controllers.AuthenticationController.$anonfun$createRealm$2(AuthenticationController.scala:288)
    at akka.http.scaladsl.server.Directive$.$anonfun$addByNameNullaryApply$2(Directive.scala:166)
    at akka.http.scaladsl.server.ConjunctionMagnet$$anon$2.$anonfun$apply$3(Directive.scala:234)
    at akka.http.scaladsl.server.directives.BasicDirectives.$anonfun$mapRouteResult$2(BasicDirectives.scala:68)
    at akka.http.scaladsl.server.directives.BasicDirectives.$anonfun$textract$2(BasicDirectives.scala:161)
    at akka.http.scaladsl.server.directives.BasicDirectives.$anonfun$mapRequestContext$2(BasicDirectives.scala:45)
    at akka.http.scaladsl.server.directives.BasicDirectives.$anonfun$textract$2(BasicDirectives.scala:161)
    at akka.http.scaladsl.server.RouteConcatenation$RouteWithConcatenation.$anonfun$$tilde$2(RouteConcatenation.scala:47)
    at akka.http.scaladsl.util.FastFuture$.strictTransform$1(FastFuture.scala:40)
    at akka.http.scaladsl.util.FastFuture$.transformWith$extension(FastFuture.scala:44)
    at akka.http.scaladsl.util.FastFuture$.flatMap$extension(FastFuture.scala:25)
    at akka.http.scaladsl.server.RouteConcatenation$RouteWithConcatenation.$anonfun$$tilde$1(RouteConcatenation.scala:44)
    at akka.http.scaladsl.server.directives.ExecutionDirectives.$anonfun$handleExceptions$2(ExecutionDirectives.scala:32)
    at akka.http.scaladsl.server.RouteConcatenation$RouteWithConcatenation.$anonfun$$tilde$1(RouteConcatenation.scala:44)
    at akka.http.scaladsl.server.directives.BasicDirectives.$anonfun$mapRouteResultWith$2(BasicDirectives.scala:74)
    at akka.http.scaladsl.server.directives.BasicDirectives.$anonfun$textract$2(BasicDirectives.scala:161)
    at akka.http.scaladsl.server.directives.ExecutionDirectives.$anonfun$handleExceptions$2(ExecutionDirectives.scala:32)
    at akka.http.scaladsl.server.Route$.$anonfun$createAsyncHandler$1(Route.scala:110)
    at akka.stream.impl.fusing.MapAsyncUnordered$$anon$31.onPush(Ops.scala:1400)
    at akka.stream.impl.fusing.GraphInterpreter.processPush(GraphInterpreter.scala:541)
    at akka.stream.impl.fusing.GraphInterpreter.execute(GraphInterpreter.scala:423)
    at akka.stream.impl.fusing.GraphInterpreterShell.runBatch(ActorGraphInterpreter.scala:625)
    at akka.stream.impl.fusing.GraphInterpreterShell$AsyncInput.execute(ActorGraphInterpreter.scala:502)
    at akka.stream.impl.fusing.GraphInterpreterShell.processEvent(ActorGraphInterpreter.scala:600)
    at akka.stream.impl.fusing.ActorGraphInterpreter.akka$stream$impl$fusing$ActorGraphInterpreter$$processEvent(ActorGraphInterpreter.scala:769)
    at akka.stream.impl.fusing.ActorGraphInterpreter$$anonfun$receive$1.applyOrElse(ActorGraphInterpreter.scala:784)
    at akka.actor.Actor.aroundReceive(Actor.scala:537)
    at akka.actor.Actor.aroundReceive$(Actor.scala:535)
    at akka.stream.impl.fusing.ActorGraphInterpreter.aroundReceive(ActorGraphInterpreter.scala:691)
    at akka.actor.ActorCell.receiveMessage(ActorCell.scala:577)
    at akka.actor.ActorCell.invoke(ActorCell.scala:547)
    at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:270)
    at akka.dispatch.Mailbox.run(Mailbox.scala:231)
    at akka.dispatch.Mailbox.exec(Mailbox.scala:243)
    at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
    at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)
    at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)
    at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)
    at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:177)

A: Based on my experience you need to provide more information for the realm representation to create:
val realm = new RealmRepresentation
        realm.setId("testRealmId")
        realm.setRealm("testRealm")
        realm.setEnabled(true) // may be unecessary
        keyclaok.realms().create(realm)


text:
Q: How to know when a collection view outline has been expanded? I am using an outline view style UICollectionView setup and setting up my header cells like so:
var content = cell.defaultContentConfiguration()
content.text = brand.name ?? "Unknown"
cell.contentConfiguration = content

let headerDisclosureOption = UICellAccessory.OutlineDisclosureOptions(style: .header)
cell.accessories = [.outlineDisclosure(options: headerDisclosureOption)]

However is it possible to receive something like a delegate call whenever a cell section is expanded? I would like to pull fresh data from the internet whenever a list is expanded.

A: Use the diffable data source's sectionSnapshotHandlers property. It is a SectionSnapshotHandlers instance, a struct consisting entirely of properties whose values are functions. Those functions, which you assign, are your callbacks.
See https://developer.apple.com/documentation/uikit/uicollectionviewdiffabledatasource/3600966-sectionsnapshothandlers


text:
Q: LibreOffice Draw tries to download 27.9 MB data when I try to remove it I'm trying to uninstall libreoffice on Ubuntu Software Center. But it says it will also remove Impress as well. When I confirm, it starts downloading some 27.9 MB data. Why is this so?
Update:
Trying to do this using apt-get, I get the following:
me@my-computer:~$ sudo apt-get remove libreoffice-draw

Reading package lists... Done
Building dependency tree
Reading state information... Done
The following extra packages will be installed:
  libreoffice-base-core libreoffice-calc libreoffice-common libreoffice-core
  libreoffice-gnome libreoffice-gtk libreoffice-writer python3-uno
Suggested packages:
  libreoffice-base libopencl1 libreoffice-style-crystal
  libreoffice-style-hicontrast libreoffice-style-oxygen libreoffice-style-sifr
  libreoffice-style-tango libreoffice-evolution libreoffice-gcj
  libreoffice-java-common default-jre gcj-jre openjdk-7-jre openjdk-6-jre
  sun-java5-jre sun-java6-jre java5-runtime jre
Recommended packages:
  libreoffice-math
The following packages will be REMOVED:
  libreoffice-draw libreoffice-impress libreoffice-ogltrans
  libreoffice-presentation-minimizer
The following packages will be upgraded:
  libreoffice-base-core libreoffice-calc libreoffice-common libreoffice-core
  libreoffice-gnome libreoffice-gtk libreoffice-writer python3-uno
8 upgraded, 0 newly installed, 4 to remove and 33 not upgraded.
Need to get 27.9 MB/64.3 MB of archives.
After this operation, 15.6 MB disk space will be freed.

A: apt-get wants to upgrade some packages at the same time as you want to remove libreoffice-draw. Of course this requires downloading new packages:

8 upgraded, 0 newly installed, 4 to remove and 33 not upgraded.
  Need to get 27.9 MB/64.3 MB of archives.

At the same time, the operation frees some space overall:

After this operation, 15.6 MB disk space will be freed.

If you run apt-get upgrade first, subsequently running apt-get remove libreoffice-draw, will no longer require downloading anything. Alternatively you can use the flag --no-upgrade to suppress the package upgrades in conjunction with the removal.

A: Here's what I think it is.
You're uninstalling LibreOffice and an upgrade to completely unrelated packages is trying to occur. Your command output says that 8 apps are to be upgraded, so I'm pretty sure that's where the 30MB download is coming from.


text:
Q: easy_install downloading directory I'm trying to install a python script packaged in egg format using easy_install.  The problem is that easy_install downloads dependencies to /tmp.  However, my tmp dir only has 4mb of free space (I am working with a NAS drive, set up this way).
Is there a way of specifying the download directory?  --help doesn't seem to throw up anything useful.
Edit:
Some more details:
I'm running python 2.5.6 and setuputils 0.6c11-2 installed from optware. The NAS is ARM based (specifically the DNS-320 with fun_plug installed).  Please let me know if you'd like any more specific info.
When I use the -b option, the file is still downloaded to /tmp.  It is in fact the extraction process which which uses the remaining space in tmp:

easy_install-2.5 -b /mnt/HD/HD_a2/ffp/home/root SQLAlchemy==0.7.2
Searching for SQLAlchemy==0.7.2
Reading http://pypi.python.org/simple/SQLAlchemy/
Reading http://www.sqlalchemy.org
Best match: SQLAlchemy 0.7.2
Downloading http://pypi.python.org/packages/source/S/SQLAlchemy/SQLAlchemy-0.7.2.tar.gz#md5=b84a26ae2e5de6f518d7069b29bf8f72
Processing SQLAlchemy-0.7.2.tar.gz
error: No space left on device

I know the file is downloaded into /tmp by running ls -l /tmp/ while the download is happening:

ls -l /tmp/easy_install*
total 891 -rw-r--r-- 1 root root 901120 Oct  1 20:35 SQLAlchemy-0.7.2.tar.gz

df -h output:

Filesystem            Size  Used Avail Use% Mounted on
rootfs                9.7M  4.8M  4.5M  52% /
/dev/root             9.7M  4.8M  4.5M  52% /
/dev/loop0             23M   23M     0 100% /usr/local/modules
/dev/mtdblock5        5.0M  464K  4.6M  10% /usr/local/config
/dev/sda4             485M   16M  469M   4% /mnt/HD_a4
/dev/sdb4             485M   11M  474M   3% /mnt/HD_b4
/dev/sda2             1.8T  213G  1.6T  12% /mnt/HD/HD_a2
/dev/sdb2             1.8T   69G  1.8T   4% /mnt/HD/HD_b2
/dev/sda2             1.8T  213G  1.6T  12% /opt

Thanks,
Jack

A: Well here's the solution if anyone's interested.
Edit line 412 of /opt/lib/python2.5/site-packages/setuptools/command/easy_install.py from:
tmpdir = tempfile.mkdtemp(prefix="easy_install-")

to:
tmpdir = tempfile.mkdtemp(prefix="easy_install-",dir="/opt/tmp")

This works, as /opt is mounted to the HDD and has plenty of free space.
I'm no python expert (never programmed with it), but it seems like the -b option has no bearing on where the file is downloaded to.

A: easy_install -b wherever

or
easy_install --build-directory wherever

A: Set TMPDIR environment variable such as following:
export TMPDIR="/opt/tmp"

I think this is a better way than rewriting the easy_install.py. You need to ensure the path exists.

A: hmmmmm, you may soft symlink that /tmp/easyinstall to another location before starting the process?
I am not a pro in the tool so it's an idea to get going, not a solution


text:
Q: homeslider.owlCarousel is not a function Добрый день дорогие друзья ,проблема заключается в том что при использовании OwlCarousel в wordpress-е вот такая ошибка:
Uncaught TypeError: homeslider.owlCarousel is not a function
at (index):449
at dispatch (jquery.js?ver=1.12.4-wp:3)
at r.handle (jquery.js?ver=1.12.4-wp:3)

не понимаю в чем проблема ,читал что возможно проблема в $ и нужно использовать jQuery но это не то.Скрипты так же подключены в правильном порядке

A: Если вы не решили свою задачу, то предлагаю для начала отделить мух от котлет:
wp написан преимущественно на php и выполняется на сервер (хостинге)
owl-карусель на js и выполняеся на компьютере посетителя - это важно.
То есть,если у вас не находится функция в JS, то значит на странице у посетителя нет определения данной функции, а так как эта функция описана в скрипте, то значит нет скрипта.
Попробуйте на странице в браузере нажать CTRL+U и в открывшейся вкладке с кодом страницы визуально или с помощью CTRL+F найти место подключения скрипта с требуемой функцией. И место подключения скрипта с jQuery. Если таковых не будет, то значит подключаете не так и не там. Причём не важно, правитили вы header.php напрямую или используете function.php. Результирующий HTML код - код вашей страницы должен соответствовать канонам HTML и содержать требуемые строки.
Если строки есть, то убедитесь, что адрес правильный - может быть в строке подключения используется не тот, где фактически лежит скрипт.

A: Решил проблему: подключил страницу в header-е страницы изменив параметр false на true в функции wp_enqueue_script().


text:
Q: How to close a pubnub connection? I'm using pubnub in a node.js project. I can initialize pubnub and publish a message like:
Node.js
var PUBNUB = require('pubnub');
var pubnub = PUBNUB.init({
  publish_key   : 'demo',
  subscribe_key : 'demo'
});

var CHANNEL = 'test1234';

pubnub.subscribe({
  channel: CHANNEL,
  message: function (message) {
    console.log('Received message:', message);

    // unsubscribe again
    pubnub.unsubscribe({channel: CHANNEL});

    // PROBLEM: The node.js process does not exit because pubnub is still
    //          active. How to close the pubnub connection so it's completely
    //          gone from memory?
  },
  connect: function () {
    // send a test message
    pubnub.publish({channel: CHANNEL, message: 'hello world!'});
  }
});

But how can I close this pubnub instance? So that it's gone from memory and event loop and does not keep the node.js process running.
I can't find anything in the API documentation, and tried pubnub.close(), pubnub.destroy(), and pubnub.disconnect() without success.

A: This issue is resolved in a newer version of pubnub (current is v3.7.8).


text:
Q: Xsl If test To display price gt Im trying to do a xsl if statement to see can i get prices all above a certain number to display out but i cant get it to work ill post the code to see if anyone can see my mistake i have a dtd and a style sheet but i dont think there is need to pst these
cheers
XSL :
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" />
    <xsl:template match="/SpecialOffers">

                <link href="style.css" rel="stylesheet" type="text/css" />

Special Offer's SuperMarket

Offers Above .99c

                            Description
                            Price
                            Offer
                            Number Of items

                        <xsl:for-each select="Hygiene/haircare">
                        <xsl:if test="Price >= 10">

                                    <xsl:value-of select="description"/>

                                    <xsl:value-of select="Price"/>

                                    <xsl:value-of select="Offer"/>

                                    <xsl:value-of select="Number_of_items"/>

                        </xsl:if>
                        </xsl:for-each>

    </xsl:template>
</xsl:stylesheet>

XML :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE SpecialOffers SYSTEM "Offers.dtd">

<?xml-stylesheet type="text/xsl" href="LoopOffers.xsl"?>
<?xml-stylesheet type="text/css" href="style.css" ?>
<SpecialOffers>
    <Hygiene>
        <haircare hid="HS">
            <Price>3.99</Price>
            <Offer> 2 for 1 </Offer>
            <Number_of_items>2</Number_of_items>
            <description>Head and Shoulders</description>
        </haircare>
        <haircare hid="HE">
            <Price>1.99</Price>
            <Offer>30% Off  </Offer>
            <Number_of_items>2</Number_of_items>
            <description>Herbal Essence</description>
        </haircare>
        <haircare hid="L">
            <Price>.99c</Price>
            <Offer> Half Price  </Offer>
            <Number_of_items>1</Number_of_items>
            <description>Loreal</description>
        </haircare>
        <face_body_care>
            <Price>1.50 </Price>
            <Offer>Half Price</Offer>
            <Number_of_items>1</Number_of_items>
            <description>Radox Shower Gel</description>
        </face_body_care>
    </Hygiene>
    <Cleaning_Products>
        <household>
            <Price>2.99</Price>
            <Offer>2 for 1</Offer>
            <Number_of_items>2</Number_of_items>
            <description>Mr Sheen</description>
        </household>
        <detergents>
            <Price>3.50</Price>
            <Offer>25% Off</Offer>
            <Number_of_items>1</Number_of_items>
            <description>Dettol</description>
        </detergents>
    </Cleaning_Products>
    <Grocery>
        <fruit fid="M">
            <name>Mango</name>
            <Price>.99c</Price>
            <Offer>6 for .99c</Offer>
            <weight>2kg</weight>
            <organic></organic>
        </fruit>
        <fruit fid="B">
            <name>Banana</name>
            <Price>1.39c</Price>
            <Offer>1kg</Offer>
            <weight>1kg</weight>
            <organic>Yes</organic>
        </fruit>
        <vegeatables>
            <name>Carrot</name>
            <Price>1.49</Price>
            <Offer>1kg for 1.49</Offer>
            <weight>1kg</weight>
            <organic>No</organic>
        </vegeatables>
        <vegeatables>
            <name>Cabbage</name>
            <Price>.89c</Price>
            <Offer>1</Offer>
            <weight>1kg</weight>
            <organic>Yes</organic>
        </vegeatables>
    </Grocery>
    <Perishables>
        <canned_goods>
            <name>Tuna</name>
            <Price>.99c</Price>
            <Offer>Half Price</Offer>
            <weight>500g</weight>
        </canned_goods>
        <canned_goods>
            <name>Beans</name>
            <Price>1.99c</Price>
            <Offer>6 For 1.99</Offer>
            <weight>500g each</weight>
        </canned_goods>
    </Perishables>
    <Alcholic_Beverages>
        <spirits>
            <name>Vodka</name>
            <Price>14.50</Price>
            <Offer>Half Price</Offer>
            <ml>70cl</ml>
            <volume_acl>37.5%</volume_acl>
        </spirits>
        <spirits>
            <name>Gin</name>
            <Price>27.50</Price>
            <Offer>20% Off</Offer>
            <ml>1 Litre</ml>
            <volume_acl>37.5%</volume_acl>
        </spirits>
        <spirits>
            <name>Gin</name>
            <Price>27.50</Price>
            <Offer>20% Off</Offer>
            <ml>1 Litre</ml>
            <volume_acl>37.5%</volume_acl>
        </spirits>
        <wine>
            <name>Proseco</name>
            <Price>13.75</Price>
            <Offer>10% Off</Offer>
            <ml>1 Litre</ml>
            <volume_acl>13.5%</volume_acl>
        </wine>
        <largers>
            <name>Heinkein</name>
            <Price>£6</Price>
            <Offer>4 for 6</Offer>
            <ml>500ml</ml>
            <volume_acl>4%</volume_acl>
        </largers>
    </Alcholic_Beverages>
    <Non-Alcholic_Beverages>
        <cordials>
            <can>
                <name>7 Up</name>
                <Price>5.00</Price>
                <Offer>12 Pack</Offer>
                <ml>330</ml>
            </can>
            <bottle>
                <name>Coke</name>
                <Price>1.39</Price>
                <Offer>2 for 1</Offer>
                <ml>1 Litre</ml>
            </bottle>
        </cordials>
        <juice>
            <name>Sunny D</name>
            <Price>.75c</Price>
            <Offer>Half Price</Offer>
            <ml>1 Litre</ml>
        </juice>
    </Non-Alcholic_Beverages>
</SpecialOffers>

A: The reason why your stylesheet does not produce any table rows is that there are no haircare products whose price is greater than or equal to 10 in your source XML.
Your title says "Offers Above .99c" - and if you want to show products whose price is above 0.99, you need to make your condition:
<xsl:if test="Price >= 1">

Note that those products in your XML whose price is .99c will not pass this test - but not because their price is lower than the threshold, but because their price is not a number. To include these prices in the comparison, you would have to remove the currency - for example:
<xsl:if test="translate(Price, 'c', '') >= .5">

The above applies to XSLT 1.0 and will also work with an XSLT 2.0 processor for as long as your stylesheet continues to be tagged as version="1.0" as it is now.


text:
Q: Rails: Return HTML from helper method So I was trying to display some font-awesome icons, when a favorite is true or either false.
I had something similar like below:
Application Controller
def favorite_text
    @favorite_exists ? '' : '<i class="fas fa-heart-o"'
end

helper_method :favorite_text

And in the view:
<%= link_to favorite_text, update_favorites_path, remote: true %>

A: You have to use the helper html_safe to signal that the hrml inside the string is safe and does not have to be escaped (simply speaking).
You can add this call inside your helper:
def favorite_text
    (@favorite_exists ? '' : '<i class="fas fa-heart-o"').html_safe
end

Then you can create a link by calling link_to with a block:
<%= link_to update_favorites_path, remote: true do %>
    <%= favorite_text %>
<% end %>

A more in-depth explanation can be found in the official docs: https://apidock.com/rails/String/html_safe

A: I faced a similar issue to show ratings stars of fontawesome but figured out a way through the below helper method
###in my application_helper.rb

    def show_big_rating_stars(count)
    if count && count > 0
       (0...count).map { content_tag(:span, "" , class: "fa fa-star gold fa-2x") }.join
    end

    ###this is how use it in my views
    show_big_rating_stars(vendor.ratings.count)

Hope it helps.


text:
Q: VirtualBox unable to capture device (USB Hard Drive) I'm facing some issues with my USB hard drive and VirtualBox. The problem is that it's detected in devices list and I activate the checkbox to capture the device but it's not captured by the guest system (Windows 7). The only way I made it work was adding a filter in virtual machine configuration and when the system starts the device is captured but I don't want this behaviour because when I unplug the device and then plug it again, the same problem occurs, it won't recognize it again until I restart the virtual machine.
Suggestions? Thanks in advance.

A: You need to have the latest virtual box installed.
Other things to check

*

*reboot once the virtual box is installed

*also install Oracle VM VirtualBox Extension Pack which is same as your installed version

*check usb 2.0 as an usb filter (usb 3.0 might not work properly)

*add yourself as part of virtual box user .command "sudo usermod -a -G vboxusers [user_name]"

*install virtual box additional pack which can be activated by   Device > Insert Additional CD image.

A: I've found an alternative, not a solution itself, that would work for all external storage devices. You can set up a shared folder that points to your external device root, checking "auto mount" option so it mounts automatically in guest machine when it starts. Your device will be displayed in guest machine as a "network device", at least in Windows (being guest).
I find that this alternative has a big pro: You can interact with your device contents in both systems, host and guest and contents will be automatically updated. Capturing a device in your guest machine will block the device for exclusive use, that could be a disadvantage.


text:
Q: Как выбрать случайную строку (несколько) из ячейки SQLite и удалить ее? (Python) У меня есть таблица, в которой хранятся товары. Вот пример товара:

Мне нужно, чтобы из столбца строки номер 1 (или любой другой, которая мне будет нужна) prods рандомно выбиралась строка (несколько), а потом удалялась (-ись).
Как это можно сделать?

A: Про работу с бд можно прочитать тут: https://docs.python.org/3/library/sqlite3.html
Потребуется реализовать два метода - получение значения "prods" из строки с заданным номером и вставка значения в поле "prods".
Предположим, что содержимое поля "prods" хранится в переменной prods в виде строки.
def rm_rnd(l, count): #удаляет из списка l count элементов на случайных позициях
    for _ in range(count):
        l.pop(random.randrange(0, len(l)))

pr_list = prods.split('\n') #разбили строку на массив продуктов
rm_rnd(pr_list, 3) #удалили из массива 3 случайных элемента
new_prods = '\n'.join(pr_list) #склеить оставшиеся продукты в строку

Значение new_prods нужно вставить в поле "prods" той же строки, из которой получили изначальный список продуктов.


text:
Q: create a custom show action to display list view as in list action sonata admin I wish to create a custom controller with a show action that to display a list view as it is done in the list action. Example: I have list of users, when i click on show to display the user messages, I want the message to be display in a list as in the pictures below
list view


text:
Q: debug.Keystore format file i try to open it using notepad? I am developing gps base app. For that i need the md5 so i have tried to open the file debug.keystore using notepad,so file format is change to notepad, now i have got the google-apiKey using key-tool menu (install plug-in keytool ), but problem is that when run my app it give me the following error
Error generating final archive: java.io.IOException: Invalid keystore format         Unknown  Android Packaging Problem
I am not even sure where to begin to look. I cannot launch the application. Can someone give me an idea on what area I can look into?
A
I am solve this problem
Delete your debug certificate under ~/.android/debug.keystore on Linux and Mac OS X; the directory is something like %USERPROFILE%/.androidon Windows.
The Eclipse plug-in should then generate a new certificate when you next try to build a debug package. You may need to clean and then build to generate the certificate.
Your debug keystore was created automatically


text:
Q: change value of method parameter using parameter annotation maybe it's very silly question. Please understand and forgive.
I'm trying to find a way to implement annotation that can change method paramter.
Please see the code:
/**
* This method does some scary things in OS file system.
* @param anyFileSystemPath is a file system path :)
*/
public File makeSomeFileSystemStuff(String anyFileSystemPath){
//some code goes here...
}

I would like to create an annotation:
public File makeSomeFileSystemStuff(@IsValid String anyFileSystemPath){
//some code goes here...
}

Where @IsValid annotation validates path (is should be at least with read access and should exist of course). Also I would like to be sure that each path ends with "/". So This annotation should append "/" to paramter value if "/" is not present at the end of line.
How can I do that?
I've tries to goolge like: java annotation change method paramter value, get method paramter value, e.t.c. but didn't find something useful for me :(
Please advice.


text:
Q: Actionscript 3 - parsing XML values I have the following XML:
<document>
    <homeitems>
        <homeitem>
            <itemURL>URL1.html</itemURL>
        </homeitem>
        <homeitem>
             <itemURL>URL2.html</itemURL>
        </homeitem>
        <homeitem>
             <itemURL>URL3.html</itemURL>
             <itemImage>image3.jpg</itemImage>
        </homeitem>
    </homeitems>
</document>

And the following code that parses it:
var XMLData:XML = new XML(LoaderMax.getContent("xmlDoc")); // loads XML
var numitems = XMLData.homeitems.homeitem.length();

for (var i=0;i<numitems;i++) {
    if ((XMLData.homeitems.homeitem[i].itemImage) && (XMLData.homeitems.homeitem[i].itemImage!=="")) {
        trace("Loading image "+XMLData.homeitems.homeitem[i].itemImage);
    }
}

Trace result:
Loading image
Loading image
Loading image image3.jpg

WHY?!?!? Shouldn't it skip the items that don't have images? Am I stupid?

A: You can see that your test if (XMLData.homeitems.homeitem[i].itemImage) evaluate to true (just do a trace(Boolean(XMLData.homeitems.homeitem[i].itemImage) you will see true).
Also don't compare a node to a String use the toString method of the node or cast it explicitely to a String (i.e. String(XMLData.homeitems.homeitem[i].itemImage)!="" or XMLData.homeitems.homeitem[i].itemImage.toString()!="" )
There is multiple way todo it :

You can test if the node is undefined :
if (XMLData.homeitems.homeitem[i].itemImage != undefined)

Use hasOwnProperty method :
if (XMLData.homeitems.homeitem[i].hasOwnProperty('itemImage'))

And you can also cast your itemImage to a String and see if it's != "" :
if (String(XMLData.homeitems.homeitem[i].itemImage) != "")

Using e4x and foreach you can have a cleaner code for your loop :
for each(var homeItem:XML in XMLData.homeitems.homeitem) {
    var itemImage:String = String(homeItem.itemImage)
    if (itemImage!="") {
        trace("Loading image "+itemImage);
    }
}

A: It's enough if you compare with != not !==
if ((XMLData.homeitems.homeitem[i].itemImage) && (XMLData.homeitems.homeitem[i].itemImage!="")) {
    /* do somethong here */
}


text:
Q: Firmware in linux kernel In the home directory of Linux kernel source tree, there is a directory "firmware". The files in the directory ends with .ihex.
When request_firmware is called, as per http://www.makelinux.net/ldd3/chp-14-sect-8,

The proper solution is to obtain the firmware from user space when you
  need it

So I suppose the firmware is loaded from /lib/firmware (not sure googled it).
So what are those .ihex files doing there? What are they for?
Thanks


text:
Q: Is there any method to extract predefined words from any text file using natural language processing and python? I am trying to make a program that extracts values like name , gender, age , hemoglobin out of a scanned blood-test report (any). I have tried to make a code but that works for a specific laboratory (aghakhan). I have heard that it can be done using nlp but i am not good at it. Kindly advice.
import pytesseract
import re

#ocr
image = r'C:\Users\User\Desktop\Image Automation\Images\WhatsApp Image 2022-06-21 at 4.41.22 PM.jpeg'
text = pytesseract.image_to_string(Image.open(image), lang="eng")

#cleaning punctuations
text = re.sub(r'\+','',text)
text = re.sub(r'\%','',text)
text = re.sub(r'\-','',text)
text = re.sub(r'\*','',text)
text = re.sub(r'\(','',text)
text = re.sub(r'\)','',text)
text = re.sub(r'\/','',text)
text = re.sub(r'\;','',text)
text = re.sub(r'\:','',text)
text = re.sub(r'\&','',text)
text = re.sub(r'\!','',text)
text = re.sub(r'\'','',text)
text = re.sub(r'\#','',text)
text = re.sub(r'\,','',text)
# print(text)

#searching particular values
PatientName=re.search(r'Patient Name (.*?) Age',text).group(1)
print("Patient Name:",PatientName)

PatientAge=re.search(r'(.*?)Y ',text).group(1)
print(f"Patient Age: {PatientAge} years")

PatientGender=re.search(r'Y (.*?)ale',text).group(1)
print(f"Patient Gender: {PatientGender}ale")

PatientRbc=re.search(r'(.*?)L 36152',text).group(1)
print(f"Rbc: {PatientRbc}/L")

PatientWbc=re.search(r'WBC. (.*?)L',text).group(1)
print(f"Wbc: {PatientWbc}/L") ```

[report][1]

  [1]: https://i.stack.imgur.com/zMWHV.jpg


text:
Q: What are x,y and curve parameters of the Apple signing key used to sign push notification tokens? As I understood, I have 2 ways of sending push notification to Apple APN : certificate-based, and token-based. I chose token-based
Apple guide says we need to create a token and refresh it every hour at least. So, i created a cron job that refreshes this token every hour and put it in a file on my server. Another cron job reads this token to send new pending push notification every second.
The problem comes in the refresh_token job, that I launch every hour. I use this librairy to create the JWT : https://web-token.spomky-labs.com/v/v2.x/components/signed-tokens-jws/jws-creation
Here is my code ( i just followed the guide I've just given as link) :
$algorithmManager = AlgorithmManager::create([
    new ES256()
]);

// Our key.
$jwk = new JWK([
    'kty' => 'EC', // *** PROBLEM HERE ***
    'k' => $keyFile
]);

// The JSON Converter.
$jsonConverter = new StandardConverter();

// We instantiate our JWS Builder.
$jwsBuilder = new JWSBuilder(
    $jsonConverter,
    $algorithmManager
);

// The payload we want to sign. The payload MUST be a string hence we use our JSON Converter.
$payload = $jsonConverter->encode([
    'iat' => time(),
    'nbf' => time(),
    'exp' => time() + 3600,

    'iss' => APPLE_TEAM_ID
]);

$jws = $jwsBuilder
    ->create()
    ->withPayload($payload)
    ->addSignature($jwk, /* with header: */['kid' => APPLE_KEY_NAME, 'alg' => 'ES256'])
    ->build();

This code throws an exception at ->build(); function, at the end. It says that x, y and crv parameters are not specified in the key. These parameters seem to be related to the algorithm (ES256), because when I choose the alg provided in the JWT guide, they dont ask me for these parameters.
Though, Apple didn't provide any of these informations about the key they gave me on their website. Here is their guide : https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/establishing_a_token-based_connection_to_apns

A: The way you load the key is not correct. The key in the guide corresponds to an Octet key, not an EC one. A JWK EC key should look like the example showed in the RFC7517 section 3 (with crv, x and y parameters).
You have to convert the key file you received from Apple services into a JWK EC key.
As you already have PHP on your platform, I recommend the use of the CLI tool:
curl -OL https://github.com/web-token/jwt-app/raw/gh-pages/jose.phar
curl -OL https://github.com/web-token/jwt-app/raw/gh-pages/jose.phar.pubkey
chmod +x jose.phar

# Replace `/path/to/you/private/key/file.p8` with the actual path to your private key
./jose.phar key:load:key /path/to/you/private/key/file.p8

rm ./jose.phar
rm ./jose.phar.pubkey

You should get something like {"kty":"EC","crv":"P-256","d":"…","x":"…","y":"…"}.
The JWK can be loaded using the following line of code:
$jwk = JWK::createFromJson('{"kty":"EC","crv":"P-256","d":"…","x":"…","y":"…"}');


text:
Q: MotionEvent Y coordinates on and off UI thread differ by height of status bar When I interrogate MotionEvent coordinates in a non-UI thread, I get Y(thread) = Y(UI thread) + status_bar_height. Does anyone know why this is?
override fun onTouch(view: View?, motionEvent: MotionEvent?): Boolean {
    Log.d(TAG, "Pre Event ${motionEvent?.x} ${motionEvent?.y}")

    Thread(Runnable {
        Log.d(TAG, "Post Event ${motionEvent?.x} ${motionEvent?.y}")
    }).start()
}

output:
Pre Event 395.45078 681.4934
Post Event 395.45078 729.4934

A: MotionEvent objects are reused by the framework to prevent the expense and memory fragmentation caused by creating hundreds/thousands of them for every touch event over the life of the app (remember that if you move by so much as 1 pixel that's a potential move event).  If you need data off of the event, save it during onTouch in a local variable.  It may not be the same later on, either in an asynchronous function or another call on the UI thread.


text:
Q: .htaccess redirect in drupal that excludes node edit page Currently I have the following htaccess redirect rule that detects any path that looks like
mysite.com/node/xxx and redirects it to a .php script that, in turn, finds the URL of the page and redirects the user to it (e.g. mysite.com/page/page.html)
 RewriteCond %{QUERY_STRING} ^(page=(31|1))?$ [NC]
 RewriteRule ^node/?$ /? [L,NC,R=301]
 RewriteRule ^(../)?node/([0-9]+)$ noderedirect.php?nid=$2 [L]

What I want, however, is that also when user accesses
mysite.com/node
or
mysite.com/node?page=xxx
they get redirected to the main page
BUT
when they access
mysite.com/node/xxx/edit
the rule doesn't get activated.
I tried several options (stopping at the one above) and so far I have this, but it still enables users to access mysite.com/node?page=xxx (all the other conditions are working fine.
Can somebody help?

A:
I just want it to go to that page, and not to do anything. but when it's /node/xxx or /node or /node?page=xxx i want it to redirect to noderedirect.php

If you want it to always go to the noderedirect, then try:
RewriteCond %{THE_REQUEST} \ /+node\?page=([0-9]+)
RewriteRule ^ /node/%1? [L,R=301]

RewriteRule ^node/?$ /noderedirect.php [L]
RewriteRUle ^node/([0-9]+)/? /noderedirect.php?nid=$1 [L]


text:
Q: Bloom filter - using the number of elements as the number of hash functions my question is, if we use k (number of hash functions) as n (the number of elements to be inserted), I saw that the probability of getting false positive is extremely low. I realize this is really slow..is this the worst case? And will this ensure that a false positive is never made?

A: No, you can never ensure that a Bloom filter has no false positives by changing the number of hash functions. The optimal number of hash functions is linear in the ratio of the space to the cardinality, so your choice will be quite far from optimal unless you use so much space that you might as well store the set directly, avoiding the Bloom filter altogether.
This last part is not true if your objects are truly enormous or you have a tiny number of them.


text:
Q: Let $C \subset \mathbb{R}^n$ be a given set. Show that the set $C^o = {\{y \in \mathbb{R}^n : y^Tx \le 0, \forall x \in C\}}$ is convex. I was wondering if this proof worked for this problem.
Let $t, s \in C$ and $\lambda \in [0,1].$ Let $z = \lambda t + (1 - \lambda)s$. Then $$y^Tz = y^T(\lambda t + (1 - \lambda)s$$
$$=\lambda y^Tt + (1-\lambda)y^Ts$$
Now $y^Tt$ and $y^Ts$ are $\le 0$, since $t, s \in C$.
So then we know that
$$\lambda y^Tt + (1-\lambda)y^Ts \le \lambda (0) + (1- \lambda) (0) = 0.$$
Thus, $z \in C$ and so the set is convex.
Also, how would one sketch this set?
Thanks ahead of time.

A: Take x $\in$ C. Consider the plane P in $\mathbb{R}^n$ with normal vector $x$. The set C$^0_x$ = {y | $y^Tx \leq 0\}$ can be thought of as the closed half-space that lies on the opposite side of P as $x$. This is obviously convex. Note C = $\bigcap_{x \in C} C^0_x$. So the intersection of all these closed half-spaces is convex.

A: If you draw a picture, then it is clear : For $y,\ z\in
 C^0$, $$ [ty +(1-t)z ]^T  x  =
 ty^Tx + (1-t)z^T x \leq 0 $$ for all $x\in C$ and any $t
 \in (0,1)$.


text:
Q: How to select a file from popup selenium python Im trying to upload a video using selenium python, whenever i try to upload it i get a pop up window to choose the file. how can i automate this task to select file from the popup window?

A: If the page HTML have this CSS_SELECTOR :
input[type='file']

you can just do send_keys.
something like this  :
driver.maximize_window()
driver.implicitly_wait(30)
driver.get("Your URL")
wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.ID, "LocationSearch_input"))).send_keys("full path of file to be uploaded")

Imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


text:
Q: Python plotly animate marker styles or points in Scatter3d over time I have a plotly & Dash based application with a 3D Scatterplot. The data head looks like this:
'Classname'    'Date'     '0'     '1'     '2'
 B              1542       0.95   0.98     0.80
 B              1725       1.00   1.00     0.75
 C              1620       0.74   0.36     0.85

I got 26 classes. not every class is represented in every year. Now I want to animate the datapoints by their Date variable but the rest of the data should always be visible so I can see where in the point cloud the data point is.
Example: All data points are grey and only the points of the current data frame are highlighted with a color.
Since I don't know if that´s possible, I just tried to add the animation frames as additional points with different style. But the animation does not work and I don´t know why. I can see the 'data', a slider and the buttons but no animated frames. If I click on PLAY nothing happens.
Sometimes if I click arount in the graph, there suddenly appear some of the additional 'diamond' points but that´s very buggy and the animation still doesnt work. Looks like this:

I was sticking to this documentation and also tried the advice in this question.
Here´s my code to create the figure:
def animate_time_tsne(dff):
    # make figure
    fig_dict = {
        "data": [],
        "layout": {},
        "frames": []
    }

    years = np.unique(dff['Date'])
    styles = np.unique(dff['Classname'])

    fig_dict["layout"]["hovermode"] = "closest"
    fig_dict["layout"]["updatemenus"] = [
        {
            "buttons": [
                {
                    "args": [None, {"frame": {"duration": 500, "redraw": False},
                                    "fromcurrent": True, "transition": {"duration": 300,
                                                                        "easing": "quadratic-in-out"}}],
                    "label": "Play",
                    "method": "animate"
                },
                {
                    "args": [[None], {"frame": {"duration": 0, "redraw": False},
                                      "mode": "immediate",
                                      "transition": {"duration": 0}}],
                    "label": "Pause",
                    "method": "animate"
                }
            ],
            "direction": "left",
            "pad": {"r": 10, "t": 87},
            "showactive": False,
            "type": "buttons",
            "x": 0.1,
            "xanchor": "right",
            "y": 0,
            "yanchor": "top"
        }
    ]

    sliders_dict = {
        "active": 0,
        "yanchor": "top",
        "xanchor": "left",
        "currentvalue": {
            "font": {"size": 20},
            "prefix": "Year:",
            "visible": True,
            "xanchor": "right"
        },
        "transition": {"duration": 300, "easing": "cubic-in-out"},
        "pad": {"b": 10, "t": 50},
        "len": 0.9,
        "x": 0.1,
        "y": 0,
        "steps": []
    }

    # create data
    colors = px.colors.qualitative.Dark24 + px.colors.qualitative.Light24,
    for i, style in enumerate(styles):
        data_by_style = dff[dff['Classname'] == style]
        data_dict = go.Scatter3d(
            x=data_by_style['0'], y=data_by_style['1'], z=data_by_style['2'],
            mode='markers', marker={'color': colors[0][i], 'size':5},
            name=style,
            #customdata=[data_by_style['Filename'], data_by_style['Classname']]
        )
        fig_dict['data'].append(data_dict)
    fig_dict['data'] = fig_dict['data']*2

    # create frames
    for year in years:
        if not np.isnan(year):
            frame = {"data": [], "name": str(year), "traces":[1]}
            data_by_year = dff[dff['Date'] == year]
            for style in styles:
                data_by_year_style = data_by_year[data_by_year['Classname'] == style]
                data_dict = go.Scatter3d(
                    x=data_by_year_style['0'], y=data_by_year_style['1'],
                    z=data_by_year_style['2'],
                    mode='markers',
                    marker={'size': 15, 'symbol': 'diamond', 'color':colors[0][-1]},
                    name=style
                )
                frame['data'].append(data_dict)

            fig_dict['frames'].append(frame)
            slider_step = {"args": [
                [year],
                {"frame": {"duration": 300, "redraw": False},
                 "mode": "immediate",
                 "transition": {"duration": 300}}
            ],
                "label": year,
                "method": "animate"}
            sliders_dict["steps"].append(slider_step)

    fig_dict["layout"]["sliders"] = [sliders_dict]

    return go.Figure(fig_dict)

A: I couldn´t find it out with go.figure but I found a working solution with plotly express.
dff.dropna(subset=['Date'], inplace=True)  # drop nan values
    dff = dff.sort_values('Date', ascending=True)
    x_range = [dff['0'].min(), dff['0'].max()]
    y_range = [dff['1'].min(), dff['1'].max()]
    z_range = [dff['2'].min(), dff['2'].max()]
    colors = px.colors.qualitative.Dark24 + px.colors.qualitative.Light24

    fig = px.scatter_3d(
        dff, x='0', y='1', z='2',
        animation_frame='Date',
        range_x=x_range, range_y=y_range, range_z=z_range,
        height=900, width=1200
    )

    fig.layout.updatemenus[0].buttons[0].args[1]['frame']['duration'] = 300
    fig.layout.updatemenus[0].buttons[0].args[1]['transition']['duration'] = 100
    for x in fig.frames:
        x.data[0]['marker']['color'] = '#ff00c2'
        x.data[0]['marker']['symbol'] = 'diamond'
        x.data[0]['marker']['size'] = 20

    styles = np.unique(dff['Classname'])

    for i, style in enumerate(styles):
        data_by_style = dff[dff['Classname'] == style]
        fig.add_trace(go.Scatter3d(
            x=data_by_style['0'], y=data_by_style['1'], z=data_by_style['2'],
            mode='markers',
            marker={'color': colors[i], 'size': 5},
            name=style,
            opacity=0.1
        ))

    return fig


text:
Q: Does it make sense to have unique_ptr for streams? Often I see std::fstreams passed by reference... but you can't copy them so if it's in a class, holding a reference to it seems finicky. In this case, I would prefer to use a std::unique_ptr. Which approach is better:
struct Handle
{
    Handle(std::string filename)
    {
        fstr.open(filename);
    }
    Handle(const Handle& o) = delete;
    Handle& operator=(const Handle& o) = delete;
private:
    std::ifstream fstr;
};

or:
struct Handle
{
    Handle(std::string filename)
        : fstr(std::make_unique<std::ifstream>(filename))
    {
    }
private:
    std::unique_ptr<std::ifstream> fstr;
};

Both forms prevent copying but the latter form takes less typing.

A: In both of your examples, Handle actually subtracts functionality from std::ifstream.  It would be better to use std::ifstream rather than Handle.
The first example takes a movable std::ifstream, and makes it not movable.
The second example makes it movable again, but at the needless cost of an allocation.
Neither of your examples make it copyable (and they should not).
Just pass around std::ifstream in the same way that you would std::unique_ptr<std::ifstream> but without the clumsy pointer syntax.  std::ifstream is MoveConstructible and MoveAssignable.  You can just return it by value from factory functions or pass it into sink functions by value (if moved from) -- Just like unique_ptr.
Caveat:  gcc hasn't yet implemented moving streams so if that is the platform you are on, your second Handle has promise as a temporary workaround.


text:
Q: Highcharts standalone framework with highcharts-ng, angular. Animation issue When I use the standalone framework for highcharts, the animation is faulty when I update the data. Jsfiddle: http://jsfiddle.net/user1572526/3stqK/3/ This error only occurs when I use the standalone framework. If I use the full jQuery library, it works. Has it something to do with the highcharts directive I'm using? https://github.com/pablojim/highcharts-ng
Any idea how I can fix this? I really want to avoid dragin in the full jQuery library cause of this.
Highcharts with standalone framework. Animation works if I change to jquery.
<script src="https://rawgithub.com/highslide-software/highcharts.com/master/js/adapters/standalone-framework.src.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>

A: It seems that the problem is with your additioanl plugin highcharts-ng, because without that, all works properly as in the example
var btn = document.getElementById('button'),
        y=30;

    btn.onclick = function(){
       chart.series[0].data[0].update(100);
    }

http://jsfiddle.net/3stqK/5/


text:
Q: How to upload large video to server (php) using AFNetworking 3.0 (Obj-C) I am trying to create a simple video upload task using AFNetworking 3.0. I know how to upload smaller videos the I need to be able to upload (stream) large files (longer videos). Below is the code I use to upload currently. Also, I use PHP on the server side, is there any special change is needed?
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"http://v.afrazsiddiqui.com/?cmd=post&id=%@",[UDM returnValueforkey:@"userid"]] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileURL:self.videoURL name:@"file" fileName:@"filename.mov" mimeType:@"video/quicktime" error:nil];
} error:nil];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
    dispatch_async(dispatch_get_main_queue(), ^{
        CGFloat done = self.view.frame.size.width*uploadProgress.fractionCompleted;
        [self updateProgressWithPercentage:done];
    });
}
completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
    if (error) {
        errorUploading=YES;
    }
    else {
        JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",JSON);
        if ([[JSON valueForKey:@"Success"] isEqualToString:@"true"]) {
            [self reloadProfile];
        }
        else if ([[JSON valueForKey:@"Error"] isEqualToString:@"Upload"]) {
            if (!errorUploading) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Vlog Error" message:@"An error occurred when trying to post your vlog." delegate:self cancelButtonTitle:@"No, Thanks" otherButtonTitles:@"Retry", nil];
                [alert show];
            }
        }
    }
}];
[uploadTask resume];


text:
Q: How to implement an IPC protocol using Boost ASIO? I'm trying to implement a simple IPC protocol for a project that will be built using Boost ASIO. The idea is to have the communication be done through IP/TCP, with a server with the backend and a client that will be using the data received from the server to build the frontend. The whole session would go like this:

*

*The connection is established

*The client sends a 2 byte packet with some information that will be used by the server to build its response (this is stored as the struct propertiesPacket)

*The server processes the data received and stores the output in a struct of variable size called processedData

*The server sends a 2 byte unsigned integer that will indicate the client what size the struct it will receive has (let's say the struct is of size n bytes)

*The server sends the struct data as a n byte packet

*The connection is ended

I tried implementing this by myself, following the great tutorial available in Boost ASIO's documentation, as well as the examples included in the library and some repos I found on Github, but as this is my first hand working with networking and IPC, I couldn't make it work, my client returns an exception saying the connection was reset by the peer.
What I have right now is this:
// File client.cpp
int main(int argc, char *argv[])
{
    try {
        propertiesPacket properties;
        // ...
        // We set the data inside the properties struct
        // ...

        boost::asio::io_context io;
        boost::asio::ip::tcp::socket socket(io);
        boost::asio::ip::tcp::resolver resolver(io);

        boost::asio::connect(socket, resolver.resolve(argv[1], argv[2]));
        boost::asio::write(socket, boost::asio::buffer(&properties, sizeof(propertiesPacket)));

        unsigned short responseSize {};
        boost::asio::read(socket, boost::asio::buffer(&responseSize, sizeof(short)));

        processedData* response = reinterpret_cast<processedData*>(malloc(responseSize));
        boost::asio::read(socket, boost::asio::buffer(response, responseSize));

        // ...
        // The client handles the data
        // ...

        return 0;
    } catch (std::exception &e) {
        std::cerr << e.what() << std::endl;
    }
}

// File server.cpp
class ServerConnection
    : public std::enable_shared_from_this<ServerConnection>
{
    public:
        using TCPSocket = boost::asio::ip::tcp::socket;

        ServerConnection::ServerConnection(TCPSocket socket)
          : socket_(std::move(socket)),
            properties_(nullptr),
            filePacket_(nullptr),
            filePacketSize_(0)
        {
        }

        void start() { doRead(); }

    private:
        void doRead()
        {
            auto self(shared_from_this());
            socket_.async_read_some(boost::asio::buffer(properties_, sizeof(propertiesPacket)),
                                    [this, self](boost::system::error_code ec, std::size_t /*length*/)
                                    {
                                        if (!ec) {
                                            processData();
                                            doWrite(&filePacketSize_, sizeof(short));

                                            doWrite(filePacket_, sizeof(*filePacket_));
                                        }
                                    });

        }

        void doWrite(void* data, size_t length)
        {
            auto self(shared_from_this());
            boost::asio::async_write(socket_, boost::asio::buffer(data, length),
                                     [this, self](boost::system::error_code ec, std::size_t /*length*/)
                                     {
                                         if (!ec) { doRead(); }
                                     });
        }

        void processData()
        { /* Data is processed */ }

        TCPSocket socket_;

        propertiesPacket* properties_;
        processedData* filePacket_;
        short filePacketSize_;
};

class Server
{
    public:
        using IOContext = boost::asio::io_context;
        using TCPSocket = boost::asio::ip::tcp::socket;
        using TCPAcceptor = boost::asio::ip::tcp::acceptor;

        Server::Server(IOContext& io, short port)
            : socket_(io),
              acceptor_(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port))
        {
            doAccept();
        }

    private:
        void doAccept()
        {
            acceptor_.async_accept(socket_,
                [this](boost::system::error_code ec)
                {
                    if (!ec) {
                        std::make_shared<ServerConnection>(std::move(socket_))->start();
                    }

                    doAccept();
                });
        }

        TCPSocket socket_;
        TCPAcceptor acceptor_;
};

What did I do wrong? My guess is that inside the doRead function, calling multiple times the doWrite function, when that function then also calls doRead is in part what's causing problems, but I don't know what the correct way of writing data asynchronously multiple times is. But I'm also sure that isn't the only part of my code that isn't behaving as I think it should.

A: Besides the problems with the code shown that I mentioned in the comments, there is indeed the problem that you suspected:

My guess is that inside the doRead function, calling multiple times the doWrite function, when that function then also calls doRead is in part what's causing problems

The fact that "doRead" is in the same function isn't necessarily a problem (that's just full-duplex socket IO). However "calling multiple times" is. See the docs:

This operation is implemented in terms of zero or more calls to the stream's async_write_some function, and is known as a composed operation. The program must ensure that the stream performs no other write operations (such as async_write, the stream's async_write_some function, or any other composed operations that perform writes) until this operation completes.

The usual way is to put the whole message in a single buffer, but if that would be "expensive" to copy, you can use a BufferSequence, which is known as scatter/gather buffers.
Specifically, you would replace
doWrite(&filePacketSize_, sizeof(short));
doWrite(filePacket_, sizeof(*filePacket_));

with something like
std::vector<boost::asio::const_buffer> msg{
    boost::asio::buffer(&filePacketSize_, sizeof(short)),
    boost::asio::buffer(filePacket_, sizeof(*filePacket_)),
};

doWrite(msg);

Note that this assumes that filePacketSize and filePacket have been assigned proper values!

You could of course modify do_write to accept the buffer sequence:
template <typename Buffers> void doWrite(Buffers msg)
{
    auto self(shared_from_this());
    boost::asio::async_write(
        socket_, msg,
        [this, self](boost::system::error_code ec, std::size_t /*length*/) {
            if (!ec) {
                doRead();
            }
        });
}

But in your case I'd simplify by inlining the body (now that you don't call it more than once anyway).
SIDE NOTES
Don't use new or delete. NEVER use malloc in C++. Never use reinterpret_cast<> (except in the very rarest of exceptions that the standard allows!). Instead of
    processedData* response = reinterpret_cast<processedData*>(malloc(responseSize));

Just use
    processedData response;

(optionally add {} for value-initialization of aggregates). If you need variable-length messages, consider to put a vector or a array<char, MAXLEN> inside the message. Of course, array is fixed length but it preserves POD-ness, so it might be easier to work with. If you use vector, you'd want a scatter/gather read into a buffer sequence like I showed above for the write side.
Instead of reinterpreting between inconsistent short and unsigned short types, perhaps just spell the type with the standard sizes: std::uint16_t everywhere.
Keep in mind that you are not taking into account byte order so your protocol will NOT be portable across compilers/architectures.
Provisional Fixes
This is the listing I ended up with after reviewing the code you shared.
Live On Coliru
#include <boost/asio.hpp>
#include <iostream>

namespace ba = boost::asio;
using boost::asio::ip::tcp;
using boost::system::error_code;
using TCPSocket = tcp::socket;

struct processedData { };
struct propertiesPacket { };

// File server.cpp
class ServerConnection : public std::enable_shared_from_this<ServerConnection> {
  public:
    ServerConnection(TCPSocket socket) : socket_(std::move(socket))
    { }

    void start() {
        std::clog << __PRETTY_FUNCTION__ << std::endl;
        doRead();
    }

  private:
    void doRead()
    {
        std::clog << __PRETTY_FUNCTION__ << std::endl;
        auto self(shared_from_this());
        socket_.async_read_some(
            ba::buffer(&properties_, sizeof(properties_)),
            [this, self](error_code ec, std::size_t length) {
                std::clog << "received: " << length << std::endl;
                if (!ec) {
                    processData();

                    std::vector<ba::const_buffer> msg{
                        ba::buffer(&filePacketSize_, sizeof(uint16_t)),
                        ba::buffer(&filePacket_, filePacketSize_),
                    };

                    ba::async_write(socket_, msg,
                        [this, self = shared_from_this()](
                            error_code ec, std::size_t length) {
                            std::clog << " written: " << length
                                      << std::endl;
                            if (!ec) {
                                doRead();
                            }
                        });
                }
            });
    }

    void processData() {
        std::clog << __PRETTY_FUNCTION__ << std::endl;
        /* Data is processed */
    }
    TCPSocket socket_;

    propertiesPacket properties_{};
    processedData    filePacket_{};
    uint16_t         filePacketSize_ = sizeof(filePacket_);
};

class Server
{
  public:
    using IOContext   = ba::io_context;
    using TCPAcceptor = tcp::acceptor;

    Server(IOContext& io, uint16_t port)
        : socket_(io)
        , acceptor_(io, {tcp::v4(), port})
    {
        doAccept();
    }

  private:
    void doAccept()
    {
        std::clog << __PRETTY_FUNCTION__ << std::endl;
        acceptor_.async_accept(socket_, [this](error_code ec) {
            if (!ec) {
                std::clog << "Accepted " << socket_.remote_endpoint()
                          << std::endl;
                std::make_shared<ServerConnection>(std::move(socket_))->start();
                doAccept();
            } else {
                std::clog << "Accept " << ec.message() << std::endl;
            }
        });
    }

    TCPSocket   socket_;
    TCPAcceptor acceptor_;
};

// File client.cpp
int main(int argc, char *argv[])
{
    ba::io_context io;
    Server         s{io, 6869};

    std::thread server_thread{[&io] {
        io.run();
    }};

    // always check argc!
    std::vector<std::string> args(argv, argv + argc);

    if (args.size() == 1)
        args = {"demo", "127.0.0.1", "6869"};

    // avoid race with server accept thread
    post(io, [&io, args] {
        try {
            propertiesPacket properties;
            // ...
            // We set the data inside the properties struct
            // ...

            tcp::socket   socket(io);
            tcp::resolver resolver(io);

            connect(socket, resolver.resolve(args.at(1), args.at(2)));
            write(socket, ba::buffer(&properties, sizeof(properties)));

            uint16_t responseSize{};
            ba::read(socket, ba::buffer(&responseSize, sizeof(uint16_t)));

            std::clog << "Client responseSize: " << responseSize << std::endl;
            processedData response{};
            assert(responseSize <= sizeof(response));
            ba::read(socket, ba::buffer(&response, responseSize));

            // ...
            // The client handles the data
            // ...

            // for online demo:
            io.stop();
        } catch (std::exception const& e) {
            std::clog << e.what() << std::endl;
        }
    });

    io.run_one();
    server_thread.join();
}

Printing something similar to
void Server::doAccept()
Server::doAccept()::<lambda(boost::system::error_code)> Success
void ServerConnection::start()
void ServerConnection::doRead()
void Server::doAccept()
received: 1
void ServerConnection::processData()
 written: 3
void ServerConnection::doRead()
Client responseSize: 1


text:
Q: ElasticBeanstalk not working config - client_max_body_size my Enviroment is

*

*ELB platform : Corretto 11 running on 64bit Amazon Linux 2/3.4.2

*Application : Spring Boot Jar

so how can edit "client_max_body_size" Amazon Linux 2?
many another stackoverflow Q/A explain this.
create path and file like this
-- .platform
   -- nginx
       -- conf.d
             -- client_max_body_size.conf

and writ "client_max_body_size 256M;" in client_max_body_size.conf
but it is not work...
here is my project structure

What do I have to fix to work properly?


text:
Q: Missing outer border of a flextable in R I have an issue I can't resolve. There may be something missing in the flextable package, but I may be wrong. Please, see the example.
This is my tabular data:
structure(list(groupName = c("Group A", "Group A", "Group A",
"Group A", "Group A", "Group B", "Group B", "Group B", "Group B",
"Group B"), ID = c("14243", "14363", "14373", "14934", "14980",
"14400", "14488", "14513", "14549", "15407"), `Day -15` = c(NA,
NA, NA, 174, 143, NA, NA, NA, NA, 169), `Day -13` = c(NA, NA,
NA, 164, 132, NA, NA, NA, NA, 178), `Day -12` = c(NA_real_, NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
NA_real_), `Day -11` = c(NA, NA, NA, NA, 189, NA, 213, NA, NA,
204), `Day -10` = c(NA, NA, NA, 187, NA, NA, NA, NA, NA, NA),
    `Day -9` = c(NA, NA, NA, NA, 178, NA, 204, 227, 257, 232),
    `Day -8` = c(NA, NA, NA, 286, NA, NA, NA, NA, NA, NA), `Day -7` = c(NA,
    NA, NA, NA, NA, NA, 258, 311, 291, NA)), row.names = c(NA,
-10L), class = c("tbl_df", "tbl", "data.frame"))

I build a flextable like this:
flx <- flextable(tbl2) %>%
  border_outer() %>%
  add_header_row(values = c(
    "groupName",
    "ID",
    rep("measurement", ncol(tbl2) - 2)
  )) %>%
  merge_h(part = "header") %>%
  merge_v(part = "header") %>%
  valign(valign = "bottom", part = "header") %>%
  align(align = "center", part = "all")

and the output is
As You can see there is missing border in the first row of the header.
I tried to add border_outer() once again, but no effect. I also tried vline_right function, but no effect too. The only thing I found was to add this step:
flx %>% border_inner_v(part = "header")

but it adds border to every cell in the header which is not what I need.
I think the step merge_h in my pipeline is the place where bad things happen. Is there a solution for this?

A: This is a special case, the border you are seeing on the right side is actually the right border of the third cell that has been merged with all following cells.
library(flextable)
library(magrittr)

tbl2 <- structure(list(groupName = c("Group A", "Group A", "Group A",
"Group A", "Group A", "Group B", "Group B", "Group B", "Group B",
"Group B"), ID = c("14243", "14363", "14373", "14934", "14980",
"14400", "14488", "14513", "14549", "15407"), `Day -15` = c(NA,
NA, NA, 174, 143, NA, NA, NA, NA, 169), `Day -13` = c(NA, NA,
NA, 164, 132, NA, NA, NA, NA, 178), `Day -12` = c(NA_real_, NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
NA_real_), `Day -11` = c(NA, NA, NA, NA, 189, NA, 213, NA, NA,
204), `Day -10` = c(NA, NA, NA, 187, NA, NA, NA, NA, NA, NA),
`Day -9` = c(NA, NA, NA, NA, 178, NA, 204, 227, 257, 232),
`Day -8` = c(NA, NA, NA, 286, NA, NA, NA, NA, NA, NA), `Day -7` = c(NA,
NA, NA, NA, NA, NA, 258, 311, 291, NA)), row.names = c(NA, -10L),
class = c("tbl_df", "tbl", "data.frame"))

# solution 1
flextable(tbl2) %>%
  border_outer() %>%
  add_header_row(values = c(
    "groupName",
    "ID",
    rep("measurement", ncol(tbl2) - 2)
  )) %>%
  merge_h(part = "header") %>%
  merge_v(part = "header") %>%
  valign(valign = "bottom", part = "header") %>%
  align(align = "center", part = "all") %>%
  vline(i = 1, j = 3, border = fp_border_default(), part = "header")

# solution 2
flextable(tbl2) %>%
  border_outer() %>%
  add_header_row(values = c(
    "groupName",
    "ID",
    rep("measurement", ncol(tbl2) - 2)
  )) %>%
  merge_h(part = "header") %>%
  merge_v(part = "header") %>%
  valign(valign = "bottom", part = "header") %>%
  align(align = "center", part = "all") %>%
  fix_border_issues()


text:
Q: Why do i get error on prepare?

#!/usr/bin/perl

use strict;

use Sybase::DBlib;

use Sys::Hostname;
use Getopt::Std;

## additionals
use lib "/opt/chsdjg/perllib";
use ADDITIONALS;

  my ($dsn, $database, $dbserver, $dbname, $user, $passwd, $rmdb_config ) = ('','','','','','','');

  my $dbhandle;
  $rmdb_config  = "$ENV{ENV_DIR}";
  $dsn          = "dbi:Sybase";
  $database     = join (' ~ ',$dsn, $dbserver, $dbname, $user, $passwd, $rmdb_config);
  $dbhandle     = connect_me($database);

  my $ctl= "select * from table_name";

  $dbhandle->dbcmd($ctl);
  my $ret = $dbhandle->dbsqlexec;
  my $res = $dbhandle->dbresults;

 my @dat;
   while($dbhandle->dbresults != NO_MORE_RESULTS) {
        while(@dat = $dbhandle->dbnextrow) {
  print "@dat\n";
}
}

I didnt use the right connection the first time. This is the code now, it makes an select statement and shows the result. Hope it helps people.

A: You never create your database handle ($dbh is undefined).
Add
my $dbh = $dbh = DBI->connect($data_source, $username, $password)
            or die $DBI::errstr;

To your code. See Documentation on CPAN for more information.


text:
Q: Where to find pythons scapy module full documentation? I've recently started using scapy and this doc.
https://scapy.readthedocs.io/en/latest/
But a lot of stuff isn't written there for ex. all methods, what fields do sniffed packets have, what layers I can get etc.
Where can I learn about scapy without loosing my sanity and googling for hours?

A: Edit: Scapy now also has an automatically generated API reference: https://scapy.readthedocs.io/en/latest/api/scapy.html which shows all fields of all packets
You have several ways to get documentation about scapy. First, I advise you to use the github version, which has updated docs
https://github.com/secdev/scapy

*

*Using the help() command. Pretty basic, but for instance help(sniff) shows tons of great stuff

*The scapy ls() builtin command. It allows to list fields in a packet, very useful

*Finally, when you have questions about a specific command, if no doc is available, feel free to have a look at the source code, ideally quite good documented, or even ask for help on the gitter or github :)


text:
Q: Create table based on the data value of another table in Laravel I try to create a new table based on the existing table. If the table value in A = 'TC' or '0', the table value in B will be '0', else the table value in B will follow the table value in A.
This is what I have tried, but I'm not sure about the logic that I code. Hopefully, someone will help me.
$subject = Scsj::get();
    if ($subject->teknologi_dan_sistem_maklumat=='TC'||'0') {
        $subject->teknologi_dan_sistem_maklumat=='0';
    } else {
        $subject->teknologi_dan_sistem_maklumat=='1';
    }

A: First of all, you use the equal operator to set the variable. As 1000Nettles said, get() will return you a collection of data. If you wish to retreive an object, use the first() method.
Besides, I would rewrite your code to make it smaller:
$subject = Scsj::first();
 $var = $subject->teknologi_dan_sistem_maklumat;
if ($var =='TC'|| $var == '0') {
    $subject->teknologi_dan_sistem_maklumat = '0';
} else {
    $subject->teknologi_dan_sistem_maklumat = '1';
}

Edit:
You are trying to make a new database record, setting the value of the old database record wont help unless you plan on updating the record.


text:
Q: service principal does not have secrets get permission on key vault I am trying to create a keyvault on Azure using Terraform which is performed by my service principal user:
data "azurerm_client_config" "current" {}

resource "azurerm_key_vault" "key_vault" {
  name                        = "${var.project_name}-keyvault"
  location                    = var.resource_group_location
  resource_group_name         = var.resource_group_name
  enabled_for_disk_encryption = true
  tenant_id                   = data.azurerm_client_config.current.tenant_id
  soft_delete_retention_days  = 7
  purge_protection_enabled    = false

  sku_name = "standard"
}

resource "azurerm_key_vault_access_policy" "access_policy" {
  key_vault_id = azurerm_key_vault.key_vault.id
  tenant_id    = data.azurerm_client_config.current.tenant_id
  object_id    = data.azurerm_client_config.current.object_id

    secret_permissions = [
      "Set", "Get", "Delete", "Purge", "List",  ]
}

resource "azurerm_key_vault_secret" "client_id" {
  name         = "client-id"
  value        = var.client_id_value
  key_vault_id = azurerm_key_vault.key_vault.id
}

resource "azurerm_key_vault_secret" "client_secret" {
  name         = "client-secret"
  value        = var.client_secret_value
  key_vault_id = azurerm_key_vault.key_vault.id
}

resource "azurerm_key_vault_secret" "subscription_id" {
  name         = "subscription-id"
  value        = var.subscription_id_value
  key_vault_id = azurerm_key_vault.key_vault.id
}

resource "azurerm_key_vault_secret" "tenant_id" {
  name         = "tenant-id"
  value        = var.tenant_id_value
  key_vault_id = azurerm_key_vault.key_vault.id
}

But i get this error:
    Error: checking for presence of existing Secret "client-id" (Key Vault "https://formulaeinsdef-keyvault.vault.azure.net/"): keyvault.BaseClient#GetSecret:
    Failure responding to request: StatusCode=403 -- Original Error: autorest/azure:
    Service returned an error. Status=403 Code="Forbidden" Message="The user, group or application 'appid=***;oid=32d24355-0d93-476d-a775-6882d5a22e0b;iss=https://sts.windows.net/***/' does not have secrets get permission on key vault 'formulaeinsdef-keyvault;location=westeurope'.
For help resolving this issue, please see https://go.microsoft.com/fwlink/?linkid=2125287" InnerError={"code":"AccessDenied"}

The above code creates the key-vault successfully, but it fails to add the secrets inside it.
My Service Principal user has Contributor role and i think, it should be enough to GET and SET key keys.
I tried to give my service principal the Reader or even Ownerpermission, but it was not helpful.
I also checked this question, but it is not helping me.
I checked the Access Policies tab and i have the permissions to Set, Get, Delete, Purge, List.

A: Each of the secrets needs an explicit dependency on the access policy. Otherwise, Terraform may attempt to create the secret before creating the access policy.
resource "azurerm_key_vault_secret" "client_id" {
  name         = "client-id"
  value        = var.client_id_value
  key_vault_id = azurerm_key_vault.key_vault.id

  ### Explicit dependency
  depends_on = [
    azurerm_key_vault_access_policy.access_policy
  ]
}

Alternatively, moving the access policy definition into the key vault block would make the explicit dependencies unnecessary:
resource "azurerm_key_vault" "key_vault" {
  # Content omitted for brevity
  .
  .
  access_policy {
    tenant_id = data.azurerm_client_config.current.tenant_id
    object_id = data.azurerm_client_config.current.object_id

    secret_permissions = [
      "Set", "Get", "Delete", "Purge", "List",  ]
  }
}


text:
Q: Insert dependencies dynamically in View (Javascript and CSS Files) Friends, I am willing to follow the rules of the W3C where it is recommended that javascript and CSS files should be in individual files and not within the page.
Good, following this rule, and not wanting to overload the master page, I would like to embed the dependencies dynamically. So how could I insert the libraries dynamically? I think the bigger problem is the Ajax requests.
Example:
<script type="text/javascript" src="http://sstatic.net/so/js/master.js?v=6523"></script>

I tried using the JavascriptResult, but he writes the content on the page, and do not run as "Stream."
Any help is welcome. Thanks

A: If I understand correctly the problem, you want to add script files dynamically to the page.
You can try jQuery load function, that can parse for you the result in very intuitive way.


text:
Q: MATLAB slowing down on long debugging sessions I have noticed that MATLAB (R2011b on Windows 7, 64 bit) tends to slow down if I am in debugging mode for a long period of time (e.g. 3 hours). I don't recall this happening on previous versions of MATLAB.
The slow down is small, but significant enough to have an impact on my productivity (sometimes MATLAB needs to wait for up to 1 sec before I can type on the command line or on the editor).
I usually spend hours on debugging mode (e.g. after stopping at a keyboard statement) coding full projects in this mode. I find working on debugging mode convenient to organically grow my code while inspecting my code anytime in execution time.
The odd thing is my machine has 16 GB of RAM and the total size of all workspaces while in debugging mode is usually less than 4 GB. I don't have any other large process running in the background, and my system reports ~8GB of free RAM.
Also, unfortunately MATLAB does not let me call pack from debugging mode; it complains with :
Warning: PACK can only be used from the MATLAB command line.

I have reproduced this behavior after restarting MATLAB, rebooting my system, and on different days. With this, my question/s are:

*

*Has anybody else noticed this? Is there anything I could do to prevent this slowdown without exiting debugging mode?

*Are there any technical notes or statements from Mathworks addressing this issue?

In case it matters, my code is on a network drive, so I added the following on my startup.m file, which should alleviate any impact on performance resulting from it:
system_dependent('RemoteCWDPolicy', 'None');
system_dependent('RemotePathPolicy', 'None');
system_dependent('DirChangeHandleWarn','Never');

A: I have experienced some similar issues.  The problem ended up being that Mathworks changed how Matlab caches files. For some users, it is now storing data in the TMP folder as defined by the environment variables.  This folder was being scanned by anti virus and causing a lot of performance problem.  Of course, IT wouldn't let us exclude the TMP folder from scans.  So we added a line to our start up script that changes the environment variable of TMP to some other location within an excluded folder.
You don't have to worry about changing the variable back or messing up other programs. When applications launch, they copy the environment variables into their own local instance of them.  Any changes made to them only change the local copy of those variables, not the system copy.
Here is the function you will need.
setenv('TEMP', 'C:\TEMP');
I'm not sure if it was TMP or TEMP.  Check your environment variables to be sure.

A: I am using MATLAB R2011 on linux 10, windows 7 (32 bit).
I experienced MATLAB slowing down while printing simple variables in command window.
It turned that there was one .m file loaded in my Editor.
It was a big file with 10000 lines. These lines were simple data that should have been saved as mat file. When i closed this file, the editor was back to its normal speed.


text:
Q: Mysql exception after moving drupal site PDOException: SQLSTATE[HY000] [2013] I just moved my drupal site to another domain/host
I moved the DB and now all my sites. But when I visit the website (juniorsteps.be), I get the following exception:

PDOException: SQLSTATE[HY000] [2013] Lost connection to MySQL server at 'reading initial communication packet', system error: 111 in lock_may_be_available() (line 165 of /home/sites/webhosting/juniorsteps/juniorsteps/www/includes/lock.inc).

I googled it but I still don't find a solution.
Hope someone can help.
UPDATE
As asked the code from line . It's the first line of the following function:
function lock_may_be_available($name) {
  $lock = db_query('SELECT expire, value FROM {semaphore} WHERE name = :name', array(':name' => $name))->fetchAssoc();
  if (!$lock) {
    return TRUE;
  }
  $expire = (float) $lock['expire'];
  $now = microtime(TRUE);
  if ($now > $expire) {
    // We check two conditions to prevent a race condition where another
    // request acquired the lock and set a new expire time. We add a small
    // number to $expire to avoid errors with float to string conversion.
    return (bool) db_delete('semaphore')
      ->condition('name', $name)
      ->condition('value', $lock['value'])
      ->condition('expire', 0.0001 + $expire, '<=')
      ->execute();
  }
  return FALSE;
}

But to be honest I do not think the mistake is in my code since it works perfectly on my development server.

A: Check your settings.php
  $databases = array (

  'default' =>

   array (

    'default' =>

    array (

      'database' => '333333',

      'username' => '333333',

      'password' => '3333333',

      'host' => '122.124.12.09', // check host -> maybe not localhost

      'port' => '3304',  // check port!

      'driver' => 'mysql',

      'prefix' => '',

      ),

    ),

   );

A: I had the same issue. The development version of the site was setup for use with the Acquia development environment. The settings.php was incorrect. Delete all the Acquia specific information from the bottom lines of the sites/default/settings.php file.

A: This answer might help you:
"Lost connection to MySQL server" when trying to connect to remote MySQL server
And readup on the MySQL documentation on error 2013: server has gone away
http://dev.mysql.com/doc/refman/5.0/en/gone-away.html


text:
Q: Saving ArrayList into .txt file - Java I'm trying to convert an ArrayList into a .txt file of my own class (admin) and its superclass (users). I'm saving data like name, surname, antiquity and stuff like that via JOptionPane requested in the main.
So far I've done this, but the problem is that the function stops working right before the writeObject.
Does not pop up any sort of error, i just get de try catch JOptionPane and i'm kinda stuck, will appreciate any help.
    public static void save_txt() {
    String PATH = null;
    try {
        File f;
        JFileChooser fileChooser = new JFileChooser();
        int seleccion = fileChooser.showSaveDialog(null);
        if (seleccion == JFileChooser.APPROVE_OPTION) {
            File JFC = fileChooser.getSelectedFile();
            PATH = JFC.getAbsolutePath();
            PATH = PATH + ".txt";
            f = new File(PATH);
            FileOutputStream fo = new FileOutputStream(f);
            ObjectOutputStream o = new ObjectOutputStream(fo);
            /**
             * ---Stops working there---
             */
            o.writeObject(singleton.ALadmin);
            o.close();
            JOptionPane.showMessageDialog(null, "TXT file saved correctly", "TXT file",
                    JOptionPane.INFORMATION_MESSAGE);
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Error saving TXT", "Error", JOptionPane.ERROR_MESSAGE);
    }
}


text:
Q: explain output from multiple threads output of this program comes as "Inside Thread Inside Thread" , How this is happening?
class MyThread extends Thread
{
    MyThread() {}
    MyThread(Runnable r) {super(r); }
    public void run()
    {
        System.out.print("Inside Thread ");
    }
}
class MyRunnable implements Runnable
{
    public void run()
    {
        System.out.print(" Inside Runnable");
    }
}
class ThreadRunnableBoth
{
    public static void main(String[] args)
    {
        new MyThread().start();
        new MyThread(new MyRunnable()).start();
    }
}

I can understand how first "Inside Thread" is printing but for second time print I am expecting to print "Inside Runnable" but it prints "Inside Thread" , how this is happening ?
Please explain .....thanks a lot

A: In your MyThread class you are overriding the run() method.  That means that even though you are passing in the Runnable into the constructor, only your run method will be called and the Runnable target will be ignored.
Here's the Thread.run() method code that you are overriding:
public void run() {
    if (target != null) {
        target.run();
    }
}

If you want to use your runnable I'd do:
new Thread(new MyRunnable()).start();

That does not use the MyThread class.

A: The run() method of java.lang.Thread simply calls target.run(), where target is the Runnable provided during construction. However, in MyThread, you've overridden this functionality; your version of run() ignores the target and prints "Inside Thread" instead.
One way to fix it is to run your Runnable with an instance of the base Thread class:
new Thread(new MyRunnable()).start();

Other possibilities would be not to override run(), or to call super.run() from your override.

A: The run method in Thread is defined as follows:
public void run() {
  if (target != null) {
    target.run();
  }
}

Because you've overridden run in MyThread, it won't actually call your MyRunnable.
To get the behaviour you're expecting:
new MyThread().start();
new Thread(new MyRunnable()).start();

A: new MyThread().start();

In this case, Thread is created calling the run() method of MyThread class through MyThread() {} constructer.
In the 2nd case, thread is created calling run() method of the same MyThread class through MyThread(Runnable) constructer.

A: change the second call to Thread:
new Thread(new MyRunnable()).start

because your custom thread override the run method that will be called even after you passing your runnable to thread constructor.


text:
Q: SharePoint 2013: How can I replace a video in an asset library? I have a video whose URL has already been distributed, but an edited version of the video now needs to replace the existing one. Is there a way to replace a video in an asset library while maintaining the URL? This can be done in Vimeo, but I can't find a way to do it in SharePoint.

A: So long as the video has the same filename, just upload it again to overwrite the existing version. The URL to the video will remain the same in that case.

A: I also had this problem. What worked for me was opening the video library in Explorer, then navigating into the folder with the video's title to find the actual MP4, making sure the filename of the new version was identical, then copying the video in through Explorer.
After some thinking, I got a prompt to Copy and Replace, Copy but don't replace, or Don't Copy, as one would expect with a file transfer. My Explorer window kept freezing up, though I don't know if that's related or if SP was just being weird today.
It did take FOREVER to upload, and seemed to get hung up around 95%, but it did eventually work. I went back to the library and can play the new version of the video and there were no issues. Checked the documents that linked to the video and the link remained the same.


text:
Q: Cannot run tomcat websocket examples remotely I can run all the websocket examples as long as my browser runs on the same machine as tomcat is running on. But once I try to connect from a remote machine the connection always fails with the error below in my Firebug console. Is there an extra bit of security configuration required to run this? I am using 7.052
"NetworkError: 403 Forbidden - http://remote-host:8080/examples/websocket/chat"

A: Had a proxy configured on my browser and that was what was blocking the access