Q: How to get text from  using Jsoup To be short. I have following code:
elements.select("#offers_table > tbody > tr:nth-child(2) > td > table > tbody > tr:nth-child(2) > td:nth-child(1) > div > p.color-9.lheight16.marginbott5.x-normal").get(0).toString();

and I am getting
<p class="color-9 lheight16 marginbott5 x-normal"> This is the text I would like to get </p>

How to get

This is the text I would like to get

from here?

A: Use element.text() where element is your Element.


Q: Row merging based on two conditions I am currently cleaning my data set for a farm and I need to merge the records from 3 separate rows into one.
I'd like the get all the records merged based on columns FARM and SHED.
The dataset currently looks like this:

Ideally, I wish to make it look like this:

What is the best solution to have it cleaned up?
I'd like to move columns 'Feed total' and 'Feed per bird' to fill the empty spaces in the rows above. Then I'd like to move around the columns 'Average weight 1A' to row, where the shed number is 1, 'Average weight 2A' to row, where the shed number is 2 etc...
Thanks!
EDIT: Sample dataset attached to give a bigger picture on the dataset

Date
Time
Age
Mortality day
Mortality total
Feed total
Feed per bird
Water total
Water per bird
Farm
Shed
DT
Average weight 1A
Average weight 1B
Average weight 2A
Average weight 2B
Average weight 3A
Average weight 3B
Average weight 4A
Average weight 4B
Average weight 5A
Average weight 6A
Average weight 5B
Average weight 6B
Average Weight 6A1
Average weight 7A
Average weight 8A

06/06/2022
23:50:01
-1.0
0.0
0.0
0.0
0.0
182.0
0.004
Park Farm
1
2022-06-06 23:50:00

06/06/2022
23:50:01
-1.0
0.0
0.0
0.0
0.0
105.0
0.003
Park Farm
2
2022-06-06 23:50:00

06/06/2022
23:50:01
-2.0
0.0
0.0
0.0
0.0
4.0
0.0
Park Farm
4
2022-06-06 23:50:00

06/06/2022
23:50:01
-1.0
0.0
0.0
0.0
0.0
82.0
0.003
Park Farm
3
2022-06-06 23:50:00

06/06/2022
23:50:01

Park Farm
1
2022-06-06 23:50:00
2494
0.0
2577.0
0.0
2460.0
0.0
2467.0
1972.0

06/06/2022
23:50:00
4.0
94.0
367.0
600.0
0.018
1473.0
0.044
Green Farm
1
2022-06-06 23:50:00

06/06/2022
23:50:00
4.0
72.0
239.0
340.0
0.01
1480.0
0.044
Green Farm
2
2022-06-06 23:50:00

06/06/2022
23:50:00
4.0
94.0
288.0
630.0
0.019
1443.0
0.043
Green Farm
3
2022-06-06 23:50:00

06/06/2022
23:50:00
3.0
88.0
176.0
290.0
0.009
487.0
0.015
Green Farm
4
2022-06-06 23:50:00

06/06/2022
23:50:00
3.0
105.0
248.0
520.0
0.016
365.0
0.011
Green Farm
5
2022-06-06 23:50:00

06/06/2022
23:50:00
3.0
72.0
168.0
560.0
0.017
289.0
0.009
Green Farm
6
2022-06-06 23:50:00

06/06/2022
23:50:00

Green Farm
1
2022-06-06 23:50:00
1861

1874.0

1990.0

2083.0

1959.0
2160.0

06/06/2022
23:50:01
27.0
40.0
1153.0

11649
0.249
Castle Farm
1
2022-06-06 23:50:00

06/06/2022
23:50:01
26.0
21.0
941.0

11289
0.261
Castle Farm
4
2022-06-06 23:50:00

06/06/2022
23:50:01
26.0
22.0
962.0

10277
0.236
Castle Farm
3
2022-06-06 23:50:00

06/06/2022
23:50:01
27.0
53.0
1004.0

12204
0.259
Castle Farm
2
2022-06-06 23:50:00

06/06/2022
23:50:01

6686.8
0.139

Castle Farm
1
2022-06-06 23:50:00

06/06/2022
23:50:01

6446.9
0.146

Castle Farm
4
2022-06-06 23:50:00

06/06/2022
23:50:01

6031.5
0.135

Castle Farm
3
2022-06-06 23:50:00

06/06/2022
23:50:01

6742.5
0.14

Castle Farm
2
2022-06-06 23:50:00

06/06/2022
23:50:01

Castle Farm
1
2022-06-06 23:50:00
1.508

06/06/2022
23:50:01

Castle Farm
4
2022-06-06 23:50:00

1.542

06/06/2022
23:50:01

Castle Farm
3
2022-06-06 23:50:00

1.493

06/06/2022
23:50:01

Castle Farm
2
2022-06-06 23:50:00

1.542

06/06/2022
23:50:01
24.0
36.0
1211.0
6380.0
0.156
9769.0
0.24
Blue Farm
1
2022-06-06 23:50:00

06/06/2022
23:50:01
24.0
31.0
1317.0
5860.0
0.144
9775.0
0.24
Blue Farm
2
2022-06-06 23:50:00

06/06/2022
23:50:01
24.0
29.0
1431.0
6470.0
0.159
9571.0
0.236
Blue Farm
2
2022-06-06 23:50:00

06/06/2022
23:50:01
24.0
28.0
947.0
5710.0
0.139
9755.0
0.238
Blue Farm
4
2022-06-06 23:50:00

06/06/2022
23:50:01
24.0
29.0
1089.0
6020.0
0.136
10399
0.234
Blue Farm
5
2022-06-06 23:50:00

06/06/2022
23:50:01
24.0
30.0
1489.0
5640.0
0.128
10303
0.234
Blue Farm
6
2022-06-06 23:50:00

06/06/2022
23:50:01

Blue Farm
15
2022-06-06 23:50:00

1289.0
1267.0
1268.0
1243.0

06/06/2022
23:50:01

Blue Farm
5
2022-06-06 23:50:00
1418
1257.0
1462.0
1320.0
1332.0
1309.0
877.0
1248.0

06/06/2022
23:50:38
1.0
0.0
0.0

0.0
0.0
Upper Farm
38
2022-06-06 23:50:00

06/06/2022
23:50:38
1.0
0.0
0.0

0.0
0.0
Upper Farm
3
2022-06-06 23:50:00

06/06/2022
23:50:38

Upper Farm
1
2022-06-06 23:50:00

2.849

06/06/2022
23:50:35
1.0
0.0
0.0
0.0
0.0
34.0
0.001
Seaside Farm
1
2022-06-06 23:50:00

06/06/2022
23:50:35
1.0
0.0
0.0
0.0
0.0
35.0
0.001
Seaside Farm
2
2022-06-06 23:50:00

06/06/2022
23:50:35
1.0
0.0
0.0
0.0
0.0
26.0
0.001
Seaside Farm
3
2022-06-06 23:50:00

06/06/2022
23:50:35
1.0
0.0
0.0
0.0
0.0
35.0
0.001
Seaside Farm
4
2022-06-06 23:50:00

06/06/2022
23:50:35

Seaside Farm
5
2022-06-06 23:50:00
39
40.0
43.0
42.0
45.0
46.0
46.0
46.0

A: I would start like this, this is assuming you only want one row/record per farm-shed.
import pandas as pd
import functools

# dataframe is df

# First combine horizontally: get the average weight into one column

weight_cols = [col for col in df.columns if col.startswith("Average weight")]
df2 = (
 df.assign(**{
    'Average weight': lambda df: functools.reduce(pd.Series.combine_first, [df[col] for col in weight_cols])
 })
 .drop(columns=weight_cols)
)

# Get first value from each column in each group

grouped_by = ['Farm', 'Shed']
remaining_cols = df2.columns.difference(grouped_by, sort=False)

(df2.groupby(grouped_by)
    .agg({col: "first" for col in remaining_cols})
    .reset_index())

If you want to safeguard against duplicated data, more checks are needed.


Q: tracking button click as goal in Google Analytics I am trying to do button click in GA, but getting this
This Goal would have a 0% conversion rate based on your data from the past 7 days.

Although in the Real Time report, there are conversations.
I found this post and I have done exactly this.
Goal type: Event

Event conditions:

Category; Equals to: button
Action; Equals to: click
Label; Equals to: trial-button

and this is my html

Unlike the user in that post, I am not using yoat plugin. but still its not working.
UPDATE
I just checked the GA and now it's showing
This Goal would have a 1.47% conversion rate based on your data from the past 7 days.
What does this mean? Does it mean that I have implemented it correctly ?


Q: Strange QGIS plugin behaviour if it runs for the first time I have made a plugin that works fine in itself. Shortly said it fills a combobox based on a MS Access table. Then features in the map are shown that meet the value I select in the combobox.
But I encounter a strange phenomenon. If I run the plugin for the first time after starting QGIS, or after reloading it, the combobox is not filled and I can't do anything but closing the plugin. Then, if I rerun the plugin it works fine.
What's happening here?
The relevant code:
conn = pyodbc.connect('Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ= [path and .accdb];')
cursor = conn.cursor()
cursor.execute( [query] )
mylist.clear()
for row in cursor.fetchall():
  mylist.append(row[0])
  self.dlg.mycombobox.addItem(row[1]+' ('+str(row[2])+')')


Q: How to send a html file with css as a response to a connecting client using express So I've been trying to figure this out for a while now and the answers that I have found are just confusing, vague without explanation and or, do not work - (At least for me).
First here is my project structure.
.. denotes a folder
- denotes a file
while four | denote a sub directory or file in parent folder
..public
|||| ..html&css
|||| |||| ..main
|||| |||| |||| - main.html
|||| |||| |||| - main.css
|||| ..javascript
|||| |||| -server.js

Hopefully the above project structure is understandable, Stack Overflows formatting is tough to work with.
Here is my code - server.js
let express = require('express');
let app = express();

app.use(express.static('../html&css'));

let server = app.listen(8080, function () {
    app.get(function (req, res) {
        res.sendFile();
    });
});

let port = server.address().port;
console.log(`Express app listening at ${port}`);

I have seen a few ways to send the files when someone connects to the server, and have managed to get html to send but never both html and css. From researching I've seen a few ways to do this but the way in which they are explained is confusing and no answers I found explain in detail how to accomplish  my question along with what and why your doing the things they are saying to accomplish it.
I have just been getting a lot about routes, static, app.get this and app.get that, res.sendFile and some other mumbojumbo but not any of it is really making sense. It also doesn't help that most of the answers don't have the persons complete project structure. If they did understanding which routes were doing what would be much easier.
This link seemed to be the best answer I came across but because of lack of project structure I cannot implement it into my own project and thus understand how it works.
If someone could even just explain how that works with a project structure implemented in their answer I would be grateful, otherwise if they have another way of doing it through the use of the fs module and express or something else.
I hope my question is understandable clear.
Thank you for your time.

A: I am going to explain how it works. But the code you have written is correct. Even I ran the code.
let express = require('express');
let app = express();

app.use(express.static('../html&css'));

let server = app.listen(8080, function () {
    app.get(function (req, res) {
        res.sendFile();
    });
});

let port = server.address().port;
console.log(`Express app listening at ${port}`);

Now, what express.static do? it exposes the particular folder and makes auto routes.
If you want to access main.css it will be hosted on localhost:8080/main/main.css
In the main.html to use that CSS you just add a link.
<link rel="stylesheet" href="main.css"> or <link rel="stylesheet" href="/main/main.css">
But, you cannot HTTP GET let's say localhost:8080/main that will not work.
So, you need to run the server by typing node javascript/server.js and it will run just fine. But as the server.js is a backend code do not put it in the public folder. Maybe make a folder called src and put it there.

A: Let's look a a few things.
First, folder structure:
According to your setup, you have your server.js file embedded within the public folder, albeit one level down.
If you think of an MVC framework, see this sample tutorial, you want to put your server at the root of your application (not inside of the JavaScript folder inside public where you would serve any client-side javascript.
Second, regarding middleware:
When you call the express.static middleware, you will want to use the path module to create an absolute rather than relative path to the public folder, which is especially important for deployment.
app.use(express.static(path.join(__dirname, 'public')));

Now, you will be able to access all the files in your public folder like so:
http://localhost:8080/main/*
http://localhost:8080/javascript/*

Of course * refers to whatever files are there.
Third, regarding app.listen:
The callback to app.listen is expecting to be returned a server object. See the documentation. Rather than setting up a listener on a route here, you should establish that outside of the app.listen call.
For instance, you may want to set up a basic get route to serve your main.html page on /. That's up to you. The express.static middleware is already serving this page as /main/main.html.
app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname, 'public', 'main.html'));
});

let server = app.listen(8080);


Q: What will happen if we try to take a voltage reading by keeping it in current mode in a multimeter? There are different modes present in a multimeter. one is
the current mode and voltage mode for their respective measurements. what
will happen if one try to take a voltage reading by keeping it in current mode?

A: Whenever a multimeter measures a current it is actually measuring the voltage drop across the so called shunt resistor. A shunt resistor is a resistor with a very low resistence so that whenever it's placed in series with the circuit, and so when you try to measure the current of said circuit, it does not effect, to an extensive degree, the current draw of the circuit.
The meter measures the voltage drop across the shunt, which has a more or less precise resistence, like $R=0.01 \Omega$, and using Ohm's law it finds the current
$$I = \frac{\Delta V}{R} = 100\Delta V\; [A]$$ where the final result is found using the hypotetical resistence of $R=0.01\Omega$.
Now that the current measurement is clear, you should be able to understand that if you measure a voltage, which requires the multimeter to be taken in parallel with the circuit, you're just putting the shunt resistor in parallel with your circuit at the point of measurement.
Suppose that you're trying to measure the volage drop across a $100\Omega$ resistor with the multimeter in current mode. What you're actually doing is putting the shunt resistor, suppose again $R = 0.01\Omega$, in parallel to the $100\Omega$ resistor. Suppose that your power supply is $10 V$. Since the shunt is in parallel to the $100\Omega$ resistor you'll have $10V$ across your shunt which means that the multimeter will display a current of $$I = \frac{\Delta V}{R} = (100*10) A =1000 A$$
So your multimeter will draw a big amount of current from your circuit, and so it will just melt the fuse that your multimeter should, hopefully, have.

A: An ammeter can be thought of as a galvanometer with a tiny shunt resistance in series (so as to not disturb the total current drawn from the source) and a voltmeter can be thought of as a galvanometer with a very high shunt resistance attached in parallel. Ammeters should thus be connected to a circuit in series in order to measure the resistance, as shown below:

When you set the multimeter to the "current" mode, it is essentially working as an ammeter, meaning that it's a galvanometer with a very low resistance (say, $r$) in series. If you were to use it to measure voltage, you would connect this (in parallel) over some resistance $R$, as shown below.

The circuit's load across will now become approximately $r$ (specifically, it will be the equivalent resistance of $r$ and $R$ in parallel $= \frac{r R}{R+r}$, very close to $r$), meaning that the circuit will be equivalent to a power source connected to a very low resistance.
As a result the circuit will draw a large amount of current from the source (in practical terms, it will be the maximum current the source can provide), and this will be the current measured by the multimeter.  Of course, the value of $r$ chosen by the multimeter depends on the the actual "current" setting. In some multimeters, I've found that this usually blows the fuse if you're using the "sensitive" current setting.
Of course, if you're using a source that can actually provide a current much larger than the multimeter can handle, Bad Things Will Happen. (But hopefully -- if you have to ask this question -- you won't be using such a source!)


Q: SQL Server reporting services version issue I am facing following error during deployment of SSRS report on server.
The definition of this report is not valid or supported by this version of Reporting Services.
I have been trying to find out issue on internet for two days but no luck.
Reporting Services version on Server:12.0.2000.8
On my local machine I have SQLManagementStudio_x64_ENU 2014, SQLEXPR_x64_ENU and VS2012 BIDS. We have few other reports already running on server. When I create a new one and try to deploy on server I got the above error.
Please help.

A: The version of SSRS (Reporting Services) is 12.0.2000.8 which according to https://sqlserverbuilds.blogspot.com/ is SQL Server 2014.  If the version of SSRS is 2014 then it is not possible to deploy an SSRS report created using Visual Studio 2012 BIDS.
As an alternatively you can use Visual Studio 2017 which can deploy to SSRS 2008, 2008 R2 2012, 2014, and 2016 upwards.  See this answer for a screenshot of where you can make the changes.
This is the method I used to deploy SSRS reports to a 2012 and then a 2016 installation of SSRS.


Q: In which order are rules of custom iptables chains evaluated? I am fairly new to iptables. The picture below shows the order in which chains are evaluated based on my current understanding. If that impression is wrong please let me know.
My question is where in the following diagramm is a custom chain placed when I add it like that?
sudo iptables -N MYCHAIN
I know that command creates a new chain in the filter table, but I am not sure what that means. Are rules of MYCHAIN evaluated before or after rules of the other chains?

A: A user defined chain is walked through when a rule from a built-in chain jumps to it. When the user defined chain ends you jump back to rule following the rule that made  you jump to the custom rule. If the packet matches a rule in a user defined chain with a terminating target (such as accept) processing ends.
Not sure my wording is clear enough but that's it.

A: After creating a CHAIN you need to add a rule to pass traffic to it. Like
iptables -A INPUT -j MYCHAIN

Now all traffic that reached the end of INPUT will go to MYCHAIN.
Then if traffic does not meet any conditions (or meet but with -j RETURN action) in MYCHAIN in continues to flow from the point it went to MYCHAIN.
So your chain can be anywhere on a diagram.


Q: Can a SignalR Application run on IIS 8.5 on Windows Server 2012 R2? Plain and simple: Is it even possible for a SignalR Application to run off IIS 8.5 on Windows Server 2012 R2, or is this not a compatible setup? There are tons of threads all over Stack Overflow that pose the same issue, that the dynamically generated script located at signalr/hubs is 404ing, but the threads with solutions are not using my iis/server setup.
I tried following the tutorial at https://learn.microsoft.com/en-us/aspnet/signalr/overview/getting-started/tutorial-getting-started-with-signalr but it seems that it only works in Visual Studio's IIS Express. As soon as I move the application to our server, I get the error everyone else on SO is getting.
Here's the supported platforms for Signalr on the official documentation:
https://learn.microsoft.com/en-us/aspnet/signalr/overview/getting-started/supported-platforms
It stops short of Windows Server 2012 R2, but the documentation is dated. Any advice is appreciated.

A: Yes, Windows Server 2012 R2 and Windows Server 2016 both support SignalR. Just ensure WebSocket support is enabled and you're all set.
IIS Express is a cut-down version of IIS (which frustratingly does not work with IIS Manager), but internally it uses the same execution engine (including HTTP.sys integration) so it uses the same web.config files as the full-fat IIS too, so it supports SignalR too.
("IIS Express" is a thing because previously VS shipped with a simple web-server called Cassini, which used ASP.NET System.Web.dll for everything, which worked for simple applications but for more complex applications there was sufficient differing behaviour that it made development difficult)


Q: Cómo unir tres tablas en una consulta?

Al ejecutar el siguiente código, me muestra la información a excepción de los servicios 16 y 17 porque tienen volumen 0 y debería mostrarme todos los servicios cuando su Volumen sea <> 0.
SELECT datos_cbr.servicio AS Num, nombreServicioSigitel AS Servicio, COUNT(importe) AS Volumen, IF((SELECT SUM(importeMas) FROM ajustes WHERE (numeroServicio = ajustes.servicio) != 0 AND fechaAjuste = '2020-06-28'), (SELECT COUNT(importeMas) FROM ajustes WHERE (numeroServicio = ajustes.servicio AND importeMas !=0 AND fechaAjuste = '2020-06-28')),0) AS 'Volumen(+)', IF((SELECT SUM(importeMenos) FROM ajustes WHERE (numeroServicio = ajustes.servicio) != 0 AND fechaAjuste = '2020-06-28'), (SELECT COUNT(importeMenos) FROM ajustes WHERE (numeroServicio = ajustes.servicio AND importeMenos !=0 AND fechaAjuste = '2020-06-28')),0) AS 'Volumen(-)',
(SELECT COUNT(importe) FROM datos_cbr WHERE (numeroServicio = servicio AND importe BETWEEN 0000.01 AND 2000.00 AND fechaOperacion = '2020-06-28')) AS '1 a 2,000' ,
(SELECT COUNT(importe) FROM datos_cbr WHERE (numeroServicio = servicio AND importe BETWEEN 2000.01 AND 3000.00 AND fechaOperacion = '2020-06-28')) AS '2,001 a 3,000' ,
(SELECT COUNT(importe) FROM datos_cbr WHERE (numeroServicio = servicio AND importe BETWEEN 3000.01 AND 4000.00 AND fechaOperacion = '2020-06-28')) AS '3,001 a 4,000' ,
(SELECT COUNT(importe) FROM datos_cbr WHERE (numeroServicio = servicio AND importe BETWEEN 4000.01 AND 5000.00 AND fechaOperacion = '2020-06-28')) AS '4,001 a 5,000' ,
(SELECT COUNT(importe) FROM datos_cbr WHERE (numeroServicio = servicio AND importe BETWEEN 5000.01 AND 7500.00 AND fechaOperacion = '2020-06-28')) AS '5,001 a 7,500' ,
(SELECT COUNT(importe) FROM datos_cbr WHERE (numeroServicio = servicio AND importe BETWEEN 7500.01 AND 10000.00 AND fechaOperacion = '2020-06-28')) AS '7,501 a 10,000' ,
(SELECT COUNT(importe) FROM datos_cbr WHERE (numeroServicio = servicio AND importe BETWEEN 10000.01 AND 15000.00 AND fechaOperacion = '2020-06-28')) AS '10,001 a 15,000',
(SELECT COUNT(importe) FROM datos_cbr WHERE (numeroServicio = servicio AND importe > 15000.01 AND fechaOperacion = '2020-06-28')) AS 'Mayor a 15,000',

(SELECT COUNT(importe) FROM datos_cbr WHERE (numeroServicio = servicio AND fechaOperacion = '2020-06-28'))

+(SELECT COUNT(importeMas) FROM ajustes WHERE (numeroServicio = ajustes.servicio AND importeMas !=0 and fechaAjuste = '2020-06-28'))
-(SELECT COUNT(importeMenos) FROM ajustes WHERE (numeroServicio = ajustes.servicio AND importeMenos !=0 and fechaAjuste = '2020-06-28')) AS 'Volumen Total',
IF(ISNULL(
(SELECT FORMAT(ROUND(SUM(importe),2),2) FROM datos_cbr WHERE (numeroServicio = servicio AND fechaOperacion = '2020-06-28'))), 0.00,
(SELECT FORMAT(ROUND(SUM(importe),2),2) FROM datos_cbr WHERE (numeroServicio = servicio AND fechaOperacion = '2020-06-28'))) AS Importe,
IF((SELECT sum(importeMas) FROM ajustes WHERE (numeroServicio = ajustes.servicio) <> 0.00 AND fechaOperacion = '2020-06-28'),
(SELECT ROUND(SUM(importeMas),2) FROM ajustes WHERE (numeroServicio = ajustes.servicio AND fechaAjuste = '2020-06-28')),0.00) AS 'Importe(+)',
IF((SELECT sum(importeMenos) FROM ajustes WHERE (numeroServicio = ajustes.servicio) <> 0.00 AND fechaOperacion = '2020-06-28'),
(SELECT ROUND(SUM(importeMenos),2) FROM ajustes WHERE (numeroServicio = ajustes.servicio AND fechaAjuste = '2020-06-28')),0.00) AS 'Importe(-)',

IF(ISNULL(
(SELECT FORMAT(ROUND(SUM(importe),2),2) FROM datos_cbr WHERE (numeroServicio = servicio AND importe BETWEEN 0000.01 AND 2000.00 AND fechaOperacion = '2020-06-28'))), 0.00,
(SELECT FORMAT(ROUND(SUM(importe),2),2) FROM datos_cbr WHERE (numeroServicio = servicio AND importe BETWEEN 0000.01 AND 2000.00 AND fechaOperacion = '2020-06-28'))) AS '1 a 2,000' ,
 IF(ISNULL(
(SELECT FORMAT(ROUND(SUM(importe),2),2) FROM datos_cbr WHERE (numeroServicio = servicio AND importe BETWEEN 2000.01 AND 3000.00 AND fechaOperacion = '2020-06-28'))), 0.00,
(SELECT FORMAT(ROUND(SUM(importe),2),2) FROM datos_cbr WHERE (numeroServicio = servicio AND importe BETWEEN 2000.01 AND 3000.00 AND fechaOperacion = '2020-06-28'))) AS '2,001 a 3,000' ,
 IF(ISNULL(
(SELECT FORMAT(ROUND(SUM(importe),2),2) FROM datos_cbr WHERE (numeroServicio = servicio AND importe BETWEEN 3000.01 AND 4000.00 AND fechaOperacion = '2020-06-28'))), 0.00,
(SELECT FORMAT(ROUND(SUM(importe),2),2) FROM datos_cbr WHERE (numeroServicio = servicio AND importe BETWEEN 3000.01 AND 4000.00 AND fechaOperacion = '2020-06-28'))) AS '3,001 a 4,000' ,
IF(ISNULL(
(SELECT FORMAT(ROUND(SUM(importe),2),2) FROM datos_cbr WHERE (numeroServicio = servicio AND importe BETWEEN 4000.01 AND 5000.00 AND fechaOperacion = '2020-06-28'))), 0.00,
(SELECT FORMAT(ROUND(SUM(importe),2),2) FROM datos_cbr WHERE (numeroServicio = servicio AND importe BETWEEN 4000.01 AND 5000.00 AND fechaOperacion = '2020-06-28'))) AS '4,001 a 5,000' ,
IF(ISNULL(
(SELECT FORMAT(ROUND(SUM(importe),2),2) FROM datos_cbr WHERE (numeroServicio = servicio AND importe BETWEEN 5000.01 AND 7500.00 AND fechaOperacion = '2020-06-28'))), 0.00,
(SELECT FORMAT(ROUND(SUM(importe),2),2) FROM datos_cbr WHERE (numeroServicio = servicio AND importe BETWEEN 5000.01 AND 7500.00 AND fechaOperacion = '2020-06-28'))) AS '5,001 a 7,500' ,
IF(ISNULL(
(SELECT FORMAT(ROUND(SUM(importe),2),2) FROM datos_cbr WHERE (numeroServicio = servicio AND importe BETWEEN 7500.01 AND 10000.00 AND fechaOperacion = '2020-06-28'))), 0.00,
(SELECT FORMAT(ROUND(SUM(importe),2),2) FROM datos_cbr WHERE (numeroServicio = servicio AND importe BETWEEN 7500.01 AND 10000.00 AND fechaOperacion = '2020-06-28'))) AS '7,501 a 10,000' ,
IF(ISNULL(
(SELECT FORMAT(ROUND(SUM(importe),2),2) FROM datos_cbr WHERE (numeroServicio = servicio AND importe BETWEEN 10000.01 AND 15000.00 AND fechaOperacion = '2020-06-28'))), 0.00,
(SELECT FORMAT(ROUND(SUM(importe),2),2) FROM datos_cbr WHERE (numeroServicio = servicio AND importe BETWEEN 10000.01 AND 15000.00 AND fechaOperacion = '2020-06-28'))) AS '10,001 a 15,000' ,
IF(ISNULL(
(SELECT FORMAT(ROUND(SUM(importe),2),2) FROM datos_cbr WHERE (numeroServicio = servicio AND importe > 15000.01 AND fechaOperacion = '2020-06-28'))), 0.00,
(SELECT FORMAT(ROUND(SUM(importe),2),2) FROM datos_cbr WHERE (numeroServicio = servicio AND importe > 15000.01 AND fechaOperacion = '2020-06-28'))) AS 'Mayor a 15,000',

FORMAT((SELECT ROUND(SUM(importe),2) FROM datos_cbr WHERE (numeroServicio = servicio AND fechaOperacion = '2020-06-28'))

+IF((SELECT SUM(importeMas) FROM ajustes WHERE (numeroServicio = ajustes.servicio) <> 0.00 AND fechaAjuste = '2020-06-28'),
(SELECT ROUND(SUM(importeMas),2) FROM ajustes WHERE (numeroServicio = ajustes.servicio)AND fechaAjuste = '2020-06-28'), 0.00)
-IF((SELECT SUM(importeMenos) FROM ajustes WHERE (numeroServicio = ajustes.servicio) <> 0.00 AND fechaAjuste = '2020-06-28'),
(SELECT ROUND(SUM(importeMenos),2) FROM ajustes WHERE (numeroServicio = ajustes.servicio)AND fechaAjuste = '2020-06-28'), 0.00),2) AS 'Importe Total'
FROM datos_cbr INNER JOIN servicios WHERE numeroServicio = datos_cbr.servicio AND fechaOperacion = '2020-06-28' or numeroServicio = ANY (SELECT servicio FROM ajustes WHERE importeMas > 0 OR importeMenos > 0)
GROUP BY servicio ORDER BY tipoComision, numeroServicio;

A: en la parte donde tienes:
FROM datos_cbr INNER JOIN servicios WHERE numeroServicio = datos
usa LEFT JOIN
el LEFT JOIN indica que tendrás todos los datos del lado izquierdo del JOIN a pesar de no tener una contraparte al lado derecho.
Recuerda que al tener un LEFT JOIN, debes especificar sobre que columnas se hace el  JOIN, p.e.
FROM datos_cbr LEFT JOIN servicios ON datos_cbr.columna1 = servicios.columna2


Q: Disable Chrome "plugin not responding" message It is quite annoying that this pop-up window appears every time I debug my GWT code using GWT dev-mode and Chrome's GWT Development plugin. Any ideas how to turn it off?

A: chromium-browser --disable-hang-monitor


Q: using File().byLine() with fold() I am trying to use the fold operation on a range returned by byLine().  I want the lambda which is passed to fold to be a multi-line function.  I have searched google and read the documentation, but cannot find a description as to what the signature of the function should be.  I surmize that one of the pair is the accumulated sum and one is the current element.  This is what I have but it will not build

    auto sum = File( fileName, "r" )
        .byLine
        .fold!( (a, b)
        {
            auto len = b.length;
            return a + len;
        });

The error I get back from dmd is:
main.d(22): Error: no property `fold` for `(File(null, null)).this(fileName, "r").byLine(Flag.no, '\n')` of type `std.stdio.File.ByLineImpl!(char, char)`

So my question is two fold:

*

*Is my use of fold in this case valid?

*How do I pass a curley brace lambda to fold?

I have tried searching google and reading the dlang documentation for fold.  All documentation uses the shortcut lambda syntax (a, b) => a + b.

A: So the way fold works is that it accepts a list of function aliases on how to fold the next element in. if you don't provide it with a starting value, it uses the first element as the starting value. Quoting the documentation (emphasis mine):

The call fold!(fun)(range, seed) first assigns seed to an internal
variable result, also called the accumulator. Then, for each element
x in range,  result = fun(result, x) gets evaluated. Finally, result
is returned. The  one-argument version fold!(fun)(range) works
similarly, but it uses the  first element of the range as the seed
(the range must be non-empty).

The reason why your original code didn't work is because you can't add an integer to a string (the seed was the first line of the file).
The reason why your latest version works (although only on 32-bit machines, since you can't reassign a size_t to an int on 64-bit machines) is because you gave it a starting value of 0 to seed the fold. So that is the correct mechanism to use for your use case.
The documentation is a bit odd, because the function is actually not an eponymous template, so it has two parts to the documentation -- one for the template, and one for the fold function. The fold function doc lists the runtime parameters that are accepted by fold, in this case, the input range and the seed. The documentation link for it is here: https://dlang.org/phobos/std_algorithm_iteration.html#.fold.fold

A: I was able to tweak the answer provied by Akshay.  The following compiled and ran:
module example;

import std.stdio;
import std.algorithm.iteration : fold;

void main() {
    string fileName = "test1.txt";
    auto sum = File(fileName, "r")
        .byLine
        .fold!( (a, b) {
            // You can define the lambda function using the `{}` syntax
            auto len = b.length;
            return a + len;
        })(0); // Initialize the fold with a value of 0
}


Q: Typescript is slower than javascript when using sequelize? I am migrating a web app from javascript to typescript. And I have noticed that the query results are a bit slower sometimes as compared to javascript. It is not consistent though.
I have two tables - User and Team. One user can have many teams. So it is hasMany and belongsTo association between them.
Team Model
import {Model, Table, Column, Default} from 'sequelize-typescript';
@Table
export class Team extends Model {

  @Column name!: string;
  @Default(true)
  @Column isActive!: boolean;
}

User Model
import {Model, Table, Column, Default,DataType} from 'sequelize-typescript';

@Table
export class User extends Model {

  @Column firstName!: string;
  @Column lastName!: string;
  @Column email!: string;
  @Default(true)
  @Column isActivated!: boolean;
  @Column source!: string;
  @Column(DataType.JSON)
  profileData: string;
  @Column(DataType.JSON)
  settings: string;
  @Column(DataType.JSON)
  paymentDetails: string;
}

The association
Team.belongsTo(User, { foreignKey: "fk_ownerId", as: 'Owner' });
User.hasMany(Team, { foreignKey: "fk_ownerId", as: 'OwnedTeams' });

Here are my results
30k records

typescript
user ins query: 2.955s
user query: 2.134s

javascript
user ins query: 3.785s
user query: 1.947s

50k records

typescript
team ins query: 4.621s
team query: 2.601s

javascript
team ins query: 4.352s
team query: 2.340s

tsconfig.json
{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "sourceMap": true,
        "strictNullChecks": false,
        "noUnusedLocals": true,
        "pretty": true,
        "skipLibCheck": true,
        "lib": [
            "es2015"
        ]
    }
}

I am running tsc --build to generate the build.
Is there anything that I have been doing wrong ?


Q: Tikz fit library: fitting only one dimension and accumulating calls The fit library is very useful for adjusting the size of a node to fit other nodes inside it.
It is also useful in conjunction with shift to make a node span to the width/height of other nodes but saty beside them.
I feel this is a common enough situation to justify dedicated keys.
From the code defining the fit key, all four anchors north, south, west and east are always considered for fitting. This does make sense for genereal fitting but in some cases it would be useful to fit only in one dimension.
This could be easily achieved by defining something like a fit width key considering only east and west anchors in its calculations.
Here's the question: is it possible to emulate this without duplicating the fit definition and with minimal hassle?
Additionally: if you use fit twice in a row, the second overrides the first; it would be great to provide an also fit key setting the max of the current size and the one fitting the given nodes.
This question is related but the answers avoid the use of the fit library.

A: I have a working workaround for the also fit key which I share here for reference.
\documentclass[tikz]{standalone}
\usetikzlibrary{fit}
\pgfmathsetseed{200}
\begin{document}
\makeatletter
\begin{tikzpicture}[
     nodes to fit/.initial={},
     fit/.append style={nodes to fit=#1},
     also fit/.style={
         nodes to fit/.append={#1},
     },
     fit now/.code={
        \xdef\@fitting@nodes{\pgfkeysvalueof{/tikz/nodes to fit}}
        \ifx\@fitting@nodes\@empty
             %%% do nothing
        \else
            \tikzset{fit={\@fitting@nodes}}
        \fi
     }
 ]
\foreach \i in {1,...,5}{
    \node[draw] (n\i) at (2*rand,3*rand) {\i};
 }

\node[draw=green, thick, fit={(n4) (n3)}] {};
\node[draw=red, thick, fit={(n1)}, also fit={(n4)}, also fit={(n2) (n3)}, fit now] {};
\node[draw=blue,also fit=(n1),also fit=(n2), fit now] {};
\end{tikzpicture}
\makeatother
\end{document}

The idea is simple: use an auxiliary key nodes to fit accumulating the list of coordinates/nodes to fit, the fit key will also set it, the also fit will add to it.
To make the additions effective you'll need to add a fit now key after the also fit and fit keys`.
The normal behaviour of fit is otherwise unaffected.
It would still be good to have these features implemented in the main library, see the relevant feature request.


Q: Standards or best practices for the content of RESTful requests and responses We may need to provide a RESTful web service interface to our application.
THe RESTFul architecture provides some guiding principles for some parts of the interface but leaves others entirely open - in particular, it doesn't seem to say anything about the format of the data transferred in a request or response.
While this is very open and flexible for implementers, we do need to make a choice!
So this question is to ask if there are any emerging standards for the way RESTful web services are implemented - e..g JSON or XML for the payload? Specified by XML schemas or something else?
If no emerging standards, are there guidelines and best practices for how to make these kinds of choices?
In our case, we're pretty free to choose what works best for our application - we are not (yet) constrained by what the systems that will be invoking these web services can handle.


Q: Реализация аутентификации на микросервисной архитектуре Пишу приложение на микросервисах и столкнулся с одной проблемой, а именно аутентификацией пользователей. Бэк на ноде, фронт на реакте + nginx, для общения с сервисами использую брокер NATS. Немного поразмыслив придумал только один способ реализации аутентификации, а именно использовать JWT, хранить его в куки пользователя, а с фронта слать его в заголовках вместе с ключом API, а в гейтвее проверять его наличие. Но тут выливается еще одна проблема, как правильней реализовать его валидацию, делать под это отдельный сервис, где будет валидация, выдача и рефреш, или же написать это все в сервисе авторизации. Есть может кто сталкивался с аутентификацией на микросервисах, есть какие еще варианты решения проблемы? Заранее спасибо.


Q: Converting to a dropdown menu firstly apologies, as I have seen this question asked before, but I'm still none the wiser, so going to have to ask it myself.
I am very new to html5 and css3, so far I have managed to get by, until now.
I would like to convert one of the options in my navigation menu to a drop down menu, I have tried many times using info from here and other sites, but I'm still having problems.
Here is my css for the Nav menu..
    /* Site Nav */

    #site-nav
{
    position: absolute;
    top: 0;
    right: 50px;
    font-family: 'Open Sans Condensed', sans-serif;
    text-align: right;
}

    #site-nav ul
    {
        list-style: none;
        overflow: hidden;
    }

        #site-nav ul li
        {
            display: block;
            float: left;
            text-decoration: none;
            font-size: 1.2em;
            height: 90px;
            line-height: 110px;
            margin: 0 0 0 1.75em;
        }

            #site-nav ul li a
            {
                color: #000;
                text-decoration: none;
                outline: 0;
            }

            #site-nav ul li a:hover
            {
                color: #fff;
            }

        #site-nav ul li.current_page_item
        {
            background: url('images/nav-arrow.png') center 77px no-repeat;
        }

            #site-nav ul li.current_page_item a
            {
                color: #662d91;
            }

and here is the html for my menu...

Homepage

About Us

Products

Bullion

Contact Us

If this can be done with just HTML5 and CSS3 then that is great, but I'm happy to go down the JavaScript route if needs be.
Thanks in advance for any help, it will be very much appreciated.
EDIT 21/03/2013...
I have tried to implement the code given to me below, and this fiddle shows how far i have got, http://jsfiddle.net/2rgSP/1/
With 2 problems, firstly, links are pushed off edge of website, 2, the drop down menu falls behind the main wrapper.
There is clearly some conflicting css going on, but i am a complete beginner at this, so I'm clueless I'm afraid.
Hopefully someone can see where I am going wrong.
Thanks
Lee

A: Below is what you could use, if javsscript/jquery is an option:

Home

Home1

Home4

Home2

Home3

Home5

About

About1

About2

About

About3

About5

Contact

Contact1

Contact2

Contact3

Contact4

Contact5

Links

Links1

Links2

Links3

Links4

Links5

CSS
body{
    padding:0px;
    margin:0px;
}
ul li{
    list-style-type:none;
}
#cssdropdown{
    padding:0px;
    margin:0px;
}
a{
    text-decoration:none;
    padding:0px;
    margin:0px;}
.headLink{
    display: inline-block;
    padding:10px;
    margin:10px;
    text-align:right;
    background-color:#999999;
    cursor:pointer;
}
.headLink ul{
    display:none;
    position: absolute;
    margin:10px 0 0 -13px;
    padding:0 10px;
    text-align:left;
    background-color:#CCC;
    cursor:pointer;
}

JS:
$(function() {
    $(".headLink").hover(function() {
        $('ul',this).slideToggle();
    });

    });

DEMO


Q: How to insert an "apply" button in WordPress I am building a job website and I am trying to insert an 'apply' button in a custom post-type single page (called 'vacancy') within WordPress.
I need this button to notify the admin of the new 'application' = meaning someone logged in clicked on the button.
I have thought about using the comment_form() function but I am not sure how to adapt it to register the "button" click. It doesn't show anything at all in fact.
I have got the following code inside the WP_Query( $mypost ) while( have_posts() ) : the_post(); loop:
if ( comments_open() || get_comments_number() ) :
    if ( post_password_required() ) {
    return;
    }
    comment_form( array(
        'comment_field' =>  '',
        'label_submit'  =>  __( 'Apply' ),
        'comment_notes_after'   => ''
    ),
    $mypost
    );
endif;

I don't want to affect the general comments as I may need them for the normal posts and pages, and preferably if I can separate it from the comments and instead have something else - but I can't think of another way to do it.
Thanks in advance! Really do appreciate any suggestions/help.


Q: awk: automatically call functions from file I need to perform the absolute value calculation a lot in awk.
But absolute value is not built into awk, so many of my awk commands look like this:
awk  'function abs(x){return ((x < 0.0) ? -x : x)}  { ...calls to "abs" .... }'  file

Is there a way to store user-defined awk functions in files, and have awk automatically load these functions whenever it is called?
Something like setting an awk "include" path or user-profile, much the same way you do for bash and other programs.

A: You can use @include "file" to import files.
e.g. Create a file named func_lib:
function abs(x){
    return ((x < 0.0) ? -x : x)
}

Then include it with awk:
awk '@include "func_lib"; { ...calls to "abs" .... }'  file

A: Also try
$ cat function_lib.awk
  function abs(x){
      return ((x < 0.0) ? -x : x)
 }

call function like this
$ awk -f function_lib.awk --source 'BEGIN{ print abs(-1)}'


Q: how to add listener to java dock icon on osx i have in my applications jframe Hide on close, but when i click the dock icon, i want it
to setVisible(true);
how do i add an action listener to the dock icon?
i tried
Image im = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("SLogo.png"));
final TrayIcon tri = new TrayIcon(im);
tri.addActionListener(this);

@Override
public void actionPerformed(ActionEvent ae) {
     this.setVisible(true);
     System.out.print("ok");

}

but its not triggered,
and also, how will it affect the app on windows machine?

A: You need to use an AppForegroundListener and/or AppReOpenedListener.  See this example:
public static void main(String[] args)
{
    final JFrame frame = new JFrame();

    Application app = Application.getApplication();
    app.addAppEventListener(new AppForegroundListener() {

        @Override
        public void appMovedToBackground(AppForegroundEvent arg0)
        {
            System.out.println("appMovedToBackground");
        }

        @Override
        public void appRaisedToForeground(AppForegroundEvent arg0)
        {
            System.out.println("appRaisedToForeground");
            frame.setVisible(true);
        }

    });

    app.addAppEventListener(new AppReOpenedListener() {
        @Override
        public void appReOpened(AppReOpenedEvent arg0)
        {
            System.out.println("app reoponed");
            frame.setVisible(true);
        }
    });

    frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    frame.setSize(200, 200);
    frame.setVisible(true);
}

If you develop on Windows, you'll need to include stubs of the Mac/Java classes or else you'll get compiler errors.  See here.
If you develop on Mac, just make sure the code is not executed when running on Windows.


Q: Javascript click element by X Y not working Hey guys I am working on a script to help me out on soundcloud. On soundcloud, each track has a waveform that you can click on to skip to certain parts of the track. I want to simulate a mouse click on the waveform of a song but I need some help.
I need to be able to click at varying parts of the waveform, not simply on the element's position.
I wrote the following code to find the coordinates of the waveform (just execute it in address bar while on any track):
(function(){ alert(document.getElementsByClassName('g-box-full sceneLayer')[0].getBoundingClientRect().top); })();

For me the coordinates are 678, 296.
If I wanted to, for example, click a few seconds into the track I though I would be able to do:
(function(){ document.elementFromPoint(750, 310).click(); })();

However, this doesn't seem to work. Nothing happens. I want to be able to execute the javascript from the address bar via javascript: <code here>
Any help would be appreciated, thanks!


Q: How to push out many mails efficiently using an MTA I'm writing an email notification system that needs to send many hundreds of emails at once. The system needs to be deployed on various setups with different MTAs. Depending on the configuration, some MTAs seem to receive an email from an application and queue it as fast as possible; others will hold the sender application while processing (sending?) the message – this would cause the application to block for extended periods of time.
Would it be reasonable to expect MTAs on production machines with modern software to queue mail quickly (or be configured to do so)?

A: Unfortunately, it depends.  If you need to work with a variety of different MTAs, then you're going to have to do things like load average detection (if the load average rises above a certain number, then throttle delivery), and probably also do your own domain aggregation to reduce the number of delivery attempts required.

A: If you ever go above a few hundred at any given moment, something like http://www.port25.com/products/prod_index.html will handle this really well for you.  It has DNS caching and can control how many connections it makes to a remote server, both of these are key to getting emails to their recipients properly.  I've managed 320K / hour on a 5 year old server with this piece of software.


Q: Flipped box with tcolorbox In the second box I tried to imitate the layout of the first box but with the title down. Obviously, the result is not correct. In fact, the result that I foresee is in the third box; but I do not know how to implement it using the tcolorbox features.
\documentclass{beamer}
\usepackage{lmodern}

\usepackage{tikz}

\usepackage[most]{tcolorbox}
\tcbuselibrary{skins}
\usetikzlibrary{patterns}
\usetikzlibrary{decorations.shapes}
\usetikzlibrary{decorations.pathmorphing}

\tcbset{%
    myboxmainstyle/.style={%
        enhanced,
        segmentation style={solid,line width=1pt,decorate,decoration={zigzag}},
        center title,
        halign=flush center,
        boxrule=1pt,
        arc is angular, arc=3pt,
    }
}

\newtcolorbox{mybox}[2][]{%
    adjusted title={#2},
    myboxmainstyle,
    #1,
}

\usepackage{environ}

\newcommand\myrotateboxgrap[1]{\reflectbox{\rotatebox[origin=c]{180}{#1}}}
\newcommand\myrotateboxtikz[1]{\tikz[baseline=(box.north)]\node[yscale=-1,inner sep=0,outer sep=0](box){#1};}

\NewEnviron{myboxflipped}[2][]{%
    %\myrotateboxgrap{\begin{mybox}[#1]{\myrotateboxgrap{#2}}\myrotateboxgrap{\BODY}\end{mybox}}
    \myrotateboxtikz{\begin{mybox}[#1]{\myrotateboxtikz{#2}}\myrotateboxtikz{\BODY}\end{mybox}}
}

\begin{document}

\begin{frame}
    \begin{mybox}[]{Test}
        bla bla
    \end{mybox}
    \begin{mybox}[attach boxed title to bottom center={yshift=0.25mm+\tcboxedtitleheight/2,yshifttext=-2mm+\tcboxedtitleheight/2}]{Test}
        bla bla
    \end{mybox}
    \begin{myboxflipped}[colback=pink]{Test}
        bla bla
    \end{myboxflipped}
\end{frame}

\end{document}

A: The tcolorbox manual has an example flipbox which does precisely this flipping of the box and title (See page 161 as of version 4.15).
The crucial point is minipage boxed title* which expands the boxed title the width of outer tcolorbox.
\documentclass{beamer}
\usepackage{lmodern}

\usepackage{tikz}

\usepackage[most]{tcolorbox}
\tcbuselibrary{skins}
\usetikzlibrary{patterns}
\usetikzlibrary{decorations.shapes}
\usetikzlibrary{decorations.pathmorphing}

\tcbset{%
    myboxmainstyle/.style={%
      enhanced,
      segmentation style={solid,line width=1pt,decorate,decoration={zigzag}},
      center title,
      halign=flush center,
      boxrule=1pt,
      arc is angular, arc=3pt,
    }
}

\newtcolorbox{mybox}[2][]{
  enhanced,
  sharp corners=south,
  myboxmainstyle,
  attach boxed title to bottom center={yshift=0.5mm},
  minipage boxed title*,
  boxed title style={enhanced,
    size=normal,
    top=0pt,
    bottom=0pt,
    %interior hidden,
    sharp corners=north,
    boxrule=1pt,
    colback=red,
    arc is angular, arc=3pt},
  title={#2},#1
}

\begin{document}

\begin{frame}
    \begin{mybox}[]{Test}
        bla bla
    \end{mybox}
    \begin{mybox}[colback={yellow},coltitle=black,colbacktitle=red]{Another Test}
        bla bla
    \end{mybox}

\end{frame}

\end{document}

Edit
\documentclass{beamer}
\usepackage{lmodern}

\usepackage{tikz}

\usepackage[most]{tcolorbox}
\tcbuselibrary{skins}
\usetikzlibrary{patterns}
\usetikzlibrary{decorations.shapes}
\usetikzlibrary{decorations.pathmorphing}

\tcbset{%
    myboxmainstyle/.style={%
      enhanced,
      segmentation style={solid,line width=1pt,decorate,decoration={zigzag}},
      center title,
      halign=flush center,
      boxrule=1pt,
      arc is angular, arc=3pt,
    }
}

\newtcolorbox{mybox}[2][]{
  enhanced,
  sharp corners=south,
  myboxmainstyle,
  attach boxed title to bottom center={yshift=0.5mm},
  minipage boxed title*,
  boxed title style={enhanced,
    size=normal,
    top=0pt,
    bottom=0pt,
    center title,
    sharp corners=north,
    boxrule=1pt,
    arc is angular, arc=3pt},
  title={{\centering #2}},#1
}

\begin{document}

\begin{frame}
    \begin{mybox}[]{Test}
        bla bla
    \end{mybox}
    \begin{mybox}[colback={yellow},coltitle=black,colbacktitle=red]{Another Test}
        bla bla
    \end{mybox}

\end{frame}

\end{document}


Q: Search form in two Regions? New to Drupal, trying to wrap my mind around the Blocks concept.
Am I right in concluding that I cannot have the SearchForm on the right side (sidebar second) for one ContentType, and on the left side (sidebar first) for another ContentType?
I'm talking standard 7(.17) with no extra modules or PHP "hacks".

A: Standard Drupal will only allow you to specify the placement of blocks once. To achieve what you're after you'll need to look into using a contributed module like Context or Panels.
Personally used Context a fair bit in the past. It's pretty powerful but relatively simple to use.

A: This module allows you to create several instances of a block, so you can duplicate a block and put the duplicates on other regions.


Q: CDK pipelines with several application repositories I have successful setup a pipeline for my application with CDK Pipelines construct that was introduced this summer. The application is a microservice (UserService) compiled with CodeBuild and creates a ECS Fargate service. The source of the application is in a GitHub repository.
The project stored in GitHub repository is like this:
.
+-- cdk
+-- Dockerfile_OrderService
+-- Dockerfile_ProductService
+-- Dockerfile_UserService
+-- OrderService
+-- ProductService
+-- UserService

OrderService, ProductService and UserService are folders containing source code of the microservices that needs to be compiled with CodeBuild. I have only implemented UserService so far, and that works fine. When I push a change from the UserService folder, the pipeline is triggered, and the source code are built with CodeBuild, and the service is deployed to ECS Fargate.
When I set up a pipeline for the other two services, a push from any of the services folders will trigger CodePipeline for all three services. I don't want that, I want the pipeline for the specific service is triggered, not the other two, but I am not sure how to do that.
I was thinking about each service to have it's own repository, but I also need the infrastructure code under cdk to be present.
Do anyone have an example of how to do this?

A: My team uses a monorepo with different cdk-pipelines for each product/service that we offer. It does trigger each pipeline when we push to the develop branch, but if there are no changes in 'ProductService' or 'OrderService' then technically I don't think there's no harm letting it update all of them.
But if you do want separate triggers, you would have to use separate branches that trigger each microservice. You are allowed to specify a branch for 'GitHubSourceActionProps.Branch'. For example, the pipeline construct for 'UserService' could look like this: (C#)
        var pipeline = new Amazon.CDK.Pipelines.CdkPipeline(this, "My-Cdk-Pipeline", new CdkPipelineProps()
        {
            SourceAction = new GitHubSourceAction(new GitHubSourceActionProps()
            {
                ActionName = "GitHubSourceAction",
                Branch = user-service,
                Repo = "my-cool-repo",
                Trigger = GitHubTrigger.WEBHOOK,
            }),
        };

aws cdk api reference githubsourceactionprops


Q: Authorization issue with python request I am trying to authenticate users and I am getting invalid
{'error': 'invalid_request'}
bellow is my code
I am following the guide on https://developer.sonos.com/build/direct-control/authorize/
import base64
import requests

        client_secret = "*******************************"
        client_id = "*******************************"

        combine_id = f'{client_id}:{client_secret}'

        base64_id = base64.b64encode(combine_id.encode("ascii"))
        base64_id = base64_id.decode("UTF-8")

        code = request.data["code"]
        state = request.data["state"]

        headers = {
            'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
            'Authorization': f'Basic {base64_id}',
        }

        data = {
            'grant_type': 'authorization_code',
            'code': code,
            'redirect_uri': 'http://localhost:8000/sonos'
        }

        response = requests.post(
            'https://api.sonos.com/login/v3/oauth/access', headers=headers, data=data)

        print("response : ", response.json())


Q: Problema ao executar jar compactado manualmente Eu estava estudando como compilar java direto pelo javac e tudo mais. Depois juntei todos os arquivos em um zip e renomeei para .jar .
Não funcionou primeiramente devido a falta do Manifest - não 'achava a classe principal'
Mas mesmo se eu entrasse diretamente usando -cp o erro persiste.
Quando adicionei o manifest surgio a mensagen : Invalid or corrupted jarfile
Tive uma hipótese de que um jar não seria exatamente um zip, mas mesmo eu extraindo um jar(funcional) e compactando novamente, nada de errado acontece.
Qual erro cometi então?

A: Para gerar um .jar você não pode apenas compactá-lo. Você deve compilar o seu código-fonte (.java) para que seja gerado um bytecode (.class). O JVM interpreta apenas esse tipo de arquivo.
Segue o link de um material sobre esse assunto => http://www.devmedia.com.br/etapas-do-desenvolvimento-e-execucao-de-uma-aplicacao-java/25099
O que você poderia fazer é usar o javac para gerar os arquivos .class (bytecodes) e depois compactá-los usando o Winrar. Junto com os arquivos compactados, você deverá incluir o manifest com o caminho da classe principal(a clase que possui o método public static void mamin(String args))


Q: User-Agents are removed by Chinese mobile networks? Kindly confirm the information below.
a. Chinese mobile networks are blocking the useragent strings.
b. The user-agent send to the server are in different encoding for Chinese mobiles.
Please let me know whether a or b is true and also pour in your experiences on the identifying the user agents in Chinese mobiles.
Everywhere the term Chinese mobile means a mobile in China with Chinese mobile network.
Thanks in advance.
[changed]

A: I just tested this with my mobile phone. The user agent that is received by remote servers is both the same when I connect via WLAN and via GPRS (my SIM card is issued by China Mobile). There doesn't seem to be any filtering of user agents.
Specifically, my browser's user agent string is:
Mozilla/5.0 (webOS/2.1.0; U; en-GB) AppleWebKit/532.2 (KHTML, like Gecko) Version/1.0 Safari/532.2 Pre/1.1
I'd say that neither a nor b is true.


Q: Accumulation of a series of payments A loan is repayable by eight annual payments, starting in one year's time with an interest rate $i$. Payments one to three are half as much as payments four to eight. What is the accumulated value of payments one year before the end of the eight annual payments.
What I thought it would be:
Let $X$ be the payment per year. From year 1 to 3 we pay $X$ Annually, and $2X$ From year 3 to 7, so the accumulated value is $$X + X(1+i) + X(1+i)^2 + 2X(1+i)^3 + 2X(1+i)^4 + 2X(1+i)^5 + 2X(1+i)^6$$, but the correct answer is in fact:
$$2X + 2X(1+i) + 2X(1+i)^2 + 2X(1+i)^3 + X(1+i)^4 + X(1+i)^5 + X(1+i)^6$$
Could someone explain the logic behind this?

A: You have the correct value of the payments, but it looks like your interest factors are a bit off. The first payment of $X$ takes place in one year. It will sit in the account for six years (since the accumulation takes place one year before the loan is paid off). This gives you that the first payment will accumulate to
\begin{equation*}
X(1+i)^6
\end{equation*}
The next two payments will follow suit, but they will each have a reduced exponent. The accumulated values of those payments are
\begin{align*}
X(1+i)^5\\
X(1+i)^4
\end{align*}
respectively.
The remaining payments are all $2X$, and they grow $3$, $2$, $1$, and $0$ years. This gives us the values
\begin{align*}
2X&(1+i)^3\\
2X&(1+i)^2\\
2X&(1+i)\\
2X&
\end{align*}
Summing the seven values I listed gives you the desired response.
\begin{equation*}
2X+2X(1+i)+2X(1+i)^2+2X(1+i)^3+X(1+i)^4+X(1+i)^5+X(1+i)^6
\end{equation*}
Although, I prefer your order:
\begin{equation*}
X(1+i)^6+X(1+i)^5+X(1+i)^4+2X(1+i)^3+2X(1+i)^2+2X(1+i)+2X
\end{equation*}


Q: How to include a jar file into Scala code This is the Scala code that I have written
object Main extends App {
    println("Hello World from Scala!")
}

This is my build file
name := "hello-world"

version := "1.0"

scalaVersion := "2.11.5"

mainClass := Some("Main")

This is command that I am using to create the jar file
java -cp "scala-library.jar:target/scala-2.11/hello-world_2.11-1.0.jar" Main
Problem: I want to include the scala-library.jar in my hello-world jar file so that I don't have to reference it in the command line. Is it possible?

A: The way I use it is add all the external jar to the "lib" folder and use "sbt assembly" to create one fat jar.

A: i suggest you bundle the jar file into your applications jar file. you can use jar command for packaging or any such utility offered by the IDE as well.


Q: Making installer but used SDKs "Classes not registered" We are trying to make an installer for our application and are using Advanced Installer.
When i add all the files from the release folder of our application and let it install. The application crashes and says that some classes are not registered. I know this is comming from some of the SDKs we are using that uses ActiveX objects. Do i have to add these SDK installers to the Prerequisites or is there another way to register these classes?


Q: Run docker with volume mapping from another docker container I have a Jenkins instance running in a Docker container which can also run docker commands of the host.
The build process of my apps includes running bower and grunt. But to avoid having to install node on the Jenkins container, I wish to run a seperate node-container to perform the node-specific commands.
ie. this works if I run this locally on my machine:
    docker run -it -v $(pwd):/usr/src/app 3bdigital/bower-grunt-gulp bower install
I basically mount my project folder to the app folder and the container will run bower install in that folder.
Unfortunately this doesn't seem to work if I run this command from inside the Jenkins container. The docker container runs, but the volume is not being mounted properly.
Is there a way to do this ? Or do I have to install Node in my Jenkins image ?
Another solution is to install node in the image of the app itself and have that docker image do the necessary build steps. The downside is that this image will be much larger than necessary (the node_modules, bower_components, source, ... folders are not needed in production)


Q: using apply function write multiple append statement Is it possible to write below code using apply function or any other, because iterrows seems not feasible here.
For creating Dataframe:
df = [[['55792', 'TRIM'], 'A', ['55792', 'TRIM']], [['ZQFC', 'DYWH'], 'A', ['MEIL', '1724']]]
df = pd.DataFrame(df, columns=['seg','cod','seg2'])
df

seg            cod  seg2
[55792, TRIM]   A   [55792, TRIM]
[ZQFC, DYWH]    A   [MEIL, 1724]

#output
seg            cod  seg2
[55792, TRIM]   A   [55792, TRIM]
[ZQFC, DYWH]    A   [MEIL, 1724]
[MEIL, 1724]    A   [MEIL, 1724]

So, I am expanding the rows if the seg column and seg2 column doesn't matches. It there any better way to do that using apply.
Code I have used:
df1 = pd.DataFrame(columns=df.columns)
for index, row in df.iterrows():
    #if seg match seg 2
    if(row['seg']==row['seg2'])==True:
        #append same row
        df1 = df1.append(row)
    else:
        #if not match, then we can create two seg, and append 2 row
        #append same row first
        df1 = df1.append(row)
        #changing existing segment to new segment, and append
        row['seg'] = row['seg2']
        df1 = df1.append(row)

Thanks a lot.

A: You don't need to use apply you can just use your conditionals as boolean masks and do your operations that way.
mask = df["seg"] == df["seg2"]

true_rows = df.loc[mask]
false_rows = df.loc[~mask]
changed_rows = false_rows.assign(seg=false_rows.seg2)

df1 = pd.concat([true_rows, false_rows, changed_rows], ignore_index=True)

print(df1)
             seg cod           seg2
0  [55792, TRIM]   A  [55792, TRIM]
1   [ZQFC, DYWH]   A   [MEIL, 1724]
2   [MEIL, 1724]   A   [MEIL, 1724]


Q: Handcoding PHP for daily log style website with mySQL database I only began learning about web development 3 weeks ago and have grasped html, css and js quite quickly and have also had some success in using php to draw values from a mySQL database that I have setup however I have a few questions if that is OK?
I am designing a website that essentially allows users to register and then login and add details to a daily log which is stored in the mySQL database. I also want a forum, content section and a shop. Obviously there is no standard open source package for this so I have been investigating how to handcode the PHP to log users in and have them logged in across all parts of the handcoded website. I initially thought I could do this using sessions but I have read that they are bad for SEO? I understand that you can disable them and use cookies but I fear this is all getting a bit over my head? Would it be easier to try and develop this in ASP.NET?
Apologies if some of this doesn't make sense but as I said I am very new to this but I am eager to learn and really serious about it so I will take any information given to me on board. Thanks for your time

A: This is all very possible in PHP, but what you are asking is for an explanation that requires a book. Speaking of books, there are tons of great books offering help with exactly what you need:
PHP 5 CMS Framework Development: Would teach you about many of the pieces you are trying to assemble by hand including MVC principles.
"Obviously there is no standard open source package.."
Just to name one, WordPress allows users to log in and add stuff to a daily log (it's called a blog), has content sections, and has forum and commerce plugins. Personally, I've been amazed at how customizable WordPress is!

A: I don't understand your comment about using cookies instead of sessions.  I recommend you use the PHP $_SESSION superglobal to keep users logged in during their session.
If you have super-sensitive data in these logs, one option might be to verify that the user's IP has not changed between requests.
I see no reason why ASP.net would be preferable.  Personally, I like to learn programming by opening up vim and going at it.
P.S. Be sure you are escaping data provided to you by users before writing it to your SQL database.


Q: Set status code on specific path in Nginx There's a particular route in our web app which we wish should always be served with a 404 status code. With Nginx, how do I return a specific route's content just as usual, but with a specific http status code, for example 404?


Q: Apache cant change listening port I am trying to install nginx as reverse frontend proxy to apache.
During this process I have to change the listening port for apache to e.g. 7070 instead of 80.
I went to the /etc/httpd/conf/httpd.conf and changed:
Listen 80

to
Listen 7070

I also added a virtualhost
NameVirtualHost *:7070
<VirtualHost *:7070>
//code
</VirtualHost>

at the end of it
However when i restart apache and nginx, nginx complains that port 80 is already in use and cannot be used
if i run
ss -plnt sport eq :80

i see lots of httpd processes/users.
What am i doing wrong, why is apache still on port 80?
If i do
sudo fuser -k 80/tcp

i can start nginx then, but then apache complains about the used port 80...
What am i doing wrong? :|
I am thankful for any help

A: You need a NameVirtualHost directive matching your virtualhosts somewhere in your config.
In your case, you'd need that, before the VirtualHosts declarations:
NameVirtualHost *:7070
As a matter of fact, you must have NameVirtualHost *:80 somewhere already, just change the port there too.


Q: DiscordAPIError: Unknown Interaction after making the /help command So I have this help command but I am getting an error saying "Unknown Interaction". I have been searching on the internet for quite a while now, but could not find a solution for this.
Here is the code:
const { Client, MessageEmbed } = require("discord.js");
const { readdirSync} = require("fs");

module.exports = {
    name: "help",
    aliases: ["h"],
    userPerms: ["SEND_MESSAGES"],
    clientPerms: ["SEND_MESSAGES", "EMBED_LINKS"],
    description: "Shows all available bot commands.",

    execute: async(interaction, args, client, message) => {
        const {user} = interaction;
        if(!args[0]){
            let categories = [];

            readdirSync("./Commands/").forEach((dir) => {
                const commands = readdirSync(`./Commands/${dir}/`).filter((file) => file.
                endsWith(".js"))

            const cmds = commands.map((command) => {
                let file = require(`../../Commands/${dir}/${command}`)
                if(!file.name) return "No command name.";

                let name = file.name.replace(".js", "");

                return `\`${name}\``;
            });

            let data = new Object();
            data = {
                name: dir.toUpperCase(),
                value: cmds.length === 0 ? "In progress." : cmds.join(" | "),
            };
            categories.push(data);
            })

            const embed = new MessageEmbed()
            .setTitle("Commands")
            .addFields(categories)
            .setDescription(`Use /help followed by a command name to get more additional information on a command. For example: /help afk`)
            .setFooter(`Requested by ${user.tag}`, user.displayAvatarURL({dynamic: true}))
            .setColor("RANDOM");
            return interaction.reply({emebds: [embed]})
        } else {
            const command = client.commands.get(args[0].toLowerCase()) || client.commands.find((c) => c.aliases && c.aliases.includes(args[0].toLowerCase()));

            if(!command){
                const embed = new MessageEmbed()
                .setTitle("Not Found")
                .setDescription("Command not found. Use /help for all commands available")
                .setColor("RANDOM");
                return interaction.reply({embeds: [embed]})
            }
            const embed = new MessageEmbed()
            .setTitle("Command Details")
            .addField("COMMAND:", command.name ? `\`${command.name}\`` : "No name for this command")
            .addField("ALIASES:", command.aliases ? `\`${command.aliases.join("` `")}\`` : "No aliases for this command.")
            .addField("USAGE:", command.usage ? `\`/${command.name} ${command.usage}\`` : `/\`${command.name}\``)
            .addField("DESCRIPTION", command.description ? command.description : "No description for this command.")
            .setFooter(`Requested by ${message.author.tag}`, message.author.displayAvatarURL({dnyamic: true}))
            .setColor("RANDOM");

            return interaction.reply({embeds: [embed]});
        }
    }
}

And this is the error I am getting after typing /help on discord
/Users/Aplex/Documents/Aplel/node_modules/discord.js/src/rest/RequestHandler.js:350
      throw new DiscordAPIError(data, res.status, request);
            ^

DiscordAPIError: Unknown interaction
    at RequestHandler.execute (/Users/Aplex/Documents/Aplel/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async RequestHandler.push (/Users/Aplex/Documents/Aplel/node_modules/discord.js/src/rest/RequestHandler.js:51:14)
    at async CommandInteraction.reply (/Users/Aplex/Documents/Aplel/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:99:5) {
  method: 'post',
  code: 10062,
  httpStatus: 404,
  requestData: {
    json: {
      type: 4,
      data: {
        content: undefined,
        tts: false,
        nonce: undefined,
        embeds: undefined,
        components: undefined,
        username: undefined,
        avatar_url: undefined,
        allowed_mentions: undefined,
        flags: undefined,
        message_reference: undefined,
        attachments: undefined,
        sticker_ids: undefined
      }
    },
    files: []
  }
}

Does anyone have an idea of where the issue exactly is and how to fix it? I would really appreciate it

A: This normally means that you took too long to respond to the Interaction. You can add an interaction.deferReply() to defer the reply.


Q: Can entities inside the aggregate be accessible or visible externally to the aggregate? I'm new to DDD and my question might seem trivial to many of you.
Consider the case of Student and Course.
The student can enroll the course only if the student's age is above the minimum age required to enroll that course.
From my point of view, Student and Course can be considered as aggregate where Student is the root entity, Course the child entity, and age the invariant to respect.
Student should have a method Student.SubscribeTo(Course course) and the method should enforce the invariant Student.Age >= Course.MinAge and generate an exception otherwise.
Is this correct in the DDD approach? Or should I  pass to SubscribeTo only CourseId? Student.SubscribeTo(int CourseId)
From my point of view, if there is no way to break the invariant, access to Course externally to the aggregate should be allowed. If I change the Course.MinAge in some other places of my code I don't break my business requirements, as I want the age be respected only when subscribing the course and I don't mind if later the Course.MinAge changes.
Different case if business requirements state: when Course.MinAge changes students already enrolled in the course should be removed from the course if Student.Age < Course.MinAge.

A: I think that the aggregate you have is not correct. A Course entity can exists on its own, it is not a child entity of a Student entity. A course has its own lifecyle: e.g. if a student leaves the school, the course keep on existing. The course id doesn't depend on the student id. The student can hold the course id, but they are different aggregates.
Anyway, to your question of passing just the course id to the "student.subscribeTo" method if they were an aggregate, the answer is no, you cannot pass the id of a child entity to an operation of the aggregate, as the child entities doesn't have a global identity known outside the aggregate. They have local id into the aggregate.
UPDATE:
Since Course and Student are two aggregates, the rule "student's age must be above the minimum age required to enroll the course" isn't an invariant. Why? Because an invariant is a business rule about the state of just an aggregate, that must always be transactionally consistent. An aggregate defines a transactional consistency boundary.
So, the rule is just a validation rule that must be checked when the student subscribes to a course ("student.subscribeTo" method). Since aggregates shouldn't use repositories, you can pass a domain service to the method, and the student aggregate would double-dispatch to the domain service in order to get the course from the course id.
Take a look at the aggregates chapter of the Red Book IDDD by Vaughn Vernon (pages 361-363) or the article by the same author:
http://www.informit.com/articles/article.aspx?p=2020371&seqNum=4
Hope it helps.

A: I'm also learning DDD and few days ago I ask a question to a similar problem you can find here.
What I've learned is that the only real answer is: it depends. There is no right or wrong approaches per se, everything must serve a purpose to the business problem and its solution. Although, there are guidelines and rules of thumb that can be very useful, for instance:

*

*Don't model reality. The domain model is an abstraction designed to solve a particular problem.

*Don't model based on data relationship. Every association must be there to enforce a rule or invariant and not because those objects are related in real life. Start modeling based on behavior.

*Prefer small aggregates.

*Prefer modify a single aggregate at the same time (use case / transaction), and use eventual consistency to update other aggregates.

*Make associations between aggregates by identity only.

I think the problem in your scenario is that there is a lot missing. Who owns that association and why? Is there any other use case that span both, student and course? Why do you put student.SubscribeTo(course) instead of course.enroll(student)? Remember that the goal of DDD is tackle a complex domain logic so it shines when approaching the write side of the model, the reading side can be done in many different ways without put a lot of associations into the model.
For what you've said, just validating the age is probably not and invariant that requires making a large aggregate:

If I change the Course.MinAge in some other places of my code I don't break my business requirements, as I want the age be respected only when subscribing the course and I don't mind if later the Course.MinAge changes.

Then there is no reason to enforce Student and Course to be consistent at all times (in this particular context/scenario), and there is no necessity of make them part of the same aggregate. If the only rule you need to enforce is Student.Age >= Course.MinAge you can stick with a simple:
Student.SubscribeTo(Course course)

where Student and Course are not part of the same aggregate. There is nothing against loading two different aggregates and use them in the same transaction, as long as you modify only one. (Well, there is nothing against modify two aggregates in the same transaction either, is just a rule of thumb, but probably you don't need to break it in this case).
Here Student.SubscribeTo will enforce the rule regarding the age. I have to say, it sounds "weird" to let the Student validate his own age, but maybe it is just right in your model (remember, don't model reality, model solutions). As the result, Student will have a new state holding the identity of the course and Course will remain unchanged.

Different case if business requirements state: when Course.MinAge changes students already enrolled in the course should be removed from the course if Student.Age < Course.MinAge.

Here you have to answer first (with the help of a domain expert) some more questions: Why should they be removed? Should they be removed immediately? What if they are attending the class in that moment? What does it mean for a student to be removed?
Chances are that there is no real need in the domain to remove the students at the same time the MinAge is changed (as when the operation is only considered successful when all happens, and if not, nothing happens). The students might need to enter a new state that can be solved eventually. If this is the case, then you also don't need to make them part of the same aggregate.
Answering the question in the title, unsurprisingly: it depends. The whole reason to have an aggregate is to protect invariants of a somehow related set of entities. An aggregate is not a HAS-A relationship (not necessarily). If you have to protect an invariant that spans several entities, you can make them an aggregate and choose an entity as the aggregate root; that root is the only access point to modify the aggregate, so every invariant is always enforced. Allowing a direct reference to an entity inside the aggregate breaks that protection: now you can modify that entity without the root knowing. As entities inside the aggregate are not accessible from the outside, those entities have only local identity and they have no meaning as standalone objects without a reference to the root. It is possible to ask the root for entities inside the aggregate, though.
You can, sometimes, pass a reference to an inner entity to another aggregate, as long as it's a transient reference and no one modify that reference outside the aggregate root. This, however, muddles the model and the boundaries starts to become blurry. A better approach is passing a copy of that entity, or event better, pass a immutable view of that entity (likely a value object) so there is no way to break invariants. If you think there is no invariant to break by passing a reference to an inner entity, then maybe there is no reason to have an aggregate to begin with.


Q: how to remove all space on indent when inserting a newline under vim Xcode I am new to Xcode and use vim for my editor under Xcode. How to use shift + O to add newline in vim under Xcode without adding space as indent?
so I will not have lots of space in blank line like following during git diff

this is what I expect during git diff

A: *

*Go to Xcode Preferences.

*Choose Text Editing tab.

*Switch to the Editing page underneath.

*Check both "Automatically trim trailing whitespace" and "Including whitespace-only lines".

This works both in Vim mode and the normal mode.


Q: How to find whether IPs in subnet used for HSRP in softlayer API We ordered a subnet on a private VLAN and when we try to use one of the IP. We realized that IP was used for HSRP on router/switches of Softlayer infrastructure. Is there any SL API to find out whether the IP is used for this purpose? We generally extract IP using softlayer python based client code like the below
ipinfo = network.ip_lookup()
and to determine whether it is used for any reserved purpose
ipinfo['isGateway'] is True or ipinfo['isBroadcast'] is True or ipinfo['isReserved'] is True
Really appreciate your inputs on this.
Thanks

A: IP Addresses reserved for HSRP have the property isReserved as True and in note property the text “Reserved for HSRP.”
You can use the method SoftLayer_Network_Subnet::getIpAddresses with the following filter to get those IP Addresses:
            objectFilter={'ipAddresses':{'note':{'operation':'Reserved for HSRP.'}}}

Below you can see an example in python.
"""
Get Ip Addresses of a subnet which are reserved for HSRP protocol.

Important manual pages:
http://sldn.softlayer.com/reference/services/SoftLayer_Network_Subnet/getIpAddresses
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Network_Subnet_IpAddress
https://sldn.softlayer.com/article/object-Masks
https://sldn.softlayer.com/article/object-filters

License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc. <sldn@softlayer.com>
"""
import SoftLayer
from pprint import pprint as pp

# Your SoftLayer API username and key.
API_USERNAME = 'set-me'
API_KEY = 'set-me'

# The id of subnet you wish to get information.
subnetId = 135840

# Object mask helps to get more and specific information
mask = 'id,ipAddress,isReserved,note'

# Use object-filter to get Ip Addresses reserved for HSRP
filter = {
            'ipAddresses': {
                'note': {'operation': 'Reserved for HSRP.'}
            }
        }

# Call SoftLayer API client
client = SoftLayer.create_client_from_env(username=API_USERNAME, api_key=API_KEY)

try:
    result = client['SoftLayer_Network_Subnet'].getIpAddresses(id=subnetId,
                                                               mask=mask,
                                                               filter=filter)
    pp(result)

except SoftLayer.SoftLayerAPIError as e:
    pp('Unable to get the Ip Addresses %s, %s' % (e.faultCode, e.faultString))

Links:
https://knowledgelayer.softlayer.com/articles/static-and-portable-ip-blocks
http://sldn.softlayer.com/reference/services/SoftLayer_Network_Subnet/getIpAddresses
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Network_Subnet
I hope this help you.
Regards,


Q: Drupal: PDOException: could not find driver in lock_may_be_available() I am running Drupal on my local machine using Windows and recently I opened a project solution within Visual Studio.  Upon opening the solution, it asked me to install PHP7 extensions via the Microsoft Web Platform Installer.  After these extensions were installed, when I navigate to my local Drupal site, I get the following error:
PDOException: could not find driver in lock_may_be_available()
I did do some research before I decided to ask this question and it seems that I'm just missing this driver.
If this is the problem, how do I install the right PDO driver for Drupal?
Any help is greatly appreciated!

A: It's not driver for Drupal, but for PHP. It's name should be "pdo_mysql", "php_pdo_mysql" or similar, depending on platform. Since you are on windows you should look for a way to install it there. I.e. check this SO post:
PHP - How to install PDO driver? (Windows)
BTW, will you site really run on windows server? If not, my advise is to develop on virtual machine, so you'll have the same development environment, as production will be (most likely linux, right?).


Q: Can one determine optimal parameters of a matrix to design the matrix kernel? (with specific example) Suppose we are given a matrix $B\in \mathbb{R}^{n\times n}$. I would like to find $n$ real values $\{a_i\}_{i=1}^n$ that form a diagonal matrix $A=\text{diag}(\{a_i\}_{i=1}^n)$ to design the kernel of the matrix $(AB-\mathbb{1})$.
Take the following as a concrete example:
Find $\{a_i\}_{i=1}^n$ such that there exist $\lambda \in \text{ker}(AB-\mathbb{1})$ with $|\lambda_i| = 1 \forall i\in \{1,...,n\}$.
Is this problem well posed?
For the specific example, can one determine assumptions on $B$ that guarantee that a solution $(\{a_i\}_{i=1}^n,\lambda)$ exists?
Can one cast this a standard optimization problem such that it can be solved with for example Matlab?

A: Let me summarize your problem:
You want to design $A=\text{diag}(\{a_i\}_{i=1}^n)$ and find $\lambda$ such that $(AB-I)\lambda = 0$ and $|\lambda_i| = 1 \forall i\in \{1,...,n\}$.
It is clear that $\lambda $ is an eigenvector with eigenvalue 1 to the matrix $AB$ since $AB \lambda = \lambda $ which follows from $(AB-I)\lambda = 0$. Now, we want $1$ to be an eigenvector of $AB$. Let $y=B\mathbf{1}$. Let us choose $A=\text{diag}(\{a_i\}_{i=1}^n)$ such that $AB\mathbf{1}=Ay = \mathbf{1}$. The latter equality is achieved by
$$ a_i = 1/y_i$$
For the latter choice, it is of course necessary that $y_i \neq 0$.


Q: Set text from sqlite rows in Pyqt textbrowser I need a way to set some rows from sqlite.db to pyqt textbrowser,But the problem is that it just put the last row.
cur = conn.cursor()
conn.text_factory = str
cur.execute(" SELECT text FROM Translation WHERE priority = ?", (m,))
for row in cur:
    print('{0}'.format(row[0]))
    self.SearchResults.setPlainText('{0}'.format(m))

I used pandas but,
query = "SELECT text FROM Translation WHERE priority=2;"

df = pd.read_sql_query(query,conn)
 self.SearchResults.setPlainText('{0}'.format(df['text']))

This is not what I want.And this:
cur = conn.cursor()
conn.text_factory = str
cur.execute(" SELECT text FROM Translation WHERE priority = ?", (m,))
    all_rows=cur.fetchall()

    self.SearchResults.setPlainText('{0}'.format(all_rows))

A: In the first code you are replacing the text every time you iterate, the solution is to use append()
cur = conn.cursor()
conn.text_factory = str
cur.execute(" SELECT text FROM Translation WHERE priority = ?", (m,))

self.SearchResults.clear() # clear previous text

for row in cur:
    self.SearchResults.append('{0}'.format(str(row[0])))


Q: Converting '0x3132333435' to '12345' in PHP I was trying to recover some password data on my SQL SERVER 2012 files, unfortunately I forgot what encryption was used in encoding the password to the tables. I know that 0x3132333435 translates as 12345, as this was my test account before.
I tried to use hexdec() but no luck, there seems to be a pattern with the structure of the password. 0x3132333435 translates as 0x3(1)3(2)3(3)3(4)3(5) with the data 12345 being 'sandwiched' between hex 0x3 and 3's.
This is one of my code's part.
            $_SESSION['error'] = 'Cannot find account with the username';
        } else {
            $row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC);
            if (hexdec($password, $row['password'])) {
                $_SESSION['admin'] = $row['id'];
            }
            else{
                $_SESSION['error'] = 'Incorrect password';
            }
        }

I've read some of the topics about this as well, but I don't have any idea on how to implement it:

Currently, classes "wep" and "wpa" are suported. The WEP
  (Wired  Equivalent  Privacy)  key  can be either 5 or 13
  bytes long. It can be provided either  as  an  ASCII  or
  hexadecimal  string  --  thus "12345" and "0x3132333435"
  are equivalent 5-byte keys (the "0x" prefix may be omit-
  ted). A file containing a WEP key must consist of a sin-
  gle line using either WEP key format.   The  WPA  (Wi-Fi
  Protected  Access)  key  must  be  provided  as an ASCII
  string with a length between 8 and 63 bytes.

Is it possible to do it manually? Or is there some link that I can use as a guide or reference?
I am trying to use the old table (user's masterfile) so that my old users can still access the system. I'm currently using hash() for my new password table.


Q: Storing keystore password for certificate pinning in Android I've recently started to learn about security in Android apps and wanted to implement certificate-pinning. Found some useful information by googling around but I stumbled upon storing the keystore password which contains the server certificate.
As I can't trust the Android filesystem to keep my keystore password secret, mainly because any rooted user would be able to dig it out eventually, I'm starting to wonder whether if it is really needed to securily store this keystore password or not, because this keystore will only contain my server's SSL certificate, which is intended to be public.
I can't think about any malicious attack if somebody could decompile my APK and see the keystore password, as the attacker wouldn't be able to modify any of the app's code and thus change, for example, the targeted server IP or even modify the keystore switching my certificate with some other malicious cert which, in combination with the changes the attacker could made on the targeted IP, would make the app work targeting any malicious server (man-in-the-middle-attack).
I found a quite good example of certificate pinning in Android here on github, but sadly the author doesn't bother with storing the passsword securely, as it is hardcoded at the MainActivity.
So my summed up question would be: Is it really needed to protect a keystore password if that keystore only has inside an intended public SSL server certificate?
From the research I did, I found that on this question the OP addresses the posibility of passing null as the password on the Android code. Maybe I could go with this and store the keystore password at my server instead of packing it up inside the Android app.

Also during my googling I found quite useful articles that might be interesting for anybody looking into this question in the future:

*

*Certificate-Pinning in Android explained easy

*Securely storing info in Android

*Android Keystore for storing keys (WARNING any rooted user can dig out info stored here)

Progress update
- Passing null as the keystore password (as I mentioned above as one of the options) if you've set one when generating it will result in keystore bypass: requests get sent anyway and custom keystore does nothing. No exception is thrown or anything, it just works as if you didn't set any custom keystore.
 KeyStore trustStore = KeyStore.getInstance("BKS");
 trustStore.load(keyStoreInputStreamFromResources, null);


Q: Backup Exec System State Does anybody see any point in backing up System State using 'Backup Exec' when 'Backup Exec System Recovery' is running on a server?
The only good thing i can see coming from it is having the System State backup on tape aswell in an image.
But i can see it bad with VSS clashes...
What do people usually do?

A: I see the value in it. There may be a case (as rare as it might seem) that you'll want the System State, outside of your image backups. I've restored domain controllers from just the System State many times, without the need for full image backups.


Q: g++/clang++ Invert compilation error order g++ and clang++ report compilation errors with the first erroneous line encountered at the top of their output. That is, the first line clang/g++ print on a compilation error are the one you usually care about. As I'm sure we have all experienced, you have to scroll up (often a lot) to see what the nasty error is. Is there any compilation flag (in clang++ or in g++) that presents compilation errors in reverse order?
I saw this question which asked the same thing I'm asking, but about GHC and thought about how much of a useful option this would be for C++ projects. I've never heard of this for clang++ or g++, and I couldn't find anything online nor on their man pages.


Q: How to show the time slots horizontally instead of vertically in agendaDay view, fullcalendar? i am trying to list the time slots in agendaDay horizontally, is it even possible? Read all the options listed for agendaDay but could not do it.
Here is js fiddle for test:

$('#calendar').fullCalendar({
      // put your options and callbacks here
      defaultView: 'agendaDay',
      allDaySlot: false,
      slotDuration: '00:60:00',
      slotLabelFormat: 'h(:mm)a',
      // columnHeader: false,
      events: [
    {
     title: 'Blood Donation',
     start: '2017-12-29T10:30:00'
    },
    {
     title: 'Concert Event',
     start: '2017-12-29T12:30:00',
     end: '2017-06-10T12:30:00'
    }
      ]
    })

Have anybody done it before, its just i don't want to do heavy customization using css?
hoping for some initialization parameters for agenda view that will turn around the list in horizontal from vertical.
The view i want is something like the below picture:


Q: How to pull the starting view for document using the Revit API How can I use the Revit API to get the Starting View for a Document?  The equivalent way to access it using the user interface is seen below:

A: I used the Revit Lookup tool and browsed through the database to find a class called StartingViewSettings with the property ViewId that will get me the ElementId of the starting view.  My actual code for getting the view is below
FilteredElementCollector startingViewSettingsCollector =
  new FilteredElementCollector(document);
startingViewSettingsCollector.OfClass(typeof(StartingViewSettings));

View startingView = null;

foreach(StartingViewSettings settings in startingViewSettingsCollector)
{
    startingView = (View)document.GetElement(settings.ViewId);
}


Q: Autocomplete Source I have 2 autocomplete text boxes on my form. What I want to do is dynamically change the source on the 2nd autocomplete textbox if a value has been selected from the first.
a snippet of my markup is below:
 $(function () {
    $("#SelectedAddress").autocomplete({
        source: "/CreateFIS/GetProperties",
        select: function(event, ui) {
            if (ui.item) {
                event.preventDefault();
                $('#SelectedAddress').val(ui.item.label);
                $('#SelectedAddressId').val(ui.item.value);
                getPropertyInformation(ui.item.value);
            }
        },
        focus: function(event, ui) {
            if (ui.item) {
                event.preventDefault();
                $('#SelectedAddress').val(ui.item.label);
                $('#SelectedAddressId').val(ui.item.value);
                //getPropertyInformation(ui.item.value);
            }
    }
    });
});

$(function () {
    $("#SelectedScheme").autocomplete({
        source: "/CreateFIS/GetSchemes",
        select: function (event, ui) {
            if (ui.item) {
                event.preventDefault();
                $('#SelectedScheme').val(ui.item.label);
                $('#SelectedSchemeId').val(ui.item.value);
            }
        },
        focus: function (event, ui) {
            if (ui.item) {
                event.preventDefault();
                $('#SelectedScheme').val(ui.item.label);
                $('#SelectedSchemeId').val(ui.item.value);
            }
        }
    });
});

                    Please Select A Scheme
                    @Html.TextBoxFor(model => model.SelectedScheme, new { @class = "largeTextBox" })
                     @Html.ValidationMessageFor(model => model.SelectedSchemeId)

                    Please Select A Property
                    @Html.TextBoxFor(model => model.SelectedAddress, new { @class = "largeTextBox" })
                     @Html.ValidationMessageFor(model => model.SelectedAddressId)

WHat is the best way to acomplish this?

A: Use the option method to change the source:
var source = $(".selector").autocomplete("option", "source", "/New/Source");


Q: Why ALTER DATABASE .. MODIFY NAME reports an error while succeeding at the same time? I am running the following query in SSMS:
SET NOCOUNT ON
ALTER DATABASE [xyz] MODIFY NAME = [xyz_]

And get this:
The database name 'xyz_' has been set.
Msg 911, Level 16, State 1, Line 2
Database 'xyz' does not exist. Make sure that the name is entered correctly.

So, the query fails, but the database is still renamed!
What is going on?

A: One possibility is that there's a DDL trigger that fires for ALTER DATABASE, and that trigger code try to refer to the (now old) database name.


Q: Could someone help to explain why the klass could not be used in wrapper? About python __closure__ I couldn't understand why my klass couldn't be used in wrapper method
#!/usr/env/bin python

class MyClassmethod(object):
    def __init__(self, func):
        self.func = func

    def __get__(self, obj, klass=None):
        def wrapper(*args, **kwargs):
            if not klass:
                klass = type(obj)
            return self.func(klass, *args, **kwargs)
        return wrapper

class Test:
    @MyClassmethod
    def mytest(cls, test=None):
        print(f"this is a classmethod belongs to {cls.__name__}")

if __name__ == '__main__':
    Test.mytest()

It shows UnboundLocalError: local variable 'klass' referenced before assignment
But If I change the code like this, put the klass assignment out of the wrapper method
#!/usr/env/bin python

class MyClassmethod(object):
    def __init__(self, func):
        self.func = func

    def __get__(self, obj, klass=None):
        if not klass:
            klass = type(obj)
        def wrapper(*args, **kwargs):
            return self.func(klass, *args, **kwargs)
        return wrapper

class Test:
    @MyClassmethod
    def mytest(cls, test=None):
        print(f"this is a classmethod belongs to {cls.__name__}")

if __name__ == '__main__':
    Test.mytest()

Could someone help to explain this？
Cheers

A: In your first example, you're referencing the variable klass before you've defined it.  That's not the case in the second example.


Q: What command are my volume keys running? In Unity I use my ThinkPad hot keys to change the volume. I need to know the command that these keys run so that I can bind it in my window manager.
I have tried using amixer but could not change the volume through command line

amixer set Master 10%- amixer: Unable to find simple control 'Master',0
amixer scontrols: Simple mixer control 'IEC958',0
amixer set 'IEC958' 50%- amixer: Invalid command!

So obviously this is not what Unity is running. I have tried changing the default sound card as well but that didn't help.

A: The following command:
pactl set-sink-volume 0 50%

will set the volume at 50%. To increase the volume with 10% you can use:
pactl set-sink-volume 0 -- +10%

To decrease the volume with 10% you can use:
pactl set-sink-volume 0 -- -10%

A: so basically they're not simple keybinding->command process, MediaKeys give you scancode which is interpreted by X.
Some reading for you https://help.ubuntu.com/community/MultimediaKeys


Q: HTML Traverse and Find Best Practices Hey I was thinking about making some crawlers so that I can get an URL and traverse through the html and just get certain things I might need/want. I was thinking about using Php + xPath but I'm not sure that might be the best way. What do you guys think? Are there any best practices, recommendations, or anything else?

A: I had some good results reusing the Parse class from Fit/Fitnesse for getting data out of html tables.


Q: Is there a way to make a cell editable where column is readonly in XtraGrid? My grid looks like this.
Key Value
1    A
2    B
3    C

I have Value column read-only in my grid. "Value" column's columnedit is associated with memoexedit repository. Now what I want to do is on some condition like when key=2,
I want my value cell to be editable.
I tried making the whole column ReadOnly = false.
and then handled ShowingEditor to cancel edit on everything else than Key=2, but that prevents even opening up the editor for other values.
What I want is able to see the editor but it should be readonly for Others
and for Key=2, It should be editable.
Please help!

A: Try to handle the ShownEditor event as the following (semi-pseudo code):
var grid = sender as GridView;
if (grid.FocusedColumn.FieldName == "Value") {
    var row = grid.GetRow(grid.FocusedRowHandle) as // your model;
    // note that previous line should be different in case of for example a DataTable datasource
    grid.ActiveEditor.Properties.ReadOnly = // your condition based on the current row object
}

This way you could refine the already opened editor with your needs.