text:
Q: How to suspend/resume a progress based on the scheduled time? There are solutions to run scheduler to start triggering. But my requirement is to trigger at the end time also.
I have a schedule input like below:-

*

*I have to resume a progress when scheduled time starts.

*I have to suspend it when there is a break in between effective scheduled date range.and resume after the break.

Seems complicated work. Please give me a better way to solve it.

*

*I have one timer. According to the above schedule, it has to calculate time interval between 11-June-2013 19:16 and 17-June-2013 23:59 (as Tuesday has custom period).
Now start the timer with 'Resume' status.

*After this timer elapsed, the interval is calculated between 17-June-2013 23:59 to 18-June-2013 06:00.Now Start the timer with 'Suspend' status. and so on....

A: I assume that the scheduling application you show above persists that information to a file. If so, you can do the following.
First, the process that you want to execute must have some way of being told that it needs to shut down. I'll assume that it's some kind of Windows event or a flag in a file or database somewhere that it checks periodically. If you don't have this facility, then you'll have a tough time killing the task safely.
Have a small application (call it the Keeper) that reads the schedule from the file. It then checks to see if the program you're scheduling is running. If it is running and it's time to pause, then send the signal telling it to stop. Then, create a scheduled task to restart the program at the next start time. Also create a scheduled task to make the Keeper run at the next suspend time. Then the Keeper exits.
Any time you modify the schedule, you just need to run the Keeper program and it will figure out what it needs to do: suspend the program, schedule the program to run again, and schedule itself to run again at the next pause time.
There's a small amount of complexity involved in maintaining the scheduled tasks, but it's not too bad. Just have Keeper delete any scheduled task for Program and for Keeper, basically maintaining things so that there is never more than one of each.
You'll need to access the task scheduler API.


text:
Q: Login loop with lightdm, startx works, .xsession-errors.old contains systemctl: unrecognized option '--value' I got a login loop in Ubuntu 18.04.5 LTS, startx works,
installed ubuntu-desktop and made it the default and the login loop persisted, reinstalled lightdm stayed the same,
after booting with startx, .xsession-errors.old shows the following at the end which I think might be the cause of the loop

systemctl: unrecognized option '--value' systemctl: unrecognized
option '--value' systemctl: unrecognized option '--value' systemctl:
unrecognized option '--value' systemctl: unrecognized option '--value'
systemctl: unrecognized option '--value' systemctl: unrecognized
option '--value' systemctl: unrecognized option '--value' systemctl:
unrecognized option '--value' systemctl: unrecognized option '--value'
systemctl: unrecognized option '--value' systemctl: unrecognized
option '--value' systemctl: unrecognized option '--value' systemctl:
unrecognized option '--value' systemctl: unrecognized option '--value'
systemctl: unrecognized option '--value' systemctl: unrecognized
option '--value' systemctl: unrecognized option '--value' systemctl:
unrecognized option '--value' systemctl: unrecognized option '--value'
systemctl: unrecognized option '--wait'

But I don't have any script in .profile, and have no idea where systemctl is being used with --value parameter at startup.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ensuring template argument type matches that of its variadic constructor I would like to have a class like this:
template<typename T>
struct Foo {
    T* data_;

    template<typename... Ts, std::enable_if<std::is_same<T,Ts>...>...>
    explicit Foo(Ts...ts) : data_{ ts... } {}
};

However; something with the syntax is wrong, and I'm not sure if you can set parameters into a pointer directly like this upon initialization.
What I would like for this to do is simply this:
Foo<int> f1{ 1, 3, 5, 7 }; // Or
// Foo<int> f1( 1, 3, 5 7 );
// f1.data_[0] = 1
// f1.data_[1] = 3
// f1.data_[2] = 5
// f1.data_[3] = 7
// f1.data_[4] = ... not our memory either garbage or undefined...

Foo<float> f2{ 3.5f, 7.2f, 9.8f }; // Or
// Foo<float> f2( 3.5f, 7.2f, 9.8f );
// f2.data_[0] = 3.5
// f2.data_[1] = 7.2
// f2.data_[2] = 9.8
// f2.data_[3] = ... not our memory

I would also like to have the constructor check to make sure that each and every parameter that is passed into the constructor is of type <T>; simply put for each Ts it must be a T.
I might be overthinking this but for the life of me I can not get this or something similar to compile. I don't know if it's within enable_if, is_same or through the class's initializer list and trying to store the contents into a pointer. I don't know if I should use an array of T instead but the array's size won't be known until the arguments are passed into the constructor. I'm also trying to do this without using a basic container such as std::vector; it's more for self education than practical source code. I just want to see how this could be done with raw pointers.

Edit
I've changed my class to something like this:
template<typename T>
struct Foo {
    T* data_;

    template<typename... Ts, std::enable_if_t<std::is_same<T, Ts...>::value>* = nullptr>
    explicit Foo( const Ts&&... ts ) : data_{ std::move(ts)... } {}
 };

And when trying to use it:
 int a = 1, b = 3, c = 5, d = 7;
 Foo<int> f1( a, b, c, d );
 Foo<int> f2{ a, b, c, d };

I'm a little closer with this iteration; but they both give different compiler errors.

*

*The first being: C2661: "No overloaded function takes 4 arguments"

*And the second:  C2440: "initializing, cannot convert from initializer list to Container, no constructor could take the source type, or constructor overload resolution was ambiguous."

A: Why not simply use a std::initialize_list:?
#include <iostream>
#include <type_traits>
#include <vector>

template <class T>
struct Foo
{
  std::vector<T> data_;

  explicit Foo(std::initializer_list<T> data) : data_(data)
  {
    std::cout << "1";
  };

  template <typename... Ts,
            typename ENABLE=std::enable_if_t<(std::is_same_v<T,Ts> && ...)> >
  explicit Foo(Ts... ts) : Foo(std::initializer_list<T>{ts...})
  {
    std::cout << "2";
  }
};

int main()
{
  Foo<int> f1{1, 3, 5, 7}; // prints 1
  Foo<int> f2(1, 3, 5, 7); // prints 1 then 2

  return 0;
}

If some Ts are different from T you will get a compile-time error.
With
gcc -std=c++17  prog.cpp

you get:
  Foo<int> f1{1, 3, 5., 7};

error: narrowing conversion of '5.0e+0' from 'double' to 'int' inside
  { } [-Wnarrowing]    Foo f1{1, 3, 5., 7};
                            ^

and
Foo<int> f2(1, 3, 5., 7);

you get

error: no matching function for call to 'Foo::Foo(int, int,
  double, int)'    Foo f2(1, 3, 5., 7);
                            ^ note: candidate: 'template Foo::Foo(Ts ...)'    explicit Foo(Ts... ts) :
  Foo(std::initializer_list{ts...})
...

Update: if you really want to use something like raw pointer, here is a complete working example:
#include <iostream>
#include <memory>
#include <type_traits>
#include <vector>

template <class T>
struct Foo
{
  size_t n_;
  std::unique_ptr<T[]> data_;

  explicit Foo(std::initializer_list<T> data) : n_(data.size()), data_(new T[n_])
  {
    std::copy(data.begin(), data.end(), data_.get());
    std::cout << "1";
  };

  template <typename... Ts, typename ENABLE = std::enable_if_t<(std::is_same_v<T, Ts> && ...)> >
  explicit Foo(Ts... ts) : Foo(std::initializer_list<T>{ts...})
  {
    std::cout << "2";
  }

  friend std::ostream& operator<<(std::ostream& out, const Foo<T>& toPrint)
  {
    for (size_t i = 0; i < toPrint.n_; i++)
      std::cout << "\n" << toPrint.data_[i];
    return out;
  }
};

int main()
{
  Foo<int> f1{1, 3, 5, 7};  // prints 1
  Foo<int> f2(1, 3, 5, 7);  // prints 1,2

  std::cout << f1;
  std::cout << f2;

  return 0;
}

I let you replace unique_ptr by a raw pointer with all the extra work: delete[] etc...

A: std::is_same only compares two types, and you can't use pack expansions to declare multiple template parameters.  That means you'll need to pull all of your std::is_same checks out into another check:
template <typename T, typename... Ts>
struct all_same : std::bool_constant<(std::is_same<T, Ts>::value && ...)> {};

template <typename T>
struct Foo
{
    std::vector<T> data_;

    template <typename... Ts, std::enable_if_t<all_same<T, std::decay_t<Ts>...>::value>* = nullptr>
    Foo(Ts&&... ts)
        : data_{std::forward<Ts>(ts)...}
    {
    }
};

Live Demo
You also need to allocate memory for your data_ array.  Here I've used std::vector to take care of that allocation for me, but you could use new[] and delete[] to manage it yourself if you really want to.

A: enable_if and is_same won't store anything anywhere, they are only compile-time constructs and do not yield to any code in the binary executable.
Regardless of the syntax, what your code is essentially doing is trying to take the address of a constructor argument (which is a temporary). This will be a dangling pointer as soon as the constructor exits.
Either Foo owns the memory area and must allocate in constructor and delete in destructor (if any doubt: use std::vector!), or it aliases some external memory, and must receive a pointer to that memory.
Now regarding syntax:

*

*std::is_same is a template that provides a value boolean constant and is to be used like so: std::is_same<T1, T2>::value. Alternatively you can use std::is_same_v<T1, T2>.

*std::enable_if provides a type type member, only if the constant expression (1st template parameter) is true. Use it like std::enable_if<expr, T>::type. If expr is true, type is a typedef to T. Otherwise it is not defined and yields a substitution failure. Alternatively you can use std::enable_if_t<expr, T>
You can have a look here for a similar approach of yours.
But you can also simplify all this by using a member vector. In that case, the vector constructor ensures that all arguments have compatible types. Here is a complete example:
#include <string>
#include <vector>
#include <iostream>
#include <type_traits>

using namespace std;

template<typename T>
struct Foo {
    vector<T> data_;

    template<typename ...Ts>
    explicit Foo(Ts... ts) : data_{ ts... } {}

    void print() {
        for (const auto &v : data_) {
            cout << v << " ";
        }
        cout << endl;
    }
};

int main() {

    Foo<int> ints { 1, 2, 3, 4, 5 };
    Foo<string> strings { "a", "b", "c", "d", "e"};
    // Foo<string> incorrect { "a", 2, "c", 4, "e"};

    ints.print();
    strings.print();
    // incorrect.print();

    return 0;
}

A: The most idiomatic way to do this in C++17 is using std::cunjunction_v. It lazily evaluates subsequent values and allows you to avoid fold expressions. Also  messages generated by the compiler are the same for both of casese you mentioned in edited piece of code.
Also, passing data by const-rvalue-ref makes no sense, since it is impossible to move data from const objects. Additionaly you were moving pack of arguments to a pointer. I didn't know what to do about it so just removed it.
Additionaly, take a look at the std::decay_t - without it it would not work, as sometimes Ts is deduced not as int but as const int & or int &. This leads to std::is_same_v being false.
The code below compiles fine at godbolt:
template<typename T>
struct Foo {
    T* data_;

    template<
        typename... Ts,
        std::enable_if_t<
            std::conjunction_v<
                std::is_same<T, std::decay_t<Ts>>...
            >
        > * = nullptr
    >
    explicit Foo( Ts&&... ts ) : data_{ } {}
 };


text:
Q: Implement while loop in Reactor to fetch latest Elasticsearch index My index name in reactive elastic search are as follow:
logs-2020.08.18
logs-2020.08.17
logs-2020.08.16

It will be created daily basis.
I wanna fetch the latest index name and get the logs using reactiveElasticsearchClient or spring data.
Is it possible?
I tried the following way in my spring webflux application:
I have the below code snippet to find index availability:
public Flux<Log> getLogFromLatestIndex(String serialId) {
    Calendar cal = Calendar.getInstance();
    String currentIndex = StringUtils.EMPTY;
    boolean indexExists = false;
    while (!indexExists) {
        currentIndex = String.format("logs-%s", format(cal.getTime(), "yyyy.MM.dd"));
        indexExists = isIndexExists(currentIndex).block();
        cal.add(Calendar.DATE, -1); // Decrease day 1 until you find index
    }

    SearchQuery searchQuery = new NativeSearchQueryBuilder()
            .withQuery(matchQuery("serialId", serialId))
            .withIndices(currentIndex)
            .build();

    return reactiveElasticsearchTemplate.find(searchQuery, Log.class);
}

public Mono<Boolean> isIndexExists(String indexName) {
    return reactiveElasticsearchClient.indices().existsIndex(new GetIndexRequest().indices(indexName));
}

How do I fetch boolean value without using block here
indexExists = isIndexExists(currentIndex).block();

Obviously I will get the below error:
java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-2

A: You can use Flux.generate and (take/skip)(Until/While) to do a while loop in reactor.
Notes:

*

*replaced Calendar with LocalDate as that is immutable and fits better with functional/reactive programming.

*the isIndexExists method returns a Tuple to have the reference for the index name but obviously it can be replaced with some more descriptive class as needed

public Flux<Log> getLog(String serialId) {
    return Flux.generate(LocalDate::now, this::generateNextDate)
               .map(day -> String.format("logs-%s", day.format(DateTimeFormatter.ofPattern("yyyy.MM.dd"))))
               .concatMap(this::isIndexExists)
               .skipUntil(Tuple2::getT2) // check index exists boolean and drop non-existing ones
               .next() // takes first existing
               .flatMapMany(tuple -> findLogs(tuple.getT1(), serialId));
}

private LocalDate generateNextDate(LocalDate currentDay, SynchronousSink<LocalDate> sink) {
    sink.next(currentDay);
    return currentDay.minusDays(1);
}

private Mono<Tuple2<String, Boolean>> isIndexExists(String indexName) {
    return reactiveElasticsearchClient.indices().existsIndex(new GetIndexRequest().indices(indexName))
            .map(exists -> Tuples.of(indexName, exists));
}

private Flux<Log> findLogs(String index, String serialId) {
    // your other ES query here
}

A: application.yml
spring.data.elasticsearch.client.reactive.endpoints: ip1:9200,ip2:9200,ip3:9200
spring.data.elasticsearch.rest.uris: ip1:9200,ip2:9200,ip3:9200

Configuration.java
@Configuration
public class ElasticSearchConfig extends AbstractReactiveElasticsearchConfiguration {

    @Value("${spring.data.elasticsearch.client.reactive.endpoints}")
    private String elasticSearchEndpoint;

    @Override
    public ReactiveElasticsearchClient reactiveElasticsearchClient() {
        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
            .connectedTo(elasticSearchEndpoint.split(","))
            .withWebClientConfigurer(webClient -> {
                ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder()
                        .codecs(configurer -> configurer.defaultCodecs()
                                .maxInMemorySize(-1))
                        .build();
                return webClient.mutate().exchangeStrategies(exchangeStrategies).build();
            })
            .build();
    return ReactiveRestClients.create(clientConfiguration);

    }
}

Controller.java
@GetMapping("/getLog/{serialId}")
public Flux<Log> getLog(@PathVariable String serialId) {
    return loggerService.getLog(serialId);
}

Rest are all your code. I am just printing index name inside map. Although I am having index logs-2020.08.21 in elastic search, it is keep on printing indices like logs-2020.08.20, logs-2020.08.19, logs-2020.08.18 and so on, eventually throws error.
Note: When I tried with single ip in application.yml, I got the same error.
public Flux<Log> getLog(String serialId) {
    return Flux.generate(LocalDate::now, this::generateNextDate)
           .map(day -> {
                System.out.println(String.format("logs-%s", day.format(DateTimeFormatter.ofPattern("yyyy.MM.dd"))));
                return String.format("logs-%s", day.format(DateTimeFormatter.ofPattern("yyyy.MM.dd")));
            })
           .flatMap(this::isIndexExists)
           .skipUntil(Tuple2::getT2) // check index exists boolean and drop non-existing ones
           .next() // takes first existing
           .flatMapMany(tuple -> findLogs(tuple.getT1(), serialId));
}

private LocalDate generateNextDate(LocalDate currentDay, SynchronousSink<LocalDate> sink) {
    sink.next(currentDay);
    return currentDay.minusDays(1);
}

private Mono<Tuple2<String, Boolean>> isIndexExists(String indexName) {
    return reactiveElasticsearchClient.indices().existsIndex(new GetIndexRequest().indices(indexName))
        .map(exists -> Tuples.of(indexName, exists));
}

private Flux<Log> findLogs(String index, String serialId) {
    // your other ES query here
}


text:
Q: discord.py BS4 can't get info out of href element I have the following HTML:
Username

How can I get "Username1" before the  tag?

A: You can use .text property:
from bs4 import BeautifulSoup

html_doc = '''Username'''
soup = BeautifulSoup(html_doc, 'html.parser')

print(soup.a.text)

Prints:
Username

If you want to parse the username from href="..." attribute:
print(soup.a['href'].split('/')[-1])

Prints:
Username1


text:
Q: Where are Kernel Headers for Fedora 21? I'm trying to install VMware on Fedora 21. I've installed the kernel headers:
sudo yum install kernel-headers-`uname -r`

And I receive the following message:
Package kernel-headers-3.18.5-201.fc21.x86_64 already installed

However, there's nothing in /usr/src/kernels:
$ ls /usr/src
$ debug     kernels
$ ls /usr/src/kernels/
$

I guess something has changed, and I'm looking in the wrong place.
Where are the kernel headers located in Fedora 21?

A: To compile programs that build Linux kernel modules, such as VMware Tools, VMware Workstation, etc., you should install both the relevant kernel-headers and kernel-devel packages.
The kernel-headers package provides include files for compiling userland programs, especially the C library, while the kernel-devel package provides include files for compiling kernel modules (which VMware Tools is full of).

Also note carefully that VMware currently recommends that you not compile VMware Tools yourself on guest operating systems which provide open-vm-tools, but you should install open-vm-tools instead. For example:
yum install open-vm-tools

A: The yum command is rpm based, and so to list the contents of a package use
rpm -ql package-name

So in your case
rpm -ql kernel-headers-3.18.5-201.fc21.x86_64

should reveal where your headers are.
Have you tried /usr/include/linux? When you find out could you post the actual location?
Hope this helps


text:
Q: MS Excel Data for CRM Upload - Merge Comments from Multiple Rows into 1 Cell on Multiple Lines and Maintain Comment Creator and Associated Contact Overview:
We're in the process of switching to a new CRM. Importing Contacts and Companies - Easy. Importing the notes associated with those Contacts - Not so easy. For reference, there's over 100,000 Contacts.
The Problem:
When I export Contacts from our old CRM, I get a .csv file that includes all Contact info and Note info for that Contact.  Every Note that was created for a Contact is logged on a new row that includes: Contact First Name / Contact Last Name / Note Author / Note Create Date /  Note. This is what a current export would look like:
Current .csv Export Example
This means that if a Contact had 8 Notes in the CRM, this Contact is duplicated for every Note.
If I upload this file to the new CRM, this contact is created 8x in the new CRM. Meaning I would have to merge this Contact 8x to merge all notes into one instance. This is clearly isn't a sufficient solution.
What I've Tried:

*

*I figured out how to combine comments from multiple rows into one cell on multiple lines using a =TRUEJOIN formula.
Ex: =TEXTJOIN(CHAR(10), TRUE, U12:U18)

*I also figured out how to merge and combine data from 2 cells using a =CONCAT formula.
Ex: =CONCAT(TEXT(R4, "mm-dd-yyyy h:mm AM/PM")," - ",S4,": ",U4)

Goal:
What I'd like to do is identify the duplicate names, merge the Notes for that Contact into 1 Cell on multiple lines, while maintaining Note Creator and Create Date per comment. So I would have 1 Contact with all associated comments loaded to the new CRM. I would like to achieve something that would look like this:
.csv Example of What I Think it Should Look Like
I need help with a formula that would:

*

*Identify duplicate names and remove all of the duplicate data from comment rows while maintaining the separate Note Creator, Note Create Date, and Note associated with that Note Creator.

*There's over 100K Contacts so conditional formula seems like the only way to achieve this.


text:
Q: Why does a string in Python resolve to True? The title might need some re-wording, but here's my question:
The code below ends up False, and thus prints nothing. Changing to d = 1<10 ends up True.
c = "text"
d = 1>10

if d:
    print c

Simple enough. But now if I change d = "more text" the if statement also prints c. Why?

A: That's how python strings are defined. When you try to evaluate them as a boolean, only the empty string returns False. All other strings return True.
>>> bool('not an empty string')
True
>>> bool('')
False

A: The only string considered as a False value is the empty string. It's how the __bool__ operation is defined for strings:
>>> bool('foobar')
True
>>> bool('False')
True
>>> bool('')
False

A: See python doc on Boolean operations

In the context of Boolean operations, and also when expressions are
  used by control flow statements, the following values are interpreted
  as false: False, None, numeric zero of all types, and empty strings
  and containers (including strings, tuples, lists, dictionaries, sets
  and frozensets). All other values are interpreted as true. (See the
  __nonzero__() special method for a way to change this.)

A: Truth Value Testing
The following values are considered false:

*

*None

*False

*Zero of any numeric type, for example, 0, 0.0, 0j.

*any empty sequence, for example, '', (), [].

*any empty mapping, for example, {}.

From python docs Truth Value Testing
So '', an empty string, returns False.

A: If d is an empty string, it will return False, otherwise, if the string has content, it will return True.

A: 1>10 is always false, and thus your code sample doesn't print anything.
While the empty string returns False, all other strings are always evaluated to True.
Thus
d = "some string"
if d:
    print c

actually prints c since it has evaluated d to be True


text:
Q: SQL Server 2012 ALL SERVER Trigger issue I am having an issue with setting an ALL SERVER trigger.
I am using the Adventureworks2012 database to try and get an auditing trigger working.
I would like to ideally have the trigger write to a database that I will make called audit2012 if anyone does an update, insert or delete at the DB level.
I have made a simple trigger which writes to a table, when I update etc. My issue is when I try to change it to ALL server. Here is the SQL. If I change the target to ALL SERVER I get the error:

Msg 1098, Level 15, State 1, Procedure EmpTrig, Line 4
  The specified event type(s) is/are not valid on the specified target object.

Code:
USE [AdventureWorks2012]
GO
/****** Object:  Trigger [HumanResources].[EmpTrig]
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [HumanResources].[EmpTrig]
ON ALL SERVER
FOR UPDATE, DELETE, INSERT
AS
BEGIN

    -- Insert statements for trigger here

    update [HumanResources].[Employee] set JobTitle = 'UPDATE TRIGGER' where BusinessEntityID = 290

END

Your help is appreciated.

A: You are trying to create an ALL SERVER trigger that captures table-level actions. This is not possible - see the list of events that are possible here:
DDL Events (MSDN)
It sounds like you should be looking into auditing instead, if you want to globally capture all inserts, updates and deletes. There are plenty of articles and tutorials out there that can help you with this.
If you can't use auditing due to edition limitations, then you could create a trigger on each table. You can automate the creation of these triggers, e.g.
  DECLARE @sql NVARCHAR(MAX) = N'';

  SELECT @sql += N'
  CREATE TRIGGER ' + QUOTENAME(s.name) + '.Audit_'
    + s.name + '_' + t.name
    + ' ON ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name)
    + ' FOR INSERT, UPDATE, DELETE
    AS
    BEGIN
      INSERT dbo.AuditTable([table], [action], ... other auditing columns ...)
        SELECT ''' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ''',
          CASE WHEN EXISTS (SELECT 1 FROM inserted) THEN
            CASE WHEN EXISTS (SELECT 1 FROM deleted) THEN ''update''
            ELSE ''insert'' END
          ELSE ''delete'' END, ... other auditing information ...;
    END
    GO'
    FROM sys.tables AS t
    INNER JOIN sys.schemas AS s
    ON t.[schema_id] = s.[schema_id];

  PRINT @sql;
  -- EXEC sp_executesql @sql;


text:
Q: Reading Arrow Feather files in GoLang or Javascript I am looking for a way to read the feather files via GoLang or Javascript, or some other languages that does not require users to do some other extra installation.
My goal is to provide a User-interface to read a feather csv file and convert it back to a human-readable csv. However I can't find much resources on how to work it out.
Currently I have a test feather file generated by below.
import pandas as pd
import datetime
import numpy as np
import pyarrow.feather as feather

# Create a dummy dataframe
todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D')

columns = ['A','B', 'C']
df = pd.DataFrame(index=index, columns=columns)
df = df.fillna(0) # with 0s rather than NaNs

feather.write_feather(df, 'test_feather.csv')

Thanks in advance.

A: The Javascript package apache-arrow comes with a script that does exactly this.  You can find the source for the script here: https://github.com/apache/arrow/blob/master/js/bin/arrow2csv.js
If it is not doing exactly what you want the script should serve as an example of how to use the API to read in a feather file.

A: Thanks for the hints from @Pace. Turns out I found that I can simply use the arrow.Table.from([arrow]) function to convert .feather file to csv.
For those people encountered same issue, you may find the code below for reference.
const apArrow = require('apache-arrow');
const fs = require('fs');

const outputDir = 'output/feather';

const writeIntoFile = (data) => {
  fs.appendFileSync(`${outputDir}/test_feather.csv`, data, function (err) {
    if (err) return console.log(err);
  });
};

const readDataFromRow = (fields, row) => {
  return fields
    .map((f) => row.get(f))
    .join(',');
};

const arrowReader = (filePath) => {
  console.log('filePath', filePath);
  const arrow = fs.readFileSync(filePath);
  const table = apArrow.Table.from([arrow]);

  const columns = table.schema.fields.map((f) => f.name);

  let buf = columns.join(',') + '\n';

  for (let i = 0; i < table.count(); i++) {
    const rowData = readDataFromRow(columns, table.get(i));
    buf += `${rowData}\n`;
    // export to csv every 10000 rows
    if (i % 10000 === 0) {
      writeIntoFile(buf);
      buf = '';
      if (i > 0) {
        break;
      }
    }
  }

  writeIntoFile(buf);
};


text:
Q: how to get object's some properties async in Angular I have Array of Json object which I was fetching from server by Http call let suppose the array is
var someArray=[
{id:1,name:'someName',status:'no-data'},
{id:1,name:'someName',status:'no-data'},
{id:1,name:'someName',status:'no-data'}]

And I have rendered the data into table in angular using ngFor

  {{it.id}}
  {{it.name}}
  {{it.status}}

I want to know how can I fetch status attribute of someArray async (currently I has no-data but It has values let say 'live'  ) so that in first API call it should fetch someArray render it on table and then it fetch the status of each object of array async wise.
Kindly refer me some docs or help will be appreciated :)

A: I'm not entirely sure what you are asking here, but there is an async pipe you can use on the for loop

  {{it.id}}
  {{it.name}}
  {{it.status}}


text:
Q: Swap black and white chec box I need to set the black and white swap function in forge viewer, for the user to be able to swap the 2D document visualization to black or white background.
When I set this function in the js code, only the black and white layers swap. The background remains white.
Can anybody help?

A: This should work for AutoCAD 2D drawings, as per documentation:

setSwapBlackAndWhite(value)
AutoCAD drawings are commonly displayed with white lines on a black
  background. Setting reverse swaps (just) these two colors.

And the code should look like:
viewer.setSwapBlackAndWhite(true)  // background black
viewer.setSwapBlackAndWhite(false) // background white

A: To set the color of the 'surrounding' background, try using this...
viewer.setBackgroundColor(0,0,0,0,0,0);
If you want a 'gradient' background from say, blue at the top, down to red at the bottom, try this...
viewer.setBackgroundColor(0,0,255,255,0,0);
So, the specification looks like this:
viewer.setBackgroundColor(colorTopRed,colorTopGreen,colorTopBlue, colorBottomRed, colorBottomGreen, colorBottomBlue);
Click here for the full spec.


text:
Q: In vb.net, what does the ! operator after DataRow do? Everyone, what does the "!" after the DataRow Object means? And why DataRow can get ColumnName Attribute?
Sub constructAttrMeta(ByVal objRows As DataRow)
        Try
            setColName(objRows!ColumnName.ToString)
            ...
        Catch ex As Exception
            Throw New Exception
        End Try
End Sub

Sub setColName(ByVal sColName As String)
        Me.m_sColName = sColName.ToUpper
End Sub


text:
Q: POE::Component::Server::NRPE, return-value I try to use your CPAN-module POE::Compoenten::Server::NRPE.
I tried the sample from the CPAN-site and tested against nagios-tool check_nrpe.
the text was fine, but I am not able to get the correct return-value.
you described this return_result in the modules-description, but I am not aware how to use it.
would be very nice, if you can give me a very short example, how to return a value <> 0.
thanks a lot!
cheers,
christoph
use POE;
use POE::Component::Server::NRPE;

# test with: check_nrpe -H localhost -c test; echo $?

my $nrped = POE::Component::Server::NRPE->spawn (port => 5666);
$nrped->add_command (command => "test", program =>
sub { print STDOUT "test CRITICAL\n";
return 2;    # always 0???
});

$poe_kernel->run ();
return 0;

A: Thank you for posting this question.  I was unaware of this module but it will be of great help to me.

*

*Try using strict and warning in your code, it is for your good

*Use return constants provided by POE::Component::Server::NRPE::Constants instead of using 0 for OK, 1 for WARNING and so on

*I believe the only problem was that you were using return 2 instead of exit 2 or better yet exit NRPE_STATE_CRITICAL in the test sub

The following code should yield the required result
use strict;
use warnings;
use POE;
use POE::Component::Server::NRPE;

# it's recommended to use the NRPE return states provided by the module
use POE::Component::Server::NRPE::Constants qw(NRPE_STATE_OK NRPE_STATE_CRITICAL);

my $nrped = POE::Component::Server::NRPE->spawn (
        port => 5666
);

$nrped->add_command (command => "test", program =>
        sub {
                print STDOUT "testing CRITICAL\n";
        # better to use NRPE_STATE_CRITICAL...
                exit NRPE_STATE_CRITICAL;
        # ... instead of the corresponding digital value
        # but it should work
        # exit 2;
        }
);

$poe_kernel->run ();
exit 0;

Thanks

A: looks like a bug in the module.
the author pushed a new version (0.16 -> 0.18) on cpan.


text:
Q: Can Powershell detect if a specific program is currently playing sound? I am trying to find a way to detect if one specific program is playing sound. To make a long story short, the computers at my workplace all have a program called ReSoin.exe which should always be playing sound if it is functioning properly. If ReSoin is active but is not playing sound, I need to close and reopen ReSoin. I want to automate this process.
Using the method described by Persistent13 here and my very basic understanding of Powershell, I have created a loop to determine if a Windows machine is playing any sound. If Resoin is active and no sound is playing on the computer, the loop closes and reopens ReSoin.
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;

namespace Foo
{
    public class Bar
    {
        public static bool IsWindowsPlayingSound()
        {
            IMMDeviceEnumerator enumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
            IMMDevice speakers = enumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
            IAudioMeterInformation meter = (IAudioMeterInformation)speakers.Activate(typeof(IAudioMeterInformation).GUID, 0, IntPtr.Zero);
            float value = meter.GetPeakValue();
            return value > 1E-08;
        }

        [ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")]
        private class MMDeviceEnumerator
        {
        }

        private enum EDataFlow
        {
            eRender,
            eCapture,
            eAll,
        }

        private enum ERole
        {
            eConsole,
            eMultimedia,
            eCommunications,
        }

        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("A95664D2-9614-4F35-A746-DE8DB63617E6")]
        private interface IMMDeviceEnumerator
        {
            void NotNeeded();
            IMMDevice GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role);
            // the rest is not defined/needed
        }

        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("D666063F-1587-4E43-81F1-B948E807363F")]
        private interface IMMDevice
        {
            [return: MarshalAs(UnmanagedType.IUnknown)]
            object Activate([MarshalAs(UnmanagedType.LPStruct)] Guid iid, int dwClsCtx, IntPtr pActivationParams);
            // the rest is not defined/needed
        }

        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("C02216F6-8C67-4B5B-9D00-D008E73E0064")]
        private interface IAudioMeterInformation
        {
            float GetPeakValue();
            // the rest is not defined/needed
        }
    }
}
'@

While(1) {
    $ReSoinIsActive = Get-Process ReSoin -ErrorAction SilentlyContinue
    if($ReSoinIsActive -ne $null) {
        $ReSoinIsPlayingSounds = [Foo.Bar]::IsWindowsPlayingSound()
        if($ReSoinIsPlayingSounds -eq $False) {
            Stop-Process -Name "ReSoin" -Force
            Start-Process -FilePath "C:\Program Files (x86)\ReLANpro\Cloud And Class Student\ReSoin.exe"
        }else {
            # Placeholder used for testing, please ignore
        }
    }else{
        # Placeholder used for testing, please ignore
    }
start-sleep -seconds 1
}

This is functional, but it has an obvious flaw. If any other program is playing noise, the computer will assume ReSoin is working. Is there a way to adapt this so that it will only detect if ReSoin is playing noise? I'm an amateur with Powershell and batch scripting, but I'm happy to try other scripting methods if anyone has another idea. If my goal is impossible to achieve, or too difficult to ask of the StackOverflow community, please let me know. Any help would be greatly appreciated.


text:
Q: Android: How to make selected spinner item to TextView? I am trying to get the selected item from the spinner to be displayed DIRECTLY after it is selected. Imagine if this is like a quiz game. If you select one of the wrong ones, a TOAST will appear(which I cannot get working). If I select the right one, a different TOAST will appear and I will link it to a new activity. How can I get the onselect to output or display its selection to the textview and how can I implement an if statement for the right/wrong answers?
package com.example.test;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends Activity implements OnItemSelectedListener{

String[] test_array;
TextView display, selected;
String result;
Spinner spinner;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Spinner spinner = (Spinner) findViewById(R.id.spinner);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.test_array, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
}

@Override
public void onItemSelected(final AdapterView<?> parent, View view, final int pos,
        long id) {
    // TODO Auto-generated method stub
    result = (String) spinner.getSelectedItem();
    display = (TextView) findViewById (R.id.display);
    display.setText(result);
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub

}
}

I REVISED ACCORDING TO GOOGLE'S SAMPLES WITHIN THE SDK. HERE IS REVISED CODE.
package com.example.test;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends Activity{

String[] test_array;
TextView display, selected;
String result, sSelect;
Spinner spinner;
int mPos;
String mSelection;
ArrayAdapter<CharSequence> mAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Spinner spinner = (Spinner) findViewById(R.id.spinner);
    this.mAdapter = ArrayAdapter.createFromResource(this, R.array.test_array, android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(this.mAdapter);
    OnItemSelectedListener listener = new myOnItemSelectedListener();
    spinner.setOnItemSelectedListener(listener);
}

public class myOnItemSelectedListener implements OnItemSelectedListener {

    @Override
    public void onItemSelected(AdapterView<?> parent, View v, int pos,
            long id) {
        // TODO Auto-generated method stub
        MainActivity.this.mPos = pos;
        MainActivity.this.mSelection = parent.getItemAtPosition(pos).toString();
        TextView resultText = (TextView) findViewById(R.id.display);
        resultText.setText(MainActivity.this.mSelection);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        // TODO Auto-generated method stub

    }

}
}

The textview now changes to the selected item, now I will attempt the if/else.
The if/else statement causes crash.
04-03 01:38:17.648: E/AndroidRuntime(817): FATAL EXCEPTION: main
04-03 01:38:17.648: E/AndroidRuntime(817): java.lang.NullPointerException
04-03 01:38:17.648: E/AndroidRuntime(817):  at com.example.test.MainActivity$myOnItemSelectedListener.onItemSelected(MainActivity.java:43)
04-03 01:38:17.648: E/AndroidRuntime(817):  at android.widget.AdapterView.fireOnSelected(AdapterView.java:892)
04-03 01:38:17.648: E/AndroidRuntime(817):  at android.widget.AdapterView.access$200(AdapterView.java:49)
04-03 01:38:17.648: E/AndroidRuntime(817):  at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:860)
04-03 01:38:17.648: E/AndroidRuntime(817):  at android.os.Handler.handleCallback(Handler.java:615)
04-03 01:38:17.648: E/AndroidRuntime(817):  at android.os.Handler.dispatchMessage(Handler.java:92)
04-03 01:38:17.648: E/AndroidRuntime(817):  at android.os.Looper.loop(Looper.java:137)
04-03 01:38:17.648: E/AndroidRuntime(817):  at android.app.ActivityThread.main(ActivityThread.java:4745)
04-03 01:38:17.648: E/AndroidRuntime(817):  at java.lang.reflect.Method.invokeNative(Native Method)
04-03 01:38:17.648: E/AndroidRuntime(817):  at java.lang.reflect.Method.invoke(Method.java:511)
04-03 01:38:17.648: E/AndroidRuntime(817):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
04-03 01:38:17.648: E/AndroidRuntime(817):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-03 01:38:17.648: E/AndroidRuntime(817):  at dalvik.system.NativeStart.main(Native Method)
04-03 01:39:04.718: E/Trace(865): error opening trace file: No such file or directory (2)
04-03 01:39:06.028: D/gralloc_goldfish(865): Emulator without GPU emulation detected.

Implemented code
public class myOnItemSelectedListener implements OnItemSelectedListener {

@Override
public void onItemSelected(AdapterView<?> parent, View v, int pos,
        long id) {
    // TODO Auto-generated method stub
    MainActivity.this.mPos = pos;
    MainActivity.this.mSelection = parent.getItemAtPosition(pos).toString();
    TextView resultText = (TextView) findViewById(R.id.display);
    resultText.setText(MainActivity.this.mSelection);
    if(result.equalsIgnoreCase("abc")){
    // Toast in here
     }else{
}
}

A: try this
@Override
    public void onItemSelected(AdapterView<?>; parent, View view, int position, long id) {
        // On selecting a spinner item
        String item = parent.getItemAtPosition(position).toString();

        // Showing selected spinner item
        Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();

    }

try this for if-else statement
spinner = (Spinner) findViewById(R.id.test);

        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {

                String item = "nothing";
                 // On selecting a spinner item
                if(parent.getItemAtPosition(position).toString().equalsIgnoreCase("novels"))
                    item = parent.getItemAtPosition(position).toString();
                else{
                    //do other things
                }

                // showing a toast on selecting an item
                Toast.makeText(parent.getContext(), item, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }

        });

A: as per your explanation:
@Override
public void onItemSelected(final AdapterView<?> parent, View view, final int pos,
        long id) {
    // TODO Auto-generated method stub
    result = spinner.getSelectedItem().toString();
    display = (TextView) findViewById (R.id.display);
    display.setText(result);
    if(result.equalsIgnoreCase("abc")){
        // for correct ans... open new activity using intent
    }else{
       // for wrong ans...
    }
}


text:
Q: Android java : null context in a class that extend Application I have a class extending Application. When I try to get the context of that class either by using "getApplicationContext" or by using "getBaseContext", the context is allways null.
I need the context to use "getSharedPreferences".
The error printed is :

Caused by: java.lang.NullPointerException
              at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109)

What am I doing Wrong or what are some other ways I can use "getSharedPreferences" without the context (if possible) ?
Thanks for the help.
edit with some code :
I'm initializing the class "DeviceInfo" in my main class. the class "DeviceInfo" extends Application. In it's constructor I tried to do :
protected DeviceInfo() {

        context = getApplicationContext();
}

wich gives me the same error as mentioned earlier.
and here is the main line that is causing me trouble...
SharedPreferences key = getApplicationContext().getSharedPreferences("keys", Context.MODE_PRIVATE);

final edit : thanks all, I took all your inputs and realized I wasn't doing it the right way at all. I changed all my code and now it works, thanks again.

A: Your problem is that your Application's Context hasn't been created before you're trying to access it.  To ensure that your Context has been created, you should wait to access your Context until onCreate() before attempting to access your context object.
For example:
public class DeviceInfo extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        SharedPreferences key = getApplicationContext().getSharedPreferences("keys", Context.MODE_PRIVATE);
    }

}

You can also use PreferenceManager.getDefaultSharedPreferences(getApplicationContext()) to access a default preferences file.

A: Whenever you create a class which extends Application, you must define the android:name=".YourClass" property inside your AndroidManifest.xml file inside the application tag.


text:
Q: How to create username and password authentication in YII2 using REST Web Services I wish to create Web Services for each single task so that i do not replicated or rewrite code for same task for different platforms.

A: What you should do is have a REST file in your model with all the curl operations performed in it for various functions like get data and post data.After that use a object of this class to get and receive parameters if needed.
    $rest_obj = new RestService("web service URL", 'param1', 'param2');
    $rest_obj->requestName = 'webservice controller name';
    $rest_obj->requestData = '';
    $rest_obj->querydata = $data['request_params'];
    $rest_obj->requestType = "html";
    $rest_obj->responseType = "json";
    $rest_obj->getData();
    $fields_array = $rest_obj->response;

If you do this then I think you can use this web service for n number of frontends.
Web services are basically another Yii app with connection to the database  and basically act as backend to a number of frontends.So my advice would be to create a controller and a model to fetch data from the db and connect it using the rest service I gave before and everything should work fine.


text:
Q: TIMESTAMP_SECONDS parsing errors I've been trying to use the TIMESTAMP_SECONDS function to convert some epoch timestamps in seconds format, but I have some bad data.  Is there such a thing as SAFE_TIMESTAMP?
Thank you

A:
Is there such a thing as SAFE_TIMESTAMP

There is! It's called SAFE.TIMESTAMP_SECONDS. You can apply the SAFE. prefix to functions to make them return NULL instead of an error; see the documentation for more reading. For example:
SELECT SAFE.TIMESTAMP_SECONDS(0xFFFFFFFFFFFFFF);
+------+
| f0_  |
+------+
| NULL |
+------+

For a valid number of seconds since the epoch:
SELECT SAFE.TIMESTAMP_SECONDS(1539973868);
+------------------------+
| f0_                    |
+------------------------+
| 2018-10-19 18:31:08+00 |
+------------------------+


text:
Q: Sending email attachment using uuencode and mailx I'm trying to get a system on my home network to send an image (.png) via email. The closest I have gotten is this:
uuencode -m snapshot.png snapshot.png | mailx -r "sending@myremoteserver.net" -s "Snapshot" -S smtp=smtp.myremoteserver.net me@myremoteserver.net

Which gets the mail to me, but the output leaves a bit to be desired...
begin-base64 755 snapshot.png
AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8A
AAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAA
AP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA
(well, you get the idea...)
AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8A
AAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAA
AP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/
====

The trouble is, I HAVE to send through smtp.myremoteserver.net. But the image file isn't getting decoded by my mail client (I've tried in Thunderbird and in various webmail interfaces, same result). Is there a better way that actually works?
Update: Just for the fun of it, I ran this:
uuencode -m snapshot.png snapshot.png > coded.txt

And upon decoding it, I got a scrambled, unviewable mess. So the problem must be with the uuencoding.

A: At my old job, the mailx program had an attachment option built in -a.
From http://linux.die.net/man/1/mailx:

-a file
Attach the given file to the message.

Then you don't have to worry about the uuencode stuff. I believe you can add multiple -a options to send multiple attachments as well.
Not sure which version this option appeared though (the servers at my new job don't have it).

A: On ubuntu, I was able to successfully send  mail with attachment using
uuencode input_file1.jpg attachment1.jpg >tempfile
uuencode input_file2.jpg attachment2.jpg >>tempfile
cat tempfile | mailx -s "subject" <email>

after email is sent run the following command to remove the tempfile
rm tempfile

A: I had the same problem and fixed by switch to sendmail, which sends mime types.
mimencode {file} | /usr/sbin/sendmail -t -oi -f {email@domain}

I don't have mimencode in production so I used openssl which seems same:
/usr/bin/openssl base64 -e < {file} | /usr/sbin/sendmail -t -oi -f {email@domain}

If you have more recipients, or subject, you can input at the beginning of the pipe, and append mimencode output at the end, eg.,
To: {email1} {email2}
Cc: {email3}
Subject: some subject
Mime-Version:1.0

Content-Type: text/plain
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename={filename}
{mimencode output here}

You can output all these to a file and then cat to the sendmail pipe.

A: You just need to get rid the "-m" option. It works on Solaris 10 as a sender and outlook/lotus_notes as a mail client.
With "-m" it shows "begin-base64 ...", without "-m" it shows the normal attachment.
Try:
uuencode snapshot.png snapshot.png | mailx -r "sending@myremoteserver.net" -s "Snapshot" -S smtp=smtp.myremoteserver.net me@myremoteserver.net

Hope it helps.

A: Read this: https://support.microsoft.com/en-us/kb/2590107
You should use mimencode.
Mimencode is intended to be a replacement for uuencode for mail and news use. The reason is simple: uuencode doesn't work very well in a number of circumstances and ways. In particular, uuencode uses characters that don't translate well across all mail gateways (particularly ASCII <-> EBCDIC gateways). Also, uuencode is not standard -- there are several variants floating around, encoding and decoding things in different and incompatible ways, with no "standard" on which to base an implementation. Finally, uuencode does not generally work well in a pipe, although some variants have been modified to do so. Mimencode implements the encodings which were defined for MIME as uuencode replacements, and should be considerably more robust for email use.

A: uuencode /pth/to/atch.jpg sendasname.jpg | mailx -s "Subject" mail@mail.com
should do fine - use it regularly in solaris.
Leave out the -m switch is all that needs to happen.

A: how about
(uuencode -m snapshot.png snapshot.png) | mailx -r "sending@myremoteserver.net" -s "Snapshot" -S smtp=smtp.myremoteserver.net me@myremoteserver.net


text:
Q: adjusting symbols above letter in mathmode I know there are plenty of similar questions. If you check out the lower picture, you can see that i've tried a bunch of things to solve my problem. That's just one picture...i'm kind of obsessed with the detail here. I've also tried all \smallfrowns and \arrowright commands and they are even uglier. The biggest problem seems to be that the curve above the letter is not proportional to the size of the letter...AND most of the times it's to far away (height).
I deleted my solution so please do not ask what commands i have used in my example. That was weeks ago. But if you need some sort of MWE let me know.
However, what i want is a solution like in the first picture.
My documentclass:
\documentclass{scrreprt}
in case it makes a difference, i also use:
\usepackage{amsmath, amssymb}

A: Here I offer two variants, where a right paren (rotated) is scaled to the proper width, or where it is stretched to the proper width.  The vertical offset is controlled by the optional argument to \stackon.  I personally find the \stretchto option superior.
EDIT: Definitions tweaked to auto-handle smaller mathstyles.
\documentclass{article}
\usepackage{stackengine,scalerel,graphicx}
\stackMath
\newcommand\overarc[1]{\ThisStyle{%
  \setbox0=\hbox{$\SavedStyle#1$}%
  \stackon[.5pt]{\SavedStyle#1}{%
  \rotatebox{90}{$\SavedStyle\scaleto{)}{.95\wd0}$}}}}
\begin{document}
\centering
Using \verb|\scaleto|:
\[ \overarc{x} \quad \overarc{X} \quad \overarc{ABC} \]
\[ \frac{F_z}{\overarc{z}}  \frac{F_z}{\scriptstyle\overarc{z}}
  \frac{F_z}{\scriptscriptstyle\overarc{z}} \]

\renewcommand\overarc[1]{\ThisStyle{%
  \setbox0=\hbox{$\SavedStyle#1$}%
  \stackon[.5pt]{\SavedStyle#1}{%
  \rotatebox{90}{$\SavedStyle\stretchto{)}{.95\wd0}$}}}}
Using \verb|\stretchto|:
\[ \overarc{x} \quad \overarc{X} \quad \overarc{ABC} \]
\[ \frac{F_z}{\overarc{z}}  \frac{F_z}{\scriptstyle\overarc{z}}
  \frac{F_z}{\scriptscriptstyle\overarc{z}} \]
\end{document}


text:
Q: Databricks Azure - How to to run API commands from a Notebook How to run within Databricks notebook - API for checking other running jobs:
https://docs.databricks.com/dev-tools/api/latest/jobs.html
Thanks

A: You could start the cell with %sh and then use the usual curl commands, e.g.:
%sh
curl -n -X GET https://<databricks-instance>/api/2.0/jobs/list

(You'll need to authenticate first though: The -n flag is for an .netrc file. This question might be useful for that.)
I think this is the only option: Jobs can be managed either through the REST API or through the Databricks GUI. I can't see anything about managing jobs using dbutils, for instance.


text:
Q: KeyBinding Label I have a TreeView with the following definition:
<TreeView ItemsSource="{Binding Folders, UpdateSourceTrigger=PropertyChanged}" x:Name="tree">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Folders, UpdateSourceTrigger=PropertyChanged}">
            <Label Content="{Binding Name}" >
                <Label.InputBindings>
                    <KeyBinding Key="Delete"
                                Command="{Binding DataContext.DeleteFolderCommand, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}"/>
                    <MouseBinding MouseAction="LeftDoubleClick"
                                  Command="{Binding DataContext.SelectFolderCommand, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}"
                                  CommandParameter="{Binding ElementName=tree, Path=SelectedItem}" />
                </Label.InputBindings>
            </Label>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

This view is boud to it's Code-Behind-File with:
DataContext="{Binding RelativeSource={RelativeSource Self}}"
The InputBinding for the LeftDoubleClick just works fine.
But the InputBinding for the 'Delete'-Key doesn't work.
The Command where the KeyBinding is bound to looks like:
public ICommand DeleteFolderCommand
{
    get { return _deleteFolderCommand; }
    set
    {
        _deleteFolderCommand = value;
        OnPropertyChanged();
    }
}

and in the constructor I define:
DeleteFolderCommand = new RelayCommand(DeleteFolder);

and the DeleteFolder-Method just looks like:
private void DeleteFolder(object parameter)
{
  // Break-Point here will not be reached
}

What am I doing wrong?
I've already checked the Output-Window for Binding-Errors, but there are none.

A: I managed it by handling the KeyBinding directly at the TreeView
<TreeView ItemsSource="{Binding Folders, UpdateSourceTrigger=PropertyChanged}" x:Name="tree">
    <TreeView.InputBindings>
        <KeyBinding Key="Delete" Command="{Binding DataContext.DeleteFolderCommand, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}"/>
    </TreeView.InputBindings>
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Folders, UpdateSourceTrigger=PropertyChanged}">
            <Label Content="{Binding Name}">
                <Label.InputBindings>
                    <MouseBinding MouseAction="LeftDoubleClick"
                                Command="{Binding DataContext.SelectFolderCommand, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}"
                                CommandParameter="{Binding ElementName=tree, Path=SelectedItem}" />
                </Label.InputBindings>
            </Label>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>


text:
Q: Pug to html converter for Mac. Seeking command line code I'm following a Pug tutorial and the narrator is using Windows. This is the command he wrote that automatically translates his Pug code to Html
Question: What's the Mac equivalent of
pug -w ./ -o ./html -P


text:
Q: Getting exception while setting layoutparams of scrollview programmatically I am getting exception while setting the layoutparams of scroolview programmatically.I have tried but getting exception while doing that.This is the code:
sv = (ScrollView)findViewById(R.id.scrollView);
        sv.setBackgroundColor(Color.TRANSPARENT);

            ScrollView.LayoutParams layoutParams = new ScrollView.LayoutParams(
                    ScrollView.LayoutParams.MATCH_PARENT,
                    ScrollView.LayoutParams.MATCH_PARENT);
            layoutParams.bottomMargin = 100;
            layoutParams.setMargins(0, 0, 0, 100);
            sv.setLayoutParams(layoutParams);

This is the error log:
09-23 12:13:20.666: E/AndroidRuntime(3284): Uncaught handler: thread main exiting due to uncaught exception
09-23 12:13:20.696: E/AndroidRuntime(3284): java.lang.ClassCastException: android.widget.FrameLayout$LayoutParams
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.widget.RelativeLayout$DependencyGraph.findRoots(RelativeLayout.java:1291)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.widget.RelativeLayout$DependencyGraph.getSortedViews(RelativeLayout.java:1238)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.widget.RelativeLayout.sortChildren(RelativeLayout.java:279)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:299)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.view.View.measure(View.java:7964)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:569)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:361)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.view.View.measure(View.java:7964)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3023)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.view.View.measure(View.java:7964)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:464)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:278)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.view.View.measure(View.java:7964)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3023)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.view.View.measure(View.java:7964)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3023)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.view.View.measure(View.java:7964)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.view.ViewRoot.performTraversals(ViewRoot.java:763)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1633)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.os.Looper.loop(Looper.java:123)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at android.app.ActivityThread.main(ActivityThread.java:4363)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at java.lang.reflect.Method.invokeNative(Native Method)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at java.lang.reflect.Method.invoke(Method.java:521)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
09-23 12:13:20.696: E/AndroidRuntime(3284):     at dalvik.system.NativeStart.main(Native Method)

This is the xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_centerHorizontal="true"
    android:orientation="vertical" >

    <RelativeLayout
        android:id="@+id/frameLayout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <ScrollView
            android:id="@+id/scrollView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="90.0dip"
            android:layout_marginLeft="1.0dip"
            android:layout_marginRight="1.0dip"
            android:layout_marginTop="-2.0dip"
            android:animateLayoutChanges="true"
            android:fadeScrollbars="true"
            android:fadingEdge="none" >

            <!-- android:layout_marginBottom="60.0dip" -->
            <!-- android:fillViewport="true" -->

            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:visibility="visible" >

                <ImageView
                    android:id="@+id/QuestionImageView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:visibility="visible" />

                <TextView
                    android:id="@+id/tv"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/QuestionImageView"
                    android:fadingEdge="vertical"
                    android:scrollbars="vertical" />

                <TextView
                    android:id="@+id/questionnumber"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:fadingEdge="vertical"
                    android:scrollbars="vertical" />

                <TextView
                    android:id="@+id/question"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_below="@id/tv"
                    android:fadingEdge="vertical"
                    android:padding="10dp"
                    android:scrollbars="vertical"
                    android:text=""
                    android:textColor="@color/dark_green" />

                <RadioGroup
                    android:id="@+id/radioGroup1"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/question"
                    android:orientation="vertical" >

                    <RadioButton
                        android:id="@+id/option1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="" />

                    <ImageView
                        android:layout_width="fill_parent"
                        android:layout_height="1.0dp"
                        android:background="@drawable/thinnest_blue_gradient" />

                    <RadioButton
                        android:id="@+id/option2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="" />

                    <ImageView
                        android:layout_width="fill_parent"
                        android:layout_height="1.0dp"
                        android:background="@drawable/thinnest_blue_gradient" />

                    <RadioButton
                        android:id="@+id/option3"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="" />

                    <ImageView
                        android:layout_width="fill_parent"
                        android:layout_height="1.0dp"
                        android:background="@drawable/thinnest_blue_gradient" />

                    <RadioButton
                        android:id="@+id/option4"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="" />
                </RadioGroup>
            </RelativeLayout>
        </ScrollView>
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/relativequestion"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" >

        <com.google.ads.AdView
            android:id="@+id/ad"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            ads:adSize="SMART_BANNER"
            ads:adUnitId="a1501e5633125fb"
            ads:loadAdOnCreate="true"
            ads:testDevices="TEST_EMULATOR, 123456789ABCDEF" />

        <LinearLayout
            android:id="@+id/newquestion"
            android:layout_width="fill_parent"
            android:layout_height="40.0dip"
            android:layout_above="@id/ad"
            android:background="#ff777777"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/PrevButton"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_centerInParent="true"
                android:layout_marginLeft="5.0dip"
                android:layout_weight="1.0"
                android:background="@drawable/ibtn"
                android:onClick="onPrevButtonClick"
                android:text="Prev" />

            <Button
                android:id="@+id/NextButton"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_centerInParent="true"
                android:layout_marginLeft="5.0dip"
                android:layout_weight="1.0"
                android:background="@drawable/ibtn"
                android:onClick="onNextButtonClick"
                android:text="Next" />

            <Button
                android:id="@+id/SkipButton"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_centerInParent="true"
                android:layout_marginLeft="5.0dip"
                android:layout_weight="1.0"
                android:background="@drawable/ibtn"
                android:onClick="onSkipButtonClick"
                android:text="Skip" >
            </Button>

            <Button
                android:id="@+id/SubmitButton"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_centerInParent="true"
                android:layout_marginLeft="5.0dip"
                android:layout_marginRight="5.0dp"
                android:layout_weight="1.0"
                android:background="@drawable/ibtn"
                android:onClick="onSubmitButtonClick"
                android:text="Submit" />
        </LinearLayout>
    </RelativeLayout>

</RelativeLayout>

Please help me.Thanks in advance.

A: The parent of your ScrollView is a RelativeLayout and for this you should use RelativeLayout.LayoutParams:
    RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) sv
            .getLayoutParams();
    lp.setMargins(0, 0, 0, 100);


text:
Q: Flutter application freezing I am working on a mobile application in Flutter to

*

*create a Bluetooth connection

*receive data from this device

*plot them on the screen using SfCartesianChart

Everything works fine, except that after a while, the application freezes completely. There is nothing I can do but quit the application. I have looked at the "Flutter performance" section, but I can't find any useful indication. Also, I don't see any errors on my command line. It is a total mystery. I keep looking but it's hopeless.
Well, I never understand why people are giving a "-1" instead of explaining something but I appreciate your suggestions on how I can resolve this error.


text:
Q: How do I edit my code to search an entire column instead of the cell on the same row? I have this code:
=IF(AND(IFERROR(SEARCH(MID(K1,1,2),B:B),"x")="x",IFERROR(SEARCH(MID(K1,3,2),B:B),"x")="x"),,K1)
But the problem is that it's not searching B:B, it's searching B1(or whatever row it's on). Is there a way to make this search all of B:B? I tried FIND too, and that didn't work.
Here's a photo recreation.


text:
Q: Listing a directory's content and checking if the element is a file or a directory (C) I've been trying to find a way to map a directory's content plus a check whether the found "element" is either a file or a directory.
I've tried all the "solutions" found here:
How can I check if a directory exists?, How do you check if a directory exists on Windows in C? and Checking if a file is a directory or just a file
(My post here is not a duplicate, therefore)
Nothing was working for me. I'm on Windows 10. I'm not a fan of these windows libraries, anyway. That's why I'm looking for a way that only standard C.
Here's my code so far:
struct dirent *de;
DIR *dr = opendir(opts->dirname);

#define DF_ISDIR 0x100
#define DF_ISFILE 0x200
#define DF_NOEXIST 0x400

while ((de = readdir(dr)) != NULL) {
    int exists = df_isdirectory(de->d_name);
    printf("[%s]: '%s'\n", exists == DF_ISDIR ? "DIR" : exists == DF_ISFILE ? "FILE" : "WHATEVER", de->d_name);
}

and
int df_isdirectory(const char *name) {
assert(name != NULL);

DIR *dp = NULL;
if (_access(name, F_OK) == 0) {
    if ((dp = opendir(name)) != NULL) {
        closedir(dp);
        return DF_ISDIR; //  element is directory
    } else {
        return DF_ISFILE; // element is a file
    }
}

return DF_NOEXIST; // element is whatever

}
It gives me the folliwing output:

As we can see, the program detects that .. and . as dirs, but not a single element in my directory. Even though "another" and "dfgsdgf" ARE DIRECTORIES!

So, why doesn't it consider my actual directories a directory?
Side note: One directory ("dfgsdgf") is empty, the other one ("another") is filled with 2 files.
After spending so much time, and trying a ton of "working" solutions, I am slowing getting tired of this. I want a detailed explanation WHY MY CODE DOESN'T WORK AS EXPECTED and a clear code snippet THAT WORKS 100%.
PS: My testing dir is C:\test
My exe file is not located in the same directory.
Thanks, and have a nice day!
~Sebastian

A: Here, you open the directory given in your opts structure:
DIR *dr = opendir(opts->dirname);

the content of opts->dirname is C:\test. However, here:
if ((dp = opendir(name)) != NULL) {

you try to open a directory entry relative to your cwd (which is somewhere else). Indeed already your _access() check fails due to that.
Try calling
chdir(opts->dirname);

before your while() loop or build a full path in a string to pass it to _access() and opendir() in your df_isdirectory() function.


text:
Q: How do I get a redirect URL back to my Chrome extension popup? I am trying to authenticate with the Hubspot API. I am using chrome.identity.getRedirectURL to get a redirect URL for the API. What do I pass in so that after the API is done authenticating, it opens my popup again? Do I need to look at this from another perspective? The ultimate end goal is to get the API response back to my popup.
To clarify, the Chrome popup is the window that shows up when you click on the Chrome extension icon next to the address bar.
My current code is below:
        let redirectURL = chrome.identity.getRedirectURL("index.html");

        let clientID = config.clientID;
        let clientSecret = config.clientSecret;

        // create object to make the authentication request with
        let details =  {
            url: "https://app.hubspot.com/oauth/authorize?client_id=" + clientID + "&scope=contacts&redirect_uri=" + redirectURL,
            interactive: true
        };

        // make authentication request
        chrome.identity.launchWebAuthFlow(details, (response) => {
            alert(response);
        })

index.html is my popup page; I don't know if this part is correct or not.
EDIT: added clarification on the index.html line of code.


text:
Q: Intuition of the proof on the minimality of $\mathbb{N}$ I know that this is fairly standard and that there are many ways to do this. I want to understand here what is happening intuitively in Stromberg's proof of Theorem (1.55).
The proof is as follows.

Assume $\mathbb{N}$ is finite. Since $\mathbb{N}\neq \lbrace\rbrace$, there is a smallest $n$ such that $\mathbb{N}\sim \lbrace k\in\mathbb{N}: 1\leq k\leq n \rbrace$. Let $f:\lbrace k\in\mathbb{N}: 1\leq k\leq n \rbrace \rightarrow \mathbb{N}$ be one-to-one and onto. Now define  $g:\lbrace k\in\mathbb{N}: 1\leq k\leq n-1 \rbrace \rightarrow \mathbb{N}$ by the rule \begin{equation}g(k) =\begin{cases} f(k),& \operatorname{if}  f(k)<f(n)\\ f(k)-1,& \operatorname{if} f(k)>f(n).\end{cases}\end{equation}
  Then $g$ is one to one and onto $\mathbb{N}$. This contradicts the minimality of $\mathbb{N}$.

Formally, I understand all the arguments. Since $f$ is one to one and onto, one can check that $g$ is also one to one and onto. If this is the case, in particular the case that I don't understand, being $g$ onto means that for $n\in\mathbb{N}$, there is a $k\in \lbrace k\in\mathbb{N}: 1\leq k\leq n-1 \rbrace$ such that $g(k)=n$.
But what I can't see is how to propose a particular $f$ such that for, say, $n\in\mathbb{N},\;g(k)=n$. There's simply "not enough" elements in the domain of $g$ to do this (but it should be, since $g$ is onto).

A: Pick $m\in\mathbb N$. We must find $k$ with $1\le k\le n-1$ such that $g(k)=m$.
First, we are given that $f$ is onto, so there is $s$ with $1\le s\le n$ such that $f(s)=m$. If $m<f(n)$, then we could let $k=s$, so that $g(k)=g(s)=f(s)=m$ by definition of $g$, as long as $s<n$ (because then $1\le s\le n-1$ and $s$ is in the domain of $g$). Now, $s\ne n$ because $f(s)<f(n)$, so we are done with this case.
So we are left with the situation where $m\ge f(n)$. Since $f$ is onto, there is a $t$ with $1\le t\le n$ such that $f(t)=m+1$ (and note that $m+1>f(n)$). If $t<n$ then, by definition of $g$, we can take $k=t$: $g(k)=g(t)=f(t)-1=m$. Again, $t=n$ is impossible, this time because $f(t)>f(n)$.


text:
Q: Apply and remove color profile with image magick I have Tiff images with embedded specific ICC profiles.
I want to convert these by means of imagemagick to JPG-Files.
The JPG-Files should use colorspace sRGB (which is the default) and no embedded profile. In other words I want to apply the profile to the image and want to save it without profile.
When I use a simple convert command like this
convert source.tif target.jpg

the ICC-Profile is preserved in the JPG file. You can remove it with a command like this
convert source.tif +profile "*" target.jpg

But that does not seem to apply the profile.
A -colorspace RGB (or -colorspace sRGB?) should do the trick. But any combination I have tried so far does not work.
Is there a color management guru out there who can give me hint?
`

A: Some iterations later I come up with this
convert source.tif -profile MY_PROFILE_PATH/sRGB.icc +profile * target.jpg

I used the ICC profile from http://www.color.org/profiles/srgb_appearance.xalter


text:
Q: IEEE754 to floating point C# The below code is simple converting a 32bit-integer from the object being passed to the function, the 32-bit integer represents a floating number. I have checked with an online calculator that that i am getting the sign, exponent and mantessa the correct way but strangely i am getting the answer wrong.
Can anyone please check if i am mathematically (or maybe programmatically) doing it wrong somehow!?
Regards
public double FromFloatSafe(object f)
    {
        uint fb = Convert.ToUInt32(f);

        uint sign, exponent = 0, mantessa = 0;
        uint bias = 127;

        sign = (fb >> 31) & 1;
        exponent = (fb >> 23) & 0xFF;
        mantessa = (fb & 0x7FFFFF);
        double fSign = Math.Pow((-1), sign);
        double fMantessa = 1 + (1 / mantessa);
        double fExponent = Math.Pow(2, (exponent -bias));
        double ret = fSign * fMantessa * fExponent;
        return ret;
    }

A: Something like that:
  uint fb = Convert.ToUInt32(f);

  return BitConverter.ToSingle(BitConverter.GetBytes((int) fb), 0);

A: This handles even denormal numbers:
public static float FromFloatSafe(object f)
{
    uint fb = Convert.ToUInt32(f);

    int sign = (int)((fb >> 31) & 1);
    int exponent = (int)((fb >> 23) & 0xFF);
    int mantissa = (int)(fb & 0x7FFFFF);

    float fMantissa;
    float fSign = sign == 0 ? 1.0f : -1.0f;

    if (exponent != 0)
    {
        exponent -= 127;
        fMantissa = 1.0f + (mantissa / (float)0x800000);
    }
    else
    {
        if (mantissa != 0)
        {
            // denormal
            exponent -= 126;
            fMantissa = 1.0f / (float)0x800000;
        }
        else
        {
            // +0 and -0 cases
            fMantissa = 0;
        }
    }

    float fExponent = (float)Math.Pow(2.0, exponent);
    float ret = fSign * fMantissa * fExponent;
    return ret;
}

note that I do think there is something fishy here, but you asked for it, I wrote it... I feel this is a XY problem.
Ah... and note that while academically what I wrote is very interesting, I normally do it this way:
[StructLayout(LayoutKind.Explicit)]
public struct UInt32ToFloat
{
    [FieldOffset(0)]
    public uint UInt32;

    [FieldOffset(0)]
    public float Single;
}

then
float f = new UInt32ToFloat { UInt32 = Convert.ToUInt32(f) }.Single;


text:
Q: Is it possible to use keyframes animation to pseudo-element? is it possible to use css keyframes animation to pseudo-element such as 'before' and 'after'?
I am developing webservice for smartphone, and want to blink element. but do not want to blink element itself.
so, ways I came up with are two;
one is to cover element with another element, and blink that element;
and another is to use pseudo-element, but it seems not working.
css:
.fadeElement {
  background-color: #000000;
  width: 60px;
  height: 60px;
}
.fadeElement:after {
  display: block;
  content: '';
  position: relative;
  height: 100%;
  width: 100%;
  z-index: 500;
  background-color: rgba(249, 4, 0, 0.5);
  animation-name: 'fade';
  animation-duration: 2s;
  animation-iteration-count: infinite;
  -webkit-animation-name: 'fade';
  -webkit-animation-duration: 2s;
  -webkit-animation-iteration-count: infinite;
}
@keyframes 'fade' {
  0% {
    opacity: 0;
  }
  40% {
    opacity: 0.5;
  }
  60% {
    opacity: 0.5;
  }
  100% {
    opacity: 0;
  }
}
@-webkit-keyframes 'fade' {
  0% {
    opacity: 0;
  }
  40% {
    opacity: 0.5;
  }
  60% {
    opacity: 0.5;
  }
  100% {
    opacity: 0;
  }
}

html:

A: Firefox, Chrome, and IE10+ support this.
See more info at Chris Coyier's site: http://css-tricks.com/transitions-and-animations-on-css-generated-content/


text:
Q: Is it possible to determine if a dataset is real or randomly generated? I've been tasked with developing regression and classification models for time series data. For each observation I have a continuous target for regression and a discrete target for classification.
I've fitted a LASSO model which works stupendously well. It has very low MAE and RMSE values, as well as low relative errors (in the order of 0.4%). R^2 is 0.99 but I never trust it too much. Residues are very regular and appear to follow a normal distribution with zero mean and 1/2 variance:

Finally, there's virtually no autocorrelation between residues for any meaningful lag value.
On the other hand, the classification task seems impossible. There are three classes which are almost perfectly distributed in the dataset, but they appear to have been chosen at random. I ran PCA to reduce the data to two components in order to plot it, and I just observed a garbled mess of colored points with no visible pattern.
My distinct impression is that the dataset is contrived and does not represent real observations. Are there techniques to determine statistically how likely is such a thing?
I know about Benford's law, but I'm not sure if it applies to real values as well as integers. Out of curiosity, I computed the frequencies for the integer-valued columns in my dataset, and these are the results:

Those certainly do not seem to match Benford's law.
I also observed that some columns approximate very well certain distributions (e.g. I have three columns whose values approximate bimodal distributions very well).
Unfortunately, the dataset has been anonymized, and it might come from a financial context. I don't know anything else about it.
EDIT: I plotted histograms for all the columns in the dataset. Some of them really look like famous distributions. Maybe someone with more experience than me? I'm not looking for a definitive judgement here, since I know it's not possible. It's just my curiosity, in the end. Here is the result (click to see full picture with all the columns):


text:
Q: .NET Core 3.1 Identity takes too long to login on Azure We've built a .NET Core 3.1 MVC web app.  We decided to go with MS Identity Microsoft.AspNetCore.Identity and Microsoft.AspNetCore.Identity.UI.  We scaffolded out all the login / user management stuff.  It created Razor Pages in \Areas\Identity\Pages\Account.
We needed to have a Username not tied to email address.  We also needed to extend IdentityUser and add things like FirstName, etc.
This Line of code in \Areas\Identity\Pages\Account\Login.cshtml.cs is giving us hell.  On local machines, with local DB's it runs just fine.  When we push to Azure, it takes 30 seconds to execute this line.
var result = await _signInManager.PasswordSignInAsync(Input.UserName, Input.Password, Input.RememberMe, lockoutOnFailure: false);

In fact anything that uses _signInManager takes 15 - 30 seconds.  Even something as simple as logging out.
private readonly SignInManager<ApplicationUser> _signInManager;

ApplicationUser inherits from IdentityUser
public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string UserType { get; set; }

    public int OrganizationID { get; set; }

    public DateTime? CreatedOn { get; set; }

    public string NPINumber { get; set; }
}

We assumed this might be because we were using a low-end hosting tier on Azure, so we kicked everything up a few notches, threw more money at it, and are still having problems.
This is really causing an issue.  I'm open to any ideas to correct this.

A: Turns out someone gave me an idea that helped me find the clue that was causing the slowdown.
Application Insights.  I turned it on on Azure... Logged in, logged out... Dug deep into the bowels of what was happening, and saw a reference to (localdb)\mssqllocaldb which absolutely should not be on the production server.
This led me to believe that NLog was misconfigured. Turns out, NLog was setup to log to a .log file but ALSO add a record to a table in the DB.
On local dev machines, it would log correctly to the local DB. But on Azure, it would also TRY to log to Server=(localdb)\mssqllocaldb; which of course it couldn't reach. It took 30 seconds or so to time out.
Removing those references having NLog post to (localdb)\mssqllocaldb; fixed the slowdown.  Logins and logouts are pretty zippy now.
It was NOT Microsoft's Identity solution as it seemed. It was instead logging and misconfigured NLog that was causing the issue.
I guess I need to take a closer look at Application Insights. I was under the impression it was just some spammy MS shit to data mine my users behavior. I guess I was very wrong.
Lesson here is that it seemed like it was Microsoft's Identity solution, but was in fact screwed up logging that happened every time Identity was used.


text:
Q: Como fazer um excelente programa C++ sem rastros de C? Como iniciante em C++ fiz aqui algumas perguntas e fui advertido algumas vezes por @Maniero que o que eu estava fazendo era C e não C++. O problema é que C++ permite-nos usar muitas coisas semelhantes a C.
Pergunto então: como fazer um programa "verdadeiramente" C++ (sem usar hábitos do C)?

A: Não é fácil fazer uma lista extensiva, vou tentar colocar o que é mais importante sem preocupação com pequenos detalhes (exemplo: não ter que usar void para garantir que uma função não tem parâmetros).
Lembrando que não é que seja proibido usar, mas é bom se acostumar com as partes específicas do C++, que é inclusive uma linguagem em mutação, então a melhor forma de fazer varia de versão para versão (que está em cadência fixa de 3 anos) e não recomendo nem mesmo usar alguns recursos que existiam em C++ antes do padrão C++11.
Algumas coisas de C precisam ser usadas em código bem de baixo nível, quando fará algo mais concreto, a própria biblioteca padrão do C++ está cheio disto, mas está lá para você não ter que usar. Se estiver fazendo algo assim pode ser interessante ou obrigatório usar. Em alguns raros casos, a performance só poderá ser obtida fazendo no estilo C, a maioria é igual ou mais rápido fazer no estilo C++ (sim o C++ pode ser mais rápido que C em muitos casos).
Está em curso um plano de implementação para futuras versões (se não foi abortado) algo que impede usar os recursos problemáticos da linguagem, incluindo aí os originários de C, com possibilidade de liberar o acesso específico de cada feature em um trecho bem demarcado.
Algumas coisas que ainda se faz em C nem mesmo em C deveria fazer mais, por exemplo declarar variável no começo da função. Estou considerando que as pessoas já seguem o estilo de C99. E que saibam fazer bem, tem erros que vejo por aí que nem é de usar C em C++, é fazer mal uso até em C, só que em C++ o bom uso seria diferente.
C++ procura mais robustez e performance, então tem que entender cada mínimo detalhe da linguagem para entender isso. Essa são duas linguagens que você não pode se comprometer pela metade como dá em várias outras, no mínimo não vale a pena usá-las se não estiver 100% comprometido.
Antes de tudo o estilo de como escreve também muda, em geral em C++ procura mais a legibilidade, em C procura ser mais sucinto e menos digitação.
Algumas coisas aqui estou falando grosso modo.

*

*A primeira coisa que não deveria usar é a biblioteca de C. Nada deveria ser usado, e ter um include com <algo.h> ou <cNomeDoC> já indica que está fazendo errado. Se considerar isso já praticamente não consegue fazer quase mais nada em C, mas pode ainda ter um estilo C (mais).

*Usar praticamente qualquer coisa que seja do pré-processador está errado, principalmente #define e macros e em parte o #ifdef e outras diretivas. Tudo tem solução melhor em C++, como o uso de const, enum, constrexpr, o inlining de funções (mais) e templates. Somando isso já elimina muitos outros casos.

*Um dos pontos mais importantes é não usar ponteiro bruto e preferir referências, ponteiros inteligentes, além de não usar array bruto que decaem para ponteiros e preferir abstrações da biblioteca como array, vector, string, string_view, etc. Estes 3 pontos matam quase tudo que é mais importante para eliminar C do seu código.

*Evite casts brutos, tem alguns templates prontos que fazem isto melhor.

*Use lambdas e suas variações no lugar de ponteiros para funções.

*Use a capacidade de generics dos templates no lugar de void * ou outros truques (mais).

*Esquecer de usar namespaces é algo ruim (logo vem os módulos).

*Em geral declarar algo como static no sentido de tornar privado a um arquivo não é mais muito adequado. A palavra-chave ainda faz sentido para outro contexto.

*Preferir for range com iteradores ou algoritmos prontos do que for bruto.

*Funções possuem overload, use-os.

*structs e classes são bem mais poderosas, por exemplo pode ter privacidade nos membros, ou as funções podem pertencer a elas, até se tornando métodos.

*Códigos mais modernos estão preferindo using no lugar de typedef.

*C++ tem auto, embora raramente necessário de fato é mais idiomático, já decltype tem situações mais úteis e necessárias, o que pode eliminar certos truques de PP.

*Alguns casos o que colocar em um .hpp pode ser diferente do que colocaria em um .h seu (mais).

*Vale lembrar que C++ é orientada a objeto, mais funcional, tem outras maneiras de produzir o mesmo resultado.

*E em C++ tem muita coisa pronta que C não tem, aprenda-as, tem um jeito novo, mais simples e robusto, quando não é mais performático também.
Essas coisas são um bom começo.
Também não é porque tem em C++ que é coisa boa pra usar. Existem casos que fazer mais estilo C++ pode complicar a interoperabilidade com C se for necessário, principalmente se C for o consumidor (isso é mais raro).


text:
Q: Fastest way to calculate binomial coefficients in Java I'm calculating binomial coefficients of arbitrary size using the following recursive function
private static final BigDecimal ZERO = new BigDecimal("0");
private static final BigDecimal ONE = new BigDecimal("1");

private static BigDecimal binomial(BigDecimal n, BigDecimal k) {
     if(n.equals(k) || k.equals(ZERO))
          return ONE;
     else if(k.compareTo(ZERO) < 0)
          return ZERO;
     else
          return binomial(n.subtract(ONE), k).add(binomial(n.subtract(ONE), k.subtract(ONE)));
}

For large numbers it gets really slow. Are there any simple and/or obvious optimizations to make? Not sure how much BigDecimals slows it down but making a custom class for large numbers seems like a lot of work.

A: Recursion is usually much slower because all function calls must be stored in a stack to allow the return back to the caller functions. In many cases, memory has to be allocated and copied to implement scope isolation.
Try an iterative algorithm like that:
 private static long binomial(int n, int k)
    {
        if (k>n-k)
            k=n-k;

        long b=1;
        for (int i=1, m=n; i<=k; i++, m--)
            b=b*m/i;
        return b;
    }

A: You can do reasonably well while keeping the recursion (arithmetics on BigInteger are pretty unpleasant though):
public class Binomials {
    private HashMap<Pair<BigInteger, BigInteger>, BigInteger> map = new HashMap();

    public BigInteger binomial(int n, int k) {
        return binomial(new Pair(valueOf(n), valueOf(k)));
    }

    public BigInteger binomial(Pair<BigInteger, BigInteger> x) {
        if(x.getValue().equals(ZERO) || x.getKey().equals(x.getValue())) {
            return ONE;
        }
        return map.computeIfAbsent(x, nk -> binomial(doP1(nk)).add(binomial(doP2(nk))));
    }

    private Pair<BigInteger, BigInteger> doP1(Pair<BigInteger, BigInteger> nk) {
        return new Pair(nk.getKey().subtract(ONE), nk.getValue());
    }
    private Pair<BigInteger, BigInteger> doP2(Pair<BigInteger, BigInteger> nk) {
        return new Pair(nk.getKey().subtract(ONE), nk.getValue().subtract(ONE));
    }

    public static void main(String[] args) {
        System.out.println(new Binomials().binomial(8, 4)); // 70
    }
}

In fact all the Pair and BigInteger shenanigans are noisy enough to obscure what is going on so here is the same approach in Kotlin:
fun BigInteger.plus(other: BigInteger): BigInteger = this.add(other)
fun BigInteger.minus(other: BigInteger): BigInteger = this.subtract(other)

object Binomial {
    val map = mutableMapOf<Pair<BigInteger, BigInteger>, BigInteger>()

    fun binomial(n: Int, k: Int): BigInteger =
        binomial(Pair(n.toBigInteger(), k.toBigInteger()))

    fun binomial(x: Pair<BigInteger, BigInteger>): BigInteger {
        val (n, k) = x
        if (k == ZERO || n == k) {
            return ONE
        }
        return map.getOrPut(x) { binomial(Pair(n - ONE, k)) + binomial(Pair(n - ONE, k - ONE)) }
    }
}

fun main() {
    println(binomial(8, 4)) // 70
}


text:
Q: Group Theory Sylow Subgroup What's an example of a group $G$ and an integer $n$ dividing $|G|$ with
$0 < n < |G|$ such that $G$ has no subgroup of order $n$.

A: In $A_4$,with $|A_4|=12$ are there subgroup of order $6$?

A: Suppose $|G|$ is simple non-cyclic, then $G$ is non-abelian (Use Cauchy's Theorem), then $G$ has even order (Apply Feit–Thompson theorem), hence $G$ has no subgroup of order $|G|/2$. So if $G$ is simple non-cyclic, then $|G|=2n$ and $G$ has no subgroup of order $n.$ In particular the monster group has no subgroup of order $$404008712397256437943229952480855378502877184000000000.$$