text:
Q: How to edit element of List of Lists? I have a:
var list = new List<List<MyClass>>();

MyClass:
public class MyClass
{
  public double X { set; get; }
  public double Y { set; get; }
  public bool Unique{ set; get; }
}

Now I have a double x and double y and I want to find element of list with same X and Y and set Unique field to false.
I already find examples for search like:
var element = (from sublist in list
               from item in sublist
               where item.X == x && item.Y == y
               select item).FirstOrDefault();

But how to edit this element?
Sure I can do something like:
foreach (var myClsList in list)
{
  foreach (var myCls in myClsList )
  {
    if (myCls.X == x && myCls.Y == y)
    {
      myCls.Unique= false;
    }
  }
}

But it doesn't look nice.

A: It looks you really want to group elements by their X and Y properties and properly set the Unique properties inside these groups. Here are some initial thoughts:
List<Element> allItems = list.SelectMany(l => l);
var groups = allItems.GroupBy(element => new { X = element.X, Y = element.Y });
foreach (var group in groups) {
    bool unique = group.Count() == 1;
    foreach (var element in group) {
        element.Unique = unique;
    }
}

A: It seems very unclear whether you want to edit one element, or the entire elements matching certain criterion.
For one element you do:
(from sublist in list
 from item in sublist
 where item.X == x && item.Y == y
 select item).First().Unique = false; //the default item will be null

This works, but quite ugly. Better:
var element = (from sublist in list
               from item in sublist
               where item.X == x && item.Y == y
               select item).FirstOrDefault();
element.Unique = false;

To change them all, use a foreach. Linq is not really for side-effects. It should be a side-effect construct. In your case I would do:
var query = list.SelectMany(sublist => sublist)
                .Where(item => item.X == x && item.Y == y);
foreach(var myClass in query)
    myClass.Unique = false;

If you really want side-effects and want to do it in linq style, you can better adopt a fluent style tweaking your MyClass like this:
public class MyClass
{
  public double X { set; get; }
  public double Y { set; get; }
  public bool Unique { set; get; }

  public MyClass Duplicate()
  {
    Unique = false;
    return this;
  }
}

// So you call:

var query = list.SelectMany(sublist => sublist)
                .Where(item => item.X == x && item.Y == y)
                .Select(item => item.Duplicate());

A: Some thoughts on the overall structure:
Look at the Dictionary<> class.  This is designed to store a list of items which may be accessed via an arbitrary type.  To use it in this context:

*

*Remove Unique from your class.

*Make your class a struct instead so it is compared by value rather than reference (i.e. two distinct MyClasses with the same X/Y are considered the same)

*Instead of a list, use Dictionary<MyClass, bool>
(seem to need text here to create a code block)
public struct MyClass
{
    public double X { get; set; }
    public double Y { get; set; }
}

var items = new Dictionary<MyClass, Bool>();

items[ new MyClass{ X = 3, Y = 7 } ] = false;
items[ new MyClass{ X = -12, Y = -24 } ] = true;

Assert.IsFalse( items[ new MyClass{ X = 3, Y = 7 } ] );
Assert.IsTrue( items[ new MyClass{ X = -12, Y = -24 } ] );

items[ new MyClass{ X = 3, Y = 7 } ] = true;
Assert.IsTrue( items[ new MyClass{ X = 3, Y = 7 } ] );

To clarify how Dictionary works:

*

*K is the "key" type; this is the type used to label the items you're storing in the dictionary and is used both when putting items into it and taking items out.

*V is the "value" type; this is the type you are storing.

*You can read or write the dictionary using an indexer:

*

*var value = dictionary[ key ]

*dictionary[ key ] = value

*Dictionary may be faster under some circumstances than manually iterating through the list as it internally may use any data structure it likes to search for matches, which may be faster for large datasets.  I believe it uses GetHashCode to shortlist matches, but that's likely unimportant in this context.


text:
Q: Python: Convert list with string sub elements to a normal list This is for Python. I want to take a list of strings and split each string out into it's own element with the comma as a delimiter. Then turn that into a list of sublists while keeping the first element a string and the next two elements ints. What I have:
 myList = ['one, 0650 ,0730','two, 1100, 1115','three, 1210, 1250','two, 1515,
 1530','four, 1130, 1430','five, 1750, 1930','four, 2000, 2100','three, 1800,
 2100']

Desired output:
newList = [['one', 0650, 0730] , ['two', 1100, 1115] , ['three', 1210, 1250]
,['two', 1515, 1530],['four', 1130, 1430] , ['five', 1750, 1930] , ['four',
2000, 2100] , ['three', 1800, 2100]]

I know that if you apply list func on each item, it would turn each item which is in string format to a list of strings. The problem is I need sublists with different data types. Sorry I'm sure where to begin with this.

A: You can do it like this:
result = []
for item in myList:
    items = [sub_item.strip() for sub_item in item.split(',')]
    items = [
        int(sub_item) if sub_item.isdigit() else sub_item
        for sub_item in items
    ]
    result.append(items)

print(result) # [['one', 650, 730], ['two', 1100, 1115], ['three', 1210, 1250], ['two', 1515, 1530], ['four', 1130, 1430], ['five', 1750, 1930], ['four', 2000, 2100], ['three', 1800, 2100]]

Also you can do the same using regex
import re

pattern = r'(\w+)\s*\,\s*(\d+)\s*\,\s*(\d+)'
for item in myList:
    items = re.findall(pattern, item)[0] # it will be ['one', '650', '730']
    items = [
        int(sub_item) if sub_item.isdigit() else sub_item
        for sub_item in items
    ]
    result.append(items)

In one line if you need this:
import re

pattern = r'(\w+)\s*\,\s*(\d+)\s*\,\s*(\d+)'
result = [[int(item) if item.isdigit() else item for item in re.findall(pattern, items)[0]] for items in myList]

The same without regexp:
result = [[int(item) if item.isdigit() else item for item in items.replace(' ', '').split(',')] for items in myList]

A: Try this.
myList = [item.split(',') for item in myList]
myList = [[i.strip() for i in item] for item in myList]
myList = [[int(i) if i.isdigit() else i for i in item] for item in myList]
print(myList) #[['one', 650, 730], ['two', 1100, 1115], ['three', 1210, 1250], ['two', 1515, 1530], ['four', 1130, 1430], ['five', 1750, 1930], ['four', 2000, 2100], ['three', 1800, 2100]]

A: newList = [e.split(",") for e in myList]
newList = [[int(x) if x.strip().isdigit() else x for x in sublst] for sublst in newList]

Just want to make sure myList = ['one, 0650 ,0730'... is not a typo. There is one space behind 0650 while the others are just followed by a comma,.
If that was a typo, you can skip the strip() step.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to count rows when creating excel file I have a GridView that I am converting to an Excel Spreadsheet. I want the first column to count the rows i.e. if there are 10 rows in the spreadsheet then the first column should display 1 to 10. But right now the spreadsheet is just displaying the last number for all columns. So if the excel has 10 rows, the number 10 is there for each row instead of counting up from one.
int Sno = 1;
for (Sno = 1; Sno < ds.Tables[0].Rows.Count; Sno++)
{
       Sno++;
}

downloadcsv.WriteLine("\"" + Sno + "\",\"" +
                    dr["CustomerName"].ToString() + "\",\"" +
                    dr["invoiceno"].ToString() + "\","
                 );

A: You have a loop that counts each row, but you aren't setting any values inside the loop. You only set a single value after the loop. So of course you are only setting the number for the last row.
You will need to set the data for each row, inside of your loop body.
Sorry, I'd sketch out the code for you but I can't really tell what downloadcsv is or why on Earth you'd be using WriteLine() like that.

A: simple add the "serial no"  in gridview column itself without using any counter,
 <asp:TemplateField HeaderText="S#" >
                        <ItemTemplate>
                            <%# Container.DataItemIndex + 1 %>
                        </ItemTemplate>
                    </asp:TemplateField>

if not showing to user then use
 <asp:TemplateField HeaderText="S#" Visible="False">
                        <ItemTemplate>
                            <%# Container.DataItemIndex + 1 %>
                        </ItemTemplate>
                    </asp:TemplateField>


text:
Q: How do I deserialize a string as a custom object with Jackson? I have this JSON that I want to parse:
{
 "name": "john",
}

I must use the following hierarchy. The classes are immutable and I must access them by the static factory method (this is imperative, so it makes no sense to suggest modifications to either Name or Person).
class Name {
  static Name valueOf(String name) {...}
  private Name() {}
  String name();
}
class Person {
  static Person create(Name name) {...}
  private Person() {...}
  Name name();
}

To that end, I want to deserialize a Person with Jackson, so I wrote this:
public class NameJsonDeserializer extends JsonDeserializer<Name> {
  @Override public Name deserialize(JsonParser parser, DeserializationContext context) {
    var tree = parser.getCodec().readTree(parser);
    var name = tree.asToken().asString();
    return Name.valueOf(name);
  }
}
public class PersonJsonDeserializer extends JsonDeserializer<Person> {
  @Override public Person deserialize(JsonParser parser, DeserializationContext context) {
    var tree = parser.getCodec().readTree(parser);
    var name = (ObjectNode) tree.get("name");
    return Person.create(name);
  }
}

But of course, this doesn't work. It doesn't even compile.
I know I can write something similar to the following, but Name is used all over the place, and not always within a Person, so I really need a separate deserializer for Name.
var tree = parser.getCodec().readTree(parser);
var name = (TextNode) tree.get("name");
return Person.create(Name.valueOf(name.asText()));

How can I deserialize without having recourse to intermediary POJOs?

A: I must use parser.getValueAsString() for NameDeserializer and codec.treeToValue() for PersonDeserializer:
public class NameJsonDeserializer extends JsonDeserializer<Name> {
  @Override public Name deserialize(JsonParser parser, DeserializationContext context) {
    var name = parser.getValueAsString();
    return Name.valueOf(name);
  }
}
public class PersonJsonDeserializer extends JsonDeserializer<Person> {
  @Override public Person deserialize(JsonParser parser, DeserializationContext context) {
    var codec = parser.getCodec();
    var tree = codec.readTree(parser);

    var name = codec.treeToValue(tree.get("name"), Name.class);

    return Person.create(name);
  }
}

A: If you can modify Person, you could use @JsonCreator:
@JsonCreator
public static Person create(@JsonProperty("name") String name) {
    Name nameInstance = Name.valueOf(name);
    return new Person(nameInstance);
}

This will consume that JSON properly, mapping the "name" property to the first param of the method.
If you cannot modify the class you can use the mixin approach, creating the mixin:
interface PersonMixin {
    @JsonCreator
    public static Person create(@JsonProperty("name") Name name) {return null;}
}

and register it in the mapper:
 mapper.addMixIn(Person.class, PersonMixin.class);


text:
Q: Level of certainty in "intend" versus "hope" I am trying to write an essay detailing my short and long term goals and I want to convey to the reader that these are goals that I fully intend on achieving. I was going to say "I intend, not hope" but I am unsure if the level of certainty conveyed by both word is the same or not.
Would that sentence work as desired if used as a title?

A: Well, let's look at the definitions:

intend: to have in mind as something to be done or brought about
hope: to feel that something desired may happen

Not quite as clear as I'd hoped, but hey. The key difference here is that intend carries the connotation that you are going to do something about it. Hence, "I hope to win" means "I desire to be the best", whereas "I intend to win" means "I'm am going to try to be the best".
In terms of level of certainty: I don't think either word signifies more, in and of itself. But if it is something that you have some control of, it's more much more likely to happen if you do something about it! That said, with the "I hope/intend to win" example you are always dependant on other people not doing well enough, hence why "intend" doesn't carry certainty.
A title for an essay of "I intend, not hope", means "I don't just sit around waiting for things I want: if I want them I go and make sure they happen!" I think it's a great title for an essay on your personal goals.


text:
Q: Lavu POS API - Send order to KDS I am facing problem in integrating the Lavu POS API. I hope to get some answer from peers that integrate Lavu POS API before. The documentation for Lavu POS API is very difficult to read and understand. Columns are not well explained.
I tried their send order API PHP codes. The codes that is provided in their basic API document.
So basically, I've created a order and order content successfully. The orders are seen on runner iPad. But when I click "send", it says that my order are already send to the kitchen. However, the KDS does not receive any order.
I notice that the order ID created from Lavu POS API codes is different from the order that are created from the app.
In the API order example created orders with ID that start from 7. In my app order created orders with ID that start from 1.
Both are order content are the same.
so my question is:

*

*why KDS doesn't get my order?

*What is the parameter I am missing?
3/ what is the parameter I had send wrongly?

Below is the content the I send to Lavu POS API for order:
Note: server and server id is changed in my real code
$set_contents = "
<row>
    <opened>".date('Y-m-d H:i:s')."</opened>
    <closed>0000-00-00 00:00:00</closed>
    <subtotal>8.30</subtotal>
    <taxrate>0.000</taxrate>
    <tax>0.98</tax>
    <total>8.30</total>
    <server>Ancori</server>
    <server_id>15</server_id>
    <tablename>Table 5</tablename>
    <cash_paid>8.30</cash_paid>
    <change_amount>0</change_amount>
    <cash_applied>8.30</cash_applied>
    <card_paid></card_paid>
    <gift_certificate></gift_certificate>
    <guests>2</guests>
</row>
";

Below is the content i send to pos lavu for order content:
$set_contents = "
    <row>
        <sent>0</sent>
        <order_id>" . $order_id . "</order_id>
        <item>testing item</item>
        <price>8.30</price>
        <quantity>1</quantity>
        <options></options>
        <special></special>
        <modify_price></modify_price>
        <check>1</check>
        <seat>1</seat>
        <item_id>666</item_id>
        <printer>1</printer>
        <apply_taxrate>0</apply_taxrate>
        <custom_taxrate>0</custom_taxrate>
        <course>1</course>
        <subtotal>8.30</subtotal>
        <discount_amount></discount_amount>
        <discount_value></discount_value>
        <discount_type></discount_type>
        <after_discount></after_discount>
        <subtotal_with_mods>8.30</subtotal_with_mods>
        <tax_amount></tax_amount>
        <notes></notes>
        <total_with_tax></total_with_tax>
        <after_gratuity></after_gratuity>
        <void>0</void>
        <discount_id></discount_id>
        <server_time>".date('Y-m-d H:i:s')."</server_time>
        <device_time>".date('Y-m-d H:i:s')."</device_time>
    </row>

A: You should set <send_status>1</send_status> in your order
if you didn't set this value, by default it will be 0, '0' means order has been sent to printer, so you need to set to 1 while you sending order to indicate that the order hasn't be printed.


text:
Q: Not detecting external dispplay with Laptop with AMD CPU + NVIDIA GPU + Ubuntu 20.04 I've installed Ubuntu 20.04 on a 2020 HP Omen 15 laptop with AMD CPU and NVidia GPU. Everything works except detecting an external monitor. I have used the "Additional Drivers" software configuration section and unsuccessfully tried all the nvidia drivers listed there (including nvidia-driver-440). The "Displays" setting of the settings app only shows one display, which is titled "Unknown Display". I also noticed that the "Nvidia X Server Settings" App is blank, and also that there is no /etc/X11/xorg.conf file present.

A: i had the issue with the driver i had installed got corrupted and on installing nvidia-driver-440 and above it started showing dependency error.
now the problem i had solved was with complete fresh installation of a Ubuntu 20.04 and installing nvidia-driver-470
this solved for me but you can check
sudo apt-get install nvidia-driver-470


text:
Q: How to find the average distance from a point to a all the points on a given segment? Suppose point $C$ is directly above point $B$ of $\overline{AB}$. $|\overline{AB}| =2$, and the distance from $C$ to $B$ is $1$.
How can I find the average distance from point $C$ to every point on $\overline{AB}$?

To further clarify my question, suppose we start to randomly pick ten points $A,D,E,F,G,H,I,J,K,B$ on $\overline{AB}$ and connect them all to point $C$.

The average distance from point $C$ to points $A,D,E,F,G,H,I,J,K,B$ would then be $$\frac{|\overline{CA}|+|\overline{CD}|+|\overline{CE}|+|\overline{CF}|+|\overline{CG}|+|\overline{CH}|+|\overline{CI}|+|\overline{CJ}|+|\overline{CK}|+|\overline{CB}|}{10}$$
Ideally, there should be infinitly many segments, but I cannot draw them all.
Now, return to my question: what is the the average distance from point $C$ to every point on $\overline{AB}$?
I think this question is related to Triangle Line Picking, but I have not been able to figure out the set up for solving this problem. Any hints would be appreciated.

A: Without loss of generality, let the coordinates of A, B, C be: $(0, 0), (b, 0)$, and $(b, c)$. An arbitrary point on AB is described by the coordinates $(x, 0)$, where $x \in [0, b]$. The distance from C to this point is given by $d(x) = \sqrt{(b-x)^2 + c^2}$. Now you can integrate $d(x)$ w.r.t. to $x$ to get the average distance $\bar{d}$.
$\bar{d} = \frac{1}{b}\int_0^{b} \sqrt{(b-x)^2 + c^2} dx$.
I think a substitution like $(b-x) = c \tan \theta$ might work.
Specifically, in your example, $b=2$ and $c=1$.

A: This is $\frac12\int_0^2 \sqrt{x^2+1}\;dx$, as Aditya Dua explains. To evaluate this integral, make the substitution $x=\sinh u$, so that $x^2+1=\cosh^2u$ and $dx=\cosh u\;du$. We get
$$\begin{align}
\frac12\int_0^{\sinh^{-1}2}\cosh^2 u\;du&=\frac14\int_0^{\sinh^{-1}2}(\cosh 2u+1)\;du\\
&=\frac14\left[\frac12\sinh 2u+u\right]_0^{\sinh^{-1}2}\\
&=\frac14\left[\sinh u\cosh u+u\right]_0^{\sinh^{-1}2}\\
&=\frac14(2\sqrt{2^2+1}+\sinh^{-1}2)\\
&=\frac12\sqrt 5+\frac14\sinh^{-1}2
\end{align}$$
which is about $1.47894285754460$. You can find the various hyperbolic identities at this link.


text:
Q: Score for classification of dataset composed by different class with class imbalance I am searching for a classification score, preferably provided by Python scikit-learn, to evaluate classification in a cross-validation routine.
This classification score must be suitable for:

*

*strong class imbalance

*multiclass classification

The cardinality of the classes is the following:
         N
Class1  19
Class2  34
Class3   8
Class4  17

Update
I defined a custom scorer based on ROC AUC score from sklearn. Basically I extended it to the multi-class problem by averaging the different scores for each class in a one-vs-all fashion. Is this feasible? Are there drawbacks in this approach?
Here is the Python/sklearn code:
from sklearn.metrics import roc_auc_score
from sklearn.preprocessing import LabelBinarizer

def custom_avg_roc_auc_score(truth, pred):

    lb = LabelBinarizer()
    lb.fit(truth)

    truth = lb.transform(truth)
    pred = lb.transform(pred)

    return roc_auc_score(truth, pred, average="macro")

avg_roc_auc_scorer = make_scorer(custom_avg_roc_auc_score)

A: I'd like to highlight two possible options for multiclass performance metrics under class imbalance:

*

*Kohen's Kappa (see here for details in scikit.learn), and

*Computing one ROC curve and area under the curve (AUC) per individual class (see here for details in scikit.learn).

For the latter: as you have $N$ classes, and ROC/AUC are conceptually designed for 2-class-problems, you will likely need to calculate one ROC curve and AUC value per individual class. This could be done e.g. in a "1-vs-all" manner, where you test for each class how much it is confused with other classes. The thereby obtained $N$ metrics can be used to e.g. look at the distribution of AUC values (e.g. boxplots or similar) to compare and select a best suited model from multiple models. If this process needs to be done fully automated, consider computing the mean/median and sd/mad of AUC over all classes (the first indicates the "average" performance over classes, the latter the performance spread). By doing this for all models you obtain scalar values which you could use to select a model suited for your problem.


text:
Q: Deploy system Spring boot in tomcat 8 - CentOS 8 I have a Java 8 system - Spring boot with tomcat 8. The system worked on CentOS 7, but the structure was changed to Azure and needed to install new version.
My system is connected to another SQL Server server
To deploy my system, I get an error:
The driver could not estalish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "Server chose TLSv1, but that protocol version is not enabled or not supoorted by the client."

My application.properties:
spring.thymeleaf.cache=false

#spring.datasource.url=jdbc:sqlserver://1.1.1.1:1433;DatabaseName=BD;integratedSecurity=true;encrypt=true;trustServerCertificate=true;
spring.datasource.url=jdbc:sqlserver://1.1.1.1:1433;DatabaseName=BD
spring.datasource.username=ss
spring.datasource.password=XXXXX
spring.jpa.hibernate.ddl-auto=none
spring.jackson.serialization.fail-on-empty-beans=false

server.port=8080

spring.mvc.favicon.enabled=false
server.context-path=/sc

What can I do to solve this problem?


text:
Q: How to add a custom GPS location to a picture? Given a .jpg picture without associated GPS coordinates, how would you suggest to add custom coordinates to it?

A: You can use the exiftool command
e.g.:
exiftool -exif:gpslatitude="Put_the_GPS_coordinate_here" -exif:gpslatituderef=S your.jpg

Verify it:
exiftool -filename -gpslatitude -gpslongitude -T your.jpg


text:
Q: check cookie - if found display link I want to display a link to a user when he has an cookie named abc in his browser
<?php
$cookie = abc;
if (!$cookie)
{
  echo
click here;
}
?>

how could I do this?
thanks

A: The PHP global $_COOKIE could be used to check the user's cookies
<?php
if (isset($_COOKIE["abc"]))
{
  echo '
click here';
}
?>

check http://www.w3schools.com/php/php_cookies.asp

A: You need to check if it is set in the $_COOKIE variable:
<?php
$cookie = abc;
if(isset($_COOKIE[$cookie]))
{
  echo
click here;
}
?>

A: study the php tag $_COOKIE on php.net
and add the "" into the right places.... like: echo "...


text:
Q: Does rowwise distribution of random values in creating a normally distributed vector variable in matrix(rnorm(.), byrow=TRUE) damage normality? (Reprodicible example added) 150-character-limitless full question is:
Does the rowwise distribution of values in creating a normally distributed vector variable via matrix(c(rep(rnorm(100),5)), ncol=5, byrow=TRUE) damages the normality of the component series?
In order to create a vector time series (V1,...,V5) with each component series has 100 obs and Vi~N(0,1), I wrote the following code, and then I suspected whether I made a mistake. If I distributed columnwise, definitely, it obeys the 100x5 values created via rep(rnorm(100),5), and no one can object to that each Vi is N(0,1) since rnorm produces normally distributed values from its definition and Vi series are being set one-to-one with these rnorm products correspondingly.
Question:
But, what if I distributed these 500 random values rowwise instead of columnwise?
1. In that case, is the normality of the component series Vi damaged?
2. Or, their normality is protected but their N(0,1) property is damaged (mean and sd get affected and changes to smt N(mu, sigma2) <> N(0,1))?
set.seed(1)
df <- as.data.frame(matrix(c(rep(rnorm(100),5)), ncol=5, byrow=TRUE))
df # class(df)=data.frame
#       V1       V2           V3          V4        V5
# 1  -0.6264538 0.1836433 -0.8356286 1.5952808  0.3295078
# ...
# 100  0.55848643 -1.27659221 -0.573265414 -1.22461261 -0.4734006

So, byrow=TRUE in the above code very dangerous or not?
What I did:
colMeans(df)
#          V1          V2          V3          V4          V5
#  0.32352799 -0.09161396  0.20740551 -0.15577361  0.26089091
sapply(df, sd) # std deviations of each column in the dataframe
#   V1        V2        V3        V4        V5
# 0.8957992 0.7092927 0.7919241 1.0210549 0.9314092

set.seed(1)   # byrow=FALSE is the default for matrix
df2 <- as.data.frame(matrix(c(rep(rnorm(100),5)), ncol=5, byrow=FALSE))
colMeans(df2) # column means of each column in the dataframe
#   V1        V2        V3        V4        V5
# 0.1088874 0.1088874 0.1088874 0.1088874 0.1088874
sapply(df2, sd) # std deviations of each column in the dataframe
#   V1        V2        V3        V4        V5
# 0.8981994 0.8981994 0.8981994 0.8981994 0.8981994

A: matrix(c(rep(rnorm(100),5)), ncol=5, byrow=FALSE) isn't doing what you probably think it does. It's not drawing 500 normal variates and placing them into a matrix with 5 columns. Rather, it's drawing 100 normal variates, replicating them 5 times, and filling the matrix with those replicated values. With byrow = FALSE, the columns are identical. With byrow = TRUE, every consecutive 20x5 submatrix will be identical (composed of those 100 values in order spread accross the 5 columns).
If you want to fill a 5-column matrix with 500 normal variates, 100 for each column, you need to draw 500 variates and then fill the matrix with them, as follows:
matrix(rnorm(5*100), ncol=5)

It doesn't matter whether you set byrow to TRUE or FALSE. Every subset of values in this matrix will be normally distributed (assuming the values themselves are not used in the subsetting).

A: set.seed(1)
df <- as.data.frame(matrix(rnorm(5*100, 10, 5), ncol=5)) # N=5*100; mean=10; sd=5
df # class(df)=data.frame
colMeans(df)   # The mean of each Vi column in the dataframe
#    V1          V2        V3         V4       V5
# 10.544437  9.810960 10.148368 10.258009  9.804329

sapply(df, sd) # The sd of each Vi column in the dataframe
# If NAs had existed in the dataframe, na.rm = TRUE must have been added
#       V1        V2     V3     V4        V5
# 4.490997 4.789395 5.171328 4.958376 5.848061

Each subset of values in the normally distributed 5*100=500-array drawn from the population with mu=10 and sigma=5 is normally distributed (if the 500-values themselves are not used in the subsetting).
Each drawing of normally distributed sample of 5*100=500 observations that is drawn from the population with mu=10 and sigma=5 is independent from all the other 500-observation drawings from this population.
No matter how this 500-observation with N(10,5^2) is sliced, and then no matter how partitions are brought togetger and reassembled to form the sample of 500-observation is irrelevant (if the 500-value themselves are not used for slicing/collecting).
Because:
In the dim=100x5 matrix, the order and placement of the 500-observation to the cells is essentially random since the 500-observation is randomly selected from the population.
That is to say, in fact, when filling each 100-observationed column variables, we are using the population with mu=10 and sigma=5 (whose number of observations are currently unknown to us), not the 500-observation itself; in a way, we are randomly pulling 100- subobservations from the population with mu=10 and sigma=5, and we are making indirectly rnorm(100,10,5) for each column.
Therefore; the rowwise distribution of values in creating a normally distributed vector variable via matrix(rnorm(5*100), ncol=5, byrow=TRUE) does NOT damage the normality of the component series.
P.S.: Many thanks to Noah.


text:
Q: Why can not I get any row in a MySQL query from SQL Server? The problem I have is that I can not visualize any row with the following query:
SELECT * FROM OPENQUERY ([LINK_MYSQL], 'SELECT * FROM mysql.vw_bd_date;')

The query did not show any error except that it did not throw me any lines either. The consulted view found in MySQL is the following:
create view vw_bd_date
as
SELECT `information_schema`.`TABLES`.`TABLE_SCHEMA` AS `base_de_datos`,MIN(`information_schema`.`TABLES`.`CREATE_TIME`) AS `FECHA_CREACION`
FROM `information_schema`.`TABLES`
WHERE ((`information_schema`.`TABLES`.`TABLE_SCHEMA` NOT IN ('information_schema','sys','mysql','performance_schema','test','test\\_%'))
AND (`information_schema`.`TABLES`.`DATA_LENGTH` IS NOT NULL) AND (`information_schema`.`TABLES`.`INDEX_LENGTH` IS NOT NULL))
GROUP BY `information_schema`.`TABLES`.`TABLE_SCHEMA`

This is the use in a much larger query where I do the join with other views to perform a database inventory, but also as commented, the fields in this particular view throw me NULL.
We tried to do all kinds of cast without success.
Any idea would be very helpful.
Thank you

A: As I'm obviously not even close to proficient in MySQL, my answer won't really focus on that side of your question.  If the view returns what you are expecting from within MySQL, I suspect the issue is on the SQL Server side.  What driver are you using?  If it's the built-in Microsoft driver for MySQL, I would strongly recommend downloading the MySQL Driver from their site and installing that as a new provider on your SQL Server.  When connecting to other RDBMS systems, I have had significantly better luck using the driver provided by the vendor of that application rather than using the generic driver provided by Microsoft.

A: I have found that using openquery requires using UPPERCASE for the object names and field names for the remote database.
This does not work for me:
select * From openquery(kace,' select *  FROM hd_ticket
        where ID in (93,105,124,146,148) ')

While this query does:
select * From openquery(kace,' select *  FROM HD_TICKET
        where ID in (93,105,124,146,148) ')


text:
Q: Disposing a memory stream properly (WPF Image Conversion) Can anyone tell me how to best dispose of a memory stream?  previously, I had this and everything worked fine:
MemoryStream strmImg = new MemoryStream(profileImage.Image);
BitmapImage myBitmapImage = new BitmapImage();
myBitmapImage.BeginInit();
myBitmapImage.StreamSource = strmImg;
myBitmapImage.DecodePixelWidth = 200;
myBitmapImage.DecodePixelWidth = 250;
myBitmapImage.EndInit();
this.DemographicInformation.EmployeeProfileImage = myBitmapImage;

I later realized, that I'm going to have a memory leak as the MemoryStream implements IDisposable and should be disposed of after I use it, which led me to this implementation:
using(MemoryStream strmImg = new MemoryStream(profileImage.Image))
{
    BitmapImage myBitmapImage = new BitmapImage();
    myBitmapImage.BeginInit();
    myBitmapImage.StreamSource = strmImg;
    myBitmapImage.DecodePixelWidth = 200;
    myBitmapImage.DecodePixelWidth = 250;
    myBitmapImage.EndInit();
    this.DemographicInformation.EmployeeProfileImage = myBitmapImage;
}

The Problem is in this line of code:
 myBitmapImage.StreamSource = strmImg;

My assumption is this is referencing the memory location, and the dispose obviously cleans up that location, and it worked in the past because it was never disposed of properly.
My question is, how do I use MemoryStream and dispose it properly after use, while still keeping the converted data (Image) that I need?

A: You need to add this line:
myBitmapImage.CacheOption = BitmapCacheOption.OnLoad;

Which caches the entire image into memory at load time. Without this line, the default value of the CacheOption property is OnDemand which retains access to the stream until the image is needed. So your code should be:
using(MemoryStream strmImg = new MemoryStream(profileImage.Image))
{
    BitmapImage myBitmapImage = new BitmapImage();
    myBitmapImage.BeginInit();
    myBitmapImage.CacheOption = BitmapCacheOption.OnLoad;
    myBitmapImage.StreamSource = strmImg;
    myBitmapImage.DecodePixelWidth = 200;
    myBitmapImage.DecodePixelWidth = 250;
    myBitmapImage.EndInit();
    this.DemographicInformation.EmployeeProfileImage = myBitmapImage;
}


text:
Q: Why am I recieving the error 'document.write can be a form of eval'? This is all I've got going, but my debugger says 'document.write can be a form of eval,' and my jsonString variable prints as undefined. Any help is appreciated, thanks.
function getUrlVars() {
        var map = {};
        var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
                                                 map[key] = value;
                                                 });
        return map;
    }

    var jsonString = getUrlVars()['json'];
    document.write(jsonString);

A: The reason document.write can be a form of eval is because if you write a script element it will be evaluated.
As for why your jsonString is undefined, you probably don't have a parameter named 'json'.


text:
Q: correct method of casting 3D array into 1D array I found multiple questions with almost the same title but none of them have a working code.
so I have the following 1D array a, once I reshape it to 3d array b, and then reshape it back to 1D array.
import numpy as np

depth = 2
row = 3
col = 4

a = np.arange(24)
b = a.reshape((depth, row, col))
c = np.zeros(row*col*depth)

print(a)
print(b)

index = 0

for i in range(depth):
    for j in range(row):
        for k in range(col):
            c[k+ j * row + i * (col*row)] = b[i][j][k]  # ???
            # c[k + row * (j + depth * i)] = b[i][j][k]
            # c[index] = b[i][j][k]
            # index+=1

print(c)

# [ 0.  1.  2.  4.  5.  6.  8.  9. 10. 11.  0.  0. 12. 13. 14. 16. 17. 18.
# 20. 21. 22. 23.  0.  0.]

I don't get Flat[x + WIDTH * (y + DEPTH * z)] = Original[x, y, z] in this case.
EDIT
I am using this code (the equivalent) in a CUDA code, so I need the loops. I am not going to use any numpy magic functions.

A: Simply reshape again to your original dimension or flatten the resulting array:
depth = 2
row = 3
col = 4
a = np.arange(24)
b = a.reshape((depth, row, col))
print(b.reshape((24,)))
print(b.flatten())

Output:
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]

A: That's because the array you created uses row-major order instead of column-major as you assumed
The correct way to compare is
depth = 2
row = 3
col = 4
a = np.arange(24)
b = a.reshape((depth, row, col))
b.strides

i,j,k = np.indices(b.shape)

assert(np.all(a[(i*row+j)*col+k] == b[i,j,k]))

If you want more information on how the matrix is arranged you can check
b.strides = (48, 16, 4), this gives the coefficient (in bytes) of each index, i.e.g (i*48+j*16+k*4) is the offset of the element b[i,j,k].
This is the column-major order is called Fortran order and you can get numpy to reshape assuming it by passing order='F'
bf = a.reshape((depth, row, col), order='F')
assert(np.all(a[i + depth * (j + row * k)] == bf))

Then bf will be
array([[[ 0,  6, 12, 18],
        [ 2,  8, 14, 20],
        [ 4, 10, 16, 22]],

       [[ 1,  7, 13, 19],
        [ 3,  9, 15, 21],
        [ 5, 11, 17, 23]]])


text:
Q: Google cloud virtual instance cannot ping my Mac (checked firewalls) I have a virtual machine instance running on Google Cloud Compute Engine — a preemptible free-tier CPU running Ubuntu 17.04. The end goal is to connect it to a MongoDB running on my local machine, a 2015 Macbook Pro (OS 10.12.6). But first, I've been trying to ensure the VM can reach my Mac via ping.

*

*Running ping <VM's external IP> from my Mac works.

*pinging my Mac from another Mac on the same wifi network works.

*Running ping <Mac's IP> from the VM via the browser terminal does not work.

I've disabled my Mac's firewall. I've also configured my VM's firewall rules to allow all inbound and outbound traffic, to no avail:
ingress firewall rules, egress firewall rules
How might I get this instance to ping my Mac successfully?

A: Does your Mac's IP address begin with 10., 192.168., or between 172.16. and 172.32.? These are private addresses only reachable within your Mac's local network, which is (part of) why GCE cannot reach your VM.
This is part of a very common configuration. An ISP only allocates one (or a small number) of IP addresses to your home or business. A router on the network performs NAT to share that IP addess between computers on the local network, which instead use private IP addresses for themselves.  As the router doesn't know what to do with the inbound MongoDB traffic, it blocks it.
There are two common ways around this that are usually found in your router settings:

*

*"port forwarding" where you tell the traffic to forward all traffic on port 1234 to your Mac. This can get MongoDB working, but not ping.

*If you have whole extra IP addresses, "DMZ" where your router directly forwards an entire extra IP to your instance. If you have only one IP address this is not an option as that IP is needed to be shared for other devices on the Wifi.

You likely also have a firewall on the router. If you use a DMZ or port-forwarding you must make sure that firewall allows traffic through too.

That said, I'm not sure that this is a sensible thing to do. Opening up your local network to the internet can create major security issues, plus it is likely unreliable more expensive (free tier only provides 1GB egress/month, your db traffic could exceed this).
Actually running MongoDB on instances within GCE is almost certainly a better option in every regard for you.


text:
Q: Convert Dictionary to Base64: error Segmentation fault 11 I am trying to create JSON Web Token using JSONSerialization class, Swift 3 and Xcode 8.1, but my project fails to build with error:

Command failed due to signal: Segmentation fault 11.

Anyone knows why my code is not correct?
If I comment out this code from the project, the project builds.
 let customerError = "Custom Error"
 enum headerError: Error {
 case customerError
 }

 let headerJWT: [Dictionary] = ["alg":"RS256","typ":"JWT"]

 //Convert headerJWT to Data
 do {
    let headerJWTData: Data = try? JSONSerialization.data(withJSONObject:headerJWT,options: JSONSerialization.WritingOptions.prettyPrinted)
 } catch headerError.customerError {
        print("could not make data")
 }

 //Convert headerData to string utf8
 do {
    let headerJWTString = try String(data: headerJWTData,encoding:String.Encoding.utf8) as! String
 } catch {
     print("string could not be created")
 }

 //Convert headerJWTString to base64EncodedString
 do {
    let headerJWTBase64 = try Data(headerJWTString.utf8).base64EncodedString()
 } catch {
"base64 could not be created"
 }

A: Once you create the Data from using JSONSerialization, you simply use the method from Data to get a base64 encoded string.
let headerJWT: [Dictionary] = ["alg":"RS256","typ":"JWT"]

do {
    let headerJWTData: Data = try? JSONSerialization.data(withJSONObject:headerJWT,options: JSONSerialization.WritingOptions.prettyPrinted)
    let headerJWTBase64 = headerJWTData.base64EncodedString()
} catch headerError.customerError {
    print("could not make data")
}

You can pass different options to base64EncodedString() depending on what format you need the base64 string to be in.


text:
Q: Add UIBarButtonItem action programmatically on iOS I have several UIBarButtonItems, and I want to set the action when you press it programmatically. How can I do this?
EDIT: if it would be possible non-programmatically, please also reply :)
The action is going to Google.com, and the button is the search button in this project: (download): click here

A: First create an outlet to the items in IB.  Then you can modify the methods called by using [myItem setTarget:] and [myItem setAction:].
See target action
ETA:  Is there any particular reason you want to do it programmatically?
ETAA:  To do it non-programmatically, make a function with return type IBAction, and argument (id)sender, like so:
- (IBAction)myMethod:(id)sender;

With whatever implementation you like.  Then, in IB, drag an object object from the Library to the MainWindow.xib window, and in the identity window (cmd-6), give it the class that has your function.  Then, in the connections window of that object (cmd-5), you can drag from your function name to whichever interface object you want.
I strongly suggest you read mac dev on IB.  The connections and bindings section will discuss this particular issue.


text:
Q: Snubber Capacitor Voltage Rating in the Real World What are voltage ratings for the capacitors inside the common off the shelf ac snubber networks, such as 0.1uF + 100 Ohm ?
It would seem that larger inductive loads can easily drive the capacitor voltage into the kilovolts. Is it ok because it only lasts a short time?
I am more interested in the real world practices than in theory. I don't know how many people in the field actually try to find or measure the load inductance and current to calculate the capacitor voltage before grabbing a snubber and wiring it in. Or is it common practice?
It is not obvious from datasheets what actual voltage ratings are on the capacitors inside those snubber networks. It is only stated for the networks themselves. And I have not taken one apart.
This applies as well to the numerous snubber examples on the web. Almost none mention capacitor voltage, only capacitance.

A: You are forgetting the capacitor is, well, a capacitor. In order to get it up to failure voltage you need to charge it up that high.
When the switch opens the voltage across the capacitor will not change instantaneously like the coil voltage does. Instead, the current in the coil passes trough the resistor to charge the capacitor. The voltage across the coil is therefor limited. The energy from the coil is then dissipated through the resistor and into the capacitor.
The capacitance then needs to be large enough to absorb the energy in the coil without exceeding it's rated voltage.


text:
Q: How to make radio buttons appear in react.js I want to make a form with radio-buttons but the radio-button does not appear only the label appears
const PollOption = ({ selected, onChange }) => {
return (

    {YES_NO.map((choice, id) => (

        {YES_NO[id].question}
        {choice.choice.map((choices, i) =>(

                <input type="radio"
                    name={YES_NO[id].question}
                    value={choice.choice[i].text}
                    checked={selected === choice.choice[i].text}
                    onChange={onChange} />
                {choice.choice[i].text}

            ))}

    ))}

);
};

A: It appears that it was a single line that gave me some trouble:
checked={selected === choice.choice[i].text}

Removing it and my radiobuttons work as they where supposed to.


text:
Q: Custom post type and custom taxonomy with the same slug using the file page taxonomy only as directory I´m new in Stackexchange and my English is very bad but i will try explain myself as best I can.
I´m creating in wordpress a new web page and i need to get this urls structure with Custom post type and taxonomies:
My CPT is => cpt_noticias with rewrite slug = 'blog'
My CUSTOM Taxonomy is => category_cpt_noticias with rewrite slug = 'blog'

Well! This is the structure that i need
mydomain.com/blog  => ARCHIVE BLOG
mydomain.com/blog/name-taxonomy => ARCHIVE taxonomy
mydomain.com/blog/slug-post => single page of custom post type

My problem is that when I go to "mydomain.com/blog/slug-post" this return an error 404. I don`t know the cause of this.
Can you help me please? :)

My code of custom post type is here:
// creating (registering) the custom type
register_post_type( 'cpt_noticias', /* (http://codex.wordpress.org/Function_Reference/register_post_type) */

    // let's now add all the options for this post type
    array( 'labels' => array(
            'name' => __( 'Blog', 'pew' ),
            /* This is the Title of the Group */

            'singular_name' => __( 'Noticia', 'pew' ),
            /* This is the individual type */

            'all_items' => __( 'Todos los Noticias', 'pew' ),
            /* the all items menu item */

            'add_new' => __( 'Añadir nuevo', 'pew' ),
            /* The add new menu item */

            'add_new_item' => __( 'Añadir nuevo Noticia', 'pew' ),
            /* Añadir nuevo Display Title */

            'edit' => __( 'Editar', 'pew' ),
            /* Edit Dialog */

            'edit_item' => __( 'Editar Noticias', 'pew' ),
            /* Edit Display Title */

            'new_item' => __( 'Nuevo/a Noticia', 'pew' ),
            /* New Display Title */

            'view_item' => __( 'View Noticia', 'pew' ),
            /* View Display Title */

            'search_items' => __( 'Buscar Noticia', 'pew' ),
            /* Search Custom Type Title */

            'not_found' =>  __( 'No se han encontrado Noticias en la base de datos.', 'pew' ),
            /* This displays if there are no entries yet */

            'not_found_in_trash' => __( 'No hay Noticias en la papelera', 'pew' ),
            /* This displays if there is nothing in the trash */

            'parent_item_colon' => ''
        ),

        'description'               => __( 'Esto es un ejemplo de Noticia', 'pew' ), /* Custom Type Description */
        'public'                    => true,
        'publicly_queryable'        => true,
        'exclude_from_search'       => false,
        'show_ui'                   => true,
        'query_var'                 => true,
        'menu_position'             => 5, /* this is what order you want it to appear in on the left hand side menu */
        'menu_icon'                 => 'dashicons-format-aside', /* the icon for the custom post type menu */
        'capability_type'           => 'page',
        'rewrite'                   => array( 'slug' => 'blogj', 'with_front' => true ),
        'has_archive'               => true, /* you can rename the slug here */
        'hierarchical'              => true,
        'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'sticky')

    )
);

flush_rewrite_rules();
register_taxonomy_for_object_type( 'category_cpt_noticias', 'cpt_noticias' );

register_taxonomy( 'category_cpt_noticias',
    array('cpt_noticias'), /* if you change the name of register_post_type( 'custom_type', then you have to change this */
    array(
        'labels' => array(
            'name' => __( 'Categorías de noticias', 'pew' ), /* name of the custom taxonomy */
            'singular_name' => __( 'Categoría de noticia', 'pew' ), /* single taxonomy name */
            'search_items' =>  __( 'Buscar Categorías de noticias', 'pew' ), /* search title for taxomony */
            'all_items' => __( 'Todas Categorías de noticias', 'pew' ), /* all title for taxonomies */
            'parent_item' => __( 'Padre Categorías de noticias', 'pew' ), /* parent title for taxonomy */
            'parent_item_colon' => __( 'Padre Categorías de noticias:', 'pew' ), /* parent taxonomy title */
            'edit_item' => __( 'Editar Categorías de noticias', 'pew' ), /* edit custom taxonomy title */
            'update_item' => __( 'Crear Categoría de noticia', 'pew' ), /* update title for taxonomy */
            'add_new_item' => __( 'Añadir nuevo Categoría de noticia', 'pew' ), /* Añadir nuevo title for taxonomy */
            'new_item_name' => __( 'Nuevo/a Categoría de noticia', 'pew' ) /* name title for taxonomy */
        ),
        'public'             => true,
        'hierarchical'       => false,
        'show_ui'            => true,
        'query_var'          => true,
        'show_admin_column'  => false,
        'show_in_rest'       => true,
        'rest_base'          => '',
        'show_in_quick_edit' => false,
        'rewrite' => array(
          'slug'                => 'blogj',
          'with_front'          => true,
          'has_archive'         => false,
          'hierarchical'        => true,
        ),

    )
);

add_action( 'init', 'custom_post_cpt_noticias');


text:
Q: MIUI not detecting ".app" as a link on QR Code I'm building an app that involves generating QR codes with a certain link (eg: mywebsite.app/cLKXz).
Everything works fine on stock android, Samsung, and Apple.
But MIUI's integrated scanner simply doesn't recognize a .app domain as a link, which causes the user to have to copy the text and paste it on their browser, instead of being able to simply tap "Open Link".
Is there any way I can "force" this QR Code to be detected as a link no matter what's inside? Of course I'd like to keep my domain and avoid using another URL shortener such as Bitly, if possible.
EDIT
I already tried adding http://, https://, and www., but nothing seems to work.
Thanks a lot!

A:
mywebsite.app/cLKXz

Prefix your URL with protocol like http:// or https://

A: It's a little late for the answer  but it's an issue of the native QR reader.
See: https://c.mi.com/oc/thread-3359510-1-0.html
Same problem occurs when using domains ending with:

*

*.cloud

*.link


text:
Q: Nest for each loop from two arrays where row of first loop signals next loop my main objective is to make a collapsible table in php/css/javascript (That I think I have sorted) but I am a little confused as to how to run a for each loop inside another (maybe a while loop?) so that it breaks out of the second loop. Basically, I have data in one array, and can use one of the values in the first array to get values from rows in the second array where they have the same value. Something like this;
Category 1
 - Book Name 1 - Author 3 - Date 1
 - Book Name 2 - Author 3 - Date 3
 - Book Name 4 - Author 2 - Date 4
 - Book Name 7 - Author 2 - Date 3
Category 2
 - Book Name 3 - Author 1 - Date 2
 - Book Name 5 - Author 3 - Date 1
 - Book Name 8 - Author 1 - Date 5
 - Book Name 9 - Author 5 - Date 1

my first array has basic info;
([0] => Array [Category]=>Category 1 [subscribers]=>13 [reads]=>4)
([1] => Array [Category]=>Category 2 [subscribers]=>13 [reads]=>4)

and my second array is set up with rows like this:
([0] => Array [Category]=>Category 1 [Name]=>Book Name 1 [Author]=>Author 3[Date]=>Date 1)
([1] => Array [Category]=>Category 1 [Name]=>Book Name 2 [Author]=>Author 3[Date]=>Date 3)
([3] => Array [Category]=>Category 2 [Name]=>Book Name 3 [Author]=>Author 1[Date]=>Date 2)
etc...

The common factor I can call is the category, so if I set it as a variable in the first while loop, would something like this work?
foreach (array1['category'] as $item){
$category = array1['category']

     while(array2['category'] = $category){
     //do stuff
}
}

FWIW I try to make my questions as generic as possible so other people can use them to adapt to their code more readily.

A: Use foreach loops, not while.
echo "
";
foreach ($array1 as $item1) {
    $category = $item1['Category'];
    echo "
$category
";
    foreach ($array2 as $item2) {
        if ($item2['Category'] == $category) {
            echo "
{$item2['Name']} - {$item2['Author']} - {$item2['Date']}
";
        }
    }
    echo "

";
}
echo "
";


text:
Q: Nested inner joins with select sql access I have two similar questions and I think this is similar to what I need but I can't figure out what it would look like in my cases
1.
I have three tables where the field dID connects fd to d and dm to d:
`fd`: `fID`, `dID` (`fID` and `dID` create the pk together)
`d`: `dID` (pk), `data`
`dm`: `dID`, `type` (`dID` and `type` create the pk together)

I am looking for a way to find all records in d that fulfill fID = 'condition1 AND type = 'condition2'
Right now I have solved it in the following way (it works, but it is very ugly so I would like to have a nicer solution)
Q1: SELECT dID FROM fd WHERE fID = 'condition1'
Q2: SELECT dID FROM dm WHERE type = 'condition2'

SELECT * FROM d WHERE d.dID IN
(SELECT Q1.dID FROM Q1 INNER JOIN Q2 ON Q1.dID = Q2.dID)

2.
Now I have three tables again. mID connects tm to m and typeID connects m to types:
<br>
`tm`: `tmID`, `mID` (pk together)
`m`: `mID` (pk), `mnum`, `typeID`
`types`: `typeID` (pk), `type`

So here I am looking for a way to select type from types and mnum from m when I have a condition on tmID
The following is not correct because I want to be able to select mnum and type at the same time like: SELECT types.type, m.mnum FROM ..... But basically I want to do these selections
Q1: SELECT mID FROM tm WHERE tmID = 'condition3'
Q2: SELECT mnum, typeID FROM m WHERE m.mID IN Q1
Q3: SELECT type FROM types WHERE typeID IN Q2

A: For your first query you just have to merge the conditions into one single query:
SELECT dID FROM fd WHERE fID = 'condition1' AND type='condition2'

For the second query, you can join all three tables together and apply the condition:
SELECT types.type
FROM tm INNER JOIN (m INNER JOIN types ON m.typeID = types.typeID) ON tm.mID = m.mID
WHERE tm.tmID='condition3';


text:
Q: How to test injected mock with try-catch I'm doing simple unit test by using mockMvc with springboot. SampleCtrl.java is origin source code and SampleCtrlTest.java is test source code. There are 3 mocks injected to SampleCtrl and they are working well except SampleService class. As you can see, SampleService wrapped with try-catch block. So, I have no idea how to call the method in mock class to get return or throw exception in test source code.
I removed try-catch block in origin code, also given() method in test code. It worked well. That's why I think the try-catch block is undoubted reason to make error.
SampleCtrl.java
@PostMapping(path = "/save", consumes = "application/json")
@ResponseBody
public ResponseEntity<Map<String, Object>> setEmp(@RequestBody
List<EmpSaveVo> vos) {

    result.clear();
    try {
        msg = service.setEmp(vos);
    } catch (Exception e) {
        msg = e.getMessage();
    }
    result = messageTrans.getMapLang(msg);

    return messageReturn.getRestResp(result, msg);
}

SampleCtrlTest.java
private MockMvc mockMvc;

@Mock
private SampleService service;

@Mock
private MessageTrans messageTrans;

@Mock
private MessageReturn messageReturn;

@InjectMocks
private SampleCtrl sampleCtrl;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    mockMvc = MockMvcBuilders.standaloneSetup(sampleCtrl).build();
}

@Test
public void givenEmployeeDataWhenPostEmpSave() throws Exception {
    List<EmpSaveVo> empSaveVos = new ArrayList<>();
    EmpSaveVo empSaveVo = new EmpSaveVo();
    empSaveVo.setEmployeeId(100L);
    empSaveVo.set_status((long) Status.Modified.getStatus());
    empSaveVos.add(empSaveVo);

    Gson gson = new Gson();
    String element = gson.toJson(empSaveVos);

    String msg = "Test";

    Map<String, Object> result = new HashMap<>();
    result.put("message", msg);

    given(service.setEmp(empSaveVos)).willThrow(new Exception());
    given(messageTrans.getMapLang(msg)).willReturn(result);
    given(messageReturn.getRestResp(any(), anyString()))
    .willReturn(new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK));

    mockMvc.perform(post("/api/emp/save")
            .content(element)
            .contentType(MediaType.APPLICATION_JSON)).andDo(print())
            .andExpect(status().isOk());
}

Consequently, I want to see this console log.
MockHttpServletResponse:
           Status = 200
    Error message = null
              Headers = [Content-Type:"application/json;charset=UTF-8"]
     Content type = application/json;charset=UTF-8
              Body = {"message":"Test"}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []


text:
Q: -Unity- providing feedback hints in order regardless of which wrong button was clicked I'm an educational researcher developing a game for my doctoral program. I'm learning on the go with tutorials and forums.
I have this scene with quiz panels (i.e., 4 buttons - 1 correct answer and 3 wrong ones)
I would love to know how to provide the feedback hints in order regardless of which wrong button was clicked.
These are some pics of the panel and the code I currently have.
Question Panel Image with canvas elements
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;

 public class PPLQuizManager : MonoBehaviour
 {

 public GameObject HNSCanvas;

 [Header("PPL Left Panel")]
 public GameObject PPLLeftPanel;
 public RectTransform PPLParentLeftPanel;

 public GameObject PPLTextBox;
 public GameObject PPLContinue;
 public GameObject PPLReturn;

 //Pictures that illustrate the tutor's reaction

 public List<Sprite> questionimages;

 public List<Sprite> HintImages;

 public List<Sprite> CorrectImages;

 public GameObject PPLStringImages;

 [Header("PPL Right Panel")]
 public GameObject PPLRightPanel;

 public GameObject PPLChoice1;
 public GameObject PPLChoice2;
 public GameObject PPLChoice3;
 public GameObject PPLChoice4;
 public int PPLChoiceMade;

 [Header("PPL Bottom Panel")]
 public GameObject PPLBottomPanel;

 public GameObject PPLHint1TextBox;
 public GameObject PPLHint2TextBox;
 public GameObject PPLHint3TextBox;
 public GameObject PPLWinTextBox;
 public GameObject PPLHintPic;
 public GameObject PPLBadge;
 public GameObject PPLMedalPic;

 [Header("PPL Center Panel")]
 public GameObject PPLCenterPanel;

 public GameObject PPLHintPic1;
 public GameObject PPLHintPic2;
 public GameObject PPLHintPic3;
 public GameObject PPLWinPic;

 public void PPLChoiceOption1()
 {

     PPLChoice1.GetComponent<Button>().interactable = false;
     PPLTextBox.GetComponent<Text>().text = "Read the hint. Try again.";
     showRandomHintImage();
     PPLChoiceMade = 1;

 }

 public void PPLChoiceOption2()
 {
     PPLChoice2.GetComponent<Button>().interactable = false;
     PPLTextBox.GetComponent<Text>().text = "Congratulations!";
     showRandomCorrectImage();
     PPLChoiceMade = 2;

 }

 public void PPLChoiceOption3()
 {
     PPLChoice3.GetComponent<Button>().interactable = false;
     PPLTextBox.GetComponent<Text>().text = "Here's a hint!";
     showRandomHintImage();
     PPLChoiceMade = 3;

 }

 public void PPLChoiceOption4()
 {
     PPLChoice4.GetComponent<Button>().interactable = false;
     PPLTextBox.GetComponent<Text>().text = "Hint time. Go for it!";
     showRandomHintImage();
     PPLChoiceMade = 4;

 }

     public void showRandomQuestionImage()
     {
             int count = questionimages.Count;
             int index = Random.Range(0, count);
             Image image1 = PPLStringImages.GetComponent<Image>();
             image1.sprite = questionimages[index];
     }

     public void showRandomCorrectImage()
     {
         int count = CorrectImages.Count;
         int index = Random.Range(0, count);
         Image image2 = PPLStringImages.GetComponent<Image>();
         image2.sprite = CorrectImages[index];
     }

     public void showRandomHintImage()
     {
         int count = HintImages.Count;
         int index = Random.Range(0, count);
         Image image3 = PPLStringImages.GetComponent<Image>();
         image3.sprite = HintImages[index];
     }

 private void Start()
 {
         showRandomQuestionImage();

 }

 // Update is called once per frame
 void Update()
 {
    //check the rest of this post
 }
 }

What I did to have it functional is to assign each hint to a certain wrong answer button. But this method will not be interesting for my research, especially because the 3rd hint is practically an answer giveaway. So, if a student clicks on a wrong answer that I manually assigned the 3rd hint to be in, they will get the answer on a silver platter, and my data be crappy. = (
Just to remember: I need to display hints 1, 2, and 3 in order regardless of which wrong button the students clicks.

EXTRA REQUEST = ) : Is there a way to manage these panel game objects in a more economical and effective way?
// Update is called once per frame
 void Update()
 {
         //PPL buttons and answer management
         if (PPLChoiceMade == 1)
         {

             PPLCenterPanel.SetActive(true);
             PPLHintPic1.SetActive(true);
             PPLHintPic2.SetActive(false);
             PPLHintPic3.SetActive(false);

             PPLHint1TextBox.SetActive(true);
             PPLHint2TextBox.SetActive(false);
             PPLHint3TextBox.SetActive(false);

         }

         if (PPLChoiceMade == 2)
         {

             PPLCenterPanel.SetActive(true);
             PPLHintPic1.SetActive(false);
             PPLHintPic2.SetActive(false);
             PPLHintPic3.SetActive(false);
             PPLWinPic.SetActive(true);

             PPLChoice1.SetActive(false);
             PPLChoice2.SetActive(true);
             PPLChoice3.SetActive(false);
             PPLChoice4.SetActive(false);

             PPLContinue.SetActive(true);
             PPLReturn.SetActive(false);

             PPLWinTextBox.SetActive(true);
             PPLHint1TextBox.SetActive(false);
             PPLHint2TextBox.SetActive(false);
             PPLHint3TextBox.SetActive(false);

             PPLBadge.SetActive(true);
             PPLMedalPic.SetActive(true);

         }

         if (PPLChoiceMade == 3)
         {

             PPLCenterPanel.SetActive(true);
             PPLHintPic1.SetActive(false);
             PPLHintPic2.SetActive(true);
             PPLHintPic3.SetActive(false);

             PPLHint1TextBox.SetActive(false);
             PPLHint2TextBox.SetActive(true);
             PPLHint3TextBox.SetActive(false);

         }

         if (PPLChoiceMade == 4)
         {

             PPLCenterPanel.SetActive(true);
             PPLHintPic1.SetActive(false);
             PPLHintPic2.SetActive(false);
             PPLHintPic3.SetActive(true);

             PPLHint1TextBox.SetActive(false);
             PPLHint2TextBox.SetActive(false);
             PPLHint3TextBox.SetActive(true);

         }

Any help will be highly appreciated!! (especially because I've already burned tons of neurons trying to figure it out myself... Lol!)

A: To answer your extra request make a parent container object and place all your containers within that parent and then loop through them in this fashion
public GameObject hintBoxContainer;

private List<GameObject> hintBoxes = new List<GameObject>();

private void Start(){
  for(int i =0; i < hintBoxContainer.transform.childCount; i++){
    hintBoxes.Add(hintBoxContainer.transform.getChild(i).gameObject);
  }
}

private void Update(){
  if(PPLChoiceMade == 1){
    //Since we know the first hintbox is at the index of 0
    for(int i =0; i < hintBoxes.Count; i++){
      if(i == 0){
        hintBox[i].SetActive(true);
      }else{
        hintBox[i].SetActive(false);
      }
    }
  }
}

As an extra note
You should create a separate function for initializing the list so you do not crowd your start function as well as break down whats inside the update into functions so you keep your code clean and modular. Remember to take some time to optimize and keep optimization and modular design techniques in mind I have had many projects fall apart in my early days by designing my systems fast instead of "right" :)

A: Let's take a look at this in pseudocode
if student clicks wrong
    Increment the number of times they have given wrong answers by 1
    What number of incorrect answers have they given?
        if 1 then display hint 1
        if 2 then display hint 2
        if 3 then display hint 3
    Allow them to answer again

You'll need a few things given this pseudcode:

*

*A counter to keep track of the number of wrong answers given
public int numberOfWrongAnswers = 0;

*An array (or list) of hints in order to be given
public string[] hints;

*An array containing references to your buttons
public GameObject[] answerButtons;

*A generic method to determine which button was pressed
public void PPLChoiceOption(int selection)
From this, I would make your method like this
public void PPLChoiceOption(int selection)
{
    buttons[selection].GetComponent<Button>().interactable = false;
    PPLTextBox.GetComponent<Text>().text = hints[numberOfWrongAnswers - 1];
    showRandomHintImage();
    PPLChoiceMade = selection;
}

Make sure that you change the reference on your buttons to point to this method and put a 0 in the parameter for the first button, 1 for the next, etc.


text:
Q: Facebook: Posting to my own wall through the API I want my application to post to a single, pre-defined user's wall something like "We just posted a new blog at [URL]" with no client-side interaction.
But every answer I can find on this topic seems to hinge on getting an access token through
https://graph.facebook.com/oauth/access_token

Which gives you some redirect url through which a user has to log in manually.
I've got near zero experience with Facebook. Is it possible to automatically get an access token for a predefined user? Am I doing it wrong? ;)

A: You can't.
Facebook doesn't give you a way to automatically get an access token for a user. That user needs to log into Facebook and explicitly give your app permission. The best you can get is a long-lived access token that remains valid for up to 60 days.
Getting that token requires a two step process:
1) Logging into Facebook using either the JavaScript API or redirecting the user to a valid Facebook login URL.
2) Retrieving the short-lived access token you got in step 1 for a long-lived access token.
Once you've got that access token, should your post fail, you know you need to re-authenticate the user and get a new long-lived access token. Your user needs to be online and logged into Facebook for this to work, though it can happen without their interaction.


text:
Q: ORA-12154: Can't Connect to Default Oracle XE 21c Database on Windows 10 I've had it. I just can't get this to work. I installed Oracle XE 21c on my Windows 10 desktop. The installation went ok, once I ran the Setup file as an administrator. I basically chose all the defaults.
So now it is running, and there was a default database XE create for me. But I get this when attempting to connect as SYSTEM using SQLPlus:

SQL*Plus: Release 21.0.0.0.0 - Production on Mon Nov 1 19:08:25 2021
Version 21.3.0.0.0

Copyright (c) 1982, 2021, Oracle.  All rights reserved.

Enter user-name: SYSTEM
Enter password:
ERROR:
ORA-12154: TNS:could not resolve the connect identifier specified

I looked and there is no tnsnames.ora or listern.ora file, so I attempted to create them, though I am not sure they are correct.
C:\app\sysde\product\21c\dbhomeXE\network\admin\listener.ora
LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    )
  )

C:\app\sysde\product\21c\dbhomeXE\network\admin\tnsnames.ora
LISTENER = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))

XE = (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = XE)
    )
  )

I then stopped the listener as follows lsnrctl stop
which yielded this:
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1)))
TNS-12541: TNS:no listener
 TNS-12560: TNS:protocol adapter error
  TNS-00511: No listener
   64-bit Windows Error: 2: No such file or directory
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))
TNS-12541: TNS:no listener
 TNS-12560: TNS:protocol adapter error
  TNS-00511: No listener
   64-bit Windows Error: 61: Unknown error

The listener OracleOraDB21Home1TNSListener is no longer running in services.msc. When trying to restart it I get this...
Error 2: The system cannot find the file specified.

My environment variables are:
  ORACLE_HOME=C:\app\sysde\product\21c\dbhomeXE\
  TNS_ADMIN=C:\app\sysde\product\21c\dbhomeXE\network\admin

I know there are numerous "Can't connect to Oracle" posts. I've tried bits and pieces of them, but none are really suited to my situation and the parts I've tried simply haven't helped. Any suggestions you have to allow me to use the default XE database and connect to it through a GUI such as SQL Developer would be tremendously helpful.

A: As per the docs, from 21c onwards the default software installation is the read only home layout, which has been available since 18c
https://docs.oracle.com/en/database/oracle/oracle-database/21/nfcon/read-only-oracle-home-default-366970591.html
So by default the sqlnet configuration files are not going to be under ORACLE_HOME/network/admin.
C:\oracle\product\21c\dbhomeXE\network\admin>dir
 Volume in drive C is System
 Volume Serial Number is EEB1-910D

 Directory of C:\oracle\product\21c\dbhomeXE\network\admin

13/10/2021  10:53 AM    <DIR>          .
13/10/2021  10:53 AM    <DIR>          ..
13/10/2021  10:51 AM    <DIR>          sample
13/10/2021  10:52 AM               263 sqlnet.ora.rooh
               1 File(s)            263 bytes
               3 Dir(s)  78,346,031,104 bytes free

C:\oracle\product\21c\dbhomeXE\network\admin>cd ..\..\..\homes\OraDB21Home1\network\admin

C:\oracle\product\21c\homes\OraDB21Home1\network\admin>dir
 Volume in drive C is System
 Volume Serial Number is EEB1-910D

 Directory of C:\oracle\product\21c\homes\OraDB21Home1\network\admin

13/10/2021  10:54 AM    <DIR>          .
13/10/2021  10:54 AM    <DIR>          ..
13/10/2021  10:53 AM               656 listener.ora
13/10/2021  10:53 AM               465 sqlnet.ora
13/10/2021  10:53 AM               263 sqlnet21101310AM5351.bak
13/10/2021  02:51 PM               852 tnsnames.ora
               4 File(s)          2,236 bytes
               2 Dir(s)  78,345,871,360 bytes free

You don't need to set ORACLE_HOME or TNS_ADMIN. You just need to edit the files in the 'homes' area and you'll be good to go.
A complete top to bottom install video is available here from the Windows team
https://youtu.be/DYleroLay5E

A: OracleXE21 default path for tnsnames.ora and sqlnet.ora has been changed in Express Edition 21c. The new path will be like this: C:\oracle\product\21c\homes\OraDB21Home1\network\admin
and there where you will find tnsnames.ora and sqlnet.ora.


text:
Q: PHP MySQL detect if the same user is already logged in I have a login system and now I want to add a function that warns the user if the user is already logged in. I don't want to prevent the login, I want to let the user in, but after the user logged in, a message should appear which is warns the user because someone else is currently logged in.
I tried to make it with session_id, but it prevented the user, and when I logged out from my account, I can't logged in back, because the session_id was NULL.
I added the session_in to my authenticate.php file, so it can check if the user is even valid or not. And if the user is valid, set the session-id value to the current session's id (session_id()). But I don't know how to continue the code. Any help?
authenticate.php:
//connect to database...
if (username & password is correct) {
   $session_id = session_id();
   $qry = mysqli_query($con, "UPDATE accounts SET session-id='$session_id' WHERE id = '$id'");
}

index.php:
if (user is not logged in) {
   go to login page
}

if ($session_id == session_id()) {
  echo "you are already logged in with this user. Log out that user?";
}

logout.php:
//connect to database...
$resid=mysqli_query($link,"UPDATE accounts SET session-id='' where id='$_SESSION[id]'");
session_destroy();


text:
Q: URL.Action link is not build correctly when creating anchor tag I'm building an anchor link using Url.Action in my view.
When built, it does not contain controller method:
function showDetails(data) {

    var link = "@Url.Action("Index", "Detail")" + "/" + data;
    var returnText = "" + data + "";

    return returnText;
}

When displaying the link in console: console.log(link), it gives me /Detail/123 instead of /Detail/Index/123
This is how the routing is defined in the RouteConfig.cs
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Login", action = "Index", id = UrlParameter.Optional }
    );

I added the following per your suggestion befor Default route
    routes.MapRoute(
        name: "TicketDetail",
        url: "Detail/Index/{data}",
        defaults: new {controller = "Detail", action = "Index", data  =UrlParameter.Optional }
    );

What am I missing?

A: Well you have a combination of problems.  First

it gives me /Detail/123 instead of /Detail/Index/123

Because Index is the default route so /Detail is actually 100% correct.
//                                            Default = Index
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

There is no reason to add Index to the URL as Asp.Net sees it.  It does add Detail because Detail != Home.  If you changed the default to Detail it would give you just /.  If you want to force the url you can create your own helper (from the duplicate question/answer).
public static string AbsoluteAction(this UrlHelper url,
  string actionName, string controllerName, object routeValues = null)
{
  string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;

  return url.Action(actionName, controllerName, routeValues, scheme);
}

You can then simply use it like that in your view:

@Url.AbsoluteAction("Action", "Controller")

Secondly, because you are adding data on the client side as a path parameter instead of query parameter it doesn't work.  You could keep your code exactly as is if you did:
var link = "@Url.Action("Index", "Detail")" + "?id=" + data;

or
var link = "@Url.Action("Index", "Detail")" + "?data=" + data;

not sure what your method is expecting because you didn't include it in the relevant code.

A: You are missing nothing, the problem is the default route registered by the ASP.NET.
I don't know which version you are using, but in my example I used ASP.NET MVC4 VS2015, and in the file RouteConfig.cs on method RegisterRoutes there is the default route registered, in some versions you will find this code on the Startup.cs.
Note the code bellow:
  routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

The default value for te action parameter in an URL {action} is "Index", so ASP.NET assumes that if you suppress this value you are inferring you want to access this action, so it follow the rule suppressing the default values from URL to understanding unnecessary.
To solve your problem you can register a new route as the following code:
routes.MapRoute(
            name: "DetailUrl",
            url: "Detail/Index/{data}",
            defaults: new { controller = "Detail", action = "Index", data = UrlParameter.Optional }
        );
routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

The ASP.NET will generate the linked based on the first match rule.


text:
Q: delete rows where two columns concatenation is duplicated Table teh - 1400 rows.
I want to delete rows having col1 and col2 duplicated.
For example - if col1 is lorem and col2 is ipsum
and some next row also - col1 is lorem and col2 is ipsum
this next row should be deleted.
Here is the code I'm using and can't see what is wrong because the final result is - only one row is remaining, all others are deleted.
The table has at least half unique rows regarding col1 and col2 concatenation.
$st = $db->query("select id, col1, col2 from teh");
$st->execute();
$arr = $st->fetchAll();
$check = [];
foreach($arr as $el){
    $str = $el['col1'] . $el['col2'];
    if(in_array($str, $check)){
        $sql = "delete from teh where id = :aid";
        $st = $db->prepare($sql);
        $st->execute([":aid" => $el['id']]);
    }
    else{
        array_push($check, $str);
    }
}

A: If you want to delete rows with higher id but the same col1 and col2 values, you can simply DELETE rows where a matching row exists with a lower id value
DELETE
t1
FROM teh t1
JOIN teh t2 ON t2.col1 = t1.col1 AND t2.col2 = t1.col2 AND t2.id < t1.id

Demo on dbfiddle

A: Try something like this:
$st = $db->query("select id, col1, col2 from teh");
$st->execute();
$arr = $st->fetchAll();
foreach($arr as $el){
    $sql = "delete from teh where col1 = acol1 and col2 = acol2 and id <> aid";
    $st = $db->prepare($sql);
    $st->execute([":acol1" => $el['col1'], ":acol2" => $el['col2'], ":aid" => $el['id']]);
}

The idea is to delete all the rows with the same values than the row you are checking at that moment but the id value is different. No need to concatenate and save it to an array this way.

A: In case you are following a logic, I think you can do it without using a loop. If you want to delete duplicate records, you can do the following steps.

*

*Get id of unique records (just use one-dimensional array return for this)
$sql = "SELECT id FROM teh GROUP BY col1, col2;";
$stmt = $db->prepare($sql);
$stmt->execute();
$result = $stmt->fetchColumn();

*Use implode to convert array to string
$toString = implode(",",$result);

*delete records that are not in the list. (the result of the query above)
$sql = "DELETE FROM teh where id NOT IN ({$toString});";
$stmt = $db->prepare($sql);
$stmt->execute();
To complete it:
$sql = "SELECT id FROM teh GROUP BY col1, col2;";
$stmt = $db->prepare($sql);
$stmt->execute();
$result = $stmt->fetchColumn();

$toString = implode(",",$result);

$sql = "DELETE FROM teh where id NOT IN ({$toString});";
$stmt = $db->prepare($sql);
$stmt->execute();

Note: Looping a SQL query might be a big problem in the long run. There's a lot of other ways to do this.


text:
Q: Подключение микрофона и запись голоса Мне нужно сделать программу, чтоб голос был как пароль, и я не знаю, как подключить к программе микрофон, чтоб он записывал голос когда надо!

A: Посмотрите на BASS. Это библиотека по работе со звуком на разных платформах, включает в том числе и запись звука.
Если разработка под голый Windows, то есть API: waveInOpen и т.п. А если под .NET, то есть опять же хорошая библиотека NAudio, которая упрощает работу со звуком в Windows.


text:
Q: Binding OSMDroid library in a MonoDroid 4.1 Java binding project I just installed MonoDroid alpha 4.1, and I'm trying to create a binding library project using the OSMDroid JAR file. OSMDroid is an opensource mapview implementation, basically a replacement for the Google Maps mapview. I followed the steps in the tutorial, but I get only an error message saying

C:\Program Files (x86)\MSBuild\Novell\Xamarin.Android.Bindings.targets(170,5): error MSB6006: "java.exe" exited with code 1.

How do I fix this problem?

A: I was able to compile the project adding the following JAR files to the project.

*

*apache-mime4j-0.4.jar

*httpmime-4.0-beta1.jar

*osmdroid-third-party-3.0.7.jar

*slf4j-android-1.5.8.jar
and setting them as "ReferenceJar" in the properties in the build action.
To see a proper output from Visual Studio, in order to debug this issue, I also had to set the build output details to normal in Visual Studio options (tools-options-projects and solutions-build and run and set MSBuild project build output to normal).
I still have no luck in using the library, but at least it compiles!


text:
Q: Reduce the original product image size to 1000x1000 dimension We uploaded product images to our site. Lot of images are in the range of 1600x1200 dimension.
We want to reduce the original size of the product images to 1000x1000.
How to reduce the image dimension so that image file size will decrease respectively?
Can you please explain how to implement in Magento site, in which file, what code do I have to place...?
Please help me to find a solution.

A: You could do this using PHP's image manipulation functions.
See http://php.net/manual/en/function.imagecopyresampled.php, the second example there comes close to what you want.
Or you could find some PHP code library that can do this for you.
I would agree with @Mmazvis to do this manually (Photoshop or some other pro tools can batch process this) as PHP image manipulation is a whole different skill.

A: I told you how to do this the other day yet another question gets opened!
It is best to keep your source images at the higher resolution - they might be useful when everyone has 4K screens. That might not be too far in the future. Therefore the approach I suggested to you last time is pretty good.
If you must resize all your images en-mass, take a look at this answer:
https://stackoverflow.com/questions/10802606/how-to-batch-resize-images-in-ubuntu-recursively-within-the-terminal
Use imagemagick, for which you will need to give 5 minutes to install and read the options available.

A: The best practice for using images in magento is to manually crop the image into your desired resolution using photoshop or any other photo editing software such as MS Paint.
I usually make 2 different sizes:
-1000px X 1000px (~80kb)
-300px X 300px (~10kb)
The 1000x1000 image is used as the base image so that it only loads on the product page & the 300x300 image is used for small image & thumbnail.
This practice helps in reducing the load time of the product list view page as many products load at the same time. Bigger images mean more data to be downloaded from server.
Note: Check "Exclude" for the thumbnail(300x300) image


text:
Q: Convolutional layer after embedding layer shapes problem in Keras I want to train a model that has 3 input channels. Every channel starts with embedding (as lambda) and a convolution next. However, I can't deal with shapes.
# Build network
def swish(x):
    return K.sigmoid(x) * x

def make_model():
    embed_size = 512 #must be 512 for embedding layer

    input_text1 = Input(shape=(1,), dtype=tf.string)
    embedding1 = Lambda(QTEmbedding, output_shape=(embed_size,))(input_text1)
    con11 = Conv1D(32, 3, activation='relu')(embedding1)
    pool11 = MaxPooling1D(2)(con11)
    con12 = Conv1D(64,3, activation='relu')(pool11)
    pool12 = MaxPooling1D(2)(con12)
    flat1 = Flatten()(pool12)

    input_text2 = Input(shape=(1,), dtype=tf.string)
    embedding2 = Lambda(QBEmbedding, output_shape=(embed_size,))(input_text2)
    con21 = Conv1D(32, 3, activation='relu')(embedding2)
    pool21 = MaxPooling1D(2)(con21)
    con22 = Conv1D(64,3, activation='relu')(pool21)
    pool22 = MaxPooling1D(2)(con22)
    flat2 = Flatten()(pool22)

    input_text3 = Input(shape=(1,), dtype=tf.string)
    embedding3 = Lambda(AEmbedding, output_shape=(embed_size,))(input_text3)
    con31 = Conv1D(32, 3, activation='relu')(embedding3)
    pool31 = MaxPooling1D(2)(con31)
    con32 = Conv1D(64,3, activation='relu')(pool31)
    pool32 = MaxPooling1D(2)(con32)
    flat3 = Flatten()(pool32)

    x = Concatenate()([flat1,flat2,flat3])
    x = Dense(512, activation=swish)(x)
    x = Dropout(0.4)(x)
    x = BatchNormalization()(x)
    x = Dense(256, activation=swish)(x)
    x = Dropout(0.4)(x)
    x = BatchNormalization()(x)
    x = Dense(64, activation=swish, kernel_regularizer=keras.regularizers.l2(0.001))(x)
    x = Dropout(0.4)(x)
    x = BatchNormalization()(x)

    output = Dense(len(targets),activation='sigmoid',name='output')(x)

    model = Model(inputs=[input_text1,input_text2,input_text3], outputs=[output])
    model.summary()
    return model

And I get this error message:

ValueError: Input 0 is incompatible with layer conv1d_24: expected
  ndim=3, found ndim=2.

I've searched around but didn't find a solution specific to this question.
Please don't link me to another LSTM problem with the same error.
I feel like embedding functions might be the problem as they output 2D tensors.
def QTEmbedding(x):
  results = qa.signatures['question_encoder'](tf.squeeze(tf.cast(x, tf.string)))['outputs']
  return keras.backend.concatenate([results])

def QBEmbedding(x):
  results = general(tf.squeeze(tf.cast(x, tf.string)))
  return keras.backend.concatenate([results])

def AEmbedding(x):
  results = qa.signatures['response_encoder'](input=tf.squeeze(tf.cast(x, tf.string)), context=tf.squeeze(tf.cast(x, tf.string)))['outputs']
  return keras.backend.concatenate([results])

And these are the models.
import tensorflow_hub as hub

general = hub.load("https://tfhub.dev/google/universal-sentence-encoder-large/5")
qa = hub.load('https://tfhub.dev/google/universal-sentence-encoder-qa/3')

A: This is a common misunderstanding when using the Conv1D layers in Keras. According to the documentation, the expected input_shape is (batch, steps, channels).
In general for 10 rows with 20 features each, you'll have to reshape your data to (10, 20, 1).
In your case, my guess is that the output from the embedding layer is causing the issue. I think the output_shape should be (1, embed_size, 1)


text:
Q: What is the difference between Console.Write(5/2) and Console.Write(5.0/2)? When in a "challenge" in the app sololearn, answering C# related questions against each other, the question was "Are the outputs below going to be the same?"
Console.Write(5 / 2 + 2.5); // 4.5
Console.Write(5.0 / 2 + 2.5); // 5

When I run it it indeed gets different results (shown as comments in the code). Why the outputs of below is not the same?

A: In case of: Console.Write(5 / 2 + 2.5);
The 5 / 2 is considered as integer/integer division. Check out this code:
    int i = 5;
    int j = 2;
    Console.WriteLine(i / j);
    //prints 2

In case of: Console.Write(5.0 / 2 + 2.5);
The 5.0 / 2 is considered as double/integer division. Same code would be:
     double i = 5.0;
     int j = 2;
     Console.WriteLine(i / j);
     //prints 2.5

So in your case 5/2 + 2.5 results to 2 + 2.5 => 4.5
But in 5.0/2 + 2.5 we get 2.5 + 2.5 => 5


text:
Q: Displaying a randomised set of image and text from a dictionary in Swift I'm trying to retrieve and display from a dictionary a randomised set of an image with its associated text on click of a button.
First, I tried having the image array and text array seperate and use Int(arc4random_uniform()) to randomly pick the elements from the array to display. It worked, BUT in doing so I need to make sure the image and its associated text are in the same position within their own array and I thought there must be better ways to structure the data by combining them into a multidimensional array or a dictionary. I end up using a dictionary, but got stuck don't know how to get the image and text to display.
See in the code below //THIS IS THE BIT I GOT STUCK AT. I don't know how to retrieve the image and its text from the dictionary.
I am not sure if it's ok to put the myImage and myText var in the dictionary and it seems a bit tedious to keep repeating 'myImage', 'myText' for each set as well.
@IBOutlet weak var myImage: UIImageView!
@IBOutlet weak var myText:  = UILabel()

var randomSet = [[myImage:"1-image", myText:"text for 1"], [myImage:"2-image", myText:"text for 2"], [myImage:"3-image", myText:"text for 3"], [myImage:"4-image", myText:"text for 4"], [myImage:"5-image", myText:"text for 5"]]

func randomiseSet (){
        let randomNumber:Int = Int(arc4random_uniform(5))
        //THIS IS THE BIT I GOT STUCK AT
        myImage.image = UIImage(named: randomSet[randomNumber])
        myText.text = randomSet[randomNumber]
        //END
    }

@IBAction func showRandomSet(_ sender: UIButton) {
        randomiseSet()
    }

I also tried instead of using myImage.image = .... myText.text = ....
return randomSet[[randomNumber]]

Both didn't work and showed 'Build Failed'
I have also investigated using CoreData but I'm a noob and that opens another can of worm for me regarding binary data for images vs using URL due to image size etc.
Any suggestion on what's the best way to fix the above is much appreciated. Thanks.

A: The problem is that the line myImage.image = UIImage(named: randomSet[randomNumber]) is wrong because randomSet[randomNumber] returns [String:String], not String. What you instead need to do is randomSet[randomNumber]["myImage"], which will return the string you want to initialize the UIImage.
Also note: your dictionary's keys should be Strings in this case. Unless myImage and myText are declared as Strings elsewhere, your dictionary is set up incorrectly. Try changing your randomSet to [["myImage":"1-image", "myText":"text for 1"], ["myImage":"2-image", "myText":"text for 2"], ["myImage":"3-image", "myText":"text for 3"], ["myImage":"4-image", "myText":"text for 4"], ["myImage":"5-image", "myText":"text for 5"]]
So, implementing the changes, your code should look something like this:
@IBOutlet weak var myImage: UIImageView!
//Note this change from `@IBOutlet weak var myText:  = UILabel()`, which is incorrect
@IBOutlet weak var myText: UILabel!

var randomSet: [[String:String]] = [["myImage":"1-image", "myText":"text for 1"], ["myImage":"2-image", "myText":"text for 2"], ["myImage":"3-image", "myText":"text for 3"], ["myImage":"4-image", "myText":"text for 4"], ["myImage":"5-image", "myText":"text for 5"]]

func randomiseSet (){
    let randomNumber:Int = Int(arc4random_uniform(5))
    myImage.image = UIImage(named: randomSet[randomNumber]["myImage"]!)
    myText.text = randomSet[randomNumber]
}

@IBAction func showRandomSet(_ sender: UIButton) {
    randomiseSet()
}

A: Just realised I can use a .plist file to keep the properties in the dictionary organised rather than listing them all out in code like that...


text:
Q: Which is more efficient process in ModelBuilder - Merge/Dissolve or Union/Dissolve? I'm creating a model which combines four very large files and dissolves them.  At the moment, my workflow uses the Merge tool and then the Dissolve tool.  However, I was wondering if using the Union tool and then dissolving would be more or less efficient.  I don't need to maintain attributes for my purposes.  I just need to create a layer which contains the geometry.  The feature classes may overlap each other, and they may also contain overlaps within themselves.  As the end result is the same, does anyone know which process would be more time efficient?
Below are screenshots of my workflows:
Merge then Dissolve:

Union then Dissolve:

A: This is a very simplistic test, but I think it shows conclusively that Merge+Dissolve is about 3 times quicker than Union+Dissolve on this dataset, and I believe that as more complex data is thrown at it, the difference will only widen.
import arcpy,time

if arcpy.Exists("C:/temp/test.gdb"):
    arcpy.Delete_management("C:/temp/test.gdb")

arcpy.CreateFileGDB_management("C:/temp","test.gdb")
arcpy.CreateFishnet_management("C:/temp/test.gdb/fishnet1","10 10","10 20","1","1","50","50","#","LABELS","0 0 75 75","POLYLINE")
arcpy.Buffer_analysis("C:/temp/test.gdb/fishnet1_label","C:/temp/test.gdb/fishnet1circles","0.51 Unknown","FULL","ROUND","NONE","#")
arcpy.CreateFishnet_management("C:/temp/test.gdb/fishnet2","10.1 10.1","10.1 20","1","1","50","50","#","LABELS","0 0 75 75","POLYLINE")
arcpy.Buffer_analysis("C:/temp/test.gdb/fishnet2_label","C:/temp/test.gdb/fishnet2circles","0.51 Unknown","FULL","ROUND","NONE","#")

start = time.clock()
arcpy.Merge_management("C:/temp/test.gdb/fishnet1circles;C:/temp/test.gdb/fishnet2circles","C:/temp/test.gdb/fishnetMerge","#")
elapsed = (time.clock() - start)
print("Merge took " + str(elapsed) + " seconds")
arcpy.Dissolve_management("C:/temp/test.gdb/fishnetMerge","C:/temp/test.gdb/fishnetMergeDissolve","#","#","MULTI_PART","DISSOLVE_LINES")
elapsed = (time.clock() - start)
print("Merge and Dissolve took " + str(elapsed) + " seconds")

start = time.clock()
arcpy.Union_analysis("C:/temp/test.gdb/fishnet1circles #;C:/temp/test.gdb/fishnet2circles #","C:/temp/test.gdb/fishnetUnion","ONLY_FID","#","GAPS")
elapsed = (time.clock() - start)
print("Union took " + str(elapsed) + " seconds")
arcpy.Dissolve_management("C:/temp/test.gdb/fishnetUnion","C:/temp/test.gdb/fishnetUnionDissolve","#","#","MULTI_PART","DISSOLVE_LINES")
elapsed = (time.clock() - start)
print("Union and Dissolve took " + str(elapsed) + " seconds")

I ran the test from IDLE using ArcGIS for Desktop 10.1 SP1 and Python 2.7.2 on Windows 7 SP1 and the results were:
>>>
Merge took 1.82999991257 seconds
Merge and Dissolve took 5.45186011302 seconds
Union took 7.6488681498 seconds
Union and Dissolve took 14.1194398165 seconds
>>>

As you suggested the Dissolve after Union was a bit quicker than the Dissolve after Merge but not enough to overcome the large gap between Merge and Union.

A: Merge is definitely faster than Union. PolyGeo has already given a test, so I won't talk about that.
What I will try to explain is the reason behind Merge being faster.
When you run a Union Operation, the geometry of the features is used for the Union Operation. Depending on the Topological nature, new features are generated. The attributes too are combined from all the input features. Further more finding the overlapping features and doing this union operation on them is Algorithmically quite CPU intensive.
Compared to this, the Merge process is just a simple collection of all features. No overlap check is done, no union of those geometries is done. Hence in all cases, Merge will always been much faster than Union.
Now coming to the combination of Merge+Dissolve v/s Union+Dissolve:

*

*In the Dissolve tool, what happens is that the geometries of all the features that have the same attribute value, are unioned, and then simplified.

*The output of the earlier Merge tool may not be planerlized (i.e without overlaps) The output of the earlier Union process is planar, i.e. There are guaranteed to be no overlapping polygons.

*Hence the Simplification of the the union operation within the Dissolve tool may be faster than compared with the output of the Merge tool.

However, with large data, the major part of the time will be taken with the first Union gp process, and hence the time saved in the Dissolve gp operation will pale in comparison to it.

A: if your merge/dissolve is taking more than a few minutes,
you can speed up the process by deleting the input's spatial index and then processing the merge/dissolve. (the resulting output shapefile will still have a spatial index)
you can do this manually in catalog (shapefile's properties > indexes tab > delete; use add to recreate the spatial index) or with python: arcpy.RemoveSpatialIndex_management()
and to recreate it if needed: arcpy.AddSpatialIndex_management()


text:
Q: Why the integration of Flutter with Unity and AR Vuforia makes no object appears? I want to integrate Flutter app with Unity and AR Vuforia. I tried to use library: flutter_unity_widget (https://pub.dev/packages/flutter_unity_widget).
When integrating Flutter app with Unity without Vuforia it works very well. But when I tried to use it with Vuforia … OK, I didn't get any error and I could build app, but when I tested it, it didn't show any object.
I did all the configuration with the library tutorial.
Maybe some of you integrated something like that?
Do you have any sample project with it?

A: You can check out this blog about "Building with Flutter + Unity (AR Experience Toolkit)" for unity.
And for AR Vuforia, it seems that support for this is not yet materialized as of this GitHub post. You can watch out for the updates there.

A: The same thing happened to me when I was testing on iOS, Android was OK
I went through all the steps, only that Vuforia didn't recognize anything. According to this issue Dataset Foo could not be loaded and cannot be activated, I dragged and dropped the data folder and Vuforia into the Runner.
And everything was working fine


text:
Q: Porting a fork of a software to a new version I have a pretty big fork, of a pretty humongous software sitting in a git repository. Since our version and the upstream have diverged significantly, the decision was made to port over to the current version.
So, what would be the best way to do this? Is there some way to mark a particular git commit with a flag notifying that is is already ported over? Or should I just try some complex rebasing scheme?
I'm mainly asking from the standpoint of the logistics, as I will definitely be pushing some of the features to upstream (thus rebased against the current head), but most of the code needs to be updated and kept in our fork.

A: It sounds like you have a tricky merge ahead!  I'd suggest you take a look at git imerge which helps with large merge problems by breaking them down into smaller pieces.  To quote the project page:

git-imerge has two primary design goals:

*

*Reduce the pain of resolving merge conflicts to its unavoidable minimum, by finding and presenting the
  smallest possible conflicts: those between the changes introduced by one commit from each branch.

*Allow a merge to be saved, tested, interrupted, published, and collaborated on while it is in progress.

If you follow the git-imerge process you'll be presented with a series of relatively small merge conflicts that you can fix one-by-one.  I'd encourage you to run any automated tests you have (or at a minimum, compile your project) after each resolution step to reduce the risk of introducing bugs as you go.
Whether you want the end result of this process to be a merge commit, or a rebase of your commits onto the upstream branch is up to you, git imerge lets you choose either of these options (and some others) as a clean-up step once you've completed the hard part of actually combining the changes.


text:
Q: I only want to validates_presence_of :group if group_id is not nil class Category < ActiveRecord::Base
  belongs_to :user
  belongs_to :group

  validates :name, presence: true
  validates :user_id, presence: true
  validates_presence_of :group
.
.
.

I only want to validate the presence of group if group_id is not nil. Is this possible? Or do I need to write a new validates method?

A: You can use a Proc to conditionally execute your validation. See the Rails Guide for more.
validates_presence_of :group, unless: Proc.new { |category| category.group_id.nil? }

A: You can use inline if for this
validates :group, :presence: true, if: "group_id.present?"