text:
Q: Selecting individual Nodes from query-xml to API I have previously achieved this using an xml file with:
XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("fileString.xml");

The query-xml I am using connects to an API and returns results, however I an having trouble selecting individual nodes because the xml is not a file so the previous way is not working.
Does anyone know how to achieve this using query-xml?
Code is: `const string hostname = "*";
            const string username = "**";
            const string password = "**";
        ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;

        var client = new InformationServiceClient("BasicHttpBinding_InformationService",
                                                  string.Format("https://{0}:17778/SolarWinds/InformationService/OrionBasic", hostname));
        client.ClientCredentials.UserName.UserName = username;
        client.ClientCredentials.UserName.Password = password;
        client.Open();

        var result = client.QueryXml("SELECT TOP 1 A.AlertDefID, I.Status, I.Node, A.ActiveObject, A.ObjectType, A.Acknowledged, A.AcknowledgedBy, A.AcknowledgedTime, A.TriggerTimeOffset, A.TriggerTimeStamp FROM Orion.AlertStatus A INNER JOIN Orion.Interface I ON A.ID = I.ID WHERE A.Acknowledged = 0 RETURN XML AUTO", null);
        `

A: Do you just need to load the string into an xml document?
You can do the following...
var xml = new XmlDocument();
xml.LoadXml(xmlString);


text:
Q: Access CakePHP controller or request object outside mvc Is there any way to access the current controller or request object outside mvc in CakePHP(2.*)?
Basically I need to access the request object in a library that is designed for CakePHP but should function on its own as much as possible - in other words I'd like to avoid any unnecessary lib-specific initialization code in the controller itself to keep the.
I have written a component for this purpose but not all calls to the lib will be directly from the controller. I'd also like to avoid passing the $controller or $request variable around anywhere else but inside the lib.
I've never looked into CakePHP class loading much, but I can recall something about ClassRegistry from when CakePHP 1.3 was new. Soon after testing ClassRegistry in a controller action I found it to be empty(determined with ClassRegistry::keys() and pr()'ing directly from the class)
So, is there any friendly way to get the request object or should I resort to uglier methods?

A: Router::getRequest() should get you the CakeRequest instance.

A: Do the following code example help you?
//in Socials Controller importing SocialUsers controller
function __checkSocialUser($title, $user_id){
    App::import('Controller', 'SocialUsers');
        $SocialUsers = new SocialUsersController;
        $SocialUsers->constructClasses();
        $ourUserId = $this->Auth->user('id');
        $SocialUsers->data = array('SocialUser' => array('title' => $title, 'identifier' => $user_id, 'user_id' => $ourUserId));
        $result = $SocialUsers->checkUser($title, $user_id);....

redpajama_set_name: RedPajamaStackExchange


text:
Q: Запрос к graphql-php получает пустой ответ У меня на локалке есть сайт site.com
Там сидит graphql-php
Открываю в браузере site.com. Из консоли делаю этот запрос (далее по тексту ЗАПРОС)
fetch("мойсайт.com", {
  body: '{"query": "mutation { sum(x: 2, y: 2) }" }',
  'mode': 'no-cors',
  method: "POST"
})
  .then(response => {
    if (response.ok) {
      response.json().then(json => {
        console.log(json);
      });
    }
  });

получаю ответ {"data":{"sum":4}}
Дальше пытаюсь со своего реакт фронта localhost:3000 сделать тот же ЗАПРОС, но ответ приходит пустой.
Хром пишет "Failed to load response data"
А если я на сервере отключю graphql, а вместо него сделаю просто echo "что-нибудь", то ЗАПРОС получает ответ "что-нибудь".
Никаких настроек с cors, Access-Control-Allow и т.д. не меняю.
На сервере прописано:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
header('Access-Control-Allow-Methods: *');

Вопрос: как мне на локалке с фронта получать ответы от graphql?


text:
Q: Copying Windows to a second drive and booting via grub? Here is my situation:
I have a netbook with an 8gb SSD as its first drive and a 32gb drive
as its secondary drive. I was hoping to install windows xp on a 20gb
partition and then share the remaining 8gb drive and 12gb partition
from drive2 for my linux experimentation.
When I boot Windows XP from the first drive, it works perfectly.
When I boot a clone of the same Windows XP install from the SECOND drive, it hangs, showing the words "Starting Up ...". The cloning of the drive was accomplished using a linux utility called partimage, but I had the same results when I used dd to copy the partition contents.
Ubuntu works fine (currently booting off the second drive).

After lots of installation and reinstallation and juggling of drives
via ubuntu I've got the following setup according to fdisk -l

Disk /dev/sda: 8069 MB, 8069677056 bytes
  255 heads, 63 sectors/track, 981 cylinders
  Units = cylinders of 16065 * 512 = 8225280 bytes
  Disk identifier: 0x294a294a
Device Boot      Start         End      Blocks   Id  System
  /dev/sda2   *         336         973     5120028    c  W95 FAT32 (LBA)
  Partition 2 has different physical/logical beginnings (non-Linux?):
      phys=(1023, 17, 4) logical=(335, 37, 55)
  Partition 2 has different physical/logical endings:
      phys=(1023, 17, 4) logical=(972, 143, 27)
  Partition 2 does not end on cylinder boundary.
  /dev/sda3             981         981        8032+  83  Linux
Disk /dev/sdb: 32.2 GB, 32279224320 bytes
  255 heads, 63 sectors/track, 3924 cylinders
  Units = cylinders of 16065 * 512 = 8225280 bytes
  Disk identifier: 0x00021104
Device Boot      Start         End      Blocks   Id  System
  /dev/sdb1   *           1         638     5124703+   c  W95 FAT32 (LBA)
  /dev/sdb2   *        2466        3924    11719417+  83  Linux

Here is the relevant section of grub's menu.lst:

title           Windows XP
  rootnoverify    (hd0,1)
  savedefault
  makeactive
  chainloader     +1
title           Windows XP (disk 2)
  root            (hd1,0)
  savedefault
  makeactive
  map             (hd0) (hd1)
  map             (hd1) (hd0)
  chainloader     +1

Anyone have any advice?
Thanks!

A: What if you installed and got XP running on the 20gb partition, then went back and installed linux after xp was up and running. I am not an expert with Grub but this is how I have done it in the past. Partition all your drives first to how you prefer, install xp on the preferred partition then linux on the preferred, during the linux setup grub should detect the different drives and automatically add entries for XP and linux.

A: Sounds like you should fix the boot sector on the second drive. I'm sure there is a linux tool to do just that, however I don't know any off the top of my head.
If you use a Windows CD and boot to Recovery Console and run "fixboot", it will likely overwrite GRUB on your first drive as well, but Windows should boot from the second drive. If you go that route, just re-install GRUB after you fix the Windows drive.
You may also need to reconfigure your windows installations from the Recovery Console, since the install has changed partitions. You can do this with the "bootcfg" command, or by editing the boot.ini file in the root of your windows partition. However, you will need to know how Windows will enumerate the partition.


text:
Q: Error parsing reference: "ubuntu:18.04 as base" is not a valid repository/tag I had a dockerfile in a repository for a while now and I built it several times in the past week.
It has this line at the top of the file:
FROM ubuntu:18.04 AS builder

Today I started getting this error:
Step 1/1 : FROM ubuntu:18.04 AS builder
Error parsing reference: "ubuntu:18.04 AS builder" is not a valid repository/tag: invalid reference format

I haven't touched the Dockerfile in that repo in a while. Nobody has touched that file in 5 months.
I ran this command to build it:
docker build .

Docker version:
bash-3.2$ docker --version
Docker version 17.03.1-ce-rc1, build 3476dbf

What am I doing wrong here.

A: Docker multi stage builds (keyword AS) were introduced in 17.06. You are using 17.03, so you need to switch to the newer docker version.


text:
Q: How to make React and Typescript to allow either base set of properties or an extended one I have a React wrapper component that renders specific components based on "variant" prop. There are basic component and two others that extend props of the basic one. Union type is not working. Here is the code of the wrapper component:
type Props =
  | ({ variant: "first" } & FirstComponentProps) }
  | ({ variant: "second" } & SecondComponentProps)
  | BaseComponentProps);

export default function WrapperComponent(props: Props) {
  switch (props.variant) {
    case "first":
      return <FirstComponent {...props} />
    case "second":
      return <SecondComponent {...props} />
    default:
      return <BaseComponent {...props} />
  }
}

Types for these components:
type BaseComponentProps = { propA: string; }
type FirstComponentProps = { propB: string } & BaseComponentProps
type SecondComponentProps = { propC: string } & BaseComponentProps

And here how this wrapper component can be used:
<WrapperComponent variant="first" propA="value" propB="value" />
<WrapperComponent variant="second" propA="value" propC="value" />
<WrapperComponent propA="value" />

This should trigger typescript warnings:
<WrapperComponent propA="value" propB="value" />

How to properly type the wrapper component props so that it allows only correct combinations of props?
Thank you!

A: There's tricky solution:
type Props =
  | ({ variant: "first" } & FirstComponentProps)
  | ({ variant: "second" } & SecondComponentProps)
  | ({ variant?: void } & { [key in Exclude<keyof (FirstComponentProps & SecondComponentProps), keyof BaseComponentProps>]?: void } & BaseComponentProps);

Playground result here
How it works?
Due to Type Compatibility, your BaseComponentProps allowed other variant's property, but it is treated as BaseComponentProps, so no any warning triggered.
Let variant's props to be void can warn you shouldn't put variant's props because that type is void.
Or use generic component:
type WrapperComponentProps<T extends 'first' | 'second' | '_base' = '_base'> =
  T extends '_base'
  ? { variant?: void } & BaseComponentProps
  : { variant: T } & ({
    'first': FirstComponentProps,
    'second': SecondComponentProps,
  }[Exclude<T, '_base'>]);

export default function WrapperComponent<T extends 'first' | 'second' | '_base' = '_base'>(props: WrapperComponentProps<T>) {
  switch (props.variant) {
    case "first":
      return <FirstComponent {...props} />
    case "second":
      return <SecondComponent {...props} />
    default:
      return <BaseComponent {...props} />
  }
}

Playground result here
This one will restrict props type by condition (default is BaseComponentProps).


text:
Q: How to maintain a custom sort order in Mysql? Say I have a dropdown buttons of credit cards.
My ordering is:
SELECT * from cards;

DISCOVER
MASTER-CARD
VISA

I actually want
MASTER-CARD
VISA
DISCOVER

This is a custom order decided by business.
So I though of maintaining a sequence_id in Mysql
DISCOVER 3
MASTER-CARD 1
VISA 2

So I can get these fields in order of their sequence_id.
SELECT * from cards order by sequence_id;

MASTER-CARD 1
VISA 2
DISCOVER 3

But the problem is when I have to add another card in the table, I will have to custom update all ids.
Is there a better way to maintain sequence?
How to define a custom ORDER BY order in mySQL does not solve my problem as I can't specify all the fields in my query as the table is huge and keeps changing.

A: The term sequence_id suggests that you want to use the primary key to keep order information. I see no benefit and lots of hassles in that approach. But it also suggest you don't have a primary key yet, which is not good either.
Just add a dedicated column:
CREATE TABLE cards (
   id int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
   card_name varchar(50) NOT NULL,
   sort_order INT(10) UNSIGNED NOT NULL DEFAULT 9999999,

   PRIMARY KEY (id)
);

... and change your query to:
SELECT *
FROM cards
ORDER BY sort_order;

The 9999999 default is just a trick to ensure newly added cars show up last until you care sorting them—it's entirely optional.

A: ORDER BY FIND_IN_SET(card, "MASTER-CARD,VISA,DISCOVER")

will sort with card = 'MASTER-CARD' first, etc.


text:
Q: Botão que muda a cor do site estou a tentar fazer no meu website um botão que seja sticky, ao clicar nesse botão, ele faz um collapse right e mostra um container com um certo numero de cores disponiveis para o utilizador escolher, o utilizador ao escolher a pallette de cores, o site mudará a cor do layout para a pallette escolhida pelo user...
Meu codigo até ao momento...
HTML:

CSS:
.color-chg {
  position: fixed;
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
    z-index: 2000;
}

/* Stylyng the icon */
.color-chg a {
  display: block;
  text-align: center;
  padding: 30px;
  transition: all 0.3s ease;
  color: white;
  font-size: 100%;
}

.color-chg a:hover {
  background-color: white;
    color: #74c8d2;
    border: 2px solid #74c8d2;
}

.color-btn {
    border: 2px solid transparent;
  background: #74c8d2;
  color: white;
}

O que eu quero:

Por favor me deem umas dicas, eu não faço a minima ideia de como fazer isso, pesquisei, mas não encontro nada na internet, estive a verificar o codigo fonte desse site, mas não ajuda muito...
Obrigado pessoal!

A: Você pode via javascript ao clicar nas cores adicionar uma class ao body e criar um css para cada cor.
JS:
$(document).ready(function(){$("#azul_bt").click(function(){$("body").toggleClass("skin_azul");

CSS:
body.skin_azul h1 {
    color: blue;
}

Seria um pouco trabalhoso e o ideal seria montar tudo já pensando nessa transição, porém funciona.

A: Cara apenas a parte do collapse com as cores vc pode fazer usando o position:fixed e transition com right para colocar a paleta escondida para fora da tela.
Fiz um exemplo bem simples apenas da parte do collapse, a dinâmica para ele trocar as cores dos outros elementos depois de clicado vou deixar por sua conta. Ele usa flex, então sempre que vc adicionar mais cores ele vai quebrando a linha de 4 em 4
Como falei é um exemplo simples, mas com o que tem ai de CSS vc consege desenvolver bem mais esse componente.
Veja como ficou:

html, body {
    width: 100%;
    height: 200%;
    margin: 0;
    padding: 0;
}

.cores {
    display: flex;
    width: 200px;
    position: fixed;
    right: -160px;
    top: 20%;
    transition: right 350ms;
}
.btn {
    width: 40px;
    height: 40px;
    background-color: #000;
    display: flex;
    justify-content: center;
    align-items: center;
    color: rgba(255, 255, 255,0.6);
    font-size: 2rem;
    transition: color 350ms;
    cursor: pointer;
    line-height: 0;
}
.btn:hover {
    color: rgba(255, 255, 255,1);
}
#btn {
    display: none;
}
.paleta {
    box-sizing: border-box;
    border: 1px solid black;
    width: 160px;
    margin: 0;
    padding: 1rem;
    background-color: #eee;
    display: flex;
    flex-wrap: wrap
}
.paleta h4 {
    margin: 0 0 0.5em;
    width: 100%;
}
.paleta .box {
    width: 30px;
    height: 30px;
    box-sizing: border-box;
    border: 1px solid #666;
    cursor: pointer;
    opacity: 0.65;
    transition: background-color 350ms;
}
.paleta .box:hover {
    opacity: 1;
}
.paleta .box.red {
    background-color: red;
}
.paleta .box.blue {
    background-color: blue;
}
.paleta .box.green {
    background-color: green;
}
.paleta .box.purple {
    background-color: purple;
}
.paleta .box.orange {
    background-color: orange;
}
.paleta .box.black {
    background-color: black;
}
input:checked + .cores {
    right: 0;
}
input:checked + .cores > .btn {
    color: rgba(255, 255, 255,1);
}
<input type="checkbox" id="btn">

    ✎

Cores


text:
Q: "this" context in a function In the following code, I am unable to understand few things about this
function Stack() {
  let items = [];
  push = function(element){
   items.push(element);
 };

 this.pop = function(){
  return items.pop(); // removes and returns the element.
 };
}
let stk= new Stack();
stk.push(); // 1
stk.pop(); //  no error

*

*throws stk.push is not a function. why ? why lack of this is blocking the push method.

*why it has to be new Stack(), why cannot it be let stk= Stack() to recognize methods inside the function?

since I am instantiating the Stack function, irrespective of whether the methods are declared with this or not , the stk var should be able to access functions, isn't it?

A: Let's see two examples:
push = function() { /*...*/ }

And
var push = function() { /*...*/ }

In the first one push is a global variable.
So we do not define anything like Stack.push it's push.
So wen you do:
push();

It's executed and fails of course!
In the second one the variable is scoped locally that means it can be used only inside Stack function.
So in that case the push is undefined anywhere outside Stack.
No push and Stack.push nor stk.push is defined.
Now let's view other options:
this.push = function() { /*...*/ }

This defines field push of the current object.
Let's clarify that:
let Stack = function() {
     this.push = function() { console.log("Hello!"); }
     console.log(this);
};
Stack();

So what we get is:

Window {frames: Window, postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, …}

Wait what? That means that the context (this) of function is Window object.
So in that case (if we work inside browser) we defined again the global
variable push!
let Stack = function() {
     this.push = function() { console.log("Hello!"); }
};
Stack();
push();

Outputs

Hello!

So now to the rescue comes the new keyword.
Basically the Mozilla docs say:

When the code new Foo(...) is executed, the following things happen:
A new object is created, inheriting from Foo.prototype.
  The constructor function Foo is called with the specified arguments, and with
  this bound to the newly created object.
  new Foo is equivalent to new Foo(),
  i.e. if no argument list is specified,
  Foo is called without arguments.
The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead.
(Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)

That's it!
The new keyword binds this to newly created object.
So when we execute
new Stack()

The this keyword refers to the object we create! Thats why when we assign
this.push = /* Something */

It can be understood like the following code:
// Create new stack object
var stack = /* This is done by the 'new' keyword */

// Run our code
stack.push = /* Something */

So bassically that's it! Hope it helps you :)

A: A function is an object and this refers to the specific instance of an object.
If you have a function within a function without the this, it is local to the function.
With the this the inner function becomes a method of the object and may be called to perform some action.


text:
Q: Reasons for : xxx.aspx has not been pre-compiled and cannot be requested (it is pre-compiled) hoping someone has some insight into this issue I get pretty commonly.
I have an ASPX Web Application that is pre-compiled. I have this application running within another IIS application working flawlessly. The parent application has an "updatable=false" property within the PreCompiledapp.config.
Now I need to add more pages to my application, which I create the same way in visual studio, and publish them with the rest of the application. When I open these files to check them in notepad, I can see the "This is a marker file generated by the precompilation tool, and should not be deleted!" as well as the .compiled file that generates with it.
On a local machine and application instance, this works... but when I copy the same applicaiton build to a client (same application, same pages, same everything) it gives me the " xxx.aspx has not been pre-compiled and cannot be requested " error.
What could be some causes of this? The pages are pre-compiled so I'm wondering if this can be thrown for something else. Any help is appreciated thanks!

A: I think the cause may be the parent application is set with updatable=false but the ASPX Web Application which you published is allow update. So it may lead to this problem. The same error message and the cause are described in detail here.
To solve this problem is convert your application to web application(has its own AppDomain and configuration) or publish the root application as updatable as well.


text:
Q: How to modify values in delimiter text file in unix I have a huge file with delimited value with '~' example
abc~poi~123~jijda~123~abc
Requirement is to replace the values at 3rd occurrence (which is 123 in our case) to be replaced with 111.
I used the below command

awk -F '~' -v OFS='~' '$3 == "123" {$3 = "111"} 1 ' file.txt > Newfile.txt

this works for manually created file but when it the file was created using utf-8 encoding it doesn't work. Can some one help on this. Thanks!

A: UTF-8 should be no problem.
# SO71048003.awk
BEGIN {
  FS = OFS = "~"
  out = "Newfile.txt"
}

{
  if ($3 == "123")
    $3 = "111"
  print $0 > out
}

Call:
awk -f SO71048003.awk file.txt
=> Newfile.txt with content:
abc~poi~111~jijda~123~abc

A: Your awk code with some changes:
awk -F'~' -v OFS='~' '{$3=111} 1' file
abc~poi~111~jijda~123~abc

*

*we assign to $3 the 111 value.


text:
Q: 'The term 'New-ComplianceTag' is not recognized as the name of a cmdlet, function, script file, or operable program what should be done , how to remove this System.Management.Automation.CommandNotFoundException error
when i try to invoke this command in powershell using c#
but i works fine when i do it directly in powershell.
enter image description here

A: This is an Exchange Online cmdlet for the Security & compliance Center. The Exchange Online module loads cmdlets remotely from Microsoft. It will only load the cmdlets you have permissions for.
My best guess is that you're missing the permissions for this cmdlet/ setting.


text:
Q: java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created I am trying to combine retrofit 2 with RxJava and Realm, by saving the response of the service call returned by the retrofit observable to local database using realm. So i get an exception saying that Realm access from incorrect thread.
Here is my code :
Trail 1:
restApi.userEntityList()
            .map(userEntityDataMapper::transformAllToRealm)
            .doOnNext(userRealmModels -> {
                if (userRealmModels != null){
                    mRealm = Realm.getInstance(mContext);
                    mRealm.asObservable()
                            .map(realm -> mRealm.copyToRealmOrUpdate(userEntity))
                            .subscribe(new Subscriber<Object>() {
                                @Override
                                public void onCompleted() {

                                }

                                @Override
                                public void onError(Throwable e) {
                                    e.printStackTrace();
                                }

                                @Override
                                public void onNext(Object o) {
                                    Log.d("RealmManager", "user added!");
                                }
                            });
                }})
            .map(userEntityDataMapper::transformAll)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<List<User>>() {
                 @Override
                 public void onCompleted() {
                     hideViewLoading();
                 }

                 @Override
                 public void onError(Throwable e) {
                     hideViewLoading();
                     showErrorMessage(new DefaultErrorBundle((Exception) e));
                     showViewRetry();
                 }

                 @Override
                 public void onNext(List<User> users) {
                     showUsersCollectionInView(users);
                 }
            });

Trail 2:
restApi.userEntityList()
            .map(userEntityDataMapper::transformAllToRealm)
            .doOnNext(userRealmModels -> {
                if (userRealmModels != null) {
                    mRealm = Realm.getInstance(mContext);
                    mRealm.beginTransaction();
                    mRealm.copyToRealmOrUpdate(userEntity);
                    mRealm.commitTransaction();
                }
            })
            .map(userEntityDataMapper::transformAll)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<List<User>>() {
                 @Override
                 public void onCompleted() {
                     hideViewLoading();
                 }

                 @Override
                 public void onError(Throwable e) {
                     hideViewLoading();
                     showErrorMessage(new DefaultErrorBundle((Exception) e));
                     showViewRetry();
                 }

                 @Override
                 public void onNext(List<User> users) {
                     showUsersCollectionInView(users);
                 }
            });

Logcat :
W/System.err: java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.
at io.realm.BaseRealm.checkIfValid(BaseRealm.java:349)
at io.realm.BaseRealm.commitTransaction(BaseRealm.java:291)
at io.realm.Realm.commitTransaction(Realm.java:108)
at com.zeyad.cleanarchitecturet.data.db.RealmManagerImpl.put(RealmManagerImpl.java:66)
at com.zeyad.cleanarchitecturet.data.db.RealmManagerImpl.putAll(RealmManagerImpl.java:91)
at com.zeyad.cleanarchitecturet.data.repository.datasource.CloudUserDataStore$2.call(CloudUserDataStore.java:36)
at com.zeyad.cleanarchitecturet.data.repository.datasource.CloudUserDataStore$2.call(CloudUserDataStore.java:32)
at rx.Observable$11.onNext(Observable.java:4445)
at rx.internal.operators.OperatorDoOnEach$1.onNext(OperatorDoOnEach.java:80)
at rx.internal.operators.OperatorMap$1.onNext(OperatorMap.java:54)
at rx.internal.operators.OperatorMerge$MergeSubscriber.emitScalar(OperatorMerge.java:477)
at rx.internal.operators.OperatorMerge$MergeSubscriber.tryEmit(OperatorMerge.java:435)
at rx.internal.operators.OperatorMerge$MergeSubscriber.onNext(OperatorMerge.java:228)
at rx.internal.operators.OperatorMerge$MergeSubscriber.onNext(OperatorMerge.java:142)
at rx.internal.operators.OperatorMap$1.onNext(OperatorMap.java:54)
at retrofit.RxJavaCallAdapterFactory$CallOnSubscribe.call(RxJavaCallAdapterFactory.java:113)
at retrofit.RxJavaCallAdapterFactory$CallOnSubscribe.call(RxJavaCallAdapterFactory.java:88)
at rx.Observable$2.call(Observable.java:162)
at rx.Observable$2.call(Observable.java:154)
at rx.Observable$2.call(Observable.java:162)
at rx.Observable$2.call(Observable.java:154)
at rx.Observable$2.call(Observable.java:162)
at rx.Observable$2.call(Observable.java:154)
at rx.Observable$2.call(Observable.java:162)
at rx.Observable$2.call(Observable.java:154)
at rx.Observable$2.call(Observable.java:162)
at rx.Observable$2.call(Observable.java:154)
at rx.Observable$2.call(Observable.java:162)
at rx.Observable$2.call(Observable.java:154)
at rx.Observable$2.call(Observable.java:162)
at rx.Observable$2.call(Observable.java:154)
at rx.Observable.unsafeSubscribe(Observable.java:8098)
at rx.internal.operators.OperatorSubscribeOn$1$1.call(OperatorSubscribeOn.java:62)
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
at rx.schedulers.ExecutorScheduler$ExecutorSchedulerWorker.run(ExecutorScheduler.java:98)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: rx.exceptions.OnErrorThrowable$OnNextValue: OnError while emitting onNext value: java.util.ArrayList.class
at rx.exceptions.Exceptions.throwOrReport(Exceptions.java:187)
at rx.internal.operators.OperatorDoOnEach$1.onNext(OperatorDoOnEach.java:82)
... 29 more

A: I found out how to fix it. To save server responses from retrofit 2 to realm then pass to the UI.
I made retrofit return realm objects by overriding the Gson Builder like this:
Retrofit.Builder()
            .baseUrl(RestApi.API_BASE_URL)
            .client(okHttpClient)
            .callbackExecutor(new JobExecutor())
            .addConverterFactory(GsonConverterFactory.create(new GsonBuilder()
                    .setExclusionStrategies(new ExclusionStrategy() {
                        @Override
                        public boolean shouldSkipField(FieldAttributes f) {
                            return f.getDeclaringClass().equals(RealmObject.class);
                        }

                        @Override
                        public boolean shouldSkipClass(Class<?> clazz) {
                            return false;
                        }
                    }).create()))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();

Then:
restApi.userRealmList()
    .doOnNext(userRealmModels -> {
        if (userRealmModels != null) {
            Realm realm = Realm.getInstance(mContext);
            realm.beginTransaction();
            realm.copyToRealmOrUpdate(userRealmModels);
            realm.commitTransaction();
            realm.close();
        }})
    .map(userEntityDataMapper::transformAll)
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Subscriber<List<User>>() {
         @Override
         public void onCompleted() {
             hideViewLoading();
         }

         @Override
         public void onError(Throwable e) {
             hideViewLoading();
             showErrorMessage(new DefaultErrorBundle((Exception) e));
             showViewRetry();
         }

         @Override
         public void onNext(List<User> users) {
             showUsersCollectionInView(users);
         }
    });

A: I think you have created Realm objects using main thread and you are using it in another or background thread. If so, then use them in the same thread they are created.
i.e.
((Activity)mContext).runOnUiThread(new Runnable() {
   @Override
   public void run() {
        // You code of realm goes here
        if (userRealmModels != null) {
               mRealm = Realm.getInstance(mContext);
               mRealm.beginTransaction();
               mRealm.copyToRealmOrUpdate(userEntity);
               mRealm.commitTransaction();
         }
   }
});


text:
Q: bash tr extra operand on redirect to another file I have a small script that downloads a value from a web page.
Before anyone looses their mind because I am not using an HTML parser, besides the headers, the  whole web page only has 3 lines of text between one pair of pre tags. I am just after the number values - that is it.

sym
---
12300

This is the script :
#!/bin/bash
wget -O foocounthtml.txt  "http://foopage"
tr -d "\n" foocounthtml.txt > foocountnonewlines.txt

Anyhow the tr command is throwing an error.
tr: extra operand 'foocounthtml.txt'
Only one string may be given when deleting without squeezing repeats.
Try 'tr --help' for more information.

Yes, I could use sed for inplace modification with the -i tag. However I am perplexed by this tr error. Redirecting tr output works fine from command line, but not in a script.

A: The 'tr' command operates on SETs of text rather than files. From the man page:
NAME
   tr - translate or delete characters

SYNOPSIS
    tr [OPTION]... SET1 [SET2]

DESCRIPTION
    Translate, squeeze, and/or delete characters from standard input, writing to standard output.

...

    SETs are specified as strings of characters.  Most represent themselves.  Interpreted sequences are:

So tr is expecting the actual content you want to operate on rather than the target file. You can simply pipe the files contents to tr for the resuts you  want
cat foocounthtml.txt | tr -d "\n" > foocountnonewlines.txt

or as @CHarlesDUffy points out, it would be faster to read directly from the file:
tr -d "\n" < foocounthtml.txt > foocountnonewlines.txt


text:
Q: python - enumerate next() not working l = []
for i, obj in enumerate(queryset):
    if queryset[i].next():
        if queryset[i].common_id == queryset[i+1].common_id:
            l.append(queryset[i])

but I am getting:
'MyModel' object has no attribute 'next'

but the docs says:

The next() method of the iterator returned by enumerate() returns a
  tuple containing a count and the
  values obtained from iterating over sequence

what am I doing wrong?

A: The next() method you are talking about is for the iterator returned by enumerate. For instance:
>>> someIterator = enumerate(range(5,10))
>>> tuple = someIterator.next()
>>> tuple
(0, 5)

When doing a for loop, the for loop calls enumerate(...).next() each step. It's like when you are doing in C for (i=0;i<10;i++), in the core of the loop, you don't have to increment i anymore.
If in your loop you just need to access some object and the next, you should take care of the last step:
>>> l = range(5,10)
>>> for i, obj in enumerate(l):
...   print l[i],l[i+1]
...
5 6
6 7
7 8
8 9
9
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IndexError: list index out of range
>>>

and instead only use range:
>>> for i in range(len(l)-1):
...   print l[i],l[i+1]
...
5 6
6 7
7 8
8 9

since in your loop, you don't use obj anyway.
You can also take special care of the last step:
>>> l = range(5,10)
>>> for i, obj in enumerate(l):
...   if i<len(l)-1:
...     print l[i],l[i+1]
...   else:
...     print l[i]
...
5 6
6 7
7 8
8 9
9

Or use the iterator in a while loop (when there is no item, next() raises a StopIteration
>>> someIterator = enumerate("abcde")
>>> current = someIterator.next()
>>> try:
...     while someIterator:
...        nextOne = someIterator.next()
...        print current, nextOne
...        if current == nextOne:
...           pass#dosomething
...        current = nextOne
... except:
...     print "end of iteration", current
...
(0, 'a') (1, 'b')
(1, 'b') (2, 'c')
(2, 'c') (3, 'd')
(3, 'd') (4, 'e')
end of iteration (4, 'e')

A: Possibly a better way to handle this is to use zip in a list comprehension:
l = [item for item, next_item in zip(queryset, queryset[1:])
         if item.common_id == next_item.common_id]


text:
Q: connect() failed (111: Connection refused) while connecting to upstream, client I am trying to deploy a django instance to ec2 . I am using a combination of nginx and gunicorn to achieve that. I got the nginx isntance and gunicorn to start correctly and I am able to get my instance running. But when i try to upload an image to the database on my application I run into this error in my gunicorn error.log  :
connect-failed-111-connection-refused-while-connecting-to-upstream
Also all my api calls from the front end to the database return a 500 internal server in the console.
My nginx.conf looks like
default_type        application/octet-stream;

# Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
include /etc/nginx/sites-available/*;
index   index.html index.htm;

server {
    listen       127.0.0.1:80;
    listen       [::]:80 default_server;
    server_name  127.0.0.1;
    root         /usr/share/nginx/html;

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    location / {
    }

    # redir

And my sites-enabled/default file as
upstream app_server_djangoapp {
server 127.0.0.1:8000 fail_timeout=0;

}
server {
    #EC2 instance security group must be configured to accept http connections over Port 80
    listen 80;
    server_name myec2isntance.com;
access_log  /var/log/nginx/guni-access.log;
error_log  /var/log/nginx/guni-error.log info;

keepalive_timeout 5;

# path for static files
location /static {
    alias xxxxxx;
}
location /media {
    alias xxxxxx;
}
location / {
 location / {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;

    if (!-f $request_filename) {
       proxy_pass http://app_server_djangoapp;
       break;
    }
}

}
I tried most of the things people talked about - adding right permissisons to the folders. Changing localhost to 127.0.0.1 etc. I am relatively new to this topic so any help would be much appreciated!
Thank you

A: I would suggest to change default to this :
upstream app_server_djangoapp {
server 127.0.0.1:8000 max_fails=3 fail_timeout=50;
keepalive 512;
}

- remove
keepalive_timeout 5;

- why do u have two location / blocks ?
    location / {
    location / {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;

    if (!-f $request_filename) {
       proxy_pass http://app_server_djangoapp;
       break;
    }
}


text:
Q: Negative Lookbehind Regex not working in PHP I wrote a piece of code in PHP that is intended to match an adverb (word ending in 'ly') that should not match any word that is daily, weekly, monthly, bi-daily, bi-weekly, etc.
For example, given the sentence Locally meet daily for 3 days, only Locally should match.
I nailed the Regex syntax using negative lookbehind, but PHP is throwing me an error:

Compilation failed: lookbehind assertion is not fixed length at offset..

Here is my full code in PHP:
<?php
$sentence = "Locally meet daily for next 3 days";

// Use preg_match() function to check match
preg_match('/(\w+ly)(?<!(daily|weekly|monthly))/', $sentence, $matches, PREG_OFFSET_CAPTURE);

// Display matches result
print_r($matches);

I have tried negative lookahead, but it is not giving me promising results. Would someone please suggest what could be done? Thanks

A: You can use a negative lookahead, but it needs to be before your match group. You also need to add a word-break (\b) assertion at the beginning of the regex so that (for example) the regex doesn't match aily in daily, and another at the end so you don't match words with ly in the middle e.g. newlywed:
$sentence = "Locally meet daily newlywed for next 3 days";

preg_match_all('/\b(?!(?:daily|weekly|monthly))(\w+ly)\b/', $sentence, $matches, PREG_OFFSET_CAPTURE);

print_r($matches);

Output:
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => Locally
                    [1] => 0
                )
        )
    [1] => Array
        (
            [0] => Array
                (
                    [0] => Locally
                    [1] => 0
                )
        )
)

Demo on 3v4l.org


text:
Q: Как сделать из десятичной дроби соответствующее целое число? Мне дали задание найти разницу между сумами целой и дробной части действительного числа. Я смог с помощью оператора mod.f разделить число на целую и дробную часть. Для нахождения суммы использую следующий цикл:
a1:
    if (k != 0) {

        g = k % 10;
        f = g + f;
        k = k / 10;
        goto a1;
    }

С целой частью я справился, но для дробной части это не подходит по понятным причинам. Ну и вот суть проблемы: как мне превратить десятичную дробь в целое число без 0. ?

A: Что-то типа
int s2i(string& s)
{
    if (auto p = s.find('.'); p != s.npos)
        s.erase(p,1);
    return stoi(s);
}

устроит? Защиту от дурака можно и дописать, как и для научной записи (эта функция не поймет что-то типа 1e3).


text:
Q: Bypassing the only_full_group_by restriction I have this simple table:
mysql> select deviceId, eventName, loggedAt from foo;
+----------+------------+---------------------+
| deviceId | eventName  | loggedAt            |
+----------+------------+---------------------+
|        1 | foo        | 2020-09-18 21:27:21 |
|        1 | bar        | 2020-09-18 21:27:26 |
|        1 | last event | 2020-09-18 21:27:43 |  <--
|        2 | xyz        | 2020-09-18 21:27:37 |
|        2 | last event | 2020-09-18 21:27:55 |  <--
|        3 | last one   | 2020-09-18 21:28:04 |  <--
+----------+------------+---------------------+

and I want to select one row per deviceId with the most recent loggedAt. I've marked those rows with an arrow in the table above for clarity.
If I append  group by id in the above query, I get the notorious:

Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'foo.eventName' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

and I don't want to change the sql_mode.
I've come pretty close to what I want using:
select deviceId, any_value(eventName), max(loggedAt) from foo group by deviceId;

but obviously the any_value returns a random result.
How can I solve this?

A: ONLY_FULL_GROUP_BY is a good thing: it enforces fundamental SQL standard rules, about which MySQL has been lax for a long time. Even if you were disabling it, you would get the same result as what you are getting with any_value().
You have a top-1-per group problem, where you cant the entire row that has the most recent date for each device. Aggregation is not the right tool for that, what you need is to filter the dataset.
One option uses a correlated subquery:
select f.*
from foo f
where f.loggedat = (
    select max(f1.loggedate) from foo where f1.deviceid = f.deviceid
)

In MySQL 8.0, you can also use row_number():
select *
from (
    select f.*, row_number() over(partition by deviceid order by loggedat desc) rn
    from foo f
) f
where rn = 1


text:
Q: How to pick bitflag values? I have a set of options, some orthogonal (can be combined in any combination), some exclusive (only one from the set is allowed), and need to pick a set of enum values so that they can be combined with bit-wise or and extracted with bit-wise and. I would prefer that or-ing invalid combination would be detectable.
Are there any tools for generating enums like this?
Edit for clarity
I'm looking for something that can leverage the fact that some flags are invalid in combination to reduce the number of bits used. The requirement that I be able to detect errors is soft. I don't need to be able to tell what was used if things are mucked up.
I'm using C#, but any solution should be helpful.
An example pattern would be:
0011 00
0101 00
1001 00
0110 00
1010 00
1100 00

0000 01
0000 10

that gets 6 exclusive flags and an orthogonal pair of 2 into 6 bits
a quick test show that 5-bits gives 9 values, 6-bits give 20,...

A: The best general method I'm aware of for doing this isn't so much a tool as a convention: defining lists of bitflags like this:
FLAG_1                    0x00000001
FLAG_2                    0x00000002
FLAG_3                    0x00000004
FLAG_4                    0x00000008
FLAG_5                    0x00000010
FLAG_6                    0x00000020

It's easy to work with because the numbers continue on that 1, 2, 4, 8 pattern moving left.
EDIT: Responding to comment.  Well, if you really want a combination of bitflags with exclusive enumerations, what you basically have to do is segment out portions of the bit list to be treated as a numeric space.  So you can take the two bits 0x1 and 0x2 and now you can represent 0-3 using those two bits.  Something like:
OPT_1_VAL_1               0x00000000
OPT_1_VAL_2               0x00000001
OPT_1_VAL_3               0x00000002
OPT_1_VAL_4               0x00000003
FLAG_1                    0x00000004
FLAG_2                    0x00000008
FLAG_3                    0x00000010
FLAG_4                    0x00000020

The masking logic you use then has to be more complex.  For looking up the flags, you can do if(settings & FLAG_1), but for the option spaces you have to do if((settings & OPT_1_VAL_3) == OPT_1_VAL_3).

A: I don't know of a tool, but here's a trick to make unique-bit enums marginally easier to produce:
public enum Critters
{
   Amorphous = 0,
   Sloth =     1 << 0,
   Armadillo = 1 << 1,
   Weasel =    1 << 2,
   Crab =      1 << 3,
   Partridge = 1 << 4,
   Parakeet =  1 << 5,
   Rhino =     1 << 6
};

A: To represent an "exclusive" set of n options (i.e. exactly one must be chosen), we require at least ceil(log2(n)) bits. For example, option k can be represented by the number k in base-2.
To represent an "orthogonal" set of n options (i.e. any combination of size 0, 1, ..., n can be chosen), we require at least n bits. For example, options k0, k1, k2 could be represented by the binary number whose bits are zero except for bits 0, 1, 2.
So, to represent multiple option sets simultaneously, we add up the number of bits required for each option set (depending on whether it is "exclusive" or "orthogonal") to get the total number of bits required.
In short, to pick the enum values,

*

*"exclusive" option k uses k << r

*"orthogonal" option k0, k1, ..., k{n-1} uses 0x1 << r, 0x1 << (r+1), ..., 0x1 << (r+n-1)
where offset r is the number of bits used by the preceding option sets.

Example of how to automate this construction, in Java:
/**
 * Construct a set of enum values, for the given sizes and types
 * (exclusive vs orthogonal) of options sets.
 *
 * @param optionSetSizes
 *     number of elements in each option set
 * @param isOptionSetExclusive
 *     true if corresponding option set is exclusive, false if
 *     orthogonal
 * @returns
 *     array of m elements representing the enum values, where
 *     m is the sum of option set sizes. The enum values are
 *     given in the order of the option sets in optionSetSizes
 *     and isOptionSetExclusive.
 */
int[] constructEnumValues(
        int[] optionSetSizes,
        boolean[] isOptionSetExclusive)
{
    assert optionSetSizes.length == isOptionSetExclusive.length;

    // determine length of the return value
    int m = 0;
    for (int i = 0; i < optionSetSizes.length; i++) m += optionSetSizes[i];
    int[] vals = new int[m];

    int r = 0; // number of bits used by the preceding options sets
    int c = 0; // counter for enum values used

    for (int i = 0; i < optionSetSizes.length; i++)
    {
        // size of this option set
        int n = optionSetSizes[i];

        // is this option set exclusive?
        boolean exclusive = isOptionSetExclusive[i];

        for (int k = 0; k < n; k++)
        {
            vals[c] = (exclusive) ? (k << r) : (0x1 << (r + k));
            c++;
        }

        r += (exclusive) ? (int) Math.ceil(Math.log(n)/Math.log(2)) : n;
    }

    return vals;
}

A:
... need to pick a set of enum values
  so that they can be combined ...

Do you really need to pick them manually? Java, for instance, has EnumSet which does the dirty work for you and presents you with a Set interface for manipulating these flags.

A: Use powers of two so that each flag corresponds to a single bit position.

A: You can use standard enums (in C#) for that purpose. To accomplish this, you need to set the FlagsAttribute, and then specifically number the values. The code would look something like this:
[Flags]
public enum AvailableColours {
    black = 1,
    red = 2,
    green = 4,
    blue = 8,
    white = 16,
}

And then, the standard bitwise operators will work as expected.
[Edit]
Um, OK, you want to generate possible combinations, right? Your requirements are very specific, so I would be very surprised if there were any tool that came close to what you want. I think you're going to have to roll your own. I'm assuming you want these as strings, correct? Here is some utility code to at least get you started:
public const int BITS_IN_BYTE = 8;
public const int BYTES_IN_INT = sizeof(int);
public const int BITS_IN_INT = BYTES_IN_INT * BITS_IN_BYTE;

/// <summary>
/// Display the bits in an integer
/// </summary>
/// <param name="intToDisplay">The integer to display</param>
/// <returns>A string representation of the bits</returns>
public string IntToBitString(int intToDisplay) {
    StringBuilder sb = new StringBuilder();
    AppendBitString(intToDisplay, sb);
    return sb.ToString();
}

/// <summary>
/// Displays the bits in an integer array
/// </summary>
/// <param name="intsToDisplay">Arrau to display</param>
/// <returns>String representation of the bits</returns>
public string IntArrayToBitString(int[] intsToDisplay) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < intsToDisplay.Length -1; i++) {
        AppendBitString(intsToDisplay[i], sb);
        sb.Append(' ');
    }
    if (intsToDisplay.Length - 1 > 0)
        AppendBitString(intsToDisplay[intsToDisplay.Length - 1], sb);
    return sb.ToString();
}

private void AppendBitString(int intToAppend, StringBuilder sb) {
    for (int j = BITS_IN_INT - 1; j >= 0; j--) {
        sb.Append((intToAppend >> j) & 1);
        if (j % 4 == 0 && j > 1)
            sb.Append(' ');
    }
}

/// <summary>
/// Creates an integer from a bit string. This method can be used
/// to explicitly set bits in an integer during testing.
/// </summary>
/// <example>
/// int i = bitUtil.IntFromBitString("0000 0000 0000 0100");
/// </example>
/// <param name="bitString">String representing the individual bits</param>
/// <returns></returns>
public int IntFromBitString(String bitString) {
    int returnInt = 0;
    int currentBitPos = bitString.Length;
    for (int i = bitString.Length - 1; i >= 0; i--) {
        char c = bitString[i];
        if (Char.IsWhiteSpace(c)) continue;

        if (c == '1') {
            returnInt |= 1 << (bitString.Length - currentBitPos);
        }
        currentBitPos--;
    }
    return returnInt;
}

/// <summary>
/// Tests the status of an individual bit in and integer. It is 0 based starting from the most
/// significant bit.
/// </summary>
/// <param name="bits">The integer to test</param>
/// <param name="pos">The position we're interested in</param>
/// <returns>True if the bit is set, false otherwise</returns>
public bool IsBitOn(int bits, int pos) {
    int shiftAmnt = (BITS_IN_INT - 1) - pos;
    return ((bits >> shiftAmnt) & 1) == 1;
}

/// <summary>
/// Calculates the number of integers (as in an array of ints) required to
/// store a given number of bits
/// </summary>
/// <param name="bitsNeeded">The total count of required bits</param>
/// <returns>The number of integers required to represent a given bit count</returns>
public int RequiredSizeOfIntArray(int bitsNeeded) {
    return (bitsNeeded / BITS_IN_INT) + (((bitsNeeded % BITS_IN_INT) == 0) ? 0 : 1);
}

/// <summary>
/// Calculates which array element would hold the individual bit for a given bit position
/// </summary>
/// <param name="bitPos">The position of the interesting bit</param>
/// <returns>An index into an array of integers</returns>
public int ArrayPositionForBit(int bitPos) {
    return bitPos / BITS_IN_INT;
}

/// <summary>
/// Sets an individual bit to a given value
/// </summary>
/// <param name="bits">The integer containing the bits</param>
/// <param name="pos">The position in the integer to set</param>
/// <param name="isSet">True for on, False for off</param>
public void SetBit(ref int bits, int pos, bool isSet) {
    int posToSet = (BITS_IN_INT - 1) - pos;
    if (isSet)
        bits |= 1 << posToSet;
    else
        bits &= ~(1 << posToSet);
}

/// <summary>
/// Converts an array of integers into a comma seperated list
/// of hexidecimal values.
/// </summary>
/// <param name="bits">The array of integers</param>
/// <returns>String format</returns>
public String IntArrayToHexString(int[] bits) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < bits.Length - 1; i++) {
        sb.Append(bits[i].ToString("X"));
        sb.Append(',');
    }
    if (bits.Length > 0) {
        sb.Append(bits[bits.Length - 1].ToString("X"));
    }
    return sb.ToString();
}

/// <summary>
/// Parses a comma seperated list of hexidecimal values and
/// returns an array of integers for those values
/// </summary>
/// <param name="hexString">Comma seperated hex values</param>
/// <returns>integer array</returns>
public int[] HexStringToIntArray(String hexString) {
    string[] hexVals = hexString.Split(new char[] {','});
    int[] retInts = new int[hexVals.Length];
    for (int i = 0; i < hexVals.Length; i++) {
        retInts[i] = Int32.Parse(hexVals[i], System.Globalization.NumberStyles.HexNumber);
    }
    return retInts;
}

A: Are you sure you need to use bit fields?
In my experience, a class with a set of boolean data members is almost always the best choice.
The only argument I've ever heard for using bit fields instead of larger booleans (which are often a byte) is that it's supposedly faster.  As with all optimizations, doing it without measuring performance is a bad idea.
Once it's encapsulated in a class, if you decide to change representation for optimization, you can do it without hitting a lot of other code.


text:
Q: Solvability by radicals implies a radical formula for its roots I've been trying for a long time to fully understand the definition of solvability by radicals of a polynomial.
These are the two definitions I have.
Definition 1: We say that a field extension $F/K$ is a radical extension if we can form a chain of fields
$$K=K_0 \leq K_1 \leq \cdots \leq K_n=F$$
where $K_{i+1}/K_i$ is a simple extension such that $K_{i+1}=K_i(a_i)$ and $a_i^{k_i} \in K_i$ for some positive integer $k_i$.
Definition 2: Let $K$ be a field and $f(x) \in K[x]$, we say that $f$ is solvable by radicals if there exits a radical extension $F/K$ such that $F$ contains a splitting field of $f$ over $K$.
Now, I know that definition 2 formalize the concept that we can express the roots of a polynomial as some formulas that only involves the basic operations on the field over the coefficients of the polynomial (and some fixed elements of the field) and taking roots of that elements.
I can see why if we have such formulas for the roots of a polynomial we can interatively construct for every root a radical extension that contains that root, and we can then "join" them to get a radical extension that contains the spplitting field of the polynomial.
But, the reciprocal of this reasoning is what I'm not really able to see.
I can see that if we have a polynomial $f$ and it is solvable by radicals, then we have a radical extension $F/K$ containing all roots of $f$.
Then, as we can iteratively express $F=K(a_0, \cdots, a_{n-1})$ where every $a_i$ is in a way a "nested chain of roots" of elements of $K$, we conclude that as every root of $f$ is in $F$, we can express it as sums and products of elements of $K$ and "chains" of roots of some more elements of $K$.
Now, my concrete doubt, althoug I was able to get an expresion for the roots of the polynomial in a "radical formula", the coefficients of the polynomial doesn't play any role here. Is there a way to show that every root of a solvable by radicals polynomial is expresable in the form of a "radical formula", as the ones mentioned, but involving explicitly the coefficients of the polynomial?
I've been searching for this in a lot of references but I haven't found anything that explicitely discuss this, so I'll be really greatful to anyone who can help me with this.
Thank you very much.


text:
Q: SAML AuthnRequest are sent every 10 minutes to the IdP I am struggling to understand why in certain cases a web application repeatedly sends AuthnRequest requests to the IdP. Is this behaviour configurable on the application side or on the IdP side? Does Spring SAML application send the AuthNRequest only once when logging in or can it send it also later? I checked the spring-security-saml source code and the method 'sendAuthenticationRequest' is executed only during SSO initialization in org.springframework.security.saml.SAMLEntryPoint#initializeSSO so I am confused.
Here is some background: application sends keep-alive requests every 10 minutes, each of those requests triggers sending AuthNRequest:
2020-10-19 12:01:50,335  INFO SAMLDefaultLogger.java:129 - log - AuthNRequest;SUCCESS;10.3.139.13;app1;https://sts.windows.net/acb2b37b-5da0-189b-9b83-0014b27a7c18/;;;
2020-10-19 12:11:50,333  INFO SAMLDefaultLogger.java:129 - log - AuthNRequest;SUCCESS;10.3.139.13;app1;https://sts.windows.net/acb2b37b-5da0-189b-9b83-0014b27a7c18/;;;
2020-10-19 12:21:50,361  INFO SAMLDefaultLogger.java:129 - log - AuthNRequest;SUCCESS;10.3.139.13;app1;https://sts.windows.net/acb2b37b-5da0-189b-9b83-0014b27a7c18/;;;

A: How long is the session between the SP and the browser? If the SP session has expired it would trigger an authentication request.
Is the application configured to require authentication even if an IDP session exists?
E.g saml.sso.profile-options.force-authn=true.


text:
Q: angularjs auto select drop down in below function i got a response and length of perfiosAnalysisData
function getPerfiosData() {

      var tribeId = vm.currentTribeId;

      getPerfiosAnalysisData(tribeId).then(function(response){
        vm.perfiosAnalysisData = response.data;
        /* Check Select Option Length */
            $scope.lengthData = vm.perfiosAnalysisData.institutions.length;
        /* Check Select Option Length */
        vm.isPerfiosEnabled = response.is_enabled;
        setChartDataConfig();
        getDrawGraph();
      },function(err){
        if(err.status === 412) {
          vm.perfiosNotPermitted = true;
        }
      });
    }

so if length is 1 i want to auto select option and call the ng-change function.
<select class="perf-select" ng-model="viewProfileCtrl.monthsForm.institution"
                           ng-options="inst.institution.institution_id as inst.institution.name for inst in viewProfileCtrl.perfiosAnalysisData.institutions"
                           ng-change="viewProfileCtrl.setCurrMonthInsti(viewProfileCtrl.monthsForm.institution)">
                           <option value=""  selected>Select a Bank
                        </select>

How to achive this?

A: if lengthData equals to 1 then assign the first object to ng model variable and call ng change function like this
function getPerfiosData() {
    var tribeId = vm.currentTribeId;
    getPerfiosAnalysisData(tribeId).then(function(response) {
        vm.perfiosAnalysisData = response.data;
        /* Check Select Option Length */
        $scope.lengthData = vm.perfiosAnalysisData.institutions.length;

        if ($scope.lengthData === 1) {
            $scope.viewProfileCtrl.monthsForm.institution = $scope.viewProfileCtrl.perfiosAnalysisData.institutions[0];
            $scope.viewProfileCtrl.setCurrMonthInsti($scope.viewProfileCtrl.monthsForm.institution);
        }

        /* Check Select Option Length */
        vm.isPerfiosEnabled = response.is_enabled;
        setChartDataConfig();
        getDrawGraph();
    }, function(err) {
        if (err.status === 412) {
            vm.perfiosNotPermitted = true;
        }
    });
}


text:
Q: Why the id of view from getview () is different in onViewCreated() and onActivityCreated() I tested with the following code in Fragment
override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val view = inflater.inflate(R.layout.fragment_view_test, container, false)
    Log.d("m", "onCreateView view id: ${view.id}")
    Log.d("m", "onCreateView view hash: ${view.hashCode()}")
    Log.d("m", "onCreateView get view id: ${getView()?.id}")
    Log.d("m", "onCreateView get view hash: ${getView()?.hashCode()}")
    return view
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    Log.d("m", "onViewCreated view id: ${view.id}")
    Log.d("m", "onViewCreated view hash: ${view.hashCode()}")
    Log.d("m", "onViewCreated get view id: ${getView()?.id}")
    Log.d("m", "onViewCreated get view hash: ${getView()?.hashCode()}")
}

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    Log.d("m", "onActivityCreated get view id: ${getView()?.id}")
    Log.d("m", "onActivityCreated get view hash: ${getView()?.hashCode()}")
}

The results are shown below. You can see that their hashcodes are the same. But id has changed in onActivityCreated(). Is that why?
onCreateView view id: 2131230839
onCreateView view hash: 211623483
onCreateView get view id: null
onCreateView get view hash: null
onViewCreated view id: 2131230839
onViewCreated view hash: 211623483
onViewCreated get view id: **2131230839**
onViewCreated get view hash: 211623483
onActivityCreated get view id: **2131230981**
onActivityCreated get view hash: 211623483


text:
Q: css how to create 2 horizontal lines next to centered circle? css how to create 2 horizontal lines next to centered circle?
I want to connect the boxes that will be next to each other with their positions centered, how can I do this?

#login {
  display: flex;
  text-align: left;
  align-items: center;
  justify-content: center;
  flex-direction: row;
}

.elips {
  width: 10rem;
  height: 10rem;
  background-color: red;
  padding: red 2rem;

  border-radius: 50%;
}

.box {
  width: 5rem;
  height: 2rem;
  background-color: black;
}

-----
  -----

A: You can make use of dashed border style for the middle div. You need not use text for it.

#login {
  display: flex;
  text-align: left;
  align-items: center;
  justify-content: center;
  flex-direction: row;
}

.elips {
  width: 10rem;
  height: 10rem;
  background-color: red;
  padding: red 2rem;
  border-radius: 50%;
}

.box {
  width: 5rem;
  height: 2rem;
  background-color: black;
}

.dashed-lines {
  border: 2px dashed black;
  width: 50px;
  height: 5px;
  border-left: transparent;
  border-right: transparent;
}


text:
Q: Angular: Type-ahead suggestions not shown again after hide on clicking outside I'm trying to implement a type-ahead functionality that shows suggestions as you type. Once the user clicks somewhere, the element (ul) that displays the suggestions is hidden (setting style.display to none).
If you take a look at this demo (test data: 1, 12, 123), I'm trying to set style.display back to block, if suggestions are available and the search textbox is not empty. But it is not setting it back to block. If you clear and focus out of the textbox and type again, the suggestions are shown.
Have been cracking my head, but couldn't figure out why. Please help!

A: I wild guess: besides setting display to none, reset matchedItems to [] on document click


text:
Q: Android change text size in TextView on click I have few buttons containing only labels. They are made using 2 image resources (pressed is little bit bigger than not pressed)
button_image.png
button_image_pressed.png

and xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/button_image" android:state_pressed="false"/>
    <item android:drawable="@drawable/button_image_pressed" android:state_pressed="true"/>

</selector>

And i want to use custom TextView insted of this.
Is it possible to chage TextView textSize when user touches text and change textSize back when text user releses screen?
I tried different solutions, but they didn't work.

A: You can try using an onTouchListener().
    textView.setOnTouchListener( new OnTouchListener() {

        @Override
        public boolean onTouch( View v, MotionEvent event ) {

            switch(event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    textView.setTextSize( ... );
                    break;
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                    textView.setTextSize( ... );
            }
            return false;
        }
    } );


text:
Q: Kubernetes - Kubectl - What format is client data in? I currently have a kubernetes cluster I've set up - I want to build some monitoring infrastructure. I've built a simple library in ruby that can communicate with a kube cluster. For minikube this is fine as I can put the client key and the client cert in. For my kops AWS instance however I have two values:

*

*client-certificate-data

*client-key-data

I have no idea what format these are in - how do i convert them into pem encoded certificates so i can use them with my library?

A: After looking at the kubernetes source code this is simply the base64 encoded data. Running a ruby base64 decode gives me the certificates I need.


text:
Q: Finding the largest interval using Dynamic programming http://www.cs.uiuc.edu/~jeffe/teaching/algorithms/notes/05-dynprog.pdf
I was doing these questions for practice where I came across one that stumped me.

7.(a) Suppose we are given a set L of n line segments in the plane, where each segment has one endpoint on the line y = 0 and one endpoint
  on the line y = 1, and all 2n endpoints are distinct. Describe and
  analyze an algorithm to compute the largest subset of L in which no
  pair of segments intersects.
(b) Suppose we are given a set L of n line segments in the plane,
  where the endpoints of each segment lie on the unit circle x 2 + y 2 =
  1, and all 2n endpoints are distinct. Describe and analyze an
  algorithm to compute the largest subset of L in which no pair of
  segments intersects.

I figured out how to do 7a, (the question is a disguised problem to find the largest subset of increasing numbers), in O(n log n) time. Im almost close to giving up on 7b, as I cant figure out a way to do it.
However, is there  a way to convert 7b's premise to something more like 7a's? I feel like that's the right way of approaching the problem, and any help in figuring this out would be much appreciated.

A: I couldn't come up with an O(n*log(n)) algorithm, but here is an O(n2) one.
The idea is that we build a directed graph with vertices representing segments from the given set and edges representing the "lies to the right of" relation.
Let L be the list of segments: {(a1, b1), (a2, b2), ..., (an, bn)}, where ak and bk are k-th segment's endpoints.
Let L' be the list of segments: {(a1, b1), (b1, a1), (a2, b2), (b2, a2), ..., (an, bn), (bn, an)}.
Let the vertices of the graph have indices from 1 to 2*n, each index k representing the segment L'[k], i.e. (ak/2, bk/2) if k is odd, and (bk/2, ak/2) if k is even.
A segment (a1, b1) is said to lie to the right of a segment (a2, b2) when the points a1, a2, b2, b1 are placed in a clockwise order on the unit circle.
Note that 1) If one segment lies to the right of another, they don't intersect; 2) If two segments from L don't intersect, two of the four corresponding segments from L' necessarily lie one to the right of another; 3) Any set of non-intersecting segments from L is defined by a series of segments of L', each lying to the right of the previous one.

Outline of the algorithm:
for every k1 from 1 to 2*n:
    for every k2 from 1 to 2*n:
        if (L'[k1].a, L'[k1].b) lies to the right of (L'[k2].a, L'[k2].b):
            add a directed edge (k1, k2) to the graph
Find the longest path in the graph: (k1, k2, ..., km).
The answer to the problem is: (k1/2, k2/2, ..., km/2).

A: Here is an O(n2) algorithm.
We have 2n endpoints on the circle. Pick any point and start labeling the points in increasing order starting from 1 in clockwise direction. So, we have points labeled from 1 to 2n. Thus, any line segment l can be represented as (i,j) where i and j are endpoints of l and 1≤i<j≤2n.
Let Li,j be a subset of L such that l=(a,b) ∈ Li,j if i ≤ a < b ≤ j. Also, define D[i,j] for 1 ≤ i ≤ j ≤ 2n as the maximum number of non-intersecting lines in Li,j. We need to find D[1,2n].
We use dynamic programming here. Initialize D[i,i] as 0 and D[i,i+1] as 1 if (i,i+1) is a line segment, otherwise set it as 0. We can build D using the following:
if (i,j) is a line segment :
     D[i,j] = D[i+1,j-1]+1
else if (i,k) is a line segment and i<k<j :
     D[i,j] = max(D[i,j] , D[i+1,k-1]+D[k+1,j]+1)
else if (k,j) is a line segment and i<k<j :
     D[i,j] = max(D[i,j] , D[i,k-1]+D[k+1,j-1]+1)
else :
     D[i,j] = max(D[i,j] , D[i+1,j-1])

Since D occupies O(n2) space and we compute each cell of D in constant time the time complexity of the algorithm is O(n2).
Reference:
http://www.cs.toronto.edu/~robere/csc373h/files/A2-sol.pdf
Look under the heading Line Intersections (Redux)

A: Create two lists.  The first list has the ordering created by sweeping counter-clockwise around the circle starting at (1,0).  The first endpoint of a segment you hit is marked.  The second list is ordered the same, but go clockwise around the circle.  In this manner, you now have two lists where the segment endpoints show an ordering for intersection.  For example, if the first point in the first list doesn't have its corresponding endpoint first in the second list, then it will intersect with all of the segments which appear before it in the second list.  (You need to be careful here in that both points for a line can be before the end of your segment.  A simple check eliminates this.)  You can then just run the list.  The total complexity of this approach seems to be O(n log n) for each list creation and O(n) for running the list.


text:
Q: What would be the PHP equivalent of this Perl regex? What would be the PHP equivalent of this Perl regex?
if (/^([a-z0-9-]+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)$/
  and $1 ne "global" and $1 ne "") {
    print "
\n";
    print "    $1	\n";
    print "    $2	\n";
    print "    $3	\n";
    print "    $4	\n";
    print "    $5	\n";
    print "    $6	\n";
    print "    $7	\n";
    print "    $8	\n";
    print "
\n";
}

A: I'd suggest that rather than using a regex, you split on whitespace.  All you're checking for is eight columns separated by whitespace.
Look at preg_split at http://www.php.net/manual/en/function.preg-split.php.  It should look something like:
$fields = preg_split( '/\s+/', $string );
if ( $fields[0] == '...' )
...

A: preg_match

A: PHP has some functions that work with PCRE. So try this:
if (preg_match('/^([a-z0-9-]+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)$/', $str, $match) && $match[1] != "global" && $match[1] != "") {
    print "
\n";
    print "    $match[1]	\n";
    print "    $match[2]	\n";
    print "    $match[3]	\n";
    print "    $match[4]	\n";
    print "    $match[5]	\n";
    print "    $match[6]	\n";
    print "    $match[7]	\n";
    print "    $match[8]	\n";
    print "
\n";
}


text:
Q: Retrive data based on pivot table in laravel I have those tables in my database
Translation

*

*id

*translation_key_id

*content

Language

*

*id

*code (it would be "eng" or "ger" or "fre")

translation_language

*

*id

*translation_id

*language_id

Now the models are
class Language extends Eloquent {

    protected $fillable = array('id','code');
    protected $table = 'language';

    private $rules = array();

    public function translation()
    {
        return $this->belongsToMany('translation','language_translation');
    }
}

class Translation extends Eloquent {

    protected $fillable = array();
    protected $table = 'translation';

    private $rules = array();

    public function language()
    {
        return $this->belongsToMany('language','language_translation');
    }
}

Now i want to retrieve those data which have transkation_key_id = abc (as for example ) and also with code = "eng"
How can i do that?

A: You've built relationships incorrect
try this
    class Language extends Eloquent {

    protected $fillable = array('id','code');
    protected $table = 'language';

    private $rules = array();

    public function translation()
    {
        return $this->belongsToMany('Translation','translation_language');
    }
}

class Translation extends Eloquent {

    protected $fillable = array();
    protected $table = 'translation';

    private $rules = array();

    public function language()
    {
        return $this->belongsToMany('Language','translation_language');
    }
}

A: First of all I don't see the need for pivot table here.
Show me why you need that, or change your relation to belongsTo. You can link translation with language using id (1) or code (2), which is unique obviously, right? So here it goes:
table translations: id, key, content, language_id (or language_code)

// Translation
public function language()
{
  // option 1
  return $this->belongsTo('Lanugage');
  // or 2:
  // return $this->belongsTo('Lanugage', 'language_code', 'code');
}t

then
// option 1
Translation::where('key', 'whatever')->whereHas('language', function ($q) {
   $q->where('code', 'eng');
})->first();

// option 2, even easier w/o any join needed
Translation::where('key', 'whatever')->where('language_code', 'eng')->first();


text:
Q: 2D Array values are not getting assigned I created an 2D array, and each contain the coin and the balance values, the problem is that the values for my 2D array don't assign to the array.
The values are correct and not empty, when I console.log them, they will output something.
async function getBalanceByCoin(account, coin) {
  const contract = new web3.eth.Contract(balanceOfABI, coin);
  const balance = await contract.methods.balanceOf(account).call();
  return web3.utils.fromWei(balance, "ether");
}

function checkBalance(account) {
  const coins = [usdc, stake, wnxm, bal, aleph, ampl, renbtc, ceth];
  const balances = coins.map(async (coin) => {
    const balance = await getBalanceByCoin(account, coin);
    console.log([coin, balance]); // Logs correctly and value prints out
    return [coin, balance];
  }).sort((a, b) => parseFloat(b[1]) - parseFloat(a[1]));

  return balances[0][1] === 0 ? 'None' : `${balances[0][0]}: ${balances[0][1]}`; // Values are not defined when logging

}
console.log(checkBalance(account)) // Logs nothing, values are undefined:undefined

A: Since I was trying to await for .map, I needed to wrap it all up with Promise.all.
Here is the fix for it:
async function getBalanceByCoin(account, coin) {
  const contract = new web3.eth.Contract(balanceOfABI, coin);
  const balance = await contract.methods.balanceOf(account).call();
  return web3.utils.fromWei(balance, "ether");
}

async function checkBalance(account) {
  const coins = [usdc, stake, wnxm, bal, aleph, ampl, renbtc, ceth];
  const balances = await Promise.all(coins.map(async (coin) => { // Wrapped everything up in Promise.all()
    const balance = await getBalanceByCoin(account, coin);
    return [coin, balance];
  }))

  balances.sort((a, b) => parseFloat(b[1]) - parseFloat(a[1]));

  return balances[0][1] === 0 ? 'None' : `${balances[0][0]}: ${balances[0][1]}`;

}


text:
Q: GAP code to calculate the a certain subgroup $E(G)$ of a group I am a research scholar from India.  At present,
I am working on a problem. For this problem,  I need to construct the subgroup
$E(G)$ of a group $G$ in GAP. Please help me. My question is as follows:
Questions:
For any group $G$, the absolute center $L(G)$ of $G$ is defined as
$$L(G) = \lbrace g\in G\mid \alpha(g)=g,\forall\alpha\in Aut(G)
\rbrace,$$ where $Aut(G)$ denote the group of all automorphisms of
$G$. An automorphism $\alpha$ of $G$ is called an absolute central
automorphism if $g^{-1}\alpha(g)\in L(G)$ for all $g\in G$. Let
$Var(G)$ denote the group of all absolute central automorphisms of
$G$. Let
$$C_{Aut(G)}(Var(G))= \lbrace \alpha\in Aut(G)\mid\alpha\beta =
\beta\alpha, \forall\beta \in Var(G)\rbrace$$ denote the centralizer
of $Var(G)$ in $Aut(G)$.
Let $$E(G)=[G,C_{Aut(G)}(Var(G))]=\langle g^{-1}\alpha(g)\mid g\in
G, \alpha\in C_{Aut(G)}(Var(G))\rangle.$$ One can easily see that
$E(G)$ is a characteristic subgroup of $G$ containing the derived
group $G^{\prime}=[G,Inn(G)]$. How to calculate $E(G)$ in GAP? I already have code which calculates $L(G)$. Will this be helpful for calculating $E(G)$?
The GAP code for finding the absolute center $L(G)$ of a group $G$ is written below:
Fusionclass:=function(G,g)
local a,aut,l;
l:=[];
aut:=AutomorphismGroup(G);
for a in aut do
  Add(l,Image(a,g));
od;
return Set(l);
end;

autocenter:=function(G)
local M,N,g;
M:=Filtered(G,g->Size(Fusionclass(G,g))=1);
N:=Subgroup(G,M);
return N;
end;

A: Since you only want fusion classes of size 1, it should be quicker to find the elements of the center that are fixed under automorphisms:
autocenter:=function(G)
local z,au,N,x;
  z:=Centre(G);
  au:=AutomorphismGroup(G);
  N:=TrivialSubgroup(G);
  for x in Elements(z) do
    if not x in N
      and ForAll(GeneratorsOfGroup(au),a->ImagesRepresentative(a,x)=x) then
      N:=ClosureGroup(N,x);
    fi;
  od;
  return N;
end;

Then the next task will be to check that an automorphism is almost central. Since you state that this test is sufficient on generators, this is easy to implement:
IsAlmostCentral:=function(a,G)
local L;
  L:=autocenter(G);
  return ForAll(GeneratorsOfGroup(G),g->g^-1*ImagesRepresentative(a,g) in L);
end;

Next you'll need to find $Var(G)$, that is you need to run through $Aut(G)$ and collect the elements that are almost central, and calculate its centralizer and so on.
Implementingthis will not bve hard, based on what I have already shown and will help you get some practice in GAP. Feel free to post another question with your code if you have problems with that.

A: @ahulpke.... With your suggestions, the GAP code to calculate $Var(G)$ has been constructed and is given below:
IsAlmostCentral:=function(G)

local L;

result:=[];

  L:=autocenter(G);

 aut:=AutomorphismGroup(G);

 for a in aut do

  result:=ForAll(GeneratorsOfGroup(G),g->g^-1*ImagesRepresentative(a,g) in L);

  if result = true then

  Print(a,"\n");

  fi;

  od;

end;

Now please guide me how to calculate the centralizer of $Var(G)$ in $Aut(G)$ and next how to calculate $E(G)$.


text:
Q: Why is there a loss of quality between programs executed in the Processing IDE and the same program executed in IntelliJ IDEA? I have been writing a Processing program in the Processing IDE, and I now need more functionality such as adding libraries with Maven, Gradle, etc. For that reason, I have been migrating from the Processing IDE to IntelliJ IDEA.
I have added Processing's core.jar to the classpath, and the program will execute without error.
The problem is that there seems to be a lack of quality when using IntelliJ. That is, everything renders just fine when using the Processing IDE, but after building with IntelliJ, everything renders with a major lack of quality as well as differences in text size. Attached below are code and images.
Processing IDE Code:
int headerHeight;
float x = 0;
float dim = 80;
boolean hasSurpassed = false;

void setup(){
  headerHeight = height/5;
  fullScreen();
  background(255);
  print(headerHeight);
  noStroke();
  smooth();
}

void draw(){
  background(255);
  drawHeader();
}

void drawHeader(){
  stroke(255, 0, 0);
  strokeWeight(7);
  fill(255, 0, 0);
  rect(0, 0, width, headerHeight);
  noFill();
  stroke(255);
  strokeJoin(ROUND);
  triangle(25, 191, 100, 25, 175, 191);
  fill(255);
  textSize(125);
  text("!", 81, 163);
  textSize(150);
  text("NOTIFICATION SYSTEM", 195, 166);
  textSize(20);
  text("You have multiple pending deltas!", 208, 200);
  noStroke();
}

Output:

IntelliJ IDEA Code:
import processing.core.PApplet;

public class NotificationSystem extends PApplet{

    private int headerHeight = 0;
    private float x = 0;
    private boolean hasSurpassed = false;

    public void setup(){
        background(255);
        headerHeight = height/5;
        noStroke();
    }

    public void settings() {
        fullScreen();
        smooth();
    }

    public void draw(){
        background(255);
        drawHeader();
    }

    private void drawHeader(){
        stroke(255, 0, 0);
        strokeWeight(7);
        fill(255, 0, 0);
        rect(0, 0, width, headerHeight);
        noFill();
        stroke(255);
        strokeJoin(ROUND);
        triangle(25, 191, 100, 25, 175, 191);
        fill(255);
        textSize(125);
        text("!", 81, 163);
        textSize(150);
        text("NOTIFICATION SYSTEM", 195, 166);
        textSize(20);
        text("You have multiple pending deltas!", 208, 200);
        noStroke();
    }

    public static void main(String[] passedArgs) {
        NotificationSystem notificationSystem = new NotificationSystem();
        PApplet.main(notificationSystem.getClass().getCanonicalName());
    }
}

Output:

I did not want to provide so much code as to post a Minimal, Complete, & Verifiable example, but I feel that you need to see both sets of code as to be able to replicate the problem.
Thanks for the help.


text:
Q: Phpmyadmin not working after upgrading to PHP I just upgraded to PHP7, but phpmyadmin has stopped working. I have followed lots of steps that I found on the internet but it is still not working.
What I keep getting is:
The localhost page isn't working

localhost is currently unable to handle this request.
HTTP ERROR 500

A: This solves it:
sudo apt-get install php-mbstring php7.0-mbstring php-gettext
sudo service apache2 restart


text:
Q: Apache 2.4 stopped logging I have a VirtualHost being served on an Apache 2.4 box and recently noticed that neither the Error nor Access logs are being written to. I can't recall making any changes to the files that would have caused this.
The VirtualHost file is as follows
<VirtualHost *:443>
  ServerName server.domain.com
  ServerAlias server.domain.com
  DocumentRoot /web/app/public_html
  ErrorLog /var/www/app/error_log
  CustomLog /var/www/app/access_log combined

<Directory "/web/app/public_html">
  Allow from all
  Require all granted
</Directory>
</VirtualHost>

I have almost this exact code running on a dev box with no issues so I am not sure why the logs are failing to write.
I've ensured the permissions are correct on the files, tried disabling SELinux for testing and re-creating the log files.
Any help would be greatly appreciated.
EDIT : Output of ls -la /var/www/app
[user@server]# ls -la /var/www/app/
total 5588
drwxr-xr-x. 2 root     root         4096 May 23 11:57 .
drwxr-xr-x. 5 root     root         4096 Apr 12 17:04 ..
-rw-r--r--. 1 http     http       0 May 23 11:25 access_log
-rw-r--r--. 1 root     root      5673320 Feb 24 09:35 access_log.bak
-rw-r--r--. 1 http     http   24643 Feb 24 08:06 error_log

EDIT 2 : It seems as though the log files have reverted back to the the default paths and are being stored in the following locations.
/var/log/httpd/access_log
/var/log/httpd/ssl_access_log
/var/log/httpd/error_log
/var/log/httpd/ssl_error_log

It looks as though the logging in my virtual host config file is being ignored all together. Can someone tell me what I'm missing?


text:
Q: Developing using a non-official kit on the Android? I have been doing some research on developing on the Android platform and found that the only way to develop an app using C++ is using the NDK. I also came to know that the NDK has limited support to C/C++, with C++ having even lesser support than C.
Here's the problem. I need to develop using C++ as I'm not very familiar with Java. In fact, not familiar at all. I'm still 18, so I don't have much experience with many programming languages. After doing some more research I have found a non-official NDK, called the NDK-CrystaX that implements more support for C/C++ than the official NDK. Before I start using I have to know if it would be legal to use this custom NDK in an Android app and still be able to sell it on the Android Marketplace. Is it? Or is it not?
Another solution would be if the newer releases of the NDK had full support for C/C++. But I'm not sure of that either, so I'm seeking your generosity again and asking you to share your knowledge on this too.

A: Your problem is that you don't know Java, but I promise you if you're proficient with C++ , its only a matter of a few months, you can master Java too.You say you're only 18 and you don't have experience with many languages, YES this is the time, dive into Java, you'll never regret.

A: I think you'll be better off just learning Java as you learn to make Android apps. The stuff you know of C++ won't really get in your way of understanding Java.
I know it seems hard to learn a new language AND a new platform all in one go, but if you try to do it in C++, you have have an third problem: understanding the mapping from Java (which the platform is designed to support) to C++ (which it isn't). I've no idea, for instance, how memory management is handled in C++ apps for Android, as it relates to the base API.
Support will be easier for you if you stick to Java as well - most developers tend to use the 'default' toolchain (due to laziness more than anything, I suspect), so you'll have the most help available if you are also using the default toolchain.

A: Just learn Java and program your app in that, in the end it will make your life a lot easier than having to go through what are you are talking about doing.


text:
Q: Add write permission to Custom folder files created with windows installer I am creating a folder inside programdata folder using windows installer. Running the project i am getting an error while trying to write to the file
C:\ProgramData\MyAppFolder\settings_file.sqlite

This is the error message
attempt to write a read-only database.

How can i grant the write permission to the db file and some other files while building the msi file using windows installer
I can see the folder permissions as like this
any way to make this read and write enables while building this via windows installer

A: ACL Permissioning: Adding write permissions for regular users is usually considered an anti-pattern, but sometimes you need to share a file among all users of the PC for pragmatic purposes.
Write Access: For the record: Here is a list of approaches to deal with permission denied issues. Most of the options listed are not good at all - and that is why the list was made - we need to remember why they are bad and what alternatives exist.
Deployment Tool: Application of custom ACL permissioning - to open a file in a protected disk location for writing by all users - is different depending on what tool you use to make your MSI. Since you don't specify WiX, Installshield, Advanced Installer or something else I am not sure how to answer. Let me use links instead:
WiX:

*

*Different WiX permission elements - there are two different PermissionEx elements (!)

*

*PermissionEx (Util Extension - WiX's own stuff)

*

*Util Version: Wix: How to set permissions for folder and all sub folders

*PermissionEx (MSI5 only - uses the built in MsiLockPermissionsEx Table)

*

*MSI5 Version: How to deny folder permission to Users with wix installer

*There are two more (do not use):

*

*Permission (legacy MSI LockPermission table)

*FileSharePermission (for share permissioning - use when you need share permissioning)

Installshield:

*

*Configuring Permissions for Files and Folders

*Setting Permissions in Windows Installer: MSILockPermissionsEX and ISLockPermissions

*Installshield Folder Permissions not working
Advanced Installer:

*

*Apply permissions by right clicking a folder and going to properties: Permission Dialog.

*It seems this uses the old, legacy LockPermission table.

There are some other tools as described here: Short List. Secondary (more links).

Other Links:

*

*Different Ways of Giving Permissions in Your Windows Installer

*Per Machine App Registration

*Create a .config folder in the user folder

*Desktop applicaton not opening after installation in client system

*http://wixtoolset.org/documentation/manual/v3/xsd/wix/permissionex.html


text:
Q: Not getting unavailable presence of User A when User B is also unavailable I am working on a chat application. I am adding functionality to get unavailable status of the user. Following the situation where i am not getting the unavailable presence of the user
There are 2 users User A and user B and both are available
First User A goes unavailable and User b gets unavailable presence of User A , so its working fine, Then user B goes unavailable and then User A become available here problems occur the User A does not receive offline Unavailable presence of User B.
But when User A is Unavailable and then user B become available and then User A become available then in that case USer A is getting offline available presence of User B so its working fine.
So here the problem is only in case of offline unavailable presence of other users are not coming. but offline available presence are coming
below is the code i am using for going available and unavailable
 - (void)goOnline {
     XMPPPresence *presence = [XMPPPresence presence]; // type="available" is implicit
 [[self xmppStream] sendElement:presence];
}

- (void)goOffline {
XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"];
[[self xmppStream] sendElement:presence];

}
Thanks in advance of any kind of help in this :-)


text:
Q: How to get distinct value for column with other column value in laravel? I have a table activites in that table it have columns id, name, description, type, user_id, created_at, updated_at from that i want to group by user_id and type and created_at want to be unique. How can i do it in laravel?
For this i did little bit of search but i didn't find any solution for this.
To get unique column value some places mentioned like
$q = DB::table('activities')->distinct()->get(['created_at']);
here my question is how to get other column value?
without unique filter my current query look like
$q = DB::table('activities')
    ->select(DB::raw('user_id, type, count(*) as total'))
    ->whereNotNull('user_id');
    ->groupBy('user_id', 'type')
    ->get();


text:
Q: Colouring by category in a pandas plot I have a DataFrame containing a continuous number for  the cumulative sum in a column called cont_col and a category column:
import pandas as pd
import numpy as np

cont = np.random.rand(100)

df = pd.DataFrame(data=cont)

df = df.sort_values(by=0)

df['quartile'] = pd.qcut(df[0], 4, labels=False)

cumsum = df[0].cumsum()
cumsum = cumsum.to_frame()
cumsum[0].plot(kind='bar', color='k')

I would like to plot the same data, but this time coloured by the quartile column.
I can do it with the following code:
def colourise(x):
    if x == 0:
        return 'k'
    elif x == 1:
        return 'r'
    elif x == 2:
        return 'g'
    else:
        return 'b'

df['colour'] = df['quartile'].apply(colourise)
cumsum = df[0].cumsum()
cumsum = cumsum.to_frame()
cumsum[0].plot(kind='bar', color=df['colour'].tolist())

I just wonder if there is a more general way - in particular, one which didn't depend on the number of qtiles I create.

A: You can define a dictionary of your color mappings.
color_map = {
    0:'k',
    1:'r',
    2:'g'
}

Then, use .map()
df['colour'] = df['quartile'].map(color_map).fillna('b')

A: If you don't particularly care about the colors, create a mapping with one of the seaborn color palettes. This way you just need to specify the column, not the number of categories or colors. If you have many ordered categories, consider switching to a sequential palette.
import seaborn as sns
import matplotlib.pyplot as plt

def map_color(df, col):
    color_d = dict(zip(df[col].unique(), sns.color_palette("hls", df[col].nunique())))
    df['color'] = df[col].map(color_d)
    return df

df  = map_color(df, 'quartile')

fig, ax = plt.subplots(figsize=(10, 5))
df.assign(y=df[0].cumsum()).plot(kind='bar', y='y', ax=ax, color=df.color.tolist(),
                                 legend=False)
plt.show()


text:
Q: How do I put files in the TFS Build drop location I'm new to using TFS build. I've got a build defined that runs as a continuous integration. It creates a drop folder, but there's nothing in it.
What's the best practice for moving stuff in the drop folder? I've seen a Binaries folder, do I need to copy things into there, or do I alter the TFSbuild.proj in some way to copy the files I want to the drop folder?

A: It sounds like you want to copy miscellaneous files from your workspace (or elsewhere) into the drop location?
The target above gives you an example of how to create a target to copy files, but you're probably wondering how to hook it up in your TFSBuild.proj.
A simple way to do this is using one of the pre-defined skeleton targets for this such as AfterDropBuild.  If you had a target like the one mentioned above for copying your files you would put this in TFSBuild.proj:
<CreateItem Include="$(SolutionRoot)\Source\RandomFilesInWorkspaceFolder\**\*.*">
  <Output TaskParameter="Include" ItemName="RandomFiles" />
</CreateItem>
<Copy SourceFiles="@(RandomFiles)" DestinationFiles="@(RandomFiles->'$(DropLocation)\RandomDestinationSubFolder\%(RecursiveDir)%(Filename)%(Extension)')" />

A: I seemed to get it working by adding this near the end of my TFSBuild.proj
<Target Name="PackageBinaries">
    <ItemGroup>
        <FilesToDrop Include="$(SolutionRoot)\MyProduct\Installer\Bin\**\*.msi"/>
    </ItemGroup>
    <Message Text="FilesToDrop=@(FilesToDrop)"/>
    <Copy SourceFiles="@(FilesToDrop)"
      DestinationFiles="@(FilesToDrop ->'$(BinariesRoot)\%(RecursiveDir)%(Filename)%(Extension)')"/>
</Target>

It copies wanted msi files into the Binaries folder which the normal tfs build system then copies to the drop location. I noticed the Binaries folder gets deleted everytime a build is started, so you don't have to worry about cleaning up.
The PackageBinaries target seems to be the standard target name that you can override for doing this kind of thing.

Update Newer versions of TFS probably have better ways!


text:
Q: How to install a python program using setup.py I am trying to install labelImg using setup.py. I run the command:
sudo python3 setup.py install

to install it and everything seemed to be fine. Unfortunately when I tried to execute the program (just tried labelImg &) got an import error:

ImportError: No module named 'resources'

So, I was wondering if I did something wrong or if there something I could do to fix it. My first thought is to provide an absolute import path to resources (and to the following libs imports) but that does not seem the right thing to do. Also it might work for a small project but it's obvious out of reach for a big one.
The git repo seem to imply that I should run it via python, but why then a setup.py exists?
I know I can use the program via python or even install it via PyPI but I am not interested in that.

A: The labelImg project depends on other libraries to work such as pyqt5-dev-tools and lxml.
If you check their documentation, first you have to install pyqt5-dev-tools:
 sudo apt-get install pyqt5-dev-tools

Then install lxml:
sudo pip3 install lxml

After that you have to run the make command in order to build the pyqt5-dev-tools library so that the python code can use it properly (make is used to build executable libraries and programs from source code):
 make qt5py3

And finally you can run python3 labelImg.py and use labelImg.


text:
Q: Get value from other dataframe with same column values If I have two data frames, data1 which is a key, and data2 is a very long data set.
data1
type    type2    contact
a       1        alex
a       2        jim
a       3        alex
b       1        john
b       2        bart
b       3        jim

and
data2
type    type2
a       1
a       1
a       1
a       2
a       3
a       3
b       1
b       2
b       2
b       3

I would like to get a formula to lookup the contact info on data2 using data1 to get the result below.
type    type2    contact
a       1        alex
a       1        alex
a       1        alex
a       2        jim
a       3        alex
a       3        alex
b       1        john
b       2        bart
b       2        bart
b       3        jim

I tried something along the lines of:
data2$contact <- data1$contact[data1$type == data2$type & data1$type2 == data2$type2]

However, that doesn't work, and I'm not sure of the right approach to take in R

A: We can use left_join
library(dplyr)
left_join(data1, data2)
#   type type2 contact
#1     a     1    alex
#2     a     1    alex
#3     a     1    alex
#4     a     2     jim
#5     a     3    alex
#6     a     3    alex
#7     b     1    john
#8     b     2    bart
#9     b     2    bart
#10    b     3     jim

Or a base R option would be match
data1$contact[match(do.call(paste0, data2), do.call(paste0, data1[-3]))]
#[1] "alex" "alex" "alex" "jim"  "alex" "alex" "john" "bart" "bart" "jim"