text:
Q: Generator Power factor Calculation with varying Output Power We are operating a generator (Stirling engine in particular) that outputs a certain active power in the range of 6.5-8.9 kW. The power output is adjusted with pressure variation. The electrical machine is rated at 400V and 15.5A nominal voltage and current. For calculating the power factor is it correct to assume that the power factor varies between 0.62 to 0.83????
I'm not sure whether changing the power output changes the current draw so as to lower the apparent power and maintain the same power factor at different loads, or the apparent power is defined as S=sqrt(3)VI with the nominal values?
One thing to mention, there is no information concerning the set power factor of the engine. The results I provided are the actual output of the engine.
Your help is appreciate in advance

A: The power and the power factor are both determined by the load characteristics and the response of the load to changing frequency and voltage. The engine speed controls the generator's output voltage and frequency. The engine determines the maximum power. If the generator delivers too much electrical power to the load, it will require more torque than the engine can deliver and overload the engine.
The generator has a maximum safe output voltage and output current. The minimum power factor will mostly be determined by the maximum current. Wound-field synchronous generators have additional limitations determined by the maximum field current limitation and control considerations.


text:
Q: Filtering invoice collection by created_at in magento I'm trying to find a way to filter the results of getInvoiceCollection in the function below:
// "eachInvoice" is each of the Invoice object of the order "$orders"
if ($order->hasInvoices()) {
    foreach ($order->getInvoiceCollection() as $eachInvoice) {
        $invoiceIncrementId = $eachInvoice->getIncrementId();
    }
}

Can adding the filter below to $order->getInvoiceCollection()
 $order->getInvoiceCollection()
->addAttributeToFilter('created_at', array(
    'from' => $from_date,
    'to' => $today,
    'date' => true,));

So the entire function would be, is the correct way to do this, it doesn't seem like its right.
// "eachInvoice" is each of the Invoice object of the order "$orders"
    if ($order->hasInvoices()) {
    foreach ($order->getInvoiceCollection()$order->getInvoiceCollection()
    ->addAttributeToFilter('created_at', array( 'from' => $from_date,
    'to' => $today, 'date' => true,)) as $eachInvoice) {
        $invoiceIncrementId = $eachInvoice->getIncrementId();
    }
}

Whats the "correct way" to go about doing this?

A: To get the increment ids as is shown in your sample code there is no need to loop:
$invoiceCollection = $order->getInvoiceCollection();

$invoiceCollection
        ->addAttributeToFilter('created_at', array(
            'from'  => $from,
            'to'    => $to,
        ));

$incrementIds = $invoiceCollection->getColumnValues('increment_id');

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to test for group differences in poisson distributed variables with unequal length? I would like to test group differences in poisson distributed variables. However, I'm struggle to find appropriate approach(using R), which encounters unequal length of the variables in question and returns p values as well:
Here some data:
set.seed(2014)
a<- rnorm(1000, mean = 5, sd = 2)
b<- rnorm(1000, mean = 4, sd = 2)
c<- rnorm(1000, mean = 2, sd = 2)
# First vector
var1<-rpois(100000, exp(3+ 0.5*a - 0.25*b+0.3*c))
# Second vector
var2<-rpois(1000, exp(3+ 0.5*a - 0.5*b+0.6*c))
# Plotting distribution of var1
hist(var1)

# Plotting distribution of var2
hist(var2)

What I found was poisson.exact test from the library(stats)
poisson.test(var1,var2)
#Error in poisson.test(var1, var2) : 'x' and 'T' have incompatible length

Which however seems to use equal vectors.

A: Your variables are conditionally Poisson, but the vector of variates (like var1) is a mixture of Poissons with different parameters.
The function poisson.test is not for comparing vectors that are different length mixtures of Poissons with different parameters.
If - as in your example - you have each poisson parameter appearing a fixed number of times in each vector (once in the second vector, 100 times in the first), then you can compare the sum of the poisson parameters, by summing var1 and var2 (which will then be Poisson with parameters equal to the sum of the parameters supplied to the rpois call, and then $T$ could contain c(100,1)).


text:
Q: Gaussian curvature of the paraboloid I was trying to calculate the Gaussian curvature of the paraboloid with Cartesian equation
$z=\frac{x^2}{a^2}+\frac{y^2}{b^2}$
I first took the parameterization $\psi(u,v)=(u,v,\frac{u^2}{a^2}+\frac{v^2}{b^2})$
and I found $K = \frac{4}{a^2 b^2 \left(1 + \frac{4u^2}{a^4} + \frac{4v^2}{b^4}\right)^2}$
I also wanted to calculate the first and second fundamental form with the parameterization $\psi(u,v)=(ar\cos(u),br\sin(v),r^2)$ to see if it was easier that way and I notice that the Gaussian curvature was zero, and not $K = \frac{4}{a^2 b^2 \left(1 + \frac{4u^2}{a^4} + \frac{4v^2}{b^4}\right)^2}$
Why is that ? Regardless of the parameterization, the Gaussian curvature should be the same, Is the second parameterization wrong ?
*

(calculations)

*

*

$\psi_u=(-ar\sin(u),0,0)$
$\psi_v=(0,br\cos(v),0)$
$E=a^2r^2\sin^2(u), F=0,G=b^2r^2\cos^2(v)$
$\psi_{uu}=(-ar\cos(u),0,0)$
$\psi_{vv}=(0,-br\sin(v),0)$
$\psi_{uv}=(0,0,0)$
$N(u,v)=(0,0,1)$
$e=f=g=0$


text:
Q: GIT_EDITOR set to Notepad++ but still getting Vi If I type "git var GIT_EDITOR" I get
"c:\program files\notepad++\notepad++.exe"
(I have it set in the system environment variable screen
and that's where notepad++.exe is located).
But if I type something like "git log  -p HEAD..FETCH_HEAD" I get vi. Also in other places like "git commit" without -m
How do I get Notepad++ to run instead of vi?
git version 2.37.1.windows.1


text:
Q: C# Interface Debug Information not linked to sources I'm trying to re-jig the layout of a very large solution which has become impossibly hard (and s l o w) to work with. My plan is to create a number of solutions containing related projects, and then use binary references where necessary to link to libraries produced by the other solutions.
The thing we rely on to make this usable is Resharper's Navigate to External Sources functionality, so we can easily browse the source of the projects we are referencing from other solutions. Quite why VS can't do this out of the box is beyond me.
This is all working very nicely for classes with implementation. However, for C# interfaces and classes containing only auto-implemented properties, Resharper isn't able to browse to the sources, and falls back to cruddy metadata viewer.
I used srctool.exe, which comes with the Symbol Server tools in MS Debugging Tools For Windows, to browse the sources listed in the .pdb file, and it's clear that the sources for these interfaces and empty(ish) classes are not referenced in the pdb file. If I switch the auto-implemented properties to those with backing fields, then the source link appears in the pdb.
I'm guessing the sources are excluded because there are no places you could set breakpoints on interfaces and auto-implemented properties.
I'm wondering, though, if there is some exotic compiler option or workaround we can employ to force the PDB file to include references to the source of C# interfaces.
Thanks,
Mark

A: The question doesn't have enough detail.  Shooting off the hip, I'd guess that you tackled the problems with the slow massive solution by converting project references to assembly references.  And used the Release build of those projects as the reference.
And yes, that stumps any tool that tries to find source code files from the PDB.  The release build of a .NET project uses a stripped version of the PDB, all the source code file and line number info has been removed from it.  That's a pretty normal thing to do with real release builds.  Release built code normally is optimized.  That causes code to be re-ordered, no longer matching the logical position of the code in the source file.  Any info you get from the source+line PDB info now tends to get between harmful and useless, you start looking in the wrong place for a problem.
That is however not a concern for IDE tooling or while debugging your app.  The optimizer is automatically disabled in a case like this.  Actually a configuration item in VS: Tools + Options, Debugging, General, "Suppress JIT optimization on module load" option.  Turned on by default.
Clearly any tooling that uses the PDB is going to catatonic when they don't have a chance to find source files.  The fix is to go back to the original project, select the Release configuration again and change a setting: Project + Properties, Build tab, scroll down, Advanced button.  Change the "Debug info" combo from "pdb-only" to "full".  Rebuild the project.
Should fix your problem.  Also revives the debugger, you can step into the source code again.
Don't move files around too much btw, you might stump the chumps again.  At least keep the PDB with the DLL in the same directory.  If the source code is no longer present in the same directory but you checked it out again in another one then you have to tell the IDE about it.  Right-click the solution, Properties, Debug Source Files setting.


text:
Q: What's wrong with my use of ng-class? I'm using ui-router and the view below accesses the controller using the 'Controller As' syntax. I'm adding the 'invalid' class onto the 'shift'-radios container. When form loads you can see both validation required messages (for requestDate and shift). When requestDate and shift are set validation messages disappear. Form's $valid is true. The only problem is that the 'invalid' class on the radio-wrapper div stays.
What am I doing wrong?
<form novalidate ng-submit="_form.$valid && formCtrl.getFormData()" name="_form">

        <datepicker date-format="yyyy-MM-dd">
            <input required ng-model="formCtrl.requestDate" name="requestDate" type="text" />
        </datepicker>

Введите дату

            <label for="<% shift.name %>">
                <input required ng-model="formCtrl.currentShift"
                       name="shift"
                       ng-value="shift"
                       id="<% shift.name %>"
                       type="radio" />

Укажите смену

</form>

A: I think you need to use the $invalid property, which is a boolean, instead of the $error property, which is a hash.
See: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

A: Your ng-class definition is checking the wrong property of the form controller.  You are checking the truthyness of _form.shift.$error.  This object will always exist, even if there are no validation errors.  When you don't have any errors, the value of _form.shift.$error is empty object {} which is truthy.
You should instead check the _form.shift.$invalid property which will properly update whether there are any problems with that form field.

A: There is no _form.shift.  The input shift is declared inside an ng-repeat so it is a property on the _form.
To fix you could for example, move your ng-class inside the ng-repeat and reference the shift using ng-form to create a sub-grouping:

        <input name="shift" />


text:
Q: Error while converting nsdata to nsstring I'm trying to convert NSData to NSString
Here's my code
NSData *Data = [[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"];
NSString *getPhone = [NSString stringWithUTF8String:[Data bytes]];
NSLog(@"%@",getPhone);

And the error I'm getting is
 -[__NSCFData rangeOfString:]: unrecognized selector sent to instance
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFData rangeOfString:]: unrecognized selector sent to instance

A: Make the following change:
NSString getPhone = [[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"];
NSLog(@"%@",getPhone);

hm, strange issue. you can print out getPhone directly after set user defaults to understand if some other part of code does not modify it. [[NSUserDefaults standardUserDefaults] setObject:myPhoneString forKey:@"phoneNumber"];
So try this:
NSLog(@"%@", myPhoneString); // check current value
[[NSUserDefaults standardUserDefaults] setObject:myPhoneString forKey:@"phoneNumber"];
NSLog(@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"]) // check value after set it.

values should be the same, but also you will need to print this value in another place to test if some other code have not modified it. (I mean in place where you print it NSLog(@"%@",getPhone);)
Alos be sure that you set NSString to the NSUserDefault instead of data because as I see in your example you set NSString and output NSString as well so you don't need NSData in this your case.

A: NSString * getPhone = [[NSUserDefaults standardUserDefaults]
    stringForKey:@"phoneNumber"];


text:
Q: User wants to remove a value, but the value isn't on the Binary Tree. How to treat it? I have this code in C for removing nodes or leafs from a Binary Tree, where 'elemento' is a value entered by a user and raiz is my tree.
My problem is: I don't know what to do if user enters a number (elemento) which is not in the tree. I tried some ways, but nothing worked. I want it to print something when the value isn't found.
Here's the function code:
void removerNo(no **raiz, int elemento)
{
 if(elemento < (*raiz)->valor){
    removerNo(&(*raiz)->esq,elemento);
 }
 else if(elemento > (*raiz)->valor){
    removerNo(&(*raiz)->dir,elemento);
 }
 else if((*raiz)->esq!=NULL && (*raiz)->dir!=NULL){
    no *aux = NULL;
    aux = DoisFilhos((*raiz)->dir);
    (*raiz)->valor = aux->valor;
    removerNo(&(*raiz)->dir,(*raiz)->valor);
 } else{
    no *aux = (*raiz);
    if((*raiz)->esq==NULL){
        (*raiz) = (*raiz)->dir;
    }
    else{
         *raiz = (*raiz)->esq;
    }
    free(aux);
 }
};

Thanks.

A: Basically if the element does not equal the current node's value and the current node's relevant child is NULL, the element doesn't exist. e.g.
if ((elemento > (*raiz)->valor && (*raiz)->dir == NULL) || ((elemento < (*raiz)->valor && (*raiz)->esq == NULL)){
    printf("Element not found.");
    return;
}

I would recommend returning a value from removeNo that can represent success/failure.

A: Your code statements assume that if your not less than and not greater than, that you are equal ( and thus present) in a tree.  You should, after finding out your not less than or greater than, check for !null and also that the element exists.
If either the null check is true, or the element exists, you then do something to indicate failure due to the tree being traversed but the value not being present.


text:
Q: Merge a column into a flat file and separate chars So I am trying to convert a column of numbers into a one string, then write each character (number in this case) into a csv as follows.  If there is a better way to solve my problem, please do tell.
set.seed(123)
x = data.frame(numbers = sample(001:999, replace = F))

numbers
847
95
350
298
682
806
98

to a text file that just has
    8479535029862898
to a csv file (END GOAL)
8,4,7,9,6,0,2,9,8,6,2,8,9,8

A: In R, we can paste the elements together and strsplit the whole string by specifying the split as ""
out <- as.numeric(strsplit(paste(x$numbers, collapse = ""), "")[[1]])

and write it to a file
cat(out, file = "fileout.txt")

If we are using python
import pandas as pd
import numpy as np
x = pd.DataFrame({'numbers': np.random.choice(range(1, 1000), size = 999, replace = True)})
list(map(int, list("".join(map(str, list(x['numbers']))))))


text:
Q: Wordpress Woocommerce alt text in images I'm building a Woocommerce and I'm having trouble getting the Alt Text displayed in the front-end.
The code that I'm working on is this:
<?php
    if ( has_post_thumbnail() ) {

        $image_title    = esc_attr( get_the_title( get_post_thumbnail_id() ) );
        $image_caption  = get_post( get_post_thumbnail_id() )->post_excerpt;
        $image_alt      = esc_attr( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) );
        $image_link     = wp_get_attachment_url( get_post_thumbnail_id() );
        $image          = get_the_post_thumbnail( $post->ID, apply_filters( 'single_product_large_thumbnail_size', 'shop_single' ), array(
            'title' => $image_title,
            'alt'   => $image_alt
            ) );

        $attachment_count = count( $product->get_gallery_attachment_ids() );

        if ( $attachment_count > 0 ) {
            $gallery = '[product-gallery]';
        } else {
            $gallery = '';
        }

        echo apply_filters( 'woocommerce_single_product_image_html', sprintf( '%s', $image_link, $image_caption, $image ), $post->ID );

    } else {

        echo apply_filters( 'woocommerce_single_product_image_html', sprintf( '', wc_placeholder_img_src(), __( 'Placeholder', 'woocommerce' ) ), $post->ID );

    }
?>

<?php do_action( 'woocommerce_product_thumbnails' ); ?>

The code that is this spitting is:

I don't get why alt is still empty?

A: There's an _(underscore) before wp_get_attachment_image, remove that to get "alt" value...
Reference: https://codex.wordpress.org/Function_Reference/wp_get_attachment_image


text:
Q: How can I get video duration by using vimeo javascript API? I am having a premium channel on vimeo. I am trying to put a list of videos and their duration on my website. They have an example by using the event listeners. But as I am interested in simple text output of video duration. So How can I do it ?

A: Use getDuration() from the Vimeo player javascript API:
player.getDuration().then(function(duration) {
    // duration = the duration of the video in seconds
}).catch(function(error) {
    // an error occurred
});

Source: https://github.com/vimeo/player.js/blob/master/README.md#getduration-promisenumber-error

A: const iframe = document.querySelector('iframe');
  const player = new Player(iframe);

  player.loadVideo(123456).then(() => {
    player.ready().then(() => {
      player.getDuration().then((data) => console.log(data));
    }).catch((err) => console.log(err));
  })

A: (function () {
        var vimeoPlayers = document.querySelectorAll('iframe'), player;

        for (var i = 0, length = vimeoPlayers.length; i


text:
Q: I used ajax to make a sql statment but nothing seems to happen I put this code but nothing seems to happen when i check my mysql database
$.ajax("ajax.php?type=insert&giftcode="+newarray[$x]+"&winner=winner1");

and i ajax.php i put
require_once('setup.php'); //where i connect to the database

if ($_GET['type']== "insert")
{

    $query='UPDATE prizes SET winner='+$_GET['winner'] +',time='+NOW()+',WHERE prizecode='+$_GET[giftcode]+'LIMIT 1';
    $insert_query = $db->query($query) ;
    checkDBError($insert_query);

    echo("something happened");

}

there is no problem with the database itself as there is no problem with connection as it works on different parts of the code but i can see what i did wrong

A: You used + signs in your query. That's only valid in javascript. Please use points!
Also, the , sign before WHERE-statement is incorrect.
if($_GET['type']== "insert") {
    $query = 'UPDATE prizes SET winner = '.$_GET['winner'].', time = NOW() WHERE prizecode = '.$_GET['giftcode'].' LIMIT 1';
    $insert_query = $db->query($query) ;
    checkDBError($insert_query);

    echo("something happened");
}


text:
Q: how to resolve undeclared inclusion(s) in rule while doing cross-compilation using Bazel I'm trying to understand Bazel and do cross-compilation for a simple c++ file
Here is my example:
├── aarch64_compiler
│   ├── BUILD
│   ├── cc_toolchain_config.bzl
│   └── CROSSTOOL
├── aarch64_compiler.BUILD
├── helloworld
│   ├── BUILD.bazel
│   └── src
│       └── helloworld.cpp
└── WORKSPACE

and here is each file,
WORKSPACE
new_local_repository(
    name = "aarch64_compiler",
    path = "/",
    build_file = "aarch64_compiler.BUILD",
)

aarch64_compiler.BUILD
package(default_visibility = ['//visibility:public'])

filegroup(
  name = 'gcc',
  srcs = [
    'usr/bin/aarch64-linux-gnu-gcc',
  ],
)

filegroup(
  name = 'ar',
  srcs = [
    'usr/bin/aarch64-linux-gnu-ar',
  ],
)

filegroup(
  name = 'ld',
  srcs = [
    'usr/bin/aarch64-linux-gnu-ld',
  ],
)

filegroup(
  name = 'nm',
  srcs = [
    'usr/bin/aarch64-linux-gnu-nm',
  ],
)

filegroup(
  name = 'objcopy',
  srcs = [
    'usr/bin/aarch64-linux-gnu-objcopy',
  ],
)

filegroup(
  name = 'objdump',
  srcs = [
    'usr/bin/aarch64-linux-gnu-objdump',
  ],
)

filegroup(
  name = 'strip',
  srcs = [
    'usr/bin/aarch64-linux-gnu-strip',
  ],
)

filegroup(
  name = 'as',
  srcs = [
    'usr/bin/aarch64-linux-gnu-as',
  ],
)

filegroup(
  name = 'compiler_pieces',
  srcs = glob([
    'usr/lib/gcc-cross/aarch64-linux-gnu/7/**',
    'usr/aarch64-linux-gnu/**',
  ]),
)

filegroup(
  name = 'compiler_components',
  srcs = [
    ':gcc',
    ':ar',
    ':ld',
    ':nm',
    ':objcopy',
    ':objdump',
    ':strip',
    ':as',
  ],
)

aarch64_compiler/BUILD
package(default_visibility = ["//visibility:public"])

load(":cc_toolchain_config.bzl", "cc_toolchain_config")

cc_toolchain_suite(
  name = 'toolchain',
  toolchains = {
  'aarch64|compiler':':gcc-linux-aarch64',
  "aarch64": ":gcc-linux-aarch64",
  },
)

filegroup(
    name = "empty",
    srcs = [],
)

filegroup(
    name = "arm_linux_all_files",
    srcs = [
    "@aarch64_compiler//:compiler_pieces",
    ],
)

cc_toolchain_config(name = "aarch64_toolchain_config")

cc_toolchain(
  name = 'gcc-linux-aarch64',
  toolchain_identifier = "aarch64-linux-gnu",
  toolchain_config = ":aarch64_toolchain_config",
  all_files = ':arm_linux_all_files',
  compiler_files = ':arm_linux_all_files',
  #cpu = 'aarch64',
  dwp_files = ':empty',
  #dynamic_runtime_libs = [':empty'],
  linker_files = ':arm_linux_all_files',
  objcopy_files = ':arm_linux_all_files',
  #static_runtime_libs = [':empty'],
  strip_files = ':arm_linux_all_files',
  supports_param_files = 1,
)

aarch64_compiler/cc_toolchain_config.bzl
# toolchain/cc_toolchain_config.bzl:
load("@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl", "tool_path")

def _impl(ctx):
    tool_paths = [
        tool_path(
            name = "gcc",
            path = "/usr/bin/aarch64-linux-gnu-gcc",
        ),
        tool_path(
            name = "ld",
            path = "/usr/bin/aarch64-linux-gnu-ld",
        ),
        tool_path(
            name = "ar",
            path = "/usr/bin/aarch64-linux-gnu-ar",
        ),
        tool_path(
            name = "cpp",
            path = "/usr/bin/aarch64-linux-gnu-cpp",
        ),
        tool_path(
            name = "gcov",
            path = "/usr/bin/aarch64-linux-gnu-gcov",
        ),
        tool_path(
            name = "nm",
            path = "/usr/bin/aarch64-linux-gnu-nm",
        ),
        tool_path(
            name = "objdump",
            path = "/usr/bin/aarch64-linux-gnu-objdump",
        ),
        tool_path(
            name = "strip",
            path = "/usr/bin/aarch64-linux-gnu-strip",
        ),
    ]
    return cc_common.create_cc_toolchain_config_info(
        ctx = ctx,
        toolchain_identifier = "aarch64-linux-gnu",
        host_system_name = "x86_64-unknown-linux-gnu",
        target_system_name = "aarch64-unknown-linux-gnu",
        target_cpu = "aarch64",
        target_libc = "unknown",
        compiler = "aarch64",
        abi_version = "unknown",
        abi_libc_version = "unknown",
        tool_paths = tool_paths,
    )

cc_toolchain_config = rule(
    implementation = _impl,
    attrs = {},
    provides = [CcToolchainConfigInfo],
)

aarch64_compiler/CROSSTOOL
major_version: "local"
minor_version: ""
default_target_cpu: "aarch64"

default_toolchain {
  cpu: "aarch64"
  toolchain_identifier: "aarch64-linux-gnu"
}

toolchain {
  abi_version: "aarch64"
  abi_libc_version: "aarch64"
  builtin_sysroot: ""
  compiler: "compiler"
  host_system_name: "aarch64"
  needsPic: true
  supports_gold_linker: true
  supports_incremental_linker: false
  supports_fission: false
  supports_interface_shared_objects: false
  supports_normalizing_ar: false
  supports_start_end_lib: true
  target_libc: "aarch64"
  target_cpu: "aarch64"
  target_system_name: "aarch64"
  toolchain_identifier: "aarch64-linux-gnu"

  cxx_flag: "-std=c++11"
  linker_flag: "-lstdc++"
  linker_flag: "-lm"
  linker_flag: "-fuse-ld=gold"
  linker_flag: "-Wl,-no-as-needed"
  linker_flag: "-Wl,-z,relro,-z,now"
  linker_flag: "-pass-exit-codes"

  cxx_builtin_include_directory: "/usr/aarch64-linux-gnu/include/c++/7/"
  cxx_builtin_include_directory: "/usr/aarch64-linux-gnu/include/c++/7/backward"
  cxx_builtin_include_directory: "/usr/aarch64-linux-gnu/include/"
  cxx_builtin_include_directory: "/usr/lib/gcc-cross/aarch64-linux-gnu/7/include"
  cxx_builtin_include_directory: "/usr/lib/gcc-cross/aarch64-linux-gnu/7/include-fixed"

  objcopy_embed_flag: "-I"
  objcopy_embed_flag: "binary"

  unfiltered_cxx_flag: "-fno-canonical-system-headers"
  unfiltered_cxx_flag: "-Wno-builtin-macro-redefined"
  unfiltered_cxx_flag: "-D__DATE__=\"redacted\""
  unfiltered_cxx_flag: "-D__TIMESTAMP__=\"redacted\""
  unfiltered_cxx_flag: "-D__TIME__=\"redacted\""
  compiler_flag: "-U_FORTIFY_SOURCE"
  compiler_flag: "-fstack-protector"
  compiler_flag: "-Wall"
  compiler_flag: "-Wunused-but-set-parameter"
  compiler_flag: "-Wno-free-nonheap-object"
  compiler_flag: "-fno-omit-frame-pointer"

  tool_path { name: "ld" path: "/usr/bin/aarch64-linux-gnu-ld" }
  tool_path { name: "cpp" path: "/usr/bin/aarch64-linux-gnu-cpp" }
  tool_path { name: "dwp" path: "/usr/bin/aarch64-linux-gnu-dwp" }
  tool_path { name: "gcov" path: "/usr/bin/aarch64-linux-gnu-gcov" }
  tool_path { name: "nm" path: "/usr/bin/aarch64-linux-gnu-nm" }
  tool_path { name: "objcopy" path: "/usr/bin/aarch64-linux-gnu-objcopy" }
  tool_path { name: "objdump" path: "/usr/bin/aarch64-linux-gnu-objdump" }
  tool_path { name: "strip" path: "/usr/bin/aarch64-linux-gnu-strip" }
  tool_path { name: "gcc" path: "/usr/bin/aarch64-linux-gnu-gcc" }
  tool_path { name: "ar" path: "/usr/bin/aarch64-linux-gnu-ar" }

  compilation_mode_flags {
    mode: DBG
    # Enable debug symbols.
    compiler_flag: "-g"
  }
  compilation_mode_flags {
    mode: OPT

    # No debug symbols.
    # Maybe we should enable https://gcc.gnu.org/wiki/DebugFission for opt or
    # even generally? However, that can't happen here, as it requires special
    # handling in Bazel.
    compiler_flag: "-g0"

    # Conservative choice for -O
    # -O3 can increase binary size and even slow down the resulting binaries.
    # Profile first and / or use FDO if you need better performance than this.
    compiler_flag: "-O2"
    compiler_flag: "-D_FORTIFY_SOURCE=1"

    # Disable assertions
    compiler_flag: "-DNDEBUG"

    # Removal of unused code and data at link time (can this increase binary size in some cases?).
    compiler_flag: "-ffunction-sections"
    compiler_flag: "-fdata-sections"
    linker_flag: "-Wl,--gc-sections"
  }
  linking_mode_flags { mode: DYNAMIC }

    feature {
      name: 'coverage'
      provides: 'profile'
      flag_set {
        action: 'preprocess-assemble'
        action: 'c-compile'
        action: 'c++-compile'
        action: 'c++-header-parsing'
        action: 'c++-header-preprocessing'
        action: 'c++-module-compile'
        flag_group {
        flag: '-fprofile-arcs'
        flag: '-ftest-coverage'
        }
      }

      flag_set {
        action: 'c++-link-interface-dynamic-library'
        action: 'c++-link-dynamic-library'
        action: 'c++-link-executable'
        flag_group {
        flag: '-lgcov'
        }
      }
    }
}

helloworld/BUILD.bazel
cc_binary(
    name = "helloworld",
    srcs = [ "src/helloworld.cpp" ],
)

helloworld/src/helloworld.cpp
#include <iostream>

int main() {
    std::cout << "Hello World from BAZEL" << std::endl;
}

The bazel command used: bazel build //helloworld:helloworld --cpu=aarch64 --crosstool_top=//aarch64_compiler:toolchain --host_crosstool_top=@bazel_tools//tools/cpp:toolchain --verbose_failures
and I got this error:
ERROR: /data/cross-compile/bazel_sample/helloworld/BUILD.bazel:1:1: undeclared inclusion(s) in rule '//helloworld:helloworld':
this rule is missing dependency declarations for the following files included by 'helloworld/src/helloworld.cpp':
  '/usr/aarch64-linux-gnu/include/stdc-predef.h'
  '/usr/aarch64-linux-gnu/include/c++/7/iostream'
  '/usr/aarch64-linux-gnu/include/c++/7/aarch64-linux-gnu/bits/c++config.h'
  '/usr/aarch64-linux-gnu/include/c++/7/aarch64-linux-gnu/bits/os_defines.h'
  '/usr/aarch64-linux-gnu/include/features.h'
  '/usr/aarch64-linux-gnu/include/sys/cdefs.h'
  '/usr/aarch64-linux-gnu/include/bits/wordsize.h'
  '/usr/aarch64-linux-gnu/include/bits/long-double.h'
  '/usr/aarch64-linux-gnu/include/gnu/stubs.h'
  .....

what is the missing in my configurations?

A: There are 2 things that might help:

*

*You need to include these search path in the compilation command with compiler_flag.

*You might also need to add -no-canonical-prefixes in compiler_flag, otherwise bazel might not be able to match understand that the path used is the same as the one declared.


text:
Q: R nls singular gradient I've tried searching the other threads on this topic but none of the fixes are working for me. I have the results of a natural experiment and I want to show the number of consecutive occurrences of an event fit an exponential distribution. My R shell is pasted below
f <- function(x,a,b) {a * exp(b * x)}
> x
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
[26] 26 27
> y
 [1] 1880  813  376  161  100   61   31    9    8    2    7    4    3    2    0
[16]    1    0    0    0    0    0    1    0    0    0    0    1
> dat2
    x    y
1   1 1880
2   2  813
3   3  376
4   4  161
5   5  100
6   6   61
7   7   31
8   8    9
9   9    8
10 10    2
11 11    7
12 12    4
13 13    3
14 14    2
> fm <- nls(y ~ f(x,a,b), data = dat2, start = c(a=1, b=1))
Error in numericDeriv(form[[3L]], names(ind), env) :
  Missing value or an infinity produced when evaluating the model
> fm <- nls(y ~ f(x,a,b), data = dat2, start = c(a=7, b=-.5))
Error in nls(y ~ f(x, a, b), data = dat2, start = c(a = 7, b = -0.5)) :
  singular gradient
> fm <- nls(y ~ f(x,a,b), data = dat2, start = c(a=7,b=-.5),control=nls.control(maxiter=1000,warnOnly=TRUE,minFactor=1e-5,tol=1e-10),trace=TRUE)
4355798 :   7.0 -0.5
Warning message:
In nls(y ~ f(x, a, b), data = dat2, start = c(a = 7, b = -0.5),  :
  singular gradient

Please forgive the bad formatting, first post here. x contains bins of a histogram, y contains the number of occurrences of each bin in that histograms. dat2 cuts off at 14 since the 0 count bins would throw off the exponential regression, and I really only need to fit those first 14. Those bins which have counts beyond 14 I have biological reason to believe they are special.
The issue I initially got was infinity, which I don't get since none of the values are 0. After giving decent starting values as suggested by a different post here I get the singular gradient error. The only other posts I saw with that had more variables, I tried increasing the number of iterations but that did not succeed. Any help is appreciated.
A

A: Please check nlsLM function in minpack.lm package. This is a more robust version of nls and can handle data with zero residual sum of squares.
https://www.r-bloggers.com/a-better-nls/

A: 1) linearize to get starting values You need better starting values:
# starting values
fm0 <- nls(log(y) ~ log(f(x, a, b)), dat2, start = c(a = 1, b = 1))

nls(y ~ f(x, a, b), dat2, start = coef(fm0))

giving:
Nonlinear regression model
  model: y ~ f(x, a, b)
   data: x
        a         b
4214.4228   -0.8106
 residual sum-of-squares: 2388

Number of iterations to convergence: 6
Achieved convergence tolerance: 3.363e-06

1a) Similarly we could use lm to get the initial value by writing
y ~ a * exp(b * x)

as
y ~ exp(log(a) + b * x)

and taking logs of both to get a model linear in log(a) and b:
log(y) ~ log(a) + b * x

which can be solved using lm:
fm_lm <- lm(log(y) ~ x, dat2)
st <- list(a = exp(coef(fm_lm)[1]), b = coef(fm_lm)[2])
nls(y ~ f(x, a, b), dat2, start = st)

giving:
Nonlinear regression model
  model: y ~ f(x, a, b)
   data: dat2
       a        b
4214.423   -0.811
 residual sum-of-squares: 2388

Number of iterations to convergence: 6
Achieved convergence tolerance: 3.36e-06

1b) We can also get it to work by reparameterizing.  In that case a = 1 and b = 1 will work provided we transform the initial values in line with the parameter transformation.
nls(y ~ exp(loga + b * x), dat2, start = list(loga = log(1), b = 1))

giving:
Nonlinear regression model
  model: y ~ exp(loga + b * x)
   data: dat2
  loga      b
 8.346 -0.811
 residual sum-of-squares: 2388

Number of iterations to convergence: 20
Achieved convergence tolerance: 3.82e-07

so b is as shown and  a = exp(loga) = exp(8.346) = 4213.3
2) plinear  Another possibility that is even easier is to use alg="plinear" in which case starting values are not needed for the parameters entering linearly.  In that case the starting value of b=1 in the question seems sufficient.
nls(y ~ exp(b * x), dat2, start = c(b = 1), alg = "plinear")

giving:
Nonlinear regression model
  model: y ~ exp(b * x)
   data: dat2
        b      .lin
  -0.8106 4214.4234
 residual sum-of-squares: 2388

Number of iterations to convergence: 11
Achieved convergence tolerance: 2.153e-06


text:
Q: Seguridad PHP SESSION con JS y AJAX Un saludo.
El caso es que estoy preparando una app web con PHP y JS y no me gusta mezclar código HTML en los PHP como se suele hacer al crear ficheros index.php y de ese estilo.
Quiero dejar los ficheros .html y .js por un lado y los .php para la conexión con phpmyadmin
Ahora mi pregunta. Resulta que si creo una seguridad con SESSION en PHP, como lo llamo a través de AJAX, aunque sea de forma síncrona, se ve que el .html carga contenido y algo se ve antes de que se redirija, ya se se redirije en la respuesta del AJAX.
Si hago un fichero .php si funciona, porque la redirección la hago arriba del todo con header, pero con AJAX no me viene como poder hacerlo.
Alguna idea?


text:
Q: Ember - Fetching live records with meta information I have created a comment model and  trying to fetch all comments records. But I need a meta info total comments which is getting as a separate attribute outside comments array.
I am using Ember store.query to fetch records from rest service(I tried store.findAll, but it is giving me only record array of comments in promise response. Is it possible to modify that?). I am getting the records with total comments(meta) while using store.query(), but that record array is not getting updated when we save new records.
After doing some analysis I found that we can use filter for loading the live record, but filter is now deprecated in Ember(Ember 2.5.1). From the documentation It is clear that we can use ember-data-filter for loading live record. But I am confused to use that addon(Mentioned like it has some memory leakage issue) and not sure whether I will get meta information from response. Is there is any other way to fetch live records with meta information from the response.
Anyone please suggest a solution

A: If you want an array of all records that updates as new records are populated you can use peekAll which returns a live record array.
Added Code sample:
loadRecords: function (){
    this.set('allComments', store.peekAll('comment'));
    this.store.findAll('comment');
},

recordCount: Ember.computed.alias('allComments.length')

A: After doing some analysis, I found a solution to access meta data using store.findAll(). We can use typeMapFor in the findAll response to get the meta info in the response
store.typeMapFor(response.type)

Full code below,
store.findAll("comment").then(function(response) {
    var meta = store.typeMapFor(response.type);

    // your meta info will be in meta.metadata
    // var totalComments = meta.metadata.totalComments;
});

And the response record array is liveRecords which will get updated automatically, if we save new records.
store.query("comment").then(function(response) {
    var meta = response.get("meta");
    // We will get meta like this but reponse record array is not a liveRecords
});

Response getting from store.query() is just a recordArray (not liveRecords) which will not get updated with new records


text:
Q: Como consumir WebService da PrefeituraSP para NFS-e Erro "cliente 'Anonymous'" VB.NET Estou desenvolvendo um projeto que irá enviar XMLs ao WS da receita federal, fiz a referencia usando o seguinte URL: https://nfe.prefeitura.sp.gov.br/ws/lotenfe.asmx
Mas quando passa pela Função de Teste EnvioRPS() da o seguinte erro:
  "A solicitação HTTP está proibida com o esquema de autenticação de cliente 'Anonymous'"
Para fazer um teste com o WS estou fazendo o seguinte, em um Evento Button_Click :
    Dim WS As New WebServiceNFSE_TESTE.LoteNFeSoapClient

    Dim Busca As X509Certificate2 = Buscar_Certificado_Nome("")

    'Teste
    MessageBox.Show(WS.EnvioRPS(1, ""))

Função que busca o certificado:
 Public Shared Function Buscar_Certificado_Nome(_nm_certificado As String) As X509Certificate2
    Dim X509_certificado As New X509Certificate2()
    Dim X509_store As New X509Store("MY", StoreLocation.CurrentUser)
    X509_store.Open(OpenFlags.[ReadOnly] Or OpenFlags.OpenExistingOnly Or OpenFlags.IncludeArchived)
    Dim X509_collection0 As X509Certificate2Collection = DirectCast(X509_store.Certificates, X509Certificate2Collection)
    Dim X509_collection1 As X509Certificate2Collection = DirectCast(X509_collection0.Find(X509FindType.FindByTimeValid, DateTime.Now, False), X509Certificate2Collection)
    Dim X509_collection2 As X509Certificate2Collection = DirectCast(X509_collection0.Find(X509FindType.FindByKeyUsage, X509KeyUsageFlags.DigitalSignature, False), X509Certificate2Collection)

    If _nm_certificado = "" Then
        Dim scollection As X509Certificate2Collection = X509Certificate2UI.SelectFromCollection(X509_collection2, "Certificado(s) Digital(is) disponível(is)", "Selecione o Certificado Digital para uso no aplicativo", X509SelectionFlag.SingleSelection)
        If scollection.Count = 0 Then
            'Nenhum certificado escolhido
            X509_certificado.Reset()
        Else
            X509_certificado = scollection(0)
        End If
    Else
        Dim scollection As X509Certificate2Collection = X509_collection1.Find(X509FindType.FindByThumbprint, "ce c9 ed 7a b6 54 fe fe 1b bf 31 78 ef 5f 74 be be 6e e8 12", True)
        If scollection.Count = 0 Then
            'Nenhum certificado válido foi encontrado com o nome informado
            X509_certificado.Reset()
        Else
            X509_certificado = scollection(0)
        End If
    End If
    X509_store.Close()
    Return X509_certificado
End Function

A: Fazendo um Binding Customizado da seguinte forma, consegui consumir o WS e ter o retorno usando o seguinte código:
        Dim Certificado As X509Certificate2
    Dim WS As WebServiceNFSE_TESTE.LoteNFeSoapClient

    Dim httpstransport As New ServiceModel.Channels.HttpsTransportBindingElement

    Try
        Certificado = Buscar_Certificado_Nome("")
        httpstransport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard
        httpstransport.ManualAddressing = False
        httpstransport.MaxBufferPoolSize = 524288
        httpstransport.MaxReceivedMessageSize = 65536
        httpstransport.AllowCookies = False
        httpstransport.BypassProxyOnLocal = False
        httpstransport.KeepAliveEnabled = True
        httpstransport.MaxBufferSize = 65536
        httpstransport.TransferMode = TransferMode.Buffered
        httpstransport.UnsafeConnectionNtlmAuthentication = True
        httpstransport.UseDefaultWebProxy = True
        httpstransport.RequireClientCertificate = True

        Dim MessageEncoding As New TextMessageEncodingBindingElement()
        MessageEncoding.MessageVersion = MessageVersion.Soap12
        MessageEncoding.WriteEncoding = Encoding.UTF8
        MessageEncoding.MaxReadPoolSize = 64
        MessageEncoding.MaxWritePoolSize = 16

        Dim CustomBinding As New ServiceModel.Channels.CustomBinding(MessageEncoding, httpstransport)

        Dim uri As String() = {"https://nfe.prefeitura.sp.gov.br/ws/lotenfe.asmx"}
        Dim EndpointAddress As New ServiceModel.EndpointAddress(uri(0))

         WS = New WebServiceNFSE_TESTE.LoteNFeSoapClient(CustomBinding, EndpointAddress)
         WS.ClientCredentials.ClientCertificate.Certificate = Certificado

        Dim oXml As New XmlDocument
        oXml.Load("C:\PedidoEnvioRPS.xml")

         MsgBox(WS.EnvioRPS(1, oXml.InnerText))

    Catch ex As Exception
        MsgBox(ex.Message)
    End Try


text:
Q: How to undo a reset after push? I wanted to revert a pushed commit and because of lack of knowledge I did
git reset --hard HEAD~1
git push -f

Now , after this , people who already had pulled the commit which i reset , they are not able to go back .
git pull does not take them 1 commit back .
How do I solve this mess now ? Any suggestions.

A: Disclaimer : In all cases, before doing anything, be sure to :

*

*discuss it in details with your team so that you all agree on a plan

*everyone saves/commits their local changes before reseting anything, either with git stash like hinted at by simbo1905 in his comment, or by commiting on the branch then backing it up with
git branch backup-branch old-branch

Now in short, 2 approaches, depending on the specifics of your project and the nature of the changes you just pushed :
1) either everyone goes for your version
Every other user updates his/her local branch with
git fetch
git reset --hard <remoteName>/<branchName>

2) or their version is to be kept
In this case, one of the other users with the old ref for this branch* does a git push -f <remoteName> <branchName>, and you are to do the above operations to sync back with them.
* (in case noone can do that for any reason, you could also recover the ref locally from the branch's reflog and push it again to remote with force, it's just often quicker to push it from the repo of someone with the old ref)


text:
Q: goog.net.xhrio.send not calling the server I am calling goog.net.XhrIo from within this onclick event
goog.events.listen(invBtn, goog.ui.Component.EventType.ACTION,
        function(e) {

   goog.net.XhrIo.sent('http://remotehost.com:8080/customer/add');
 (update :typo here send instead of sent )

This is the very basic task I want to accomplish but this call doesn't even reach the server. I also tried passing url as goog.Uri , doesn't help.
I wonder what is stopping from making this call to the server, I tried both host name and ip address but neither helps. It just does nothing.
Is there any thing I can do to see why this call fails to even reach the server.
Appreciate any help
regards
Eddie

A: In your plovr config file, set the warning level to VERBOSE:

// config.js
{
  "paths": "js",
  "mode": "ADVANCED",
  "level": "VERBOSE"
}

With VERBOSE warnings enabled, running your program shows the following warning:

JSC_INEXISTENT_PROPERTY: Property sent never defined on goog.net.XhrIo ...
goog.net.XhrIo.sent('http://remotehost.com:8080/customer/add');
^

Try changing goog.net.XhrIo.sent(); to goog.net.XhrIo.send();.
In addition, you may want to pass a callback function to the XhrIo send function as follows:
goog.net.XhrIo.send('http://remotehost.com:8080/customer/add', function(e) {
  var xhr = /** @type {goog.net.XhrIo} */ (e.target);
  alert(xhr.getResponseText());
});

Another common pattern is to create an xhr object and register an event listener:
var xhr = new goog.net.XhrIo();
goog.events.listenOnce(xhr, goog.net.EventType.COMPLETE, function(e) {
  var xhr = /** @type {goog.net.XhrIo} */ (e.target);
  alert(xhr.getResponseText());
  xhr.dispose(); // Dispose of the XHR if it is not going to be reused.
});
xhr.send('http://remotehost.com:8080/customer/add');

Further Reading
Closure: The Definitive Guide, Chapter 7: Client-Server Communication


text:
Q: firefox drag and drop image to file explorer Since Firefox v68 the drag and dropping of an image from the browser (firefox.exe) to Windows File Explorer or Desktop (explorer.exe) is not working anymore.

What I tried so far:

*

*Tried turning it off and on again didn't work

*Started firefox in safemode with no add-ons didn't work

*Started windows in safe mode and then started firefox in safemode with no add-ons didn't work

*Drag n Drop + holding Ctrl key didn't work Drag n Drop + holding Alt key didn't work

*Created a new profile didn't work

*Re-installed v68 didn't work

*uninstalled and erased ALL firefox files, then installed v68 didn't work

*Installed v68 on a fresh install of Windows didn't work

*Installed a fresh copy of Windows on a freshly assembled computer and made a fresh installation of v68 Firefox didn't work

*Reverting to Firefox v67 did work !!
So after investigation it must be an issue with the Firefox 68 update.

A: This is caused by a new launcher process which forces Firefox at a medium integrity level when it detects that it is running at a high integrity level, as is the case when User Account Control (UAC) is disabled in Windows. Processes with lower integrity levels cannot send data to higher integrity levels (such as Windows Explorer when running as Administrator). There are several workarounds provided by Mozilla:

*

*Enable the default level of UAC in Windows

*Keep UAC disabled and use workarounds. For example, to copy an image to the desktop, instead of drag-and-drop, use right-click > Copy Image, then right-click > Paste on the desktop.

*Keep UAC disabled and change how Firefox starts up by adding a command-line switch to your Firefox shortcut (-no-deelevate). For example "C:\Program Files (x86)\Mozilla Firefox\firefox.exe" -no-deelevate
This bypasses the reduction of Firefox's privilege level.

*Keep UAC disabled and disable the launcher process, which both bypasses the reduction of Firefox's privilege level and reduces protection against DLL injection (least secure). This can be done by going to about:config in the URL bar and setting browser.launcherProcess.enabled to False
Sources:
https://support.mozilla.org/en-US/kb/windows-administrator-launcher-process-error-fix
https://support.mozilla.org/en-US/questions/1264292?page=2#answer-1238489
https://support.mozilla.org/en-US/questions/1264413#answer-1239116

A: After some research I found the issue was caused by a new security feature that was released to the general public in Firefox 68. You can disable the new feature by adding this command to your Firefox (taskbar) shortcut:
-no-deelevate
example: "C:\Program Files\Mozilla Firefox\firefox.exe" -no-deelevate

watch out for the quotes when there are spaces in your startup path. After restarting Firefox with this command the problem was solved!


text:
Q: При запуске jar файла выдает ошибку : Error: JavaFx runtime components are missing, and are required to run this application Продолжил бороться с данной проблемой. Скачал последний javaFX-sdk версии 17.0.0.1 (September 2021).
Через батник пытаюсь открыть таким образом:
java --module-path C:\Program_Files\JavaFX\javafx-sdk\lib --add-modules javafx.controls,javafx.fxml,javafx.graphics -jar C:\Users\USER\IdeaProjects\keys\out\artifacts\keys_jar\keys.jar

Через intellij приложение запускается без проблем.
Если нужна дополнительная информация, только скажите.

A: Я запускаю так:
java --module-path c:\Java\javafx-sdk-11.0.2\lib --add-modules ALL-MODULE-PATH -jar [fullpath]\myjar.jar


text:
Q: SQL check if value exists in a partition using CASE WHEN without any JOIN I have a table with similar look with much more possible pages, ids and other columns, but those are the ones I'm stuck on.
+--------+-------+------+--+
| page   | id    | time |  |
+--------+-------+------+--+
| Page1  | A     |    1 |  |
| Page2  | A     |    3 |  |
| Page3  | A     |    5 |  |
| Page1  | A     |    3 |  |
| Page5  | A     |    4 |  |
| Page6  | B     |    3 |  |
| Page6  | B     |    7 |  |
| Page4  | B     |    4 |  |
+--------+-------+------+--+

My goal is to check if the page appears in a partition of id and if that is true than put 1 for each row of a group in new column.
f.e. if I'm trying to check for 'Page4' than it should look like this.
+--------+-------+------+-----------+
| page   | id    | time | condition |
+--------+-------+------+-----------+
| Page1  | A     |    1 | 0         |
| Page2  | A     |    3 | 0         |
| Page3  | A     |    5 | 0         |
| Page1  | A     |    3 | 0         |
| Page5  | A     |    4 | 0         |
| Page6  | B     |    3 | 1         |
| Page6  | B     |    7 | 1         |
| Page4  | B     |    4 | 1         |
+--------+-------+------+-----------+

I want to use CASE WHEN because I'm going to write more complex conditions later. And most annoying part for me is that I can't use any of JOIN because I'm getting a permission error when using temporary tables.
At the moment I want it to be something like this, but this one doesn't work, giving me the syntax error:
SELECT *,
CASE WHEN page = 'Page4' OVER (PARTITION BY id) THEN 1 ELSE  0 END as condition
FROM my_table

Is there any way to implement check whether the value exists in any row of a partition by id using CASE WHEN statement? Or maybe there is some other solution I just don't see?
I'm using Redshift.

A: You want logic like this:
SELECT t.*,
       MAX(CASE WHEN page = 'Page4' THEN 1 ELSE 0 END) OVER (PARTITION BY id) as condition
FROM my_table t;

You have the right idea.  The syntax is just off a bit.


text:
Q: boost interprocess : shared memory and stl types I have a simple struct :
struct MyType
{
    std::string name;
    std::string description;
}

and I'm putting it in a shared memory :
managed_shared_memory sharedMemory(open_or_create, "name", 65535);
MyType* pType = sharedMemory.construct<MyType>("myType")();
// ... setting pType members ...

If the two applications communicating with the shared memory are built using different version of Visual Studio (different version of stl implementation) should I put native types in the shared memory (e.g. char*) instead of stl types?
Edit :
I tried with
typedef boost::interprocess::basic_string<char> shared_string;

and it works!

A: You should use
typedef boost::interprocess::basic_string<char> shared_string;
struct MyType
{
    shared_string name;
    shared_string description;
}

A: Boost.Interprocess often offers replacements for STL types, for usage in shared memory.  std::string, especially when just a member of a struct, will not be accessible from another process.  Other people also had such a problem.


text:
Q: What is the result of using negative inf here def covidLQ(array, n):
    lastSpot = float('-inf')
    i = 0

    while i < n:
        if array[i] == 1:
            if (i - lastSpot) < 6:
                return 'NO'
            else:
                lastSpot = i
        i += 1
    return 'YES'

for _ in range(int(input())):
    n = int(input())
    array = list(map(int, input('').split()))
    print(covidLQ(array, n))

The situation right now is if the distance b\w A = array[i] and next or previous point B is 6 or above then return yes, else return no. Here I don't understand if what can come out if i - a negative infinite number, how to know if it is 6?
Also, what is _ in for _in range(int(input)))? Is it just a meaningless symbol or something else?

A: The interactive python interpreter is a great tool for understanding this code:
>>> float("-inf")
-inf
>>> 0 - float("-inf")
inf
>>> 10000 - float("-inf")
inf

Any time you subtract -inf (aka, negative infinity) from a finite number, the result is inf (aka, positive infinity). No matter what value i has, the first time array[i] == 1 is True then (i - lastSpot) < 6 is False and lastSpot is set to the value of i.


text:
Q: How to Change KeyList KeyCode to Crossplatformmobileinput? i want to change keycode input to crossplatforminput to be able to played on android device , but its really hard
below is a code code related to my problem
and I have tried tweaking based on my knowledge, and i have tried to googling it but still dont find the answer
 private List<KeyList> _keysList;

void Update() {
      if (!photonView.isMine || _player.Hp.Cur.Value <= 0 || _player.State.Rigor || !IsCorrectAnimationState() || _player.Debuff.State[DebuffType.Stun])
        return;
      for (int i=0; i<_keysList.Count; ++i) {
        if (_player.Level.Cur.Value < _requireLv[i])
          continue;
        if (_isDisabled[i] && (_player.Level.Cur.Value == _requireLv[i]))
          EnableSkill(i);

        for (int k=0; k<_keysList[i].keys.Count; ++k) {
          if (_canUseList[i] && CrossPlatformInputManager.GetButton(_keysList[i].keys[k])) {
            InstantiateSkill(i);
            StartCT(i);
            UpdateCT(i);
            break;
          }
        }
      }
    }

 public class KeyList {
    public List<KeyList> keys;
  }

the result is still failed , because I can't solve the problem yet


text:
Q: Проблема подключения компонентов в React js Доброго времени суток друзья.Возникла проблема подключения компонентов  в проекте React js.
Выводится такой код ошибки . Помогите разобратся .Заранее Спасибо.
/project/src/App.js
  9:9  warning  Expected an assignment or function call and instead saw an expression  no-unused-expressions
  9:9  warning  Unreachable code                                                       no-unreachable

✖ 2 problems (0 errors, 2 warnings)

printWarnings @ webpackHotDevClient.js:198
handleWarnings @ webpackHotDevClient.js:211
connection.onmessage @ webpackHotDevClient.js:258
EventTarget.dispatchEvent @ eventtarget.js:49
(anonymous) @ main.js:274
SockJS._transportMessage @ main.js:272
EventEmitter.emit @ emitter.js:44
WebSocketTransport.ws.onmessage @ websocket.js:35
webpackHotDevClient.js:198 ./src/components/Header.js

/project/src/components/Header.js
  6:4  warning  Expected an assignment or function call and instead saw an expression  no-unused-expressions
  6:4  warning  Unreachable code                                                       no-unreachable

✖ 2 problems (0 errors, 2 warnings)

printWarnings @ webpackHotDevClient.js:198
handleWarnings @ webpackHotDevClient.js:211
connection.onmessage @ webpackHotDevClient.js:258
EventTarget.dispatchEvent @ eventtarget.js:49
(anonymous) @ main.js:274
SockJS._transportMessage @ main.js:272
EventEmitter.emit @ emitter.js:44
WebSocketTransport.ws.onmessage @ websocket.js:35
webpackHotDevClient.js:198 ./src/components/Footer.js

/project/src/components/Footer.js
  6:4  warning  Expected an assignment or function call and instead saw an expression  no-unused-expressions
  6:4  warning  Unreachable code                                                       no-unreachable

✖ 2 problems (0 errors, 2 warnings)

printWarnings @ webpackHotDevClient.js:198
handleWarnings @ webpackHotDevClient.js:211
connection.onmessage @ webpackHotDevClient.js:258
EventTarget.dispatchEvent @ eventtarget.js:49
(anonymous) @ main.js:274
SockJS._transportMessage @ main.js:272
EventEmitter.emit @ emitter.js:44
WebSocketTransport.ws.onmessage @ websocket.js:35
webpackHotDevClient.js:198 ./src/components/Main.js

/project/src/components/Main.js
  6:4  warning  Expected an assignment or function call and instead saw an expression  no-unused-expressions
  6:4  warning  Unreachable code                                                       no-unreachable

✖ 2 problems (0 errors, 2 warnings)

printWarnings @ webpackHotDevClient.js:198
handleWarnings @ webpackHotDevClient.js:211
connection.onmessage @ webpackHotDevClient.js:258
EventTarget.dispatchEvent @ eventtarget.js:49
(anonymous) @ main.js:274
SockJS._transportMessage @ main.js:272
EventEmitter.emit @ emitter.js:44
WebSocketTransport.ws.onmessage @ websocket.js:35

Вот сам код
project/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));

project/src/App.js
import React  from 'react';
import Header from './components/Header';
import Main   from './components/Main';
import Footer from './components/Footer';

 function App()
 {
     return
        (

        );
 }

export default App;

/project/src/components/Header.js
import React from 'react';

function Header()
{
   return
   (

Hellow I am Header

   );
}

export default Header;

/project/src/components/Main.js
import React from 'react';

function Main()
{
   return
   (

Hellow I am Main

   );
}

export default Main;

/project/src/components/Footer.js
import React from 'react';

function Footer()
{
   return
   (

Hellow I am Footer

   );
}

export default Footer;

A: После return сразу напишите скобки а не в следующей строке потому и ошибки у вас во всех компонентах.
Интерпретатор возвращает  undefined если написано таким образом return (и в конце ничего) поэтому не проверяет следующую строку от сюда и выводитсья ошибка потому что нету  JSX кода (но он есть проста скобки не правильно поставлены)
Пример как правильно:
return (

Hellow I am Footer

);

Полный код:
Codesandbox
function Footer() {
  return (

Hellow I am Footer

  );
}

function Header() {
  return (

Hellow I am Header

  );
}

function Main() {
  return (

Hellow I am Main

  );
}

function App() {
  return (

  );
}


text:
Q: Problem to control div with blueprint css I´m having a problem with divs when I´m trying to apply background-color to #header for example so it will cover all of the header.
it dosen't show any changes that I made to the css of the #header, #maincontainer and more can you please help me I have tried so many things and nothings seems to work.
Here is the Html sample :

Íris

Ættleiðingartengd fræðsla

<input class="text" onfocus="this.value=''" type="text"     name="searchbar" value="Leita..">

Here is the rest of the HTML if you prefer to see to all :
http://pastebin.com/8AyENrdn

A: It's hard to tell from what you have described and no CSS - Try this
#header {overflow:hidden;background:#eee;}


text:
Q: Chrome shows Lottie animation blurry I have the issue with scaled Lottie animation that Chrome blurs the animation. This is especial visible when the animation is scaled.
In my example, the original Animation is 842x596px as smaller it gets renders as worse gets the result:

Here is the example code, if you want to reproduce it in your Chrome Browser:

lottie-player {
  border: 1px solid lightblue;
}

body {
  color: lightgray;
}
<script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js"></script>

<!--
<lottie-player src="https://assets6.lottiefiles.com/packages/lf20_srq2xawa.json" background="transparent" speed="1" style="width: 300px; height: 300px;" loop controls autoplay></lottie-player>
300x300px
-->

<lottie-player src="https://assets6.lottiefiles.com/packages/lf20_srq2xawa.json" background="transparent" speed="1" style="width: 200px; height: 200px;" loop autoplay></lottie-player>
200x200px

<lottie-player src="https://assets6.lottiefiles.com/packages/lf20_srq2xawa.json" background="transparent" speed="1" style="width: 150px; height: 150px;" loop autoplay></lottie-player>
150x150px

 <lottie-player src="https://assets6.lottiefiles.com/packages/lf20_srq2xawa.json" background="transparent" speed="1" style="width: 100px; height: 100px;" loop autoplay></lottie-player>
100x100px

 <lottie-player src="https://assets6.lottiefiles.com/packages/lf20_srq2xawa.json" background="transparent" speed="1" style="width: 50px; height: 50px;" loop autoplay></lottie-player>
50x50px

It seems there are already other question which have a similar problem but don't provide further information or don't provide a working solution:

*

*Lottie animation blurry on Chrome only

*Blurry content on css animation on Chrome

*Blurry text after using CSS transform: scale(); in Chrome

A: The issue is caused by the following style tag on the SVG inside the Lottie animation:

transform: translate3d(0px, 0px, 0px);

The simplest solution is to remove this tag via JS:
document.addEventListener("DOMContentLoaded", function(){

  let elements = document.getElementsByTagName('lottie-player');

  for (var i = 0; i < elements.length; i++) {

    elements[i].addEventListener('play', (event) => {
      // console.log(event.target.shadowRoot.querySelector('svg').style.transform);
      event.target.shadowRoot.querySelector('svg').style.transform = '';
    });
    elements[i].play(); // trigger (again)

  }
});

document.addEventListener("DOMContentLoaded", function(){

  let elements = document.getElementsByTagName('lottie-player');

  for (var i = 0; i < elements.length; i++) {

    elements[i].addEventListener('play', (event) => {
      // console.log(event.target.shadowRoot.querySelector('svg').style.transform);
      event.target.shadowRoot.querySelector('svg').style.transform = '';
    });

  }

});
lottie-player {
  border: 1px solid lightblue;
}

body {
  color: lightgray;
}
<script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js"></script>

<!--
<lottie-player src="https://assets6.lottiefiles.com/packages/lf20_srq2xawa.json" background="transparent" speed="1" style="width: 300px; height: 300px;" loop controls autoplay></lottie-player>
300x300px
-->

<lottie-player src="https://assets6.lottiefiles.com/packages/lf20_srq2xawa.json" background="transparent" speed="1" style="width: 200px; height: 200px;" loop autoplay></lottie-player>
200x200px

<lottie-player src="https://assets6.lottiefiles.com/packages/lf20_srq2xawa.json" background="transparent" speed="1" style="width: 150px; height: 150px;" loop autoplay></lottie-player>
150x150px

 <lottie-player src="https://assets6.lottiefiles.com/packages/lf20_srq2xawa.json" background="transparent" speed="1" style="width: 100px; height: 100px;" loop autoplay></lottie-player>
100x100px

 <lottie-player src="https://assets6.lottiefiles.com/packages/lf20_srq2xawa.json" background="transparent" speed="1" style="width: 50px; height: 50px;" loop autoplay></lottie-player>
50x50px


text:
Q: Can Application Insights merge Azure.Mobile.Server.Files activity with Azure Storage blob diagnostic logs? When a client calls GetStorageTokenAsync on the server, it gets a token that can read, write, or delete objects on the target container.
The activity done on this container is more or less hidden from my application unless I scan the logs.
Therefore I'm left to guess, or do some cumbersome programming to determine what the files where, the content of the files, determine what changed, etc...
I want to gather empirical evidence of what a given userID did with a certain known token Shared Access Signature, and aggregate the into either an administrative console like Application Insights, or some other tool that will allow programmatic response to the user's actions.
Question
What is the best way to align the actions a user takes, with a given Shared Access Signature (specifically in the context of the Nuget package Microsoft.Azure.Mobile.Server.Files?

A:
and aggregate the into either an administrative console like Application Insights, or some other tool that will allow programmatic response to the user's actions.

There is not a tool or service which support it until now. I am afraid that you need to develop this tool by yourself. Storage Analytics Log stored in the $logs container of your storage account.  All the logs are written to a text file line by line.

What is the best way to align the actions a user takes, with a given Shared Access Signature

Based on the Storage Analytics Log Format, we can only get whether a storage operation is authenticated by Shared Access Signature or account key by 'authentication-type' (If the operation is authenticated by Shared Access Signature, the value of authentication-type will be 'sas'). We can't get the operations which related to a given Shared Access Signature.
Azure Storage Analytics log also contains the requester-ip-address which could identity the client which send the storage operate request. If the IP address of client is static, it will help you get all the actions which the specific user taked.


text:
Q: Components don't re-render after a change in the Redux state I am trying to make a To do list. I nicked UI from Redux example of that, and I started to write the logic in my own way. I was faced with a problem.
So, the problem is that when I click on  Mark All Completed button all my checkmarks on to dos are not visible on UI, but the state is updated, which is perfectly visible in Redux Dev Tool.
Please, help me to understand what is the matter.
gitHub:https://github.com/Alexander-Korniichuk/Redux_Practice/commit/6c981f47d068614b56ab37410210e43869f7247d
Here I dispatch an action. (Footer.js)
import React from 'react';
import {useDispatch} from "react-redux";
import {markAllCompleted} from "../actions";

const Footer = () => {
    const dispatch = useDispatch();
    return (

Actions

                <button className="button"
                        onClick={() => dispatch(markAllCompleted())}>
                    Mark All Completed
                </button>
                <button className="button">
                    Clear Completed
                </button>

            <RemainingTodos/>
            <StatusFilter/>
            <ColorFilters/>

    )
}

export default Footer

Right here I select the Completed field of the needed object and paste it into defaultValue (TodoListItem.js)
import React, {useState} from 'react';
import {ReactComponent as TimesSolid} from './times-solid.svg';
import {markCompleted, deleteToDo, addColor} from "../actions";
import {useDispatch, useSelector} from "react-redux";

const TodoListItem = ({todo}) => {
    const dispatch = useDispatch();
    const {text, id} = todo;
    const completed = useSelector(state => state.todos.find(item => item.id === id).completed);
    const colorNames = useSelector(state => state.filters.filterColors);
    const [innerSelectColor, setInnerSelectColor] = useState("");

    console.log(completed);
    console.log("render TodoListItem");

    const colorSetter = (e) => {
        dispatch(addColor(id, e.target.value));
        setInnerSelectColor(e.target.value);
    }

    return (

                    <input className="toggle"
                           type="checkbox"
                           defaultChecked={completed}
                           onClick={() => dispatch(markCompleted(id, completed))}
                    />

{text}

                    <select className="colorPicker"
                            onChange={colorSetter}
                            style={{color: innerSelectColor}}
                    >
                        {colorNames.map((color, index) =>
                            <option key={index} value={color}>{color.toUpperCase()}</option>)}
                    </select>

                    <button className="destroy" onClick={() => dispatch(deleteToDo(id))}>
                        <TimesSolid/>
                    </button>

    )
}

export default React.memo(TodoListItem);

Thanks in advance.


text:
Q: Solving a PDE with source and degradation I am studying the following PDE for a function $c(r,t)$:
$$
\frac{\partial c}{\partial t} =
D \frac{1}{r^2} \frac{\partial}{\partial r} \left(r^2 \frac{ \partial c}{\partial r} \right) - \gamma c + \eta \delta(r-R)
$$
The steady-state solution of this equation has the form
$$
c(r) = \frac{c_R R}{r} \exp{\left(\frac{R-r}{\lambda}\right)},
$$
where $\lambda=\sqrt{\frac{D}{\gamma}}$ and $c_R = \frac{\eta \gamma R}{\lambda (\lambda+R)}$.
I am looking for the time-dependent solution $c(r,t)$ on the domain $(r,t) \in (R,\infty) \times (0, \infty)$ without resorting to numerical computation.
As boundary conditions I would like to take
$$
-D\frac{\partial c}{\partial r} = \eta, \\
 \lim\limits_{r\rightarrow \infty} c(r) = 0
$$
I still have to think about the initial condition, but let's suppose it is $c(r,0) = f(r)$ for some function $f(r)$ that satisfies the first boundary condition.

*

*Is there a general solution to $c(r,t)$ for this problem, i.e. is this a well-posed problem?

*What are general approaches that will help me in studying this problem? I have only basic background in solving PDEs, so any suggestion for how to approach this problem will be appreciated!

*It is perhaps possible to leave out the last term $\eta \delta(r-R)$ since production is already implied by taking the first boundary condition $-D \frac{\partial c}{\partial t}$.

Note
Without the degradation term $-\gamma c$, this reduces to the heat equation with a constant source. The solution of this equation with the given boundary conditions is known, see e.g. this paper (in the context of signaling molecules too). However, I couldn't find any straightforward generalization to the system with degradation term.
Some physical background
The equation is a so-called reaction-diffusion equation meant to describe the concentration of a molecule secreted by a cell. The cell has radius $R$ and secretes with a rate $\eta$. The diffusion constant is $D$ and the molecules are degraded at a rate $\gamma$.
$$
\frac{\partial c}{\partial t} =
\nabla \cdot (D \nabla c) - \gamma c + \eta \delta(r-R)
$$
Since the problem is spherically symmetric, we can limit ourselves to finding a solution for $c(r,t)$. Here is a paper for a (complicated) system of interacting cells that uses the steady-state solution I gave above.

A: You have
$$\partial_{t}c=D\frac{1}{r^{2}}\partial_{r}(r^{2}\partial_{r}c)-\gamma{c}+\eta\delta(r-R)$$
Let
$$c(t, r)=\frac{g(t, r)}{r}$$
The equation becomes
$$\partial_{t}g=D\partial^{2}_{r}g-\gamma{g}+\eta{r}\delta(r-R)$$
Fourier transform the equation in $r-q$
$$\partial_{t}\hat{g}(t, q)+(Dq^{2}+\gamma)\hat{g}(t, q)=\eta{R}e^{-iq{R}}$$
Thus
$$\hat{g}(t, q)=C(q)\exp\Big(-(Dq^{2}+\gamma)t\Big)+\frac{\eta{R}e^{-iq{R}}}{(Dq^{2}+\gamma)}$$
Hence
$$g(t, r)=\frac{1}{2\pi}\int_{\mathbb{R}}C(q)\exp\Big(iq{r}-(Dq^{2}+\gamma)t\Big)dq+\frac{\eta{R}}{2\pi{D}}\int_{\mathbb{R}}\frac{e^{iq(r-{R})}}{(q^{2}+\gamma/D)}dq=$$
$$=\frac{1}{2\pi}\int_{\mathbb{R}}C(q)\exp\Big(iq{r}-(Dq^{2}+\gamma)t\Big)dq+\frac{\eta{R}}{2\sqrt{{D}\gamma}}\exp\Big(-\Big{|}\sqrt{\frac{\gamma}{D}}(r-R)\Big{|}\Big)$$
Thus
$$c(t, r)=\frac{1}{2\pi{r}}\int_{\mathbb{R}}C(q)\exp\Big(iq{r}-(Dq^{2}+\gamma)t\Big)dq+\frac{\eta{R}}{2\sqrt{{D}\gamma}r}\exp\Big(-\Big{|}\sqrt{\frac{\gamma}{D}}(r-R)\Big{|}\Big)$$
Note, the second term already satisfies the conditions at infinity. At $t=0$
$$c(0, r)=f(r)=\frac{1}{2\pi{r}}\int_{\mathbb{R}}C(q)e^{iq{r}}dq+\frac{\eta{R}}{2\sqrt{{D}\gamma}r}\exp\Big(-\Big{|}\sqrt{\frac{\gamma}{D}}(r-R)\Big{|}\Big)$$
Or
$$rf(r)-\frac{\eta{R}}{2\sqrt{{D}\gamma}}\exp\Big(-\Big{|}\sqrt{\frac{\gamma}{D}}(r-R)\Big{|}\Big)=\frac{1}{2\pi}\int_{\mathbb{R}}C(q)e^{iq{r}}dq$$
Thus
$$C(q)=\int_{\mathbb{R}}\Big(rf(r)-\frac{\eta{R}}{2\sqrt{{D}\gamma}}\exp\Big(-\Big{|}\sqrt{\frac{\gamma}{D}}(r-R)\Big{|}\Big)\Big)e^{-iqr}dr=$$
$$\int_{\mathbb{R}}rf(r)e^{-iqr}dr-\frac{\eta{R}}{2\pi{D}}\frac{e^{iq(r-{R})}}{(q^{2}+\gamma/D)}$$


text:
Q: Call I/O status from the API on Okuma Lathes I am working on a testing program for checking the Barfeeder interface on Okuma machines.  I will need to check status of certain inputs and output.  I am a little confused on the GetBitIO Method.  I am wanting to check the status of for example the iIN24 input at 0104 bit 7.
Code:
 private CIO IO;

 IO = new CIO();

 private void button1_Click(object sender, EventArgs e)
 {
 string IOin24 = IO.GetBitIO(Input, 0104, 7).ToString();
 }

The above line test the "Input" with an error that the name doesn't exist in the current context.
 private CIO IO;

 IO = new CIO();

 private void button1_Click(object sender, EventArgs e)
 {
 string IOin24 = IO.GetBitIO(104, 7, 0).ToString();
 }

Try a minor change to the line of this.
 string IOin24 = IO.GetBitIO(0, 7, 104).ToString();

The above line gets an error for whole command from the api. Error states that the it cannot convert from int to Okuma.CLDATAPI.Enumerations.BitsEnum.  This line is similar to how I got data for VB.Net without issues.
VB code used before to get the NC reset push button (ipNCRT) at address 0 bit 2.
 Private Sub RadioButton4_Checked(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles RadioButton4.Checked
 TextBox2.Text = IO.GetBitIO(0, 2, 0).ToString
 End Sub

Reading the help for the API for Lathes I get the following rules.
Parameters:

[C#]
  public OnOffStateEnum GetBitIO(IOTypeEnum enIO, int intAddressIndex, BitsEnum enBits);
enIO  I/O variable type. Values of parameter come from Okuma.CLDATAPI.Enumerations.IOTypeEnum enumeration.
ntAddressIndex Logical I/O address index
enBits  Bit number. Values of parameter
  come from Okuma.CLDATAPI.Enumerations.BitsEnum enumeration.

A: The basic problem is that you compiled the VB program with Option Strict turned off and it allowed you to pass raw integers into a function that expected to take an Enum.
I don't have a manual for your specific library from the machine manufacturer, but the general idea will be something like :
string IOin24 = IO.GetBitIO(IOTypeEnum.Input, 0104, BitsEnum.Bit4).ToString();

I've just made up the names for the enum members but if you read through the documentation you got with your software (or maybe even just type in IOTypeEnum. and see if IntelliSense gives you a list) to find out what the corresponding strongly typed members are for the integers you are trying to pass.
You will need to make sure, also, that you have included the assembly in question - ie :
using Okuma.CLDATAPI.Enumerations;

should appear at the top of your class file somewhere.


text:
Q: Mediawiki error: File upload not working I've installed Mediawiki v1.24.1 on my server which is running RHEL7.
I've installed it under /var/www/foohelp/wiki. However, when I try to upload a file, I get the following error:
[f3eae72a] /foohelp/wiki/index.php/Special:Upload Exception from line 1871 of /var/www/foohelp/mediawiki-1.24.1/includes/filerepo/file/LocalFile.php: Could not acquire lock for 'User-default.png.'
Backtrace:
#0 /var/www/foohelp/mediawiki-1.24.1/includes/filerepo/file/LocalFile.php(1174): LocalFile->lock()
#1 /var/www/foohelp/mediawiki-1.24.1/includes/upload/UploadBase.php(738): LocalFile->upload(string, string, string, integer, array, boolean, User)
#2 /var/www/foohelp/mediawiki-1.24.1/includes/specials/SpecialUpload.php(467): UploadBase->performUpload(string, string, boolean, User)
#3 /var/www/foohelp/mediawiki-1.24.1/includes/specials/SpecialUpload.php(186): SpecialUpload->processUpload()
#4 /var/www/foohelp/mediawiki-1.24.1/includes/specialpage/SpecialPage.php(363): SpecialUpload->execute(NULL)
#5 /var/www/foohelp/mediawiki-1.24.1/includes/specialpage/SpecialPageFactory.php(584): SpecialPage->run(NULL)
#6 /var/www/foohelp/mediawiki-1.24.1/includes/MediaWiki.php(275): SpecialPageFactory::executePath(Title, RequestContext)
#7 /var/www/foohelp/mediawiki-1.24.1/includes/MediaWiki.php(584): MediaWiki->performRequest()
#8 /var/www/foohelp/mediawiki-1.24.1/includes/MediaWiki.php(435): MediaWiki->main()
#9 /var/www/foohelp/mediawiki-1.24.1/index.php(46): MediaWiki->run()
#10 {main}

If I edit /includes/filebackend/FileBackendGroup.php
and modify LockManager to
'lockManager' => 'fsLockManager',

and modify permissions as follows:
chown -R apache:apache images/
chown -R 755 images/

I get the following error:
(Could not create directory "mwstore://local-backend/local-public)

I've tried most of the forums and there is no solution that seems to fix my problem. Any help would be appreciated.

A: You need to set the proper security context type so that SELinux stops complaining.
sudo chcon -R -t httpd_sys_script_rw_t /var/www/mediawiki123/images/

Don't forget to set the directory back to the correct permissions.
sudo chmod 755 /var/www/mediawiki123/images/

For all of your SELinux needs, browse through here.


text:
Q: Wrong parameter count for str_replace() error <?php
$kw = $_POST["kw"];
$kw= str_replace("*","%",$kw,$count);
if($count > 1)
{
echo "not supported";
exit;
}
...
?>

I'm getting this warning "Wrong parameter count for str_replace() error".
where am I wrong?
Thanks.

A: What version of PHP are you using? I suspect <5.0.0
From http://php.net/manual/en/function.str-replace.php

5.0.0  The count parameter was added.

A: try
$kw= str_replace("*","%",$kw,&$count);


text:
Q: Category tree in AngularJS don´t display correctly with use of recursive template I am using AngularJs and Bootstrap and I want to show in grouped form according to the category the different varieties of wines, this I want to do in the form of thumbnails, for this I use the bootstrap classes "thumbnail" and inside "caption", to show data of the wine . The problem I'm having is that I do not know because it shows me an empty thumbnail after the category name.
I cant make me show separate groups varietals and not after the last previous varietal wine.
My HTML:

My JS:
angular.module("app", []).
controller("ctrl", ['$scope', function ($scope) {
    $scope.categories =[
    {
    "category_name":"Tintos",
    "subcategories":
    [
       {
          "id": 1,
          "parentId": 1,
          "name": "El Enemigo",
          "variedad": "Cabernet Sauvignon",
          "bodega": "Catena Zapata",
          "price":"13.75",
          "photo":"http://www.sietespirits.com/product_images/g/598/El_enemigo_Malbec__72225_zoom.jpg?id=1"
        },
        {
          "id": 2,
          "parentId": 1,
          "name": "Altas Cumbres",
          "variedad": "Malbec",
          "bodega": "Lagarde",
          "price":"82",
          "photo":"http://www.lagarde.com.ar/uploads/wines/altascumbres.png"
        }
    ]
    },
    {
    "category_name":"Blancos",
    "subcategories":[{
          "id": 5,
          "name": "El Zorzal",
          "variedad": "Chardonnay",
          "bodega": "Zorzal",
          "price":"13.75",
          "photo":"http://tonelprivado.vteximg.com.br/arquivos/ids/163090-1000-1000/Finca-El-Zorzal-.-Chardonnay-.-750-ml.300424.jpg"
    }]
  }

]

}
])

I leave you a fiddle JSFiddle
Thank you very much for reading me.

A: Recursive templates work well when the sub categories have the same property names as the parent category so as to create a generic template. Data structure for parent and child is different here.
Anyhow, sub category has a property as id which parent does not, you could conditional check for it and hide the default thumbnail.

     .....

Working Demo with ng-include
If the data structure is what you have that is object with different property names, I'd suggest to go with nested ng-repeat to create an additional scope for sub categories.
In future, if you decide to add an id property for the parent category, the above fiddle won't work as expected. See the below fiddle.
Working demo with nested ng-repeat


text:
Q: How to access Azure REST APIs without a Service Principal? How do I generate a bearer token for my personal identity, like the Microsoft web page does here when you click Try it and log in with your personal credentials?
For example, I would like to generate the bearer token programmatically in a pre-request script in Postman.
UPDATE: The below error happens in Postman if you don't remove "Bearer " from the token. See @BrunoLucasAzure answer.
Also, I have tried to copy the bearer token manually from the Microsoft "Try It" page into Postman as suggested by this answer and I get a 401:
{
    "error": {
        "code": "InvalidAuthenticationToken",
        "message": "The access token is invalid."
    }
}

Before you say it, I realize that I would want a Service Principal for productionalized usage, but I shouldn't need one to explore the APIs via my own tool (e.g. Postman).

A: How did you set your postman?
if you login into the "try" you should get this:

copy #1 and #2 like this. Dont copy the word bearer, only the token and under authorization select bearer token


text:
Q: Can convex hulls contain duplicate points? Given 4 vertices:
(-3.2, 0.8), (-3.2, -0.8), (3.2, -0.8), (3.2, 0.8)
A function which I did not write, and given vertices, will return the points of a convex hull.
Using the points above, it returns these points:
(-3.2, 0.8), (-3.2, -0.8), (3.2, -0.8), (3.2, 0.8), (-3.2, 0.8)
Is it improper to have a duplicate point?
Sometime tells me it is, but I'd hate to suggest to the author that he made a mistake when he did not.

A: The convex hull (call this $H$) of points $P_1,\cdots P_n$ is the set of combinations
$$\sum_{k=1}^n c_kP_k$$
where each $c_k \ge 0$ and the sum of the $c_k$ is 1. If a copy of one of the points, say $P_n$ is adjoined to the list $P_1,\cdots P_n$, the now possibly different hull, call it $H'$ is by the above definition the set of combinations
$$c_{n+1}P_n+\sum_{k=1}^n c_kP_k$$
where now all the $c_k,\ k=1,2,...,n+1$ are nonnegative and their sum is $1$.
Now the claim is that in fact $H'=H$ as sets, i.e. the hulls are the same. It's clear that $H \subset H'$ by taking $c_{n+1}=0$.
For the reverse direction, define a new coefficient name $e_n=c_n+c_{n+1}$ and note that now $H'$ is given by the set of combinations
$$\sum_{k=1}^{n-1} c_kP_k+e_nP_n.$$
The constraints on these $n$ coefficients are again that they be each nonnegative and sum to $1$. This then shows that $H' \subset H$, and we arrive at the claimed statement, that adding a copy of a point in describing a convex hull has no effect on the hull generated.


text:
Q: Connecting wireless router to sonicwall firewall I have no idea what I'm doing and I don't have time to learn about it. I need a quick fix and am out of options so I am sorry if this post breaks the rules, I have done my due diligence in searching for a similar question but they all have the same result and due to my inexperience I am unable to find one that answers my question. It's really a series of questions...
The company I work for lost their sysadmin and has appointed me (audio engineer) to manage the network until further notice (ie forever until I fail, probably). I have accepted the position and risen to the occasion but have hit a brick wall (or should i say 'firewall')
We have a sonicwall NSA 250m firewall managing our net and everything else is networked with a bunch of passive switches. I need to hook up a linksys wireless router (wrt54g2) to one of these switches so I can enable wireless access to our network (and WAN). I have followed the instructions for setting up the linksys as an access point to a Tee. I am able to ping devices on the LAN but cannot access any shares or the WAN. I am almost certain that i have to create some sort of object (Access/Address/etc) in SonicOS to manage its configuration but have NO CLUE what is going on in there. Can somebody please assist me?


text:
Q: maven plugin to create intellij files? Is there a maven plugin to create intellij files?
I have a maven project for which I would like to generate intellij files so that I can import it into my IDE. I know there is an eclipse plugin: http://maven.apache.org/plugins/maven-eclipse-plugin/
and I found a plugin for intellij as well however it says its retired, so I wasn't sure whether I should be using something else:  http://maven.apache.org/plugins/maven-idea-plugin/
I'm following a tutorial that wants me to use eclipse but I would like to use intellij. The pom.xml of the tutorial uses eclipse plugin with these configurations:
        <plugin>
            <groupId>org.eclipse.m2e</groupId>
            <artifactId>lifecycle-mapping</artifactId>
            <version>1.0.0</version>
            <configuration>
                <lifecycleMappingMetadata>
                    <pluginExecutions>
                        <pluginExecution>
                            <pluginExecutionFilter>
                                <groupId>
                                    org.apache.felix
                                </groupId>
                                <artifactId>
                                    maven-scr-plugin
                                </artifactId>
                                <versionRange>
                                    [1.0.0,)
                                </versionRange>
                                <goals>
                                    <goal>scr</goal>
                                </goals>
                            </pluginExecutionFilter>
                            <action>
                                <ignore/>
                            </action>
                        </pluginExecution>
                    </pluginExecutions>
                </lifecycleMappingMetadata>
            </configuration>
        </plugin>

If I try to open the project in intellij then none of the imports work..

A: You can actually open Maven projects directly from IntelliJ:
File → Import Project → "Import project from external model (Maven)"

A: No need of any plugin to import maven project in itelliJ just file -> import project-> then select the pom.xml file of the project to be imported it will handle automatically all the dependencies.First time it will download the dependencies better have internet connection while importing first time


text:
Q: Finding an appropriate data structure I have N keys.
I need to find a data structure which i can do with the following operations :

*

*building it in O(N)

*finding min in O(1)

*deleting the median in O(logn)

*finding the n/2+7-th biggest number
I thought about using a minimum heap (building is O(n),minimum is O(1) - root).
however, I'm having hard time finding a way to do 3 and 4.
I think the median suppose to be on of the leaves, but that's as far as i reached.

A: When you say building in O(n), do you mean that addition has to be O(n), or that you have to build a collection of elements in O(n) such that addition has to be O(1)?
You could augment pretty much any data structure with an extra reference to retrieve the minimal element in constant time.
For #3, it sounds like you need to be able to find the median in O(lg n) and delete in O(1), or vice versa.
For #4, you didn't specify the time complexity.
To other posters - this is marked as homework.  Please give hints rather than posting the answer.

A: A popular question asked in Data Structures 1 exams/hws/tutorials.
I'll try to give you some hints, if they don't suffice, comment, and I'll give you more hints.

*

*Remember that you don't have to use just one data structure, you can use several data structures.

*Recall the definition of a median: n/2 of the numbers are larger, and n/2 of the numbers are smaller

*What data structures do you know that are built in O(n), and complex operations on them are O(logn) or less? - Reread the tutorials slides on these data structures.

*It might be easier for you to solve 1+3 seperately from 1+2, and then think about merging them.

A: Simple sorted Array would solve the problem for #2 #3 and #4. But the construction of it would take O(nn). However, there are no restrictions put on space complexity. I am thinking hard to use Hashing concept during the construction of the data structure which would bring down the order to O(n).
Hope this helps. Will get back if I find a better solution


text:
Q: returning one value from a dict key with multiple values in python I am trying to return "runnerName" from the following dict:
{u'marketId': u'1.112422365',
 u'marketName': u'1m Mdn Stks',
 u'runners': [{u'handicap': 0.0,
               u'runnerName': u'La Napoule',
               u'selectionId': 8095372,
               u'sortPriority': 1},
              {u'handicap': 0.0,
               u'runnerName': u'Swivel',
               u'selectionId': 701378,
               u'sortPriority': 2},
              {u'handicap': 0.0,
               u'runnerName': u'Deanos Devil',
               u'selectionId': 8100420,
               u'sortPriority': 3},
              {u'handicap': 0.0,
               u'runnerName': u'Bishan Bedi',
               u'selectionId': 8084336,
               u'sortPriority': 4},
              {u'handicap': 0.0,
               u'runnerName': u'In Seine',
               u'selectionId': 8199415,
               u'sortPriority': 5},
              {u'handicap': 0.0,
               u'runnerName': u'Needs The Run',
               u'selectionId': 8199416,
               u'sortPriority': 6},
              {u'handicap': 0.0,
               u'runnerName': u'Appellez Baileys',
               u'selectionId': 8148513,
               u'sortPriority': 7},
              {u'handicap': 0.0,
               u'runnerName': u'Jessy Mae',
               u'selectionId': 7652545,
               u'sortPriority': 8},
              {u'handicap': 0.0,
               u'runnerName': u'Redy To Rumble',
               u'selectionId': 7366163,
               u'sortPriority': 9}]}

I have tried many different ways but cannot figure out how to access a value from a key with multiple values.

A: *

*You can use list comprehension, like this, to retrieve the runner names from the dictionary of runners.
print [runner["runnerName"] for runner in runners_dict["runners"]]

*Or you can use operator.itemgetter, like this
from operator import itemgetter
print map(itemgetter("runnerName"), runners_dict["runners"])

Output
[u'La Napoule', u'Swivel', u'Deanos Devil', u'Bishan Bedi', u'In Seine',
 u'Needs The Run', u'Appellez Baileys', u'Jessy Mae', u'Redy To Rumble']


text:
Q: Сохранить дату и время в MS SQLServer 2008 r2 в hibernate пытаюсь сохранить
java.util.Date

в базу,но не выходит.
для подключения использую вот эту либу
<dependency>
        <groupId>net.sourceforge.jtds</groupId>
        <artifactId>jtds</artifactId>
        <version>1.3.1</version>
    </dependency>

диалект
org.hibernate.dialect.SQLServer2008Dialect

Entity :
package com.springapp.mvc.models_local_db;

import javax.persistence.*;
import java.util.Date;

@Entity
@Table(name = "counterr")
public class Counterr {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String counters;
    private String adress;
    private String dom;
    private String tel;
    private String ls;
    private Integer raion;
    private String users;
    private Integer comand;
    private int otmetka;
    private String sost;
    private String status;
    private String new_status;
    private Integer t_out;
    private String debetors;
    private String akt;
    private String penya;
    private String fio_podkl;
    private String note;
    private Integer kod_prich;
    private String note2;
    private String kto;
    private String filename;
    private String type_meter;
    private Integer type_mvalue;
    private Integer type_customer;
    private String fio_customer;
    private Date timesend;
    private Date timesave;
    private Date date_podkl;

    public Date getTimesend() {
        return timesend;
    }

    public void setTimesend(Date timesend) {
        this.timesend = timesend;
    }

    public Date getTimesave() {
        return timesave;
    }

    public void setTimesave(Date timesave) {
        this.timesave = timesave;
    }

    public Date getDate_podkl() {
        return date_podkl;
    }

    public void setDate_podkl(Date date_podkl) {
        this.date_podkl = date_podkl;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCounters() {
        return counters;
    }

    public void setCounters(String counters) {
        this.counters = counters;
    }

    public String getAdress() {
        return adress;
    }

    public void setAdress(String adress) {
        this.adress = adress;
    }

    public String getDom() {
        return dom;
    }

    public void setDom(String dom) {
        this.dom = dom;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getLs() {
        return ls;
    }

    public void setLs(String ls) {
        this.ls = ls;
    }

    public Integer getRaion() {
        return raion;
    }

    public void setRaion(Integer raion) {
        this.raion = raion;
    }

    public String getUsers() {
        return users;
    }

    public void setUsers(String users) {
        this.users = users;
    }

    public Integer getComand() {
        return comand;
    }

    public void setComand(Integer comand) {
        this.comand = comand;
    }

    public int getOtmetka() {
        return otmetka;
    }

    public void setOtmetka(int otmetka) {
        this.otmetka = otmetka;
    }

    public String getSost() {
        return sost;
    }

    public void setSost(String sost) {
        this.sost = sost;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getNew_status() {
        return new_status;
    }

    public void setNew_status(String new_status) {
        this.new_status = new_status;
    }

    public Integer getT_out() {
        return t_out;
    }

    public void setT_out(Integer t_out) {
        this.t_out = t_out;
    }

    public String getDebetors() {
        return debetors;
    }

    public void setDebetors(String debetors) {
        this.debetors = debetors;
    }

    public String getAkt() {
        return akt;
    }

    public void setAkt(String akt) {
        this.akt = akt;
    }

    public String getPenya() {
        return penya;
    }

    public void setPenya(String penya) {
        this.penya = penya;
    }

    public String getFio_podkl() {
        return fio_podkl;
    }

    public void setFio_podkl(String fio_podkl) {
        this.fio_podkl = fio_podkl;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    public Integer getKod_prich() {
        return kod_prich;
    }

    public void setKod_prich(Integer kod_prich) {
        this.kod_prich = kod_prich;
    }

    public String getNote2() {
        return note2;
    }

    public void setNote2(String note2) {
        this.note2 = note2;
    }

    public String getKto() {
        return kto;
    }

    public void setKto(String kto) {
        this.kto = kto;
    }

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public String getType_meter() {
        return type_meter;
    }

    public void setType_meter(String type_meter) {
        this.type_meter = type_meter;
    }

    public Integer getType_mvalue() {
        return type_mvalue;
    }

    public void setType_mvalue(Integer type_mvalue) {
        this.type_mvalue = type_mvalue;
    }

    public Integer getType_customer() {
        return type_customer;
    }

    public void setType_customer(Integer type_customer) {
        this.type_customer = type_customer;
    }

    public String getFio_customer() {
        return fio_customer;
    }

    public void setFio_customer(String fio_customer) {
        this.fio_customer = fio_customer;
    }
}

Один из робованных мною вариантов сохранения
java.util.Date date = new java.util.Date();
java.sql.Timestamp tstamp = new java.sql.Timestamp(date.getTime());

                counterr.setDate_podkl(tstamp);
                counterr.setTimesend(tstamp);
                counterr.setTimesave(tstamp);

sessionFactory.getCurrentSession().save(counterr);


text:
Q: Why is Polybar not starting (from AwesomeWM)? I have a shell script that contains startup logic for apps that are supposed to run after the Awesome window manager is up and running. Currently, it launches both polybar and picom. Picom works fine, but Polybar does not start at all.
#!/bin/sh
# See https://wiki.archlinux.org/title/Awesome#Autostart

run() {
  if ! pgrep -f "$1" ;
  then
    "$@"&
  fi
}

run "~/.config/polybar/launch.sh"
run "picom --experimental-backends -b"

rc.lua fires the shell script from above after everything is initialized. Meaning that the following code is sitting at the end of my rc file.
-- See https://wiki.archlinux.org/title/Awesome#Autostart
awful.spawn.with_shell("~/.config/awesome/autorun.sh")

~/.config/polybar/launch.sh:
#!/bin/bash

# Terminate already running bar instances
killall -q polybar
# If all your bars have ipc enabled, you can also use
# polybar-msg cmd quit

# Launch Polybar, using default config location ~/.config/polybar/config.ini
polybar mybar 2>&1 | tee -a /tmp/polybar.log & disown

echo "Polybar launched..."

The strange thing is that when I run ~/.config/polybar/launch.sh from the terminal, it runs perfectly fine. Why does it not start when launched from my window manager (from the rc.lua file to be exact)?

A: Fixed it by updating autorun.sh to:
#!/bin/sh
# See https://wiki.archlinux.org/title/Awesome#Autostart

run() {
  if ! pgrep -f "$1" ;
  then
    "$@"&
  fi
}

run "$HOME/.config/polybar/launch.sh"

exec picom --experimental-backends &

I copied this from someone else's dotfiles, but I still have no idea why my initial code did not work...


text:
Q: How to use Cox proportional hazards model in interval-censored data with time-dependent variables? The question is self-explanatory. I have survival data (n=156) which, in about half of the observations, is right-censored or interval-censored. I'm am using R to do the analysis and I know I can use intcox() and survfit() to deal with interval-censored data. But, in my point of view, none of this functions can deal with time-dependent variables.
To deal with time-dependent variables without interval-censored data, I am using coxph().
How can I analyse this type of data (if it is possible)?