text:
Q: i7 9700k running up to 100 degrees celcius I have an i7 9700k cooled with an ARCTIC Freezer 34 eSports DUO in a Corsair Carbide Series SPEC-04 Tempered Glass (1x 120mm fan at the front).
I remounted the cooler once, reapplied fresh thermal paste and I have the fans mounted complementary to each other, so they pull air in on one side and push air out on the other side towards the rear end of the PC. The problem is that while playing games such as Call of Duty Modern Warfare the temperatures are rising up to 99°C (measured with HWInfo64).
I did a little research on the CPU cooler and it is mostly desrcribed as sufficient for the i7 9700k. I could imagine that it might be the bad airflow in the case, as the heat kinda stacks up, but it is really weird since the case is really open at the rear end at the top rear end.
The GPU temperatures rise up to 85°C with 96°C at the memory junction and 102°C hotspot temperature, which I am not sure about whether this is fine or not.
Does anybody have some experience or tips for me on this issue and could the CPU have possibly already taken damage from running at such high temperatures?


text:
Q: Default value of line-width in HTML, or how to set box height to N lines What is the default value of line-height in built-in HTML style, i.e. how many em does one line height takes?
Alternatively, how to set length (border width) to N lines of text?

A: Depends on the user agent. Desktop browsers (including Firefox) use a default value of roughly 1.2, depending on the element's font-family. Thanks

A: Sets the line height to a 'reasonable' value relative to the element's font face. Browser dependent results. CSS2 recommends a computed value between 1.0 and 1.2.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to trigger PHP-CI webhook manually aside from pushing does anyone know how to trigger the PHP-CI webhook manually?
cause I wanted it to connect to Hipchat Integration.

A: The URL to trigger a webhook is built as follows:
PHPCI_URL/webhook/git/PROJECT_ID
As answer you should receive a JSON response as follows:
{"status":"ok","buildID":"7"}
Keep in mind you'll just be queueing a build, it will not do the build.


text:
Q: React fetch data from API gives error Cannot read property of undefined I'm using a React Hook to fetching data from a JSON object by using the native fetch method.
const COVID_API_URL = "https://api.covid19api.com/summary";
const [infected, setInfected] = useState([]);

async function fetchData() {
  const response = await fetch(COVID_API_URL);

  response.json().then(response => setInfected(response));
}

useEffect(() => {
  fetchData();
}, []);

console.log(infected.Global.TotalConfirmed);

When I console.log the value from TotalConfirmed, I get the correct result, but when I refresh the browser, I keep getting:
TypeError: Cannot read property 'TotalConfirmed' of undefined

Anyone know why this is happening? I'm using Gatsby.js default starter, does this have anything to do with this?

A: The problem here is the value for infected state arrives asynchronously. What you can do is using useEffect hook.
Try as the following:
useEffect(() => {
   console.log(infected.Global.TotalConfirmed);
}, [infected]);

By doing this useEffect callback will be triggered once infected value is changing - API call responses - so after setInfected(response) updates the value of infected state.
I hope this helps!

A: The first time you access infected it is still undefined, all you need to do is validate the variable before using it. You don't need another useEffect.
console.log(infected && infected.Global && infected.Global.TotalConfirmed);

const {useState, useEffect} = React;

const COVID_API_URL = "https://api.covid19api.com/summary";

function App() {
  const [infected, setInfected] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  function fetchData() {
    fetch(COVID_API_URL)
      .then(jsonResponse => jsonResponse.json())
      .then(response => {
        setIsLoading(false);
        setInfected(response);
      })
      .catch(e => {
        console.log("error", e);
        setIsLoading(false);
      });
  }

  useEffect(() => {
    fetchData();
  }, []);

  console.log(infected && infected.Global && infected.Global.TotalConfirmed);
  return (

COVID-19 Summary

      {isLoading &&
Getting data...
}

  );
}

ReactDOM.render(
  <App />,
  document.getElementById("app")
);

A: You can add a new state like in my example isFetched then set it's default value to false
const [isFetched,setIsFetched] = useState(false);

and then use the setIsFetched function after your setInfected(response)
and finally you can check if isFetched is true then use your api data(infected state) in your code.
const COVID_API_URL = "https://api.covid19api.com/summary";
const [infected, setInfected] = useState([]);
const [isFetched,setIsFetched] = useState(false);

async function fetchData() {
  const response = await fetch(COVID_API_URL);

  response.json().then(response =>
  {
     setInfected(response));
     setIsFetched(true);
  }
}

useEffect(() => {
  fetchData();
}, []);

then when you want to show api data on page you do:
{
  isFetched ?
  // use api data : null
}

A: I was also having this issue, even after using axios. Its easy to fix, you just need to add if else statement before return. like this
`if(myArray.length > 0){
return (data and everything)}
else{return
Loading
}`


text:
Q: Improving the bound on the probability of censored waiting times Suppose one observes a series of actions in time (say, user logins to a site). For each user, denote the time elapsed between logins as a random variable $T_{ik}$. Here $i$ denotes user for whom we have $k$ login time points.
So the average time elapsed between logins $E(T_i) = \mu_i$ will have some distribution over the set of users. Then, Markov's inequality tells us that:
$P(E(T_i) > t) \leq \frac{E(\mu_i)}{t}$
Suppose we want to filter out "extreme users". Define "extreme" as any user whose average time-between-logins has less than $p$ percent chance of occurring. Then the value of the critical threshold above which we will filter a given user as extreme will be:
$ p \leq \frac{E(\mu_i)}{t_c} \implies t_c \leq \frac{E(\mu_i)}{p}$
So if for any user $\mu_i > t_c$, we will filter them out as "extreme" (for a given value of $p$). Note further that we don't observe users until "death" (they may just be taking a really long time to long-in again, or they may have exited, we don't know).
I am wondering if there is a way to sharpen this bound, given the context of the problem.


text:
Q: Can I add common argument to subparsers AFTER the subparser arguments? I have 2 subparsers:
from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument('--say')

subparsers = parser.add_subparsers(dest='action', help='what should I do')
a = subparsers.add_parser('eat')
a.add_argument('food')

b = subparsers.add_parser('drink')
b.add_argument('beverage')

print(parser.parse_args(['eat', 'apple']))
print(parser.parse_args(['drink', 'water']))
print(parser.parse_args(['--say', 'thanks', 'drink', 'water'])) # Works, but I don't like it
print(parser.parse_args(['drink', 'water', '--say', 'thanks'])) # I want this to work

Namespace(action='eat', food='apple', say=None)
Namespace(action='drink', beverage='water', say=None)
Namespace(action='drink', beverage='water', say='thanks')
usage: test.py [-h] [--say SAY] {eat,drink} ...
test.py: error: unrecognized arguments: --say thanks

Adding parents gets everything complicated...
from argparse import ArgumentParser

parser = ArgumentParser(add_help=False)
parser.add_argument('--say')

subparsers = parser.add_subparsers(dest='action', help='what should I do')
a = subparsers.add_parser('eat', parents=[parser])
a.add_argument('food')

b = subparsers.add_parser('drink', parents=[parser])
b.add_argument('beverage')

print(parser.parse_args(['eat', 'apple']))

usage: test.py eat [-h] [--say SAY] {eat,drink} ... food
test.py eat: error: invalid choice: 'apple' (choose from 'eat', 'drink')

Suddenly nothing works because I have to input "eat" TWICE??? (the 2nd time is for the action, but why do I need the 1st?)
All I want is to have a shared argument, that I can add at the end, or the start of my argument list (to my choosing), for multiple subparsers, i.e. I want all of the following to work:

*

*test.py eat apple --say thanks

*test.py --say grace drink coffee

*test.py --say grace eat bread --clap hands (if I add another shared argument)

A: Once parse_args has recognized the subcommand, all further arguments are passed to the subparser, not the main parser. Using parents= inherits all arguments, including the subcommands, not just the other options.
Instead, you want yet another parser that does nothing except provide --say; you can then use that as a parent for each of the main parser and its two subparsers.
from argparse import ArgumentParser

say_parser = ArgumentParser(add_help=False)
say_parser.add_argument('--say')

parser = ArgumentParser(parents=[say_parser])

subparsers = parser.add_subparsers(dest='action', help='what should I do')
a = subparsers.add_parser('eat', parents=[say_parser])
a.add_argument('food')

b = subparsers.add_parser('drink', parents=[say_parser])
b.add_argument('beverage')

print(parser.parse_args(['eat', 'apple']))
print(parser.parse_args(['drink', 'water']))
print(parser.parse_args(['--say', 'thanks', 'drink', 'water']))
print(parser.parse_args(['drink', 'water', '--say', 'thanks']))

If you don't want the third one to work, you can omit the say_parser from the parent list of the main parser.


text:
Q: Return JSON from angular service to component I'm trying to pass a JSON from my api service to any component without subscribing in the component it self.
What happens it that I get the data inner the .subscribe without any problem in the api.service.ts function
But when I'm trying to get that data outside of it returns something else
Here is the code:
api.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class ApiService {

constructor(private http: HttpClient) {}

public getInfo(URL: string): Observable<any> {
  return this.http.get( URL )
    .pipe(
      tap( (fetchJSON) => JSON.stringify(fetchJSON) )
    )
}

// I'm planning to create more functions like this one to get particular data:

public getParticularData(){
  let infoJSON;
  let URL = "https://jsonplaceholder.typicode.com/posts";
  infoJSON = this.getInfo(URL)
  .subscribe(data =>{ console.log(data) });
  // the console.log(data) inside the .subscribe returns my Json data perfectly

  return infoJSON;
  //this returns: Subscriber {closed: false, _parent: null, _parents: null, _subscriptions: Array(1), syncErrorValue: null, …}

}

}

home.component.ts
*the rest of the imports are here don't worry*
import { ApiService } from '@api/api.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class homeComponent implements OnInit {

constructor( private ApiService: ApiService){

 JSON = this.ApiService.getParticularData();
 console.log(JSON) // returns undefined

}

}

A: You are making two mistakes:

*

*You are returning subsciption.

*You are trying to access data synchronously but ajax is async.
As a simple solution, dont subscribe inside the service but in the component
public getParticularData(){
  let infoJSON;
  let URL = "https://jsonplaceholder.typicode.com/posts";
  infoJSON = this.getInfo(URL)
  .map(data =>{ console.log(data) });
  // the console.log(data) inside the .subscribe returns my Json data perfectly

  return new Promise((resolve)=>{
      infoJSON.subscribe((data)=>resolve(data))
  })

}

component:
   async myMethod(){
    let data = await this.ApiService.getParticularData();
    console.log(data);
   }


text:
Q: Проверка доступности порта на сервере Доброе время суток!
Интересует пара вопросов:
1. Как при помощи javascript определить доступность порта на сервере?
При попытке открыть страницу с несуществующим url (http://localhost:12345) браузер отображает сообщение о невозможности открыть страницу.
Если же открываем страницу с доступным портом, то спокойно открывает страницу. Или сбрасывает соединение, не важно. Главное - для браузера есть различие - закрыт порт (нельзя отобразить страницу) или открыт порт (отображаем, либо сбрасываем соединение).
А как это отловить через JS?
На данный момент я не могу отличить - сброшено соединение или страница недоступна.
2. Как при отправке запроса получить header этого запроса?
Отправлял запросы ручками через Opera.
При отправке запроса на закрытый порт показывает только URL.
Если отсылаем на открытый порт - показывает еще и тело запроса (даже если сервер сбросил соединение и страница не загрузилась).
*показывает - естественно в консоли))
Т.е. если получится перехватить эти данные, то тогда, вроде как, можно будет решить и п. 1 - потому и спрашиваю.

Пробовал по всякому, и WebSocket'ы пытался подключить - что-то не получилось... Может не так что-то делал?
С WebSocket'ами выдавало следующее:

*

*если соединение сброшено, либо порт закрыт - то сокет закрывался, разница была только в задержке между попыткой подключения к порту и его закрытием

*если страница открывалась нормально - то сокет открывался (onconnect) и почти сразу же закрывался.

Т.е. все равно не получилось различить - закрыт порт или просто соединение сбрасывается...
Судить по времени между запросом и закрытием соединения - не вариант.
Есть идеи? Вопрос по JS, поэтому FLASH и PHP не предлагать)) Таким образом и сам могу все проверить)
Заранее спасибо)
A: Ну, на счет есть/нет страница, открыт ли порт, то поможет AJAX, отправляете запрос на url и смотрите какой статус приходит
var http = new XMLHttpRequest();
http.open("GET","http://laviro.tk");
http.onreadystatechange = function() {
    if(http.readyState != 4) return;
    console.log(http.status);
    console.log(http.getAllResponseHeaders());
}
http.send(null); // отправляем запрос

http.status - код, который нам возвращает сервер ( 404 тоже вернет )
http.getAllResponseHeaders - метод, возвращает все заголовки

A: Вообще js это предназначен для работы на стороне клиента. Сомневаюсь что есть возможность или, что это будет правильно с точки зрения использования.


text:
Q: Windows - sharing connection to WinTun interface - ping fails with protocol unreachable I'm trying to access the network from the Windows app which creates TUN interface connection.

*

*Windows 10 Home Edition.

*TUN interface created with https://www.wintun.net/ project example code.

*When calling ping -S 102.168.137.1 192.168.0.109, ping finishes with success.

*Windows firewall is turned off.

*Windows network profile is private network (trusted network where computer may be discovered by others).

*Problem: When calling ping programmatically (sending bytes) through WinTun interface, an error occurs as described below.

There is following network structure:

There is following ICMP packet flow:

*

*TUN Interface sends the ping packet to shared WiFi connection

*Shared WiFi changes the packet's source IP address (NAT?) and sends it to the Linux computer.

*Linux computer responds normally.

*Unexpectedly, the Windows 10 responds to Linux: Destination Unreachable (Protocol unreachable).

*I've expected that Windows 10 will perform backward translation of IP address and forward it to the TUN interface.

Details
ICMP Packets

*

*Ping request (Windows to Linux) packet analysis 144f8ab3be0bb46d839a069608004500001c00000000fd013bbfc0a80064c0a8006d0800f6ff01000000

*Ping replay (Linux to Windows) packet analysis
b46d839a0696144f8ab3be0b08004500001c18d100004001dfeec0a8006dc0a800640000feff01000000

*ICMP error packet - Destination unreachable (Protocol unreachable) (Windows to Linux) packet analysis
144f8ab3be0bb46d839a069608004500003800b400008001b7efc0a80064c0a8006d0302fcfd000000004500001c18d100003f015851c0a8006dc0a889010000000000000000
Windows ip and route configuration (not changed manually)
C:\WINDOWS\system32>ipconfig

Windows IP Configuration

Ethernet adapter Ethernet:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Unknown adapter Demo:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::219f:2800:9778:a5e3%8
   IPv4 Address. . . . . . . . . . . : 192.168.137.1
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . :

Wireless LAN adapter Połączenie lokalne* 2:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Wireless LAN adapter Połączenie lokalne* 3:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Wireless LAN adapter Wi-Fi:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::86ac:ff4b:556a:dc0d%14
   IPv4 Address. . . . . . . . . . . : 192.168.0.100
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.0.1

C:\WINDOWS\system32>route print
===========================================================================
Interface List
 13...50 7b 9d 2f 13 80 ......Realtek PCIe GBE Family Controller
  8...........................Example Tunnel
 15...b4 6d 83 9a 06 97 ......Microsoft Wi-Fi Direct Virtual Adapter #2
 24...b6 6d 83 9a 06 96 ......Microsoft Wi-Fi Direct Virtual Adapter #3
 14...b4 6d 83 9a 06 96 ......Intel(R) Dual Band Wireless-AC 3160
  1...........................Software Loopback Interface 1
===========================================================================

IPv4 Route Table
===========================================================================
Active Routes:
Network Destination        Netmask          Gateway       Interface  Metric
          0.0.0.0          0.0.0.0      192.168.0.1    192.168.0.100     55
        127.0.0.0        255.0.0.0         On-link         127.0.0.1    331
        127.0.0.1  255.255.255.255         On-link         127.0.0.1    331
  127.255.255.255  255.255.255.255         On-link         127.0.0.1    331
      192.168.0.0    255.255.255.0         On-link     192.168.0.100    311
    192.168.0.100  255.255.255.255         On-link     192.168.0.100    311
    192.168.0.255  255.255.255.255         On-link     192.168.0.100    311
    192.168.137.0    255.255.255.0         On-link     192.168.137.1    261
    192.168.137.1  255.255.255.255         On-link     192.168.137.1    261
  192.168.137.255  255.255.255.255         On-link     192.168.137.1    261
        224.0.0.0        240.0.0.0         On-link         127.0.0.1    331
        224.0.0.0        240.0.0.0         On-link     192.168.0.100    311
        224.0.0.0        240.0.0.0         On-link     192.168.137.1    261
  255.255.255.255  255.255.255.255         On-link         127.0.0.1    331
  255.255.255.255  255.255.255.255         On-link     192.168.0.100    311
  255.255.255.255  255.255.255.255         On-link     192.168.137.1    261
===========================================================================
Persistent Routes:
  None

IPv6 Route Table
===========================================================================
Active Routes:
 If Metric Network Destination      Gateway
  1    331 ::1/128                  On-link
 14    311 fe80::/64                On-link
  8    261 fe80::/64                On-link
  8    261 fe80::219f:2800:9778:a5e3/128
                                    On-link
 14    311 fe80::86ac:ff4b:556a:dc0d/128
                                    On-link
  1    331 ff00::/8                 On-link
 14    311 ff00::/8                 On-link
  8    261 ff00::/8                 On-link
===========================================================================
Persistent Routes:
  None

My questions:

*

*Why Windows responds with ping error and how to make it working?

*Does Windows use NAT when sharing internet connection?

Thank you for your attention. Any comments and tips will be appreciated.


text:
Q: How to test the self-updating mechanism in Firefox? I've developed a Firefox extension, packaged it with jpm and have successfully in-line installed it on my local machine. It is self-hosted, and intended to be self-updating. I've followed the instructions at Automatic Add-on Update Checking as well as at Supporting updates for self-hosted addons in JPM.
My question is, how do I test that the self-updating mechanism is working, and debug it if it isn't? My web server is correctly serving the .xpi and the .update.rdf. When I click "Check for updates" in the Firefox Add-ons menu it finds the update.rdf, which has a higher version number than the add-on I've locally installed, but it always says "No updates found".
There are no errors in the add-on debugging window when I click "check for updates".
I've seen and fixed this issue in my update.rdf but I am not sure if there are others lurking. Any help is appreciated.


text:
Q: mysql remote server connection fails I'm working on this for 4 days and I know it is all over google, but I did all the required stuff but still no connection.
I created to 2 vagrant boxes, one for web server and one for mysql.
web: 192.168.50.50
mysql: 192.168.40.40
I edited the /etc/mysql/my.cnf file and placed:
 bind-address        = 192.168.40.40

now I created a user named "bob" with password "12345"
with all permissions.
CREATE USER 'bob'@'localhost' IDENTIFIED BY '12345';

GRANT ALL PRIVILEGES ON *.* TO 'bob'@'192.168.50.50';

and flushed privileges
now I can see all is good in the database:
 +--------------+------------------+
| Host          | User             |
+---------------+------------------+
| %             | root             |
| 192.168.50.50 | bob              |
| 127.0.0.1     | root             |
| ::1           | root             |
| localhost     | debian-sys-maint |
| localhost     | root             |
| mysql         | root             |
+---------------+------------------+

but when I try to connect threw the webserver:
mysql -ubob -h192.168.40.40 -p12345

I get this:
ERROR 1045 (28000): Access denied for user 'bob'@'192.168.40.1' (using password: YES)

what is that ip "192.168.40.1" who is he and how did he appeared?
and how do I fix that?

A: This is your accessing from your machine as bob.
ERROR 1045 (28000): Access denied for user 'bob'@'192.168.40.1' (using password: YES)
You created a local user named bob but then you also need to create a bob user that can be user remotely see as follows and try to log in.
CREATE USER 'bob'@'192.168.40.1' IDENTIFIED BY '12345';
GRANT ALL PRIVILEGES ON *.* TO 'bob'@'192.168.40.1';

https://stackoverflow.com/questions/16287559/mysql-adding-user-for-remote-access


text:
Q: AngularJS sort People into Alphabetical List and Filter In AngularJS I have an Object with keys that are letters of the alphabet and each key is an array of people.

This is to create something like this in HTML:
A. Arnold, Avery, Adam, Alex
B. Bob, Boris
C. Chris, Connor, Caleb

How would I go about filtering each individual field by name? For example applying this.

Works fine, however, you get a result like this when you type "A" in:
A. Arnold, Avery, Adam, Alex
B.
C.

How can I collapse B and C? Is there a better organization method for this data?

A: The trick here is to store your filtered names in a scope variable so you can do a length check to hide the empty result.
You can do this with the following markup:

Then add ng-if="filtered.length > 0" to the tag you want to hide if result is 0.
Please have a look at the demo below or in this jsfiddle.

angular.module('demoApp', [])
.controller('mainController', function($scope) {
    $scope.peoples = {
        A: ['Arnold', 'Avery', 'Adam', 'Alex'],
        B: ['Bob', 'Boris'],
        C: ['Chris', 'Connor', 'Caleb']
    };

});

    <input ng-model="search" placeholder="enter search string"></input>

     0">{{letter}}

{{people}}

 0"/>


text:
Q: Redirect to the POST form page I'm developing an application using Django. The main page contains a textarea input where you must enter a list of IDs(this list can be large, so I submit the form using POST). After submiting the form, the server will render a page with a table where you can find informations about every ID. If you click on an ID, you will go to a page where you can modify some fields. For saving the modified fields into the database, the form action is: 'manage_ids/<>/save' and on the server I have a view for this url. How can I redirect the user back to the page with the table? I'm submiting the form using POST so a simple redirect wouldn't work. Or, to remain on the page where you can modify the fields(in this case, if you press the 'Back' browser button, to be redirected to the table page).
Workflow:
/
POST
/manage_ids
GET
/manage_ids/<<md5>>
POST(save)
/manage_ids/<<md5>>/save

Now, I should be redirected to:
/manage_ids

A: If you need to preserve a long list of IDs across multiple page requests, you should use the session.

A: I'd like to recommend you take a look at Django Form wizards


text:
Q: How do I define a type-aware groovy DSL which can propagate a type to inner blocks? I'm trying to implement a Groovy DSL, which takes a class name in a top-level block parameter, then allows static type checking against methods of that class in inner blocks, without needing to re-declare that class name redundantly.
(I am using Groovy v2.5.6)
For example, given this class:
// A message data type to parse
@Canonical
class MessageX {
    int size
    boolean hasName

    // an optional field to read, depending on whether #hasName is true
    String name
}

I'd want to be able to define things in the DSL something like this:
parserFor(MessageX) {
    readInt 'size'
    readBool 'hasName'

    // #hasName is a property of MessageX
    when { hasName }  {
        readString 'name'
    }
}

An attempt at implementing this might be:
import groovy.transform.Canonical
import groovy.transform.CompileStatic

@CompileStatic
@Canonical
class MessageX {
    boolean hasName
    String name
    int size
}

/** Generic message builder class for parsing messages */
@CompileStatic
class MessageBlock<T> {
    MessageBlock(Map<String, Object> values) {
        this.value = values
    }

    private final Map<String, Object> value

    void readString(String field) {
        // ...
    }
    void readInt(String field) {
        // ..
    }
    void readBool(String field) {
        // ...
    }
    /** Defines a condition */
    void when(@DelegatesTo(type = "T") Closure conditionBlock, @DelegatesTo(value = MessageBlock, type = "MessageBlock<T>") Closure bodyBlock) {
        // ...
    }
}

@CompileStatic
class Parser {
    static final <T> Closure<T> parserFor(Class<T> type, @DelegatesTo(value = MessageBlock, type = "MessageBlock<T>") Closure block) {
        println "parser get type $type.name"
        return {
            Map<String, Object> values = [:]
            MessageBlock<T> blockImpl = new MessageBlock<T>(values);
            block.delegate = blockImpl
            block()
            return type.newInstance(values)
        }
    }

    static void build() {

        // Define a parser using our DSL
        Closure<MessageX> messageXParser = parserFor(MessageX) {
            readBool 'hasName'

            when { hasName }  {
                readString 'name'
            }
        }

        messageXParser()
    }
}

Parser.build()

The documentation here suggests this should be possible with just the type = "MessageBlock<T>" tag on DelegatesTo.
However, that gives me null pointer exceptions when compiling.
Caught: BUG! exception in phase 'instruction selection' in source unit 'test.groovy' unexpected NullpointerException
BUG! exception in phase 'instruction selection' in source unit 'test.groovy' unexpected NullpointerException
Caused by: java.lang.NullPointerException

In the above example I also have the value = MessageBlock tag, which at least avoids an NPE - but I still get an error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
test.groovy: 57: [Static type checking] - The variable [hasName] is undeclared.
 @ line 57, column 20.
               when { hasName }  {
                      ^

I have not yet found a way to get the #when method's closure block to correctly delegate to MessageX class. I've tried these annotations for the second parameter to #parserFor and various other permutations, to no avail:

*

*DelegatesTo(MessageX)

*DelegatesTo(value = MessageX, type = "T")

*DelegatesTo(value = MessageX, type = "MessageX<T>")

*DelegatesTo(type = "MessageX<T>")
Can anyone help?


text:
Q: Django duplicate key value violates unique constraint error model form I have a legacy DB on PostgreSQL with a simple products table with 2 columns (productid, productname) with 70 products. I am trying to start using Django as a frontend and I have the model as below and a model form. The save process is failing with the error below.
duplicate key value violates unique constraint "productidentifier"
DETAIL:  Key (productid)=(4) already exists.

Could anyone help correct the error. I have confirmed on the Postgres table that the index get sequence is set right, expected value should be 72. See below the model, form and view.
#models.py
class Products(models.Model):
    productid = models.AutoField(primary_key=True)
    productname = models.TextField(verbose_name='Product Name')

    class Meta:
        managed = False
#Views.py
def new_product(request):
    if request.method == 'POST':
        form= forms.EditProductForm(request.POST)
        if form.is_valid():
            product = form.save()
            return redirect('views.full_product_list')
    else:
        form = forms.EditProductForm()
        return render(request, 'edit_product.html', {'form': form})

#forms.py
class EditProductForm(forms.ModelForm):
    productname = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))

    class Meta:
        model = models.Products
        fields = ('productname')

A: There is propably some issue with your auto field sequence. You can use ./manage.py sqlsequencereset to fix that. It will generate SQL queries to fix sequence on your tables.


text:
Q: Rest API and UserSign - Correct endpoint I'm planning to make a WCF rest api but I am confused about something.
I get how a rest api would work for getting or registering a user...
GetUser
GET
/user/username

Register user
POST
/user
[POST DETAILS]

What I don't get is user sign in. Logically it should be on the 'User' endpoint but it doesn't really work with the CRUD model.
Should it just be on it's own /login endpoint? And if so, should it be a GET or POST?

A: It should be on a /login endpoint:
POST /login
[CREDENTIALS]


text:
Q: Tesseract.js doesn't work for arabic language? I'm using tesseract.js with nodeJs to recognize arabic text from an image
but, unfortunately, it gives me a text which is not compliant with the text of the input image.
the input:
1
the output:
2
var tesseract = require('tesseract.js')
var request = require('request')
var fs = require('fs')
var util = require('util');
var path = 'C:/Users/Lenovo/Desktop/projet'
var log_file = fs.createWriteStream(path + '/arab.txt', {flags : 'w'});
var log_stdout = process.stdout;
var filename = 'capture.PNG'
tesseract.create({ langPath: "ara.cube.fold"  })
       .recognize(filename, 'ara')
       .progress(function  (p) { console.log('progress', p)  })
       .catch(err => console.error(err))
       .then(function (result) {
    console.log = function(result) {
      log_file.write(util.format(result) + '\n');
      log_stdout.write(util.format(result) + '\n');
     };
    console.log(result.text)
    process.exit(0)
})

any solution please!!


text:
Q: AWS CDK Codepipeline to build docker before cdk-synth My use case is as follows:

*

*Github repositories A, B and C have the source code for Lambda. A and B are libraries and C is the application that uses libraries A and B.

*GitHub repository X has the AWS CDK source code

*Each time a git commit is made to any of A, B, C or X the application C needs to be rebuilt in a Docker and the artifact (the application and the compiled libraries) packaged into a production Docker - the usual multi-stage Docker.

*The production Docker needs to be pushed to ECR

*Any infra changes due to any changes in X must also now be cdk-synthesised and cdk-deployed.

*Finally Lambda needs to use this updated image from ECR which I suppose will automatically happen after cdk-deploy above

I want this to be done via self-mutating CodePipeline via CDK.
I'm unable to figure out the details of how to set up this multirepository cdk code-pipeline up. There is the new(er) aws_cdk.pipelines module with synth property. Am I supposed to sequentially specify all the build steps in the given order above using a single ShellStep ? A ShellStep only gives the ability to specify one input source, whereas I would need all 4 (A, B, C and X).
Eg (python):
aws_cdk.pipelines.CodePipeline(self, 'Pipeline',
   ...,
   synth=ShellStep("<...>",
      input=<only one repo allowed to be specified>

Q1) What is the correct way to achieve the code build and self mutating steps mentioned above?
Q2) Since cdk synth and other builds will likely be run locally before committing to GitHub, I was thinking of creating a docker image with a build environment in which as a part of local build, I could build and test all repositories needed locally. This will give everyone an environment where the compilation and artifact generation just works. Then this Docker dev-image can be pushed to ECR. In this case, the CodePipeline will just read the Dockerfile (present in say X), build A,B and C in a docker and then create a production Docker image with the artifacts as usual (multi-stage Docker builds), push it to ECR, restart the dev-docker again, this time to run the cdk-synth + cdk-deploy, passing in the credentials as environment variables to the dev-docker container. Will this method work? How do I get what credentials to pass via CodePipeline to the docker container?


text:
Q: MS SQL Server - System Rollback We have a looped procedure which does a high volume data processing of transcating, loading and merging two tables using split and merge. During the data processing the system is rolling back the processed data even though there are no explicit rollbacks set up on the procedures.
Are there situations where the SQL Server will automatically rollback these transactions when there is not enough space or if something is wrong with the proc.
There are no validation errors in the procedure or any message while the procedure is executed. The data just disappears.
Thank you for your time and help.


text:
Q: Flutter Bottom sheet is hiding behind the keyboard I have 2 inputs in my bottom sheet but the problem is when I am opening keyboard it's covering the whole bottom sheet and the background page is move to the upside, not the bottom sheet.
Here is my code
class _addQuestionState extends State<addQuestion> {

  void _submitData(){
    Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    double stackHeight = (MediaQuery.of(context).size.height);
    return Container(
      color: new Color.fromRGBO(255, 0, 0, 0.5),
      child: Container(
        height: stackHeight * 0.4,
        decoration: BoxDecoration(
            color: Color(0xff404040),
            borderRadius: BorderRadius.only(topLeft: Radius.circular(15.0), topRight: Radius.circular(15.0))
        ),
        child: Center(
          child: SingleChildScrollView(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Container(

                  padding: EdgeInsets.only(top: 10, left: 10, right:10,
                    bottom: MediaQuery.of(context).viewInsets.bottom + 10 ,
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      TextField(
                        maxLength: 56,
                        style: TextStyle(
                          color: Colors.white,
                        ),
                        textAlign: TextAlign.center,
                        decoration: InputDecoration(
                          counterText: '',
                          labelText: 'Would Question',
                          labelStyle: TextStyle(
                              color: Colors.blue
                          ),
                          enabledBorder: UnderlineInputBorder(
                            borderSide: BorderSide(color: Colors.blue),
                          ),
                          focusedBorder: UnderlineInputBorder(
                            borderSide: BorderSide(color: Colors.blue),
                          ),
                        ),
                        onSubmitted: (_) => _submitData(),
                      ),
                      TextField(
                        maxLength: 56,
                        style: TextStyle(
                          color: Colors.white,
                        ),
                        textAlign: TextAlign.center,
                        decoration: InputDecoration(
                          counterText: '',
                          labelText: 'Rather Question',
                          labelStyle: TextStyle(
                              color: Colors.red
                          ),
                          enabledBorder: UnderlineInputBorder(
                            borderSide: BorderSide(color: Colors.red),
                          ),
                          focusedBorder: UnderlineInputBorder(
                            borderSide: BorderSide(color: Colors.red),
                          ),
                        ),
                        onSubmitted: (_) => _submitData(),
                      ),
                      SizedBox(height: stackHeight * 0.04,),
                      RaisedButton(onPressed: () {
                        _submitData();

                      }, child: Text('Add Question', style: TextStyle(
                          color: Colors.white
                      ),),color: Theme.of(context).primaryColor,
                      ),

                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

And I am calling this like
void _startAddnewTransaction(BuildContext ctx){
  showModalBottomSheet(context: ctx, builder: (_) {
    return addQuestion();
  });
}

Here is the image

As you can see in image 2 when keyboard open the background is moving on the upside but the bottom sheet isn't moving

A: use SingleChildScrollView in the root for widget tree in "build" method
like this :
@override
  Widget build(BuildContext context) {
    double stackHeight = (MediaQuery.of(context).size.height);
    return SingleChildScrollView(
           child: Container(child:....));
}


text:
Q: Adding an icon to a cell in a WPF DecExpress grid I need a fresh set of eyes because I am doing something wrong and can't figure out what. I am trying to add an icon to a DevExpress grid. The icon will be clickable to open the survey for editing. The icon is not displaying.
In the SurveyVMO:
  public Image EditIcon { get; set; }
    public static List<VMOSurvey> PopulateSurveyList()
    {
        List<Survey> surveyList = Survey.PopulateSurveyList();
        List<VMOSurvey> surveys = new List<VMOSurvey>();
        foreach (Survey svy in surveyList)
        {
            VMOSurvey s = new VMOSurvey(svy);

            if (svy.IsEditable)
                s.EditIcon =  Image.FromFile(@".\Images\pencil.png");
            surveys.Add(s);
        }
        return surveys;
    }

Then in the ManageSurveyWindow.xaml:
<Window.Resources>
    <Style x:Key="SurveyGrid" TargetType="{x:Type dxg:GridControl}">
        <Setter Property="AllowLiveDataShaping" Value="True"/>
        <Setter Property="SelectionMode" Value="Row"/>
        <Setter Property="Foreground" Value="Black"/>
        <Setter Property="FontSize" Value="18"/>
        <Setter Property="FontWeight" Value="Thin"/>
        <Setter Property="FontFamily" Value="Helvetica"/>
        <Setter Property="Margin" Value="10, 10, 10, 10"/>
        <Setter Property="HorizontalContentAlignment" Value="Left"/>
    </Style>
    <Style x:Key="ColumnHeaderStyling" TargetType="TextBlock">
        <Setter Property="Foreground" Value="White"/>
        <Setter Property="FontFamily" Value="Helvetica"/>
        <Setter Property="FontWeight" Value="Thin"/>
        <Setter Property="FontSize" Value="24"/>
    </Style>
    <Style x:Key="ManageSurveyTableStyling" TargetType="{x:Type dxg:TableView}">
        <Setter Property="ShowFixedTotalSummary" Value="True"/>
        <Setter Property="IsTotalSummaryMenuEnabled" Value="False"/>
        <Setter Property="ShowGroupedColumns" Value="False" />
        <Setter Property="ShowGroupPanel" Value="False"/>
        <Setter Property="EnableImmediatePosting" Value="True"/>
        <Setter Property="AutoWidth" Value="True"/>
        <Setter Property="HorizontalContentAlignment" Value="Left"/>
        <Setter Property="VerticalScrollbarVisibility" Value="Auto"/>
    </Style>
</Window.Resources>
<Grid>
    <dxg:GridControl AllowLiveDataShaping="True" ItemsSource="{Binding Surveys}" >
        <dxg:GridControl.Columns>
<dxg:GridColumn x:Name="EditIconColumn">
<dxg:GridColumn.HeaderTemplate>
  <DataTemplate>
   <TextBlock Text=" " Style="{StaticResource ColumnHeaderStyling}"/>
                    </DataTemplate>
                </dxg:GridColumn.HeaderTemplate>
                <dxg:GridColumn.HeaderStyle>
                    <Style TargetType="Control">
                        <Setter Property="Background" Value="#52658F"/>
                    </Style>
                </dxg:GridColumn.HeaderStyle>
                <DataTemplate>
                    <Image Height="32" Width="32" Source="{Binding EditIcon}" />
                </DataTemplate>
            </dxg:GridColumn>
        </dxg:GridControl.Columns>
        <dxg:GridControl.View>
            <dxg:TableView AllowEditing="False" Style="{StaticResource ManageSurveyTableStyling}"/>
        </dxg:GridControl.View>
    </dxg:GridControl>

</Grid>

A: I did figure it out. My EditIcon needed to be an ImageSource:
public ImageSource EditIcon { get; set; }

And then I had to add the following code to my xaml file:
<dxg:GridColumn.EditSettings >
                    <dxe:ImageEditSettings MaxWidth="30">
</dxe:ImageEditSettings>

Now I'm trying to figure out how to add a click event to the image. :)


text:
Q: SQL запрос, группировка данных по неделям Всем привет. Нужна помощь в составлении SQL запроса.
Суть, есть таблица:
CREATE TABLE IF NOT EXISTS `htable` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `date` int(10) NOT NULL DEFAULT '0',
  `userid` int(10) NOT NULL DEFAULT '0',
  `items` set('item1','item2','item3','item4','item5') DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=cp1251;

Есть запрос:
select week( from_unixtime(date),0 ) as hweek
 ,date_sub(from_unixtime(date), interval (dayofweek(from_unixtime(date))-1) day) as hstart
 ,date_add(from_unixtime(date), interval (7-dayofweek(from_unixtime(date))) day) as hend
 ,count(items) as hcount
 from htable where items LIKE '%item1%' AND (date BETWEEN 1393963200 AND 1396123200)
 group by week(from_unixtime(date))

Запрос выводит количество записей с items LIKE '%item1%' за промежуток времени 03/01/2014 - 03/30/2014 и группирует их по неделям, но есть одно но, если в какую-то неделю из промежутка нету записей, то в результаты запроса эти недели не попадают.
Вопрос: можно ли как-то добавить эти данные (чтобы выводило нули) в результат запроса?
A: В году 52 недели. Создать таблицу из 52 строк, и соединить (внешнее) её с вашим запросом по номеру недели.
create table T (dt datetime);
insert into T values('2014-02-20'),('2014-02-27'),('2014-03-02'),('2014-02-9'),('2014-03-25');
create table weeks(w int);
insert into weeks values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),
(11),(12),(13),(14),(15),(16),(17),(18),(19),(20),
(21),(22),(23),(24),(25),(26),(27),(28),(29),(30),
(31),(32),(33),(34),(35),(36),(37),(38),(39),(30),
(41),(42),(43),(44),(45),(46),(47),(48),(49),(50),
(51),(52);
SELECT W,WD FROM (
SELECT WEEK(DT) WD FROM t
) x
RIGHT JOIN (SELECT * FROM WEEKS CROSS JOIN (SELECT WEEK(MAX(DT)) WMAX, WEEK(MIN(DT)) WMIN FROM T) y) z ON WD=W
WHERE W BETWEEN WMIN AND WMAX;

A: При помощи средств MySQL этого сделать нельзя (если только не прибегать к дико шаманским методам). Но очень легко дополнить данные на стороне PHP (или что Вы используете).
Если Вы уверены, что для каждой недели есть хоть одна запись в таблице, но она не обязательно содержит item1, то можно сделать выборку без фильтра по items, а кол-во подходящих строк считать не как count(items), а как sum(items LIKE '%item1%'). Но это хак системы, я бы в своем проекте такое не использовал. Первый вариант надежнее.


text:
Q: QGIS 3 modeler: how to use the fields of an intermediate output as input in another algorithm? I'm working on a model to calculate land uses (usos) in different areas (zonas):

I have corrected geometries, cutted the uses layer, corrected geometries again and used the fields calculator to assing the area ID to every uses polygon contained in it [geomintersects ('zonas', 'ID')]. After that, I want to use the "collect geometries" algorithm to summarize uses by code and area. However, none of the fields of this last output appears in the dialog box.

I have searched through the "input" window of the modeler without any success. How can it be done?


text:
Q: Implementing an iterator for an unmodifiable list I'm implementing an unmodifiable list based on AbstractSequentialList. Now, according to Oracle's documentation:

For an unmodifiable list, the programmer need only implement the list
  iterator's hasNext, next, hasPrevious, previous and index methods.

The problem is that it seems I must provide an implementation for remove, set and add methods, although these are not needed at all due the unmodifiable nature of the list, otherwise the compiler complains because these methods are not implemented.
So, am I doing something wrong or is this the real way to go? am I supposed to implement such methods and throw some kind of exception within them or so?
Thanks a lot in advance,

A: Just throw an UnsupportedOperationException on the methods you do not need to implement. As specified by the Iterator/ListIterator interface documentation https://docs.oracle.com/javase/7/docs/api/java/util/ListIterator.html#remove()

Throws: UnsupportedOperationException - if the remove operation is not
  supported by this list iterator

e.g.
@Override
public void remove() {
    throw new UnsupportedOperationException("Not supported yet.");
}

A: http://docs.oracle.com/javase/6/docs/api/java/lang/UnsupportedOperationException.html

Thrown to indicate that the requested operation is not supported.

e.g.
@Override
public void remove() {
    throw new UnsupportedOperationException("Cannot remove from unmodifiableList");
}


text:
Q: Issue while sending messages on WhatsApp at specific time everyday using Node.js I'm writing a program in Node.js which sends a WhatsApp template every day at a specific time. I used node-cron and setInterval. When I deployed the program on https://dashboard.render.com/# or https://id.heroku.com/login to run it remotely it doesn't work. but when I run it locally on VSCode it works fine, I can't seem to figure out the issue.
Help is appreciated.
const express = require('express');
const webApp = express();

webApp.use(express.json());
const PORT = process.env.PORT;
function myFunc() {
    // console.log("Checking every 2 second")
    cron.schedule('15 16 * * *', () => {
        console.log("Checking every 2 second")
        sendDayTemplate();

    })
}
setTimeout(myFunc, 1000);

webApp.listen(PORT, () => {
    console.log(`Server is up and running at ${PORT}`);
});

Heroku logs
Render logs


text:
Q: checking individual element of an array by calling a method Can i optimize my code bit more to reduce number of line?
I am checking/passing individual array elements? Can i make it re-write in a generic way?
for (var i = 0; i < $scope.studentReport.Students.length; i++)
{
    if (_isValueNan($$scope.studentReport.Students[i].Age))
        $$scope.studentReport.Students[i].Age = null;

    if (_isValueNan($$scope.studentReport.Students[i].Number))
        $$scope.studentReport.Students[i].Number = null;

    if (_isValueNan($$scope.studentReport.Students[i].Height))
        $$scope.studentReport.Students[i].Height = null;
}

var _isValueNan = function (item) {
    var result = false;
    if (typeof item == 'number' && isNaN(item))
        result = true;
    return result;
}

A: With ref to Stumblor's answer:
for (var i = 0; i < $scope.studentReport.Students.length; i++) {
    _checkValueNan($$scope.studentReport.Students[i], ["Age", "Number", "Height"]);
}

var _checkValueNan = function (item, values) {
    values.forEach(function (val) {
        if (typeof item[val] === 'number' && isNaN(item[val])) item[val] = null;
    });
}

A: You can nullify the property internally in the function, and also pass the item and property value in independently. For example:
for (var i = 0; i < $scope.studentReport.Students.length; i++)
{
    _checkValueNan($$scope.studentReport.Students[i], "Age");
    _checkValueNan($$scope.studentReport.Students[i], "Number");
    _checkValueNan($$scope.studentReport.Students[i], "Height");
}

var _checkValueNan = function (item, valueName) {
    if (typeof item[valueName] == 'number' && isNaN(item[valueName]))
        item[valueName] = null;
}

EDIT:
Leading on from Vicky Gonsalves answer, you could additionally check ANY of the properties of the object, which might be a more scalable solution.
var _checkAllValueNan = function (item) {
    for(var key in item) { // iterates all item properties
        if (!item.hasOwnProperty(key)) continue; // ensures not prop of prototype
        if (typeof item[key] == 'number' && isNaN(item[key])) item[key] = null;
    }
}

for (var i = 0; i < $scope.studentReport.Students.length; i++)
{
    _checkAllValueNan($scope.studentReport.Students[i]);
}


text:
Q: Is there an easy way to get a list of all successful captures from a regex pre-5.10? I know the right way to do this if I have Perl 5.10 is to use named captures and values %+, but in Perl 5.8.9 and how can I get a list of successful captures?  I have come up with two methods that are both just terrible:
#you need to list each possible match
my @captures = grep { defined } ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16);

and
#ew, I turned on symbolic references
{
    no strict 'refs';
    my @captures = map { defined $+[$_] ? $$_ : () } 1 .. $#+;
}

There is a third option I have found involving (?{}), but it requires global variables (because the closure happens at compile time) and takes the regex from reasonably clear to ungodly mess.
The only alternative I have found is to capture the whole match and then use another set of regexes to get the values I want (actually I build the first regex out of the other regexes because there is no good reason to duplicate the logic).
I obvious left out an important piece of information.  I am using the regex in scalar context along with the \G assertion because the regex can change between matches (one of the tokens changes the way you grab tokens off the string).  For an example of the code written for Perl 5.10, see this question, specifically this answer.

A: You can use @+ and @- as in
substr $var, $-[N], $+[N] - $-[N] # corresponds to $N

But as said earlier, if you can, use the @list = grep defined, $var =~ /regex/ form.

A: The following solution uses string eval but in a fairly safe way I think.
Update: Maybe I am still missing something, but AFAICS, the fact that the pattern is using \G and the match is in scalar context only matters because the results of the match cannot be assigned to @matches directly.
In fact, the method below is a variation of the second proposed method in Chas.' OP where he used symbolic references. IMHO, either using symbolic references or string eval is fine because they happen in a very well defined way.
#!/usr/bin/perl

use strict; use warnings;

my $text = <<EOT;
a
2 b
3 c 3
EOT

my $re = qr/([a-z])/;

while ( $text =~ /$re/g  ) {
    my @matches = grep defined, map eval "\$$_", 1 .. $#-;
    print "@matches\n";
    if ( $matches[0] eq 'a' ) {
        $re = qr/\G\s+([0-9])\s+([a-z])/;
        next;
    }
    if ( defined $matches[1] and $matches[1] eq 'b' ) {
        $re = qr/\G\s+([0-9])(?: ([a-z]))(?: ([0-9]))/;
        next;
    }
}

Output:
C:\Temp> jj
a
2 b
3 c 3


text:
Q: python pandas wildcard? Replace all values in df with a constant I have a df and want to make a new_df of the same size but with all 1s. Something to the spirit of: new_df=df.replace("*","1"). I think this is faster than creating a new df from scratch, because i would need to get the dimensions, fill it with 1s, and copy all the headers over. Unless I'm wrong about that.

A: df_new = pd.DataFrame(np.ones(df.shape), columns=df.columns)
import numpy as np
import pandas as pd

d = [
    [1,1,1,1,1],
    [2,2,2,2,2],
    [3,3,3,3,3],
    [4,4,4,4,4],
    [5,5,5,5,5],
]

cols = ["A","B","C","D","E"]

%timeit df1 = pd.DataFrame(np.ones(df.shape), columns=df.columns)
10000 loops, best of 3: 94.6 µs per loop

%timeit df2 = df.copy(); df2.loc[:, :] = 1
1000 loops, best of 3: 245 µs per loop

%timeit df3 = df * 0 + 1
1000 loops, best of 3: 200 µs per loop

A: It's actually pretty easy.
import pandas as pd

d = [
    [1,1,1,1,1],
    [2,2,2,2,2],
    [3,3,3,3,3],
    [4,4,4,4,4],
    [5,5,5,5,5],
]

cols = ["A","B","C","D","E"]

df = pd.DataFrame(d, columns=cols)
print df

print "------------------------"

df.loc[:,:] = 1
print df

Result:
   A  B  C  D  E
0  1  1  1  1  1
1  2  2  2  2  2
2  3  3  3  3  3
3  4  4  4  4  4
4  5  5  5  5  5
------------------------
   A  B  C  D  E
0  1  1  1  1  1
1  1  1  1  1  1
2  1  1  1  1  1
3  1  1  1  1  1
4  1  1  1  1  1

Obviously, df.loc[:,:] means you target all rows across all columns. Just use df2 = df.copy() or something if you want a new dataframe.


text:
Q: Find a substring in parts within a string I'm learning Python, and came across a situation where I have to find a substring within a string but in parts.
For example, my string could be
My string="this is stack overflow" OR
My string="this stack is overflow"
And i have to find if stack overflow is present.
The order must be same, but there can be anything written in between two portions that is stack and overflow.
Any help is appreciated.!

A: use regular expression, code below
import re

mystr = ["this is stack overflow", "this stack is overflow"]
my_key = "stack overflow"

rexpr = re.compile(".*".join(my_key.split()))
for s in mystr:
    print(re.search(rexpr, s))

output
<re.Match object; span=(8, 22), match='stack overflow'>
<re.Match object; span=(5, 22), match='stack is overflow'>

A: You can do this several ways. The two I can think of are:

*

*Regular expressions

*Finding two strings in the same string.

s1 = "this is stack overflow"
s2 = "this stack is overflow"

Using regular expressions you can do it this way:
re_so = re.compile('stack(.*)overflow') #Here's the regex to use...
if m := re_so.search(s1):
    print('We have a match')
else:
    print('No match...')
if m := re_so.search(s2):
    print('We have a match')
else:
    print('No match...')

Using finding string in the same string:
if ('stack' in s1) and ('overflow' in s1):
    print('We have a match')
else:
    print('No match...')
if ('stack' in s2) and ('overflow' in s2):
    print('We have a match')
else:
    print('No match...')

In all cases your output should be
We have a match

A: s="This stack is overflow"
a=["stack","overflow"]

def f(s,a):
    s=s.split(" ")
    n,m=len(s),len(a)
    i=j=0
    while i<n:
        if s[i]==a[j]:
            j+=1
            if j==m:
                return True
        i+=1
    return False
print(f(s,a))


text:
Q: Prevent a windows update from ever installing I have downgraded my Skype from version 6.14 to 5.8 but windows keeps trying to run the upgrade back to 6.11 (a version that doest even work...). So I usually can keep 5.8 for a few days and suddenly when I shut down my computer it installs an update and the next morning I'm back to Skype 6.11.
I have tried setting 'Hide update' in the update manager,  removed the updater.exe from the skype folder and turned off automatic updates in Skype, but it doesn't prevent the upgrade.
Is there a way to permanently ignore an update and make sure it never gets installed?

A: Sign in to Skype.
In the menu bar, select Tools > Options....
In the Advanced tab, select Automatic updates.
Click Turn off automatic updates.
Click Save.

Source (currently has links to Windows 8 and Mac instructions too)
Or, block the updates in your firewall by blocking 204.9.163.247 and 204.9.163.158.
Or try this registry hack:

Open Registry Editor (Start → Run, type regedit.exe)
      Go to HKEY_LOCAL_MACHINE/SOFTWARE/Policies
      Create a new key named «Skype» and a new subkey of it named «Phone»
      You can check that you're in the right place by looking at the status bar – it must say
  HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Skype\Phone
      Finally, create a new DWord Value named «DisableVersionCheck» and with the value 1 (Base radiogroup can be set to any choice)

Or update the hosts file

Open Windows Notepad or any equivalently simple editor (not MS Word or similar)
  Click File → Open and type the following path: \windows\system32\drivers\etc\hosts (don't miss the leading backslash)
  – then click Open
      You should now have a file opened; add the following line to its end and save it (changes should be in effect immediately but you might
  want to restart to make sure):
204.9.163.158 127.0.0.1
  204.9.163.247 127.0.0.1
The above blocks access to Skype's update server by mapping its IP to
  your local machine (which of course won't respond to its update
  requests).
Skype gets updates from 204.9.163.XXX subnetwork which they
  own entirely according to MaxMind. Sometimes they change the exact
  server IP (XXX) like it was in 2012.

Source for hosts and registry hack


text:
Q: app crashing because of animationDidStart selector is sent to objects that don't support it In my app i'm starting to see a new type of crash resulting from animationDidStart selector being sent to objects that don't support it like UIScrollViewDelayedTouchesBeganGestureRecognizer and UIImageView. i started getting them on my new iphone 5s iOS 7.0.3 device (not sure if that is relevant to the crash).
the call stacks are :
 Stack Trace: (
0   CoreFoundation                      0x2de06e9b <redacted> + 154
1   libobjc.A.dylib                     0x381676c7 objc_exception_throw + 38
2   CoreFoundation                      0x2de0a7b7 <redacted> + 202
3   CoreFoundation                      0x2de090af <redacted> + 706
4   CoreFoundation                      0x2dd57dc8 _CF_forwarding_prep_0 + 24
5   QuartzCore                          0x302183c1 <redacted> + 152
6   libdispatch.dylib                   0x3864c0af <redacted> + 22
7   libdispatch.dylib                   0x3864e9a9 _dispatch_main_queue_callback_4CF + 268
8   CoreFoundation                      0x2ddd15b1 <redacted> + 8
9   CoreFoundation                      0x2ddcfe7d <redacted> + 1308
10  CoreFoundation                      0x2dd3a471 CFRunLoopRunSpecific + 524
11  CoreFoundation                      0x2dd3a253 CFRunLoopRunInMode + 106
12  GraphicsServices                    0x32a6e2eb GSEventRunModal + 138
13  UIKit                               0x305ef845 UIApplicationMain + 1136
14  spIM                                0x001398cd main + 116
15  libdyld.dylib                       0x38660ab7 <redacted> + 2
  )

 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIImageView animationDidStart:]: unrecognized selector sent to instance 0x1a3e5260'
 *** First throw call stack:
(0x2de06e83 0x381676c7 0x2de0a7b7 0x2de090af 0x2dd57dc8 0x302183c1 0x3864c0af 0x3864e9a9 0x2ddd15b1 0x2ddcfe7d 0x2dd3a471 0x2dd3a253 0x32a6e2eb 0x305ef845 0x1398cd 0x38660ab7)
libc++abi.dylib: terminating with uncaught exception of type NSException

and
   Stack Trace: (
0   CoreFoundation                      0x2de06e9b <redacted> + 154
1   libobjc.A.dylib                     0x381676c7 objc_exception_throw + 38
2   CoreFoundation                      0x2de0a7b7 <redacted> + 202
3   CoreFoundation                      0x2de090af <redacted> + 706
4   CoreFoundation                      0x2dd57dc8 _CF_forwarding_prep_0 + 24
5   QuartzCore                          0x302183c1 <redacted> + 152
6   libdispatch.dylib                   0x3864c0af <redacted> + 22
7   libdispatch.dylib                   0x3864e9a9 _dispatch_main_queue_callback_4CF + 268
8   CoreFoundation                      0x2ddd15b1 <redacted> + 8
9   CoreFoundation                      0x2ddcfe7d <redacted> + 1308
10  CoreFoundation                      0x2dd3a471 CFRunLoopRunSpecific + 524
11  CoreFoundation                      0x2dd3a253 CFRunLoopRunInMode + 106
12  GraphicsServices                    0x32a6e2eb GSEventRunModal + 138
13  UIKit                               0x305ef845 UIApplicationMain + 1136
14  spIM                                0x001378cd main + 116
15  libdyld.dylib                       0x38660ab7 <redacted> + 2
 )
 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIScrollViewDelayedTouchesBeganGestureRecognizer animationDidStart:]: unrecognized selector sent to instance 0x1abc2c80'
 *** First throw call stack:
 (0x2de06e83 0x381676c7 0x2de0a7b7 0x2de090af 0x2dd57dc8 0x302183c1 0x3864c0af 0x3864e9a9 0x2ddd15b1 0x2ddcfe7d 0x2dd3a471 0x2dd3a253 0x32a6e2eb 0x305ef845 0x1378cd 0x38660ab7)
 libc++abi.dylib: terminating with uncaught exception of type NSException


text:
Q: Magento 2: load product by product id or product sku I need to load product by product id or product sku.

A: <?php
namespace Mageplaza\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
    protected $_productRepository;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Catalog\Model\ProductRepository $productRepository,
        array $data = []
    )
    {
        $this->_productRepository = $productRepository;
        parent::__construct($context, $data);
    }

    public function getProductById($id)
    {
        return $this->_productRepository->getById($id);
    }

    public function getProductBySku($sku)
    {
        return $this->_productRepository->get($sku);
    }
}
?>

In Phtml file:
$id = YOUR_PRODUCT_ID;
$sku = 'YOUR_PRODUCT_SKU';
$_product = $block->getProductById($id);
$_product = $block->getProductBySku($sku);
echo $_product->getEntityId();
echo '<br />';
echo $_product->getName();


text:
Q: Taylor Expansion of Normal CDF I read the following paragraph which claims to be the Taylor expansion of standard normal CDF for positive $x$.
$1 - \frac{1}{\sqrt{2\pi}}e^{-\frac{x^2}{2}}  (a_1k + a_2k^2 + a_3k^3 + a_4k^4 + a_5k^5)$,
where $k:=\frac{1}{1+0.2316419x}, a_1=0.319381530, a_2=-0.356563782, a_3=1.781477937, a_4=-1.821255978, a_5=1.330274429.$
I do not get how this is derived even though I am numerically convinced of its truth. Could anyone explain this to me, please?

A: This is no Taylor expansion. It is a rational approximation listed as
formula 26.2.17 in Abramowitz / Stegun (see http://people.math.sfu.ca/~cbm/aands/page_932.htm)  and attributed to Hastings (1955), Approximations for Digital Computers.


text:
Q: Sending custom frame / packet in Python I read many articles and found how to send custom packet based on IP using socket(AF_INET, SOCK_RAW, IPPROTO_RAW). But I want to send completely custom packet  starting from Ethernet header. I can't send ARP packet if I can't form Ethernet header cause ARP don't based IP. Please, help!
P.S. I am on Windows 7, not Linux :(

A: In python, the easiest way is to use the cross-platform scapy library. It's well known for that
Scapy
You can sniff, send.... lots of packets, add your own protocols, use existing ones... and it works on nearly all platforms. (On windows, it uses Npcap/Winpcap)
You can then build an ARP packet using
from scapy.all import *
pkt = ARP()
pkt.show()
sendp(Ether(dst=..., src=...)/pkt)

Which will create such packets
###[ ARP ]###
hwtype= 0x1
ptype= 0x800
hwlen= 6
plen= 4
op= who-has
hwsrc= 00:50:56:00:1e:3d
psrc= 212.83.148.19
hwdst= 00:00:00:00:00:00
pdst= 0.0.0.0

To build the packet, use the / operator
ether = Ether()
ether.src = "00:00:00:00:00:00"
ether.dst = "ff:ff:ff:ff:ff:ff"
arp = ARP()
[edit arp.psrc, arp.pdst, arp.hwsrc, arp.hwdst]
packet = ether/arp
sendp(packet) # sens packet on layer 2

Have a look at its Scapy documentation

A: There's no cross-platform way to do what you want, of course.
Python is just passing these values through to the underlying C API. So, on a platform with a complete BSD sockets API including the packet interface, you can just use AF_PACKET and the other appropriate flags. (I think you'd want ETH_P_ALL or ETH_P_802_2 rather than IPPROTO_RAW, or you might want SOCK_DGRAM… anyway, read your platform's man packet and figure it out based on what you actually need to do.) On Linux, at least most of these flags should be available on the SOCKET module; on other Unixes, they often don't get picked up, so you have to manually look them up in the system headers and use hardcoded constant ints in your code.
Unfortunately, if you're on Windows, this doesn't do any good. While WinSock has a feature they call TCP/IP Raw Sockets, accessed via SOCK_RAW, and recent versions of Python do expose this, it's just an emulation of a small subset of what actual BSD sockets implementations can do, and doesn't offer any way to go below the IP level (hence the name of the feature).
Microsoft's solution to this used to be that you'd write a TDI provider with the DDK, which would implement whatever protocol you wanted to expose as another WinSock protocol, and then your application-level code could just use that protocol the same way it would use, e.g., TCP. From the linked document above, it looks like this is obsolete, but the replacement seems like the same idea but with different acronyms (and, presumably, different APIs).
On the other hand, I'm pretty sure Windows already comes with protocols for ARP, ICMP, and anything other protocols needed for its usermode tools (because they obviously can't be written around raw packets). I'm just not sure how to access them.

As far as I know, the usual alternative is to use WinPcap.
While this was originally designed to be a packet capture library, it also implements a complete link-level socket interface that you can use for sending and receiving raw frames.
And there are Python wrappers for it, like WinPcapy.
So, as long as you can require that the WinPcap driver be installed, you can write ARP code, etc., on Windows in Python. It's just different from doing it on Unix.
In fact, one of the examples on the front page of WinPcapY, "Easy Packet sending", should get you started:
from winpcapy import WinPcapUtils
# Build a packet buffer
# This example-code is built for tutorial purposes, for actual packet crafting use modules like dpkt
arp_request_hex_template = "%(dst_mac)s%(src_mac)s08060001080006040001" \
                           "%(sender_mac)s%(sender_ip)s%(target_mac)s%(target_ip)s" + "00" * 18
packet = arp_request_hex_template % {
    "dst_mac": "aa"*6,
    "src_mac": "bb"*6,
    "sender_mac": "bb"*6,
    "target_mac": "cc"*6,
    # 192.168.0.1
    "sender_ip": "c0a80001",
    # 192.168.0.2
    "target_ip": "c0a80002"
}
# Send the packet (ethernet frame with an arp request) on the interface
WinPcapUtils.send_packet("*Ethernet*", packet.decode("hex"))


text:
Q: Reactjs promise.all order of calls I'm trying to fetch the studentDataPromise before fetchLoansPromise since it depends on the data studentDataPromise returns.
This is my current code:
Promise.all([studentDataPromise, fetchclassesPromise, fetchLoansPromise])
        .then(() => {
            toggleIsReady();
        })
        .catch(error => {
            throw new Error(error);
        });

This is the current order of events:

*

*toggleIsReady initially set to false, but is now true.

*fetchLoansPromise - can't fetch it doesn't have the studentDataPromise fetched

*studentDataPromise- fetches it correctly

*toggleIsReady - Is now set to false

*fetchclassesPromise - fetches it correctly

Any suggestions?

A:
This is how I solved it, Now 'fetchStudentData' is resolved before 'fetchLoansPromise'.

    let studentDataPromise = null;
    let fetchClassesPromise = null;
    let fetchLoansPromise = null;

    useEffect(() => {
        studentDataPromise = fetchStudentData();
    }, []);

    useEffect(() => {
        fetchClassesPromise = fetchClasses();
    }, []);

    useEffect(() => {
        fetchLoansPromise = resolveStudentDataPromise();
    }, []);

    async function resolveStudentDataPromise() {
        await Promise.all([studentDataPromise]);
        fetchLoans();
    }

    Promise.all([studentDataPromise, fetchClassesPromise, fetchLoansPromise])
        .then(() => {
            toggleIsReady();
        })
        .catch(error => {
            throw new Error(error);
        });

Thank you everyone

A: Promise.all() gets executed when all the promises you pass in resolve. That means you don't have guarantee that your studentDataPromise gets resolved before fetchLoanPromise. I recommend having a glance here Promise.all
The easy way around it would be to use .then() once the promise resolves. This could look like so:
let studentDataPromise = new Promise((resolve, reject) => {
  /**
   *
   *
   * **/
   reject(/**Something goes here**/)

  /**
   * Some Code here
   *
   */
  resolve(/**Something goes here**/)

})

studentDataPromise
  .then((/**Whatever you return from resolve()**/) => {
    // Here you can call your fetchLoansPromise
    fetchLoansPromise
      .then(() => {
        /*** ***/
      })
  })

Or even more eleganty, with using async/await:
let studentDataPromise = () => {
  return new Promise((resolve, reject) => {

    /**
     *
     * **/

     resolve()

  })
}

let someAsyncFunction = async () => {
  try {
    let studentData = await studentDataPromise()
    // Here you are guaranteed that your promise resolved
    // And you can call your other function
  }
  catch (err) {
  }
}

In either way you have to make sure that your first promise resolves, then you can your other functions. Promise.all() is great when you want to make sure that something happens after all your promises (which you pass on) get resolved.
Hope this helps

A: Call studentDataPromise before other promisses.
studentDataPromise().then((data) => {
  Promise.all([fetchclassesPromise, fetchLoansPromise])
})

A: You could do something like
Promise.all([studentDataPromise, fetchclassesPromise])
    .then(([studentData, classesData]) => fetchLoans(studentData))
    .then(() => toggleIsReady())
    .catch(error => {
        // handle exception
    });

Or using async await:
try {
    const [studentData, classesData] = await Promise.all([studentDataPromise, fetchclassesPromise]);
    const loansData = await fetchLoans(studentData);
    toggleIsRead();
} catch (e) {
    // handle exception
}

Where fetchLoans would return a fetchLoansPromise.


text:
Q: Reading netCDF in ArcMap? I'd like to work on netCDF data from two website : ISIMIP and earthstat. You can have an example of data on http://www.earthstat.org/data-download/ (harvested area and yield for 175 crops) and https://esg.pik-potsdam.de/search/isimip/.
The idea is to match these data with an other layer on ArcMap (joint to a shapefile for example).
I know netCDF files are to big but I just need to extract one layer from these files. I mean I need an array with all latitude and longitude but for data from earthstat I only need the production layer and for data from ISIMIP (with a time dimension) I only need an array for one year for example.
How can I extract the data I want from these netCDF files and convert it in csv or txt file to read it with ArcMap 10.5.1?


text:
Q: Incorrect error If you assign an invalid date (like December 39th) to a datetime column ActiveRecord returns a "can't be blank" error when is should probably return an error like "Not a valid date"
My question.  Is this expected rails behavior, a bug or, something that I could patch?
class ExerciseLog < ActiveRecord::Base
  validates_presence_of :scheduled_datetime
end

Fire up the console.
e = Log.new
# lets set a date for Dec 39th which obviously doesn't exist
e.scheduled_datetime = "2010-12-39"
e.save
=> false
# this is the confusing message since our form did post a valid date
e.errors.on(:scheduled_datetime)
=> "can't be blank"
e.scheduled_datetime = "2010-12-30"
e.save
=> true

I discovered this issue when I accidentally transposed the month and day values.
btw This is in Rails 2.3.5

A: My guess, without digging through the rails code, is that that magic parsing that rails does with the date returns nil when an invalid string is assigned to a Date column.
If you do t = Date.parse("2010-12-39") in the rails console then you get:
ArgumentError: invalid date
    from /usr/local/lib/ruby/1.8/date.rb:931:in `new_by_frags'
    from /usr/local/lib/ruby/1.8/date.rb:975:in `parse'
    from (irb):2
    from :0

I am guessing that rails traps this error and sets the value to nil. Thus firing off the validation.


text:
Q: Is there a way to define list(obj) method on a user defined class in python? One can can implement the method __str__(self) to return a string. Is there an __list__(self) counterpart? (__list__ doesn't work!)
Is .toList() the way to go?

A: There is no direct counterpart, but list() is implemented by iterating over the argument. So implement either the iterator protocol (__iter__()) or bound indexing (__len__() and __getitem__()).

A: Generator:
def __iter__(self):
    return (i for i in [1,5,6,8])

List:
def __iter__(self):
    return iter([1,5,6,8])

Tuple:
def __iter__(self):
    return iter((1,5,6,8))


text:
Q: MySQL Pivot View Dynamic I have a table like

+-----------------------------------+-------------------------------------------+-------------+
| warehouse                         | item_code                                 | stock_value |
+-----------------------------------+-------------------------------------------+-------------+
| 103-VAN DXB- U56403 NADEEM - DLTL | Alcatel 1054D 1054E BLACK CHARCOAL GREY   | 500         |
+-----------------------------------+-------------------------------------------+-------------+
| 103-VAN DXB- U56403 NADEEM - DLTL | Alcatel 1054D 1054E BLACK+PURE WHITE      | 15000       |
+-----------------------------------+-------------------------------------------+-------------+
| 100-Main Warehouse - Nahda - DLTL | Alcatel 2008D WHITE+METAL SILVER DUAL SIM | 45643       |
+-----------------------------------+-------------------------------------------+-------------+
| 100-Main Warehouse - Nahda - DLTL | Alcatel 2008D-BLACK METAL SILVER DUAL SIM | 4544        |
+-----------------------------------+-------------------------------------------+-------------+

http://www.sqlfiddle.com/#!9/c4fe92/1/0
The column warehouse name is not fixed. So how I can create a Pivot table like below

+-------------------------------------------+----------------+--------+----------------+-------------+
| item                                      | Main Warehouse | NADEEM | total quantity | total value |
+-------------------------------------------+----------------+--------+----------------+-------------+
| Alcatel 1054D 1054E BLACK CHARCOAL GREY   | 0              | 1      | 1              | 500         |
+-------------------------------------------+----------------+--------+----------------+-------------+
| Alcatel 1054D 1054E BLACK+PURE WHITE      | 0              | 1      | 1              | 1500        |
+-------------------------------------------+----------------+--------+----------------+-------------+
| Alcatel 2008D WHITE+METAL SILVER DUAL SIM | 1              | 0      | 1              | 45643       |
+-------------------------------------------+----------------+--------+----------------+-------------+
| Alcatel 2008D-BLACK METAL SILVER DUAL SIM | 1              | 0      | 1              | 4544        |
+-------------------------------------------+----------------+--------+----------------+-------------+

A: Here is one way to do it assuming you are going to parse the desired information out of your warehouse field:
SELECT item_code,
  IF(LOCATE('Main Warehouse', warehouse), 1, 0) AS `Main Warehouse`,
  IF(LOCATE('NADEEM', warehouse), 1, 0) AS `NADEEM`,
  COUNT(item_code) AS total_quantity
FROM some_table
GROUP BY item_code


text:
Q: Allow DPMS to turn off screen with force when the screen is locked? I discover that command xset dpms 300 which turn off the screen for example after 5 minutes (300s), and it wonderfully doesn't turn off the screen if a youtube video is actually playing even in a background window.
However sometimes I want to keep a video playing on the background while not using the computer, so I can manually lock the computer with a custom script (I'm using i3) that will also turn off the screen (with xset s activate).
However if a keyboard (or mouse) event happen the screen will turn on again and then never go back since the video..
Is it possible to have the timeout to be applied regardless of media context as long as the computer is locked?

A: Your video player is probably using session DBus (documentation for GNOME) or the xdg-screensaver utility to inhibit the screensaver while the video player is active. See if your video player has an option to make it not do that.
That should remove the need to force the screensaver.


text:
Q: Includes and classes in C++ Well, i have the following problem.. I have main.cpp
#include "serverClass.h"
...

and then in serverClass.h,
#ifndef SERVERCLASS_H_
#define SERVERCLASS_H_
#include <stdio.h>
#include <stdlib.h>
#include "clientThread.h"
....

and in clientThread,
class ClientThread {
private:
serverClass* server;
....

But when it tries to compile ClientThread, it says serverClass isn't a type, because it wasn't compiled yet. I can't avoid including clientThread.h in serverClass. Is there anyway to tell the compiler that there is a type called serverClass that wasn't compiled yet?

A: You need to forward delcare serverClass:
class serverClass;

class ClientThread {
private:
serverClass* server;
....

A: In clientThread.h, before ClientThread class definition, you can  forward-declare the ServerClass class:
// Forward declaration
class ServerClass;

class ClientThread {
private:
ServerClass* server;
 ....


text:
Q: Two buttons in a div are misaligned The second button in a div is always lower than the first one across the entire project. The two buttons are have the same height: 30px. Code:

            <button class="btn btn-secondary action btn-sm" (click)=navigateToDetails(financialPlatform.publicIdentifier)>
              {{ 'general.button.details' | translate }}
            </button>
            <button class="btn btn-secondary action btn-sm" (click)="navigateToPlatforms(financialPlatform.publicIdentifier)">
              {{'financial.institutions.overview.button.platforms' | translate}}
            </button>

Two misaligned buttons
If I have three buttons, the second and third one are aligned but are slightly lower than the first one.
Edit with css and more code:
CSS:
button {
  margin: 2px;
  font-size: 12px !important;
}

.btn-primary {
  background-color: darkslategrey !important;
  border: none;
}

.btn-secondary {
  background-color: darkblue !important;
  border: none;
}

        {{financialPlatform.name}}
        {{financialPlatform.code}}
        {{financialPlatform.country}}
        {{financialPlatform.aisStatus | apiStatus | translate}}
        {{financialPlatform.pisStatus | apiStatus | translate}}
        {{financialPlatform.provider}}

            <button class="btn btn-secondary action btn-sm" (click)=navigateToDetails(financialPlatform.publicIdentifier)>
              {{ 'general.button.details' | translate }}
            </button>
            <button class="btn btn-secondary action btn-sm" (click)="navigateToPlatforms(financialPlatform.publicIdentifier)">
              {{'financial.institutions.overview.button.platforms' | translate}}
            </button>

The above is just a table with one actions column that includes two buttons, but my problem is in the entire project.

A: To ensure the child <button> elements nested in the parent
 are aligned vertically, you can make the parent container a flexbox and use align-items: center so the flex items margin boxes are centered within the line on the cross axis.

.parent {
  display: flex;
  align-items: center;
}

.parent button {
  margin: 2px;
  font-size: 12px !important;
}

.btn-primary {
  background-color: darkslategrey !important;
  border: none;
}

.btn-secondary {
  background-color: darkblue !important;
  border: none;
}

 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

        <button class="btn btn-secondary action btn-sm" (click)=navigateToDetails(financialPlatform.publicIdentifier)>Details</button>
        <button class="btn btn-secondary action btn-sm" (click)="navigateToPlatforms(financialPlatform.publicIdentifier)">Platforms</button>


text:
Q: opensuse (tumbleweed) + nginx + codeigniter 404 issue I've been fighting with this for a while now ans still cannot get it to run. I got nginx running on opensuse tumbleweed with codeigniter application.
I get to the front page with no problem but any attempt open a controller fails with 404 error.
When I was working on Ubuntu I was able to solve this within minutes with a little bit of googling, but here for some reason I am struggling. I am attaching my default config file for nginx. There must be something I am really not seeing here, since I got this working in the past. Is nginx on opensuse really such a pain?
server {
    listen       80;
    server_name  localhost;
    root /usr/share/nginx/html/;
    index index.php;

    #charset koi8-r;
    #access_log  /var/log/nginx/log/host.access.log  main;

    location / {
        root   /usr/share/nginx/html/;
        index  index.php index.html index.htm;

        ## Handling of CORS
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*';
        #
        # Om nom nom cookies
        #
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        #
        # Custom headers and headers various browsers *should* be OK with but aren't
        #
            add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
        #
        # Tell client that this pre-flight info is valid for 20 days
        #
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain charset=UTF-8';
            add_header 'Content-Length' 0;
            return 204;
        }
        if ($request_method = 'POST') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
        }
        if ($request_method = 'GET') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
        }
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php$ {

        try_files $uri =404;
        fastcgi_pass    127.0.0.1:9000;
        fastcgi_index   index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        #fastcgi_ignore_client_abort off;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny  all;
    }
}

A: Right, I eventually found and answer to the problem. I have pretty much completely erased the the contents of the config file and replaced them with what I found on nginx website (here).
Funny thing is, if you notice there are no more directives for handling CORS in the config file, yet all the contents such as fonts, scripts, etc. are working fine without a glitch on localhost.
server {
    listen       80;
    server_name  localhost;
    root /usr/share/nginx/html;
    autoindex on;
    index index.php;

    location / {

            try_files $uri $uri/ /index.php;

            location = /index.php {

                fastcgi_pass   127.0.0.1:9000;
                fastcgi_param  SCRIPT_FILENAME /usr/share/nginx/html$fastcgi_script_name;
                include        fastcgi_params;
            }
        }

        location ~ \.php$ {
            return 444;
        }

}

Hope that will be of use to someone ;)


text:
Q: Group by priority I have this
+---------+--------+-------+
| article | name   |status |
+---------+--------+-------+
|    0001 | A      | enable|
|    0002 | A      | temp  |
|    0003 | B      | enable|
|    0004 | C      | enable|
+---------+--------+-------+

I want to select all from this table 'product' but I want to group by name and if there is a status temp I want to ignore the enable status and display only the product with the temp status
This result after query will be :
+---------+--------+-------+
| article | name   |status |
+---------+--------+-------+
|    0002 | A      | temp  |
|    0003 | B      | enable|
|    0004 | C      | enable|
+---------+--------+-------+

Could you help me to build this query ?

A: If find at least one temp in group, show it. Else show enable
select article, name, if(sum(status='temp'), 'temp', 'enable')
    from  thetable
  group by name

To get article corresponding  to temp status, use such query
select * from table1
   where status = 'temp'
union
select * from table1
   where name not in (select distinct name from table1 where status = 'temp' )

A: Try this, hope help for you;)
SQL Fiddle
MySQL 5.6 Schema:
CREATE TABLE table1
    (`article` int, `name` varchar(1), `status` varchar(6))
;

INSERT INTO table1
    (`article`, `name`, `status`)
VALUES
    (0001, 'A', 'enable'),
    (0002, 'A', 'temp'),
    (0003, 'B', 'enable'),
    (0004, 'C', 'enable')
;

Query 1:
select  t1.*
from table1 t1
inner join (
  select count(distinct status) cnt, name, group_concat(status) as names from table1 group by name
) t2 on t1.name = t2.name
and (t2.cnt = 1 or (find_in_set('temp', names) > 0 and t1.status = 'temp'))
group by t1.name, t1.status

Results:
| article | name | status |
|---------|------|--------|
|       2 |    A |   temp |
|       3 |    B | enable |
|       4 |    C | enable |


text:
Q: JQuery UI Sortable + Laravel Collection Chunk: Rows draggable instead of single elements I've got a Problem. As I am using Bootstrap, I have rows containing 3 images each. In order to do it like this (because the images come from the databse) I'm using the chunk() function available in Laravel. This allows me to insert a .row, then show 3 images with a .col-md-4 each and then creates another .row and so on.

    @foreach($product->images->chunk(3) as $chunk)

            @foreach($chunk as $image)

                             $product->id, 'iid' => $image->id]) }}" class="btn btn-danger">X

            @endforeach

    @endforeach

Now I want to integrate jQuery UI's Sortable to those images using:
$('#sortable-image-container').sortable({});

However, it declares a row as a draggable element, instead of a product-image box.

In the picture here are two rows, the first containing 3 images boxes and the second one image box. as you can see I am grabbing the entire row to drag instead of a single element. Because I'm using chunk() I can't find a nice solution to make single elements draggable.

A: Seem to have figured it out by myself. There is an items option which defaults to: > *. By setting: items: '> .row > *', I can now grab single elements.
    $('#sortable-image-container').sortable({
        items: '> .row > *'
    });


text:
Q: How to print change from previous printed line? I have a function that reads temperatures from a device. After printing the temperature, I'd like to print the change in temperature from the previous printed line. Is there an easy way to do this?
While i < 50000:
T = getTemps()
print(T)
print(deltaT) # <-- I want to do this

A: I think you can keep the previous temperature as a separate variable, and once you print the delta, you can reassign previous one with the current one, because anyway with next loop you will get new value;
t = getTemps()
tPrevious = t
while i < 50000:
    t = getTemps()
    print(t)
    print(t - tPrevious)
    tPrevious = t

A: I think somethink like that
prev_T = 0  # Default value for first iteration
i = 0
while i < 50000:
    T = getTemps()
    print(T)
    print(T - prev_T)
    prev_T = T
    i += 1


text:
Q: If $64$ is divided into three parts proportional to $2$, $4$ and $6$, what is the smallest part? If $64$ is divided into three parts proportional to $2$, $4$ and $6$, what is the smallest part?
The problem I have is with understanding what the question means.
What does it mean for a number $N$ to be divided into $n$-parts proportional to $x_1,...,x_n$? Is it like this means that there exist constants $\xi_1,...,\xi_2$ such that $$N=x_1\xi_1+x_2\xi_2+...+x_{n-1}\xi_{n-1}+x_n\xi_n$$ or that for a single constant $\xi$ we have $$N=x_1\xi+...+x_n\xi=\xi(x_1+...+x_n)?.$$

A: If the number $N$ is divided into $n$ parts proportional to $x_1, \dots, x_n$, I would imagine that means
$$N= a_1+\cdots + a_n$$
such that $a_1:a_2:\dots:a_n = x_1:x_2:\dots:x_n$ or in other words, there exists such a positive constant $\lambda$ that $a_1=\lambda x_1$, $a_2=\lambda x_2,\dots, a_n = \lambda x_n$.


text:
Q: Update values in json (array elements) using jq in loop I have a input json file with an array. I need to updated two values (ver & date) in each array element. I could come up with below script but need help. I have hardcoded the ver & date to simplify the script.
input.json
[
  {
    "svcname": "svc1",
    "repo": "https://repo.mycom.org/repocontext/svc1-list",
    "ver": "0.1",
    "date": "2019-11-05"
  },
  {
    "svcname": "svc1",
    "repo": "https://repo.mycom.org/repocontext/svc1-list",
    "ver": "0.1",
    "date": "2019-12-21"
  }
]

Script:
#!/bin/bash
set +x
injson=input.json
updatedjson=$(jq .[] ${injson})

services=$(cat ${injson} | jq '.[] | .svcname' | tr -d \")
i=1
for svc in $services; do

        echo "==>$svc"
        echo "======> input json=${updatedjson}"
        echo "======> update ver=${i}"
        updatedjson=$(echo ${updatedjson} | jq ". | select( .name ==\"$svc\").ver=\"$i\"" | jq . )
        svcdate="2020-01-$i"
        echo "======> update date=$svcdate"
        updatedjson=$(echo ${updatedjson} | jq ". | select( .name ==\"$svc\").date=\"$svcdate\"" | jq . )
        echo "============================================"
        echo
        i=`expr $i + 1`

done

echo "======= write to file ====="
echo ${updatedjson}
echo ${updatedjson} | jq . > outjson.json

A: You are not using the true features of jq. What you shown in a loop, iterating over all the JSON objects can be simply reduced to one reduce() construct that is sort of a for loop in jq given an initial value and runs the filter incrementally
jq 'reduce range(0, length) as $d (.; (.[$d].ver = ($d+1|tostring)) | (.[$d].date = "2020-01-\($d+1)")) '

A brief explanation of how it works

*

*The range expression returns a list with numbers generated from 0 to upto the length of the objects in the array. For your given input it produces 0,1 which is assigned to d

*The reduce expression given the input value . the whole JSON, runs by setting the values in each object indexed by $d. So .[$d].ver refers to the ver field in the zeroth index. This is done incrementally till all the objects are processed.

*The same way the date field is modified using [$d].date with the value string prefixed (YYYY-MM-) and date is set accordingly.


text:
Q: A paradox in hyperbolic geometry? I was making some routine calculations when I found the strange following result : in the hyperbolic plane (with the Gauss curvature set at K=-1), let's $C$ a circle of center $O$ and radius $R$ and $A$ a point with $OA=R+h$, $AT$ the tangent (at $T$) to the circle, and $A_0$ the intersection of $OA$ and $C$. In Euclidean geometry, we have $AT=\sqrt {2hR+h^2}$, which tends towards infinity as $R$ does (in other words, applied to a sphere, the horizon expands as the radius of the sphere augments and the sphere flattens), but in hyperbolic geometry, the triangle $ATO$ is rectangle in $T$, so $\cosh OA=\cosh AT\cosh OT$, $\cosh AT=\frac{\cosh (R+h)}{\cosh R}\simeq e^h$ (well, there is a small error getting very quickly to 0), which means that even at the limit, the horizon has no relation to the angle of parallelism. A confirmation is given by calculation of angles : the angle $\theta$  of parallelism  (i.e. the angle between $OA$ and $D$, a parallel asymptote through $A$ to the tangent at the circle in $A_0$) is given by the Lobatchevski formula $\sin\theta=\frac{1 }{\cosh h}$, while the angle $\alpha=\widehat{OAT}$ satisfies (sinus law) $\sin\alpha=\frac{\sinh R }{\sinh (R+ h)}$, which tends very fast to $\frac{1 }{e^ h}$, a difference of a factor of 2... What is happening here ?

A: Sorry , I found the answer by myself : the limit of the circle as $R$ tends to infinity is NOT the tangent (at $A_0$) ! To see it, fix $B$ at a distance $d$ from  $A_0$ on the tangent, and call $B_0$ the point on the circle and on $OB$. It is easy to check that  $\cosh d = \frac{\cosh (R+B_0B)}{\cosh R}\simeq \exp(B_0B)$... Of course, I could also have noticed that the limit is not a line, but the horocycle having its center at the point at infinity of $AO$, and passing through $A_0$...


text:
Q: Choosing a random number from 1, 2 or 3, and summing them, what is the probability that the sum is 4 at one point? For example we get 1+1+1+2 which can't be 4 after this point or 1+3 which is 4 after the second number chosen.
So we don't need to sum more than 4 random numbers since the minimum sum equal to for is 1+1+1+1. So for the 4 random numbers that get chosen we have $3^4$ combinations in total. There are 7 ways to sum 4 numbers or less to 4 which are $$ 1+1+1+1$$ $$1+1+2$$ $$1+2+1$$ $$2+1+1$$ $$2+2$$ $$3+1$$ $$1+3$$ so there should be a probability of $\frac{7}{81}$ which for some reason isn't the right answer. What did I get wrong?

A: The probability of $1+1+2$ is $1/27$ not $1/81$. Likewise the probability of $2+2$ is $1/9$ etc

A: To get $1+1+2$ the four numbers you have should be
$$1,1,2, \mbox{anything}$$
Same way, for $2+2$ you need
$$2,2, \mbox{anything}, \mbox{anything}$$

A: Lord Shark is correct. The probability of $2+2$ is not $\frac{1}{81}$ but $\frac{1}{9}.$
More generally, if you select numbers from $1$ to $n$ and want the probability that the sum at some point is exactly equal to $k$, this is the coefficient of $x^k$ in:
$$\sum_{i=0}^{\infty} \left(\frac{x+x^2+\cdots +x^n}{n}\right)^i=\frac{n(1-x)}{n-(n+1)x+x^{n+1}}$$
So if $a_k$ is the coefficient of $x^k$ then $$a_{n+1+k}=\frac{1}{n}\left((n+1)a_{n+k}-a_{k}\right)$$
We also get $a_0=1,a_1=\frac{1}{n}$ and for $2\leq k\leq n$ we get $a_{k}=\frac{1}{n}\left(1+\frac{1}{n}\right)^{k-1}$.
In particular, then, $a_{n+1}=\frac{1}{n}\left(\left(1+\frac{1}{n}\right)^n-1\right)$
For $n=3$, this gives $a_4=\frac{4^3-3^3}{3^4}=\frac{37}{81}$.
When $n=3$, we get the exact formula:
$$a_{k}=\frac{1}{2}+\frac{1}{4}\left(\left(\frac{-1+\sqrt{-2}}{3}\right)^k+\left(\frac{-1-\sqrt{-2}}{3}\right)^k\right)$$
Which gives us an estimate:
$$\frac{1}{2\cdot 3^k}\leq\left|a_k-\frac{1}{2}\right|<\frac{1}{2\cdot 3^{k/2}}$$
For general $n$ we have $\lim_{k\to\infty} a_k=\frac{2}{n+1}.$

A: Consider reaching the sum $4$ as a win, and denote by $p_k$ $(0\leq k\leq 4)$ the probability of winning when standing at $k$. Then $p_4=1$, and
$$\eqalign{p_0&={1\over3}(p_1+p_2+p_3)\cr
p_1&={1\over3}(p_2+p_3+1)\cr
p_2&={1\over3}(p_3+1)\cr
p_3&={1\over3}\cdot 1\ .\cr}$$
Solving this we obtain $p_0={37\over81}$.


text:
Q: Maven multimodule project and SVN I have a problem related to subversion and a maven multimodule project in eclipse.
Right now my project structure is (ignore the errors =)):

Then I upload the parent directory to SVN and make a checkout in another location, thinking that the eclipse directory structure will maintain, but it didn't, and it's a pain in the back to work using folders.
So my question is: how can I upload my project to a svn repository and keep the structure of the picture above?
Thanks

A: You can avoid this by never creating project inside the eclipse workspace. Always put them somewhere else, and then check them into and out of svn.