Isn't it always possible that one can perturb the metric such that it has positive sectional curvature at a point?

Question: This is the famous theorem of Gromoll and Meyer:

Theorem (Gromoll-Meyer, 1974) There is an exotic 7-sphere with nonnegative
  sectional curvature and positive sectional curvature at a point.

I don't understand the second part of theorem "positive sectional curvature at a point". Isn't it always possible that one cane perturb the metric such that it has positive sectional curvature at a point and we have $\sec_{\min}(M)\leq \sec_q\leq \sec_p$ for all $q$ in a small neighborhoods of $p$?
Comment: I'm not sure that I quite understand the question. Perhaps it helps to mention that (1) there is a metric on the torus $S^1 \times S^1$ with nonnegative sectional curvature (the flat metric) but (2) Gauss-Bonnet implies that any metric on the torus with positive sectional curvature at a point has negative sectional curvature at some other point.
Comment: For what it's worth, I wouldn't call (2) 'exotic'---it's just an application of G-B. I'm not sure whether gets at the kind of intuition you're looking for, but think of a torus embedded in $\Bbb R^3$ in the usual way and equipped with the induced metric. At the points on the "outside" of the torus (so, far from its axis of symmetry) the curvature is positive. At the points on the inside it is negative. Reading through a proof of G-B might help with intuition, at least for the $2$d case.
Comment: (2) is very very exotic!!! Thanks.
Comment: Although it is hard to illustrate, but can you explain how you perturb the (shape) of torus to make positive curvature in some points and why some points has negative sectional curvature intuitively?
Comment: I think your claim about perturbations is off. If you perturb the metric to get a positive sectional curvature at some point you can't guarantee that the sectional curvature increases at all points. It does increase in a small enough neighboorhood of $p$ because it is continuous but not globally.
Comment: @quarague Indeed, and for compact $2$-manifolds G-B again implies that for *any* metric you cannot increase the sectional curvature at one point without reducing it at some other point.
Comment: @C.F.G If my comments here adequately get at what you're looking for, let me know, and I'll write then up a little more formally as an answer. (But if not, feel free to elaborate.)
Comment: @TravisWillse, Your comments are OK. but your second comment isn't about perturbation!!
Comment: I suppose that's a matter of perspective: The conservation of the total Gaussian curvature implies that a perturbation of the metric (on a compact surface) that increases the curvature at one point must decrease the curvature at another.
Comment: @TravisWillse: all your comments fits to my question (and a bit more) please post your answer.
Comment: @C.F.G I'm glad you've found my comments (and others') useful; I've posted an answer.
Answer: The short answer is that you cannot necessarily perturb a metric to get positive sectional curvature while still maintaining non-negative/positive sectional curvature everywhere else.
My favorite example of this is due to Wilking

 Manifolds with positive sectional curvature almost everywhere, Inventiones mathematicae 148(1):117-141, 2002

He constructs a smooth Riemannian metric $g$ on $M:=\mathbb{R}P^2\times \mathbb{R}P^3$ with the following properties.
1)  It is non-negatively curved everywhere.
2)  If $U\subseteq M$ is the subset of all points $p$ for which every $2$-plane $\sigma \subseteq T_p M$ is positively curved, then $U$ has full measure in $M$
In other words, in the measure-theoretic sense, $M$ is positively curved almost everywhere (and non-negatively curved everywhere).
Note, however, that $M$ is non-orientable.  The classical Synge theorem says that in odd dimensions, a positively curved closed Riemannian manifold must be orientable.  Thus, the metric $g$ cannot be deformed to being positively curved everywhere, despite the fact that it started off with positive curvature almost everywhere.
Edit  Following Travis's suggestion, I'll move part of my comment below into the answer here.
Proposition.  Suppose $(M,g)$ is a Riemannian manifold and $p\in M$.  Let $p\in U\subseteq M$ be an open set diffeomorphic to a ball in $\mathbb{R}^n$  Then $g$ can be deformed to a metric $g_1$ for which all sectional curvatures are positive near $p$, but $g= g_1$ outside of $U$.
Proof:  Because $U$ is diffeomorphic to a ball, there is a diffeomorphism $f:U\rightarrow D^n_+\subseteq S^n$, where $D^n_+$ denotes the open northern hemisphere.  Let $g_0$ denote the canonical (positively curved) metric on $S^n$.
Choose an open set $V\subseteq U$ with $\overline{V}\subseteq U$ and let $\lambda:M\rightarrow \mathbb{R}$ be a bump function with $\lambda \equiv 1$ near $p$, and $\operatorname{supp} \lambda \subseteq \overline{V}$.
The family of metrics $(1-t)g + \lambda t f^\ast g_0$ has the required properties.
Comment: This is a very neat example; I hadn't seen it before.
Comment: That said, it's not entirely clear to me what OP wants, but it's not clear to me that this provides a counterexample. Without knowing more about the metric, it seems conceivable that around any given point where sectional curvature vanishes the metric can be deformed so that the resulting sectional curvature is positive everywhere in some neighborhood of that point---the argument in the answer as I understand it just shows that you cannot adjust the metric to make it have positive sectional curvature at all points at once. Perhaps I am overlooking something?
Comment: @TravisWillse:  I agree that it may or may not be what the OP wants.  Also, any metric can be deformed to positive curvature in a neighborhood of a point - you just lose control of it else where.  (Sketch:  wlog work on an open ball of $\mathbb{R}^n$.  Let $g$ be your starting metric with whatever curvature you want.  Let $g_1$ be the pullback metric from the inclusion $i:U\rightarrow S^n$ as the open northern hemisphere.  Pick some smaller neighborhood $V\subseteq U$ with $\overline{V}\subseteq U$, and let $\lambda$ be a bump function supported on $\overline{V}$.  Then $(1-t)g + t\lambda g_1$
Comment: is the required deformation.)
Comment: Yes, I agree, and this is what I tried to get at in my comments under the original question. I think the content of your first comment here might be close to what OP is looking for; perhaps it would be worth adding it to your (already good) answer?
Comment: C.F.G.  To my knowledge, this isn't in any book or paper.  As far as papers are concerend, I image that the experts, this counts as "well known".
Comment: Thanks @JasonDeVito. What surprised me was this part: " we lose control of it else where"!! always your answers are easy to understand for me but Wilking example is hard to imagine.
Comment: Excellent proposition. Why I never saw this before in books or papers? Is there any?
Comment: @JasonDeVito: consider product of two 2-sphere. Then Isn't it true that the product metric is positively curved almost everywhere?
Comment: @C.F.G:  No, a product metric never has positive curvature.  The "mixed" planes are always zero curvature.  In more detail, given a product of Riemannian manifolds $M\times N$, if $v\in T_p M$ and $w\in T_q N$, then $(w,v)\in T_{(p,q)}(M\times N)$ and $\operatorname{sec}(v,w) = 0$.  To be clear, when one says "positive curvature" at a point, the usual meaning is "all $2$-planes $\sigma\subseteq T_p M$ have positive curvature", as opposed to "there is a $2$-plane with positive curvature" or even "almost  all $2$-planes have positive curvature".
Answer:
Isn't it always possible that one can perturb the metric such that it has positive sectional curvature at a point and we have "$\sec_{\min}(M)\leq \sec_q\leq \sec_p$" for all $q$ in a small neighborhoods of $p$?

This statement isn't quite precise, since $\sec_a$ is not a scalar but rather a map $$Gr(2, T_a M) \to \Bbb R .$$ In the special case that $(M, g)$ is a surface (i.e., $\dim M = 2$), however, $Gr(2, T_a M)$ is the singleton set $\{T_a M\}$, so we may identify $\operatorname{sec}_a$ with a scalar and hence view $\operatorname{sec}$ as a function $M \to \Bbb R$, namely, the Gaussian curvature, $K$, and hence interpret the inequalities in the quotation in the usual way.
A standard partition-of-unity argument shows that for any smooth surface $(M, g)$ and point $p \in M$ one can deform $g$ to $g'$ in some neighborhood of $p$ so that for all $q$ in some (a priori possibly smaller) neighborhood we have $\inf K(g) \leq K'_q \leq K'_p$, where $K'$ is the Gaussian curvature of $g'$. (See Jason DeVito's good answer for details of this argument.)
This result, however, is manifestly local, and it does not guarantee the global conclusion that $K'_a \geq \inf K(M)$ for all $a \in M$.

Example Consider the flat torus $(S^1 \times S^1, g)$, for which $K \equiv 0$; in particular $g$ has nonnegative sectional curvature. We can perturb $g$ to produce a metric $g'$ with positive Gaussian curvature $K'_p$ at a point $p$. But the Gauss-Bonnet Theorem gives that
  $$\int_{S^1 \times S^1} K' \,dA = 2 \pi \chi(S^1 \times S^1) = 0.$$ By continuity $K'$ is positive in some neighborhood of $p$, which thus gives a positive contribution to the integral. To satisfy the above equality, $K'$ must also be negative on some open subset of $M$.

In short, the existence of a metric on a given manifold with nonnegative sectional curvature does not imply the existence of a metric on the same manifold with nonnegative sectional curvature at a point and positive sectional curvature at some point.
Comment: The general rule is: Just pick whichever answer helped you more, and don't worry about the politics of which answer to accept. Everyone knows that you can only pick one, so there are generally no hurt feelings---especially among people who have been around and active as long as Jason and I have. If you really can't decide in this particular case, I encourage you to accept Jason's answer: Not only does his answer give a useful example, it also provides details of the partition-of-unity argument that establishes the positive answer to the local version of your question.
Comment: @C.F.G  Just to chime in, I do not care one way or another about who gets the accepted answer.  My answer only contains the proposition you like at Travis's suggestion, so Travis should get all the credit ;).
Comment: I followed your advice and added my comment to my answer.  Sorry it took so long - this weekend has been quite busy.
Comment: Cheers! I've updated my answer to refer to yours (rather than your comment) for the details of the partition-of-unity argument.
Comment: @TravisWillse: your argument and example are so good, but I can't ignore Jason DeVito last edit (his proposition)!! what I should do in this situation for accepting answer?
Comment: Thanks @JasonDeVito. I just don't want anyone to be upset!!


How to avoid accidental invocation on UIKit's private classes?

Question: I have just encountered very weird problem. In my current project i am working with complex views and doing some modifications on the fly.
e.g. If view responds to setTextColor then was setting new color by using following code
if ([view respondsToSelector:propertySelector]) {
    // Invoke method.
}

Accidentally calling method returned UIButtonLabel (which is private hidden
class in UIKit), and executed above method. In above code UIButtonLabel responded to
setTextColor: but then application crashed in the invocation.
How to avoid accidental access and invocation on UIKit's private classes ?
Comment: ??? Just make sure that the method you are calling is declared in the header.  Also don't just tromp through the subviews of a UIKit provided view as you please.
Comment: @borrrden any programatic way to check and avoid this situation?
Comment: Not with the way you are doing it.  You should check if the view is a certain type of class, not if it responds to a selector.  There is no such thing as private methods (in the traditional sense) in Objective-C.
Answer: Yes you can traverse reverse superclasses chain starting from NSObject up to your class, checking that your method is not part of class_copyMethodList for the currently inspected class and it's metaclass (for class methods). While doing so, check that the currently inspected class is not coming from your [NSBundle mainBundle] ([NSBundle bundleForClass:]) as soon as it does, you can terminate the search - you reached your code. But, as you can imagine, even with caching it's a really slow way of doing things.
You are probably better of by redesigning your code: try using conformsToProtocol: instead of respondsToSelector. For example you declare a protocol
@protocol XYZSettableColor <NSObject>

@required
- (void)setSomethingWithColor:(UIColor *)textColor;

@end

Then, in you class (classes) you want to declare that it conforms to the protocol (and obviously implement required methods)
@interface XYZMyControl : UIControl <XYZSettableColor>

@end

Then later, when you want to make sure that passed component is qualified to execute specified method:
- (void)applyTextColor:(UIColor *)color toControl:(id)control {
    if ([control conformsToProtocol:@protocol(XYZSettableColor)]) {
        [(id<XYZSettableColor>)control setSomethingWithColor:color];
    }
}

Comment: can you point me to some example which demonstrates conformsToProtocol usage?
Answer: I think there is no way 100% sure to check this.
You've got to know that objective-c works with method invocations, which means there is no real private method. (At least, anyone can invoke "private" methods).
To prevent calling such methods, you should avoid using "performSelector" and other invocation methods with selectors that you don't already know about.
Moreover, a safeguard exists during the app-submition process. At the end of the submition process, if you have used "risky" selectors, or method calls with names that Apple knows as "method used in private API", then a warning will appear, telling you where you have used private API.
So in the end, everything should be fine at the end of the submission process.


Migrate taxonomy terms with CSV

Question: I would like to import some taxonomy terms with a taxonomy term in it.
field_regio2 is a entityreference field to an existing taxonomy term Regio.
But for some reason it is not working. Everything is working except the field_regio2.
$ drush mmsg import_gemeentes gives:

the entity_lookup plugin requires a value_key, none located

?
uuid: 7eef6b86-80db-40ab-8359-91d20675e0f2
langcode: en
status: true
dependencies: {  }
id: import_gemeentes
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags: null
migration_group: migrated_terms
label: 'Migrate gemeentes from the source CSV to taxonomy terms'
source:
  plugin: csv
  path: 'public://gemeentes.csv'
  header_row_count: 1
  keys:
    - id
  column_names:
    -
      id: id
    -
      vid: vid
    -
      name: name
    -
      field_stratenplan_luchtfoto_refe: field_stratenplan_luchtfoto_refe
    -
      rid: rid
    -
      rid22: rid2
process:
  vid:
    plugin: default_value
    default_value: gemeente
  name: name
  field_stratenplan_luchtfoto_refe: field_stratenplan_luchtfoto_refe
  field_regio: rid
  field_regio2:
    plugin: entity_generate
    source: rid22
destination:
  plugin: 'entity:taxonomy_term'
migration_dependencies: null

Comment: I have resolved the problem myself. For `vid` it is better to use the `default_value plugin` . I have updated the code, if someone needs it. First, I added an extra column in the CSV file `vid = gemeente`, but that is not working.
Answer: The syntax for entity_generate is:
field_regio2:
    plugin: entity_generate
    source: rid22
    entity_type: taxonomy_term
    # This is where migration breaks. It need to know which key to look for.
    value_key: name
    bundle_key: vid
    bundle: YOUR_VOCABULARY_MACHINE_NAME

Answer: It's important to realize that it's the value_key that will be matched to whatever is coming from the source. So if we say value_key: name then the source should contain strings (not IDs!) that will be matched to or create taxonomy term names.
Here's a working section of code from the process section of a node migration YAML-file. It gets names of category terms via source, matching them to names in vocabulary called "categories". If a a term with the given name does not exist in the vocabulary, it will be created.
# Name of the entityreference field, and we specify its property target_id:
field_category/target_id:
    plugin: entity_generate
    # "category" contains the textual name of the category, coming e.g. from CSV:
    source: category
    # Do not change this:
    entity_type: taxonomy_term
    # Do not change this:
    value_key: name
    # Do not change this:
    bundle_key: vid
    # Machine name of your vocabulary:
    bundle: categories

Here's the best page ever I've found on the subject: https://understanddrupal.com/articles/understanding-entitylookup-and-entitygenerate-process-plugins-migrate-tools

Migrate taxonomy terms with CSV


Sendgrid v3 api returns bad request

Question: I am trying to use the sendgrid V3 api to add our users to a mailing list. I have constructed the following Ajax request to hit their API, but I keep getting a bad request error. I omitted xhr.setRequestHeader, but I do have a valid API key and it works, because when it is omitted, it returns a 403. Now, I just get 400 for bad request body. I have made my request body look EXACTLY like their example and am still stuck.
var sendgridData =
  [
    {
       "marketing_emails": 0,
        "weekly_emails": 0,
        "email": userProfile.email,
        "first_name": "foo",
        "last_name": 'bar',
        "userid": 2,
    }
  ]
 $.ajax({
   method: 'POST',
   url: 'https://api.sendgrid.com/v3/contactdb/recipients',
   data: sendgridData,
   dataType: 'json',
   contentType: 'application/json',
 },
 success:
 function(res)
 {
   console.log(1, res)

  Modal.close();
   },
   error:
     function(e)
     {
      Modal.close();
      console.log(1,e);
     }
 })

Comment: Sendgrid API V3 Hope that helps! https://stackoverflow.com/a/50479562/2392211
Answer: Updated with working sample of code and a working jsfiddle:
var apiKey = 'Bearer [API KEY HERE]'

var sendgridData = [
  {
    "marketing_emails": 0,
    "weekly_emails": 0,
    "email": 'email@example.com',
    "first_name": "foo",
    "last_name": 'bar',
    "userid": 2,
  }
]

$.ajax({
  method: 'POST',
  url: 'https://api.sendgrid.com/v3/contactdb/recipients',
  data: JSON.stringify(sendgridData),
  dataType: 'json',
  headers: { 'Authorization': apiKey },
  crossDomain: true
})
.done(function(res) {
  console.log(1, res)
})
.fail(function (e) {
  console.log(2, e.status, e.responseText)
})

Let's take a look at the request you're making and go from there. You're making a request to an API and sending along some data, as a Content-Type: application/json;. The API is responding with 400 Bad Request. The reason the API is returning a 400 is because you're sending a request that the server did not like or could not read/parse.
There are a few other things wrong with your code as well:

The endpoint for the Contacts API on v3 is https://api.sendgrid.com/v3/contactdb/recipients
You're not sending along any authentication headers at all. You'll likely not be able to do this client side as this would be a huge security risk exposing your API key for Sendgrid to the world.
Comment: Thanks for the response Brandon. "contacts" is a typo. In my code, it has always been `/contactdb/`, and the error persists. I do also have authorization with a key, but left it out of my question body for obvious reasons. Any other ideas?
Comment: I am able to reproduce the issue and have a working piece of code, I will update my answer with it.

Sendgrid v3 api returns bad request


box-shadow should appear inside border on right hand side

Question: I am trying to achieve the box-shadow inside the right-border, currently everything is working fine except the shadow is getting display outside the right border. Following is the js-fiddle sample code I have tried...
http://jsfiddle.net/5y1guk6d/1/
HTML:

Page title

             Menu Content

        Main content area

CSS:
.header {
    width: 100%;
    height: 40px;
    top: 0;
    color: white;
}
.header-bar {
    height: 100%;
    overflow: hidden;
    background-color: #009BE1;
}

h1.title {
    display: inline-block;
    font: bold 16px Arial, sans-serif;
    margin: 0 5px 0 15px;
    position: relative;
    top: 25%;
}
.main {
    width: 100%;
    overflow: hidden;
    position: absolute;
    top: 48px;
    bottom: 0;
}

/* left bar */
.left-bar {
    width: 160px;
    float: left;
    padding:10px;
    background-color: #F0F0F0;
    height: 100%;
    position: relative;
    border-right:1px solid #aaa;
    box-shadow:5px 0 5px #ccc;
}
.content {
    overflow: hidden;
    left: 12px;
    padding: 5px 17px 5px 5px;
    height: 100%;
    position: relative;
}

Appreciated your help..
Answer: If you want the box shadow to appear inside of the element instead of outside, use inset.  Then you want to invert the x-offset so it appears on the right side.
box-shadow:inset -5px 0 5px #ccc;

http://jsfiddle.net/5y1guk6d/3/


What are advantages of multi-point statistics compared to variogram?

Question: Variogram is simple but effective way to investigated the spatial variation in the variable of interest in the field being studied. However it has been reported that variogram cannot be considered as the most satisfactory model especially where there are curvature (e.g., permeable channels in reservoir engineering) in the medium being studied. That is different patterns could have more and less exact copy of the same variogram.
A suggestion for development an approach was multi-point statistics (geostatistics), in which for example, a training image, a 2D matrix template is being used for inference of spatial variation. It was shown in the literature that training images are useful to dictate the output the desired pattern honoring conditioning data and being based on stochastic approaches to satisfy statistical inferences.

Questions:

Q1: What else about advantages and or disadvantages of multi-point statistics ?
Q2: How to obtain training images?
  __Q2.1: How to generate training images using existing knowledge etc?
Q3: How about 3D and further dimensions?
Q3: What is the next stage after training image?
Comment: Any chance of some references to where 'it has been reported' or this stuff about training images? I'm not really sure what you are on about here.
Comment: There are many works around in literature such as (Atkinson & Lloyd, Geostatistics for Environmental Applications:P142; and Multiple-point geostatistics: a quantitative vehicle for integrating geologic analogs into multiple reservoir models, Caers & Zhang, P6)
Answer: Your questions are very broad, which makes it hard to give a to-the-point answer. I'll try and provide a few pointers from my own experience using multiple point geostatistics (snesim).

Q1: What else about advantages and or disadvantages of multi-point statistics ?

The advantage is that complex geological structures, which are hard to recreate using random field techniques such as indicator kriging, can be modeled.

Q2: How to obtain training images?
__Q2.1: How to generate training images using existing knowledge etc?

Some options:

Expert knowledge (i.e. draw them by hand)
Digitizing existing maps
Using model output
etc

What is most appropriate in your situation is hard to say.

Q3: How about 3D and further dimensions?

There is no reason for multiple dimensions not to work. Fitting a pattern to a multidimensional training image becomes more and more work as the number of possible patterns grows.

Q4: What is the next stage after training image?

No sure what you are asking for here.
In general, the greatest challenge in MP geostatistics is a) find a training image and b) match patterns in the observations to the training image in a meaningful manner.
Answer:
Q1: What else about advantages and or disadvantages of multi-point statistics?

The advantages are that you can preserve high-order features of the heterogeneity that cannot be described, thus preserved with classical geostatistical techniques based on low-order moments (mean and variance).
The disadvantages are that these features must be observable under form of data patterns inside the training image (TI). Therefore one must provide a representative TI.

Q2: How to obtain training images?

It depends on the nature of the variables one wants to model: for geology one can draw a 2D model or obtain an image from other data sources (lidar images or interpretations of outcrops, satellite data, interpreted geophysical data).

Q2.1: How to generate training images using existing knowledge etc?

Any type of spatial/temporal variable can be simulated (some algorithms allow also continuous variables too): 2D images can be obtained by realized by drawing or filtering secondary image data.

Q3: How about 3D and further dimensions?

3D images can be obtained from object-based models or genetic models. Some MPS algorithms allow using simple training images and conditioning the simulation to obtain more complex results, e.g. with rotated or bended structures.

Q3: What is the next stage after training image?

If the algorithm allows that, one can assign conditioning data for one or more simulated variables, setup the simulation parameters, and run the model. The details of these operations depend on the algorithm. For example, Direct Sampling (www.randlab.org) allows simulating, together with the geological facies, other "auxiliary" variables, for example describing the orientation or dimension of geological structures.


How do i pass a variable value from Console application to windows form application in C# (visual studio)

Question: I am doing a project in which i have to send the variable data from my console application project to windows form application( i have to write that data into textbox). I am trying to pass a variable val to my form and below code is what i tried to do but passed value(num variable in windows form) is zero instead of 1 (serial.Val in console application which is passed as argument and then i am calling the form).
Can anyone please help me with that ?
This is my windows forms code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApplication2;

namespace WindowsFormsApplication2
{
    public partial class Serial_comm_1 : Form
    {
        //private static int temp;
        private DateTime Datetime;
        string indata;
        static SerialPort COMport;
       // private static int num;

        public Serial_comm_1(int num)
        {
            InitializeComponent();
            string Port_Name = "COM3";    // Store the selected COM port name to "Port_Name" varaiable
            int Baud_Rate = 9600; // Convert the string "9600" to int32 9600
            COMport = new SerialPort(Port_Name, Baud_Rate);
            COMport.Parity = Parity.None;
            COMport.StopBits = StopBits.One;
            COMport.DataBits = 8;
            COMport.Handshake = Handshake.None;
            COMport.RtsEnable = true;
            COMport.DtrEnable = true;
            TextBox_Transmit_Data.Text = num.ToString();

            //try to open the port
            #region
            try
            {
                COMport.Open();
                textBox_System_Log.Text = "";
            }

            catch (UnauthorizedAccessException SerialException) //exception that is thrown when the operating system denies access
            {
                MessageBox.Show(SerialException.ToString());
                textBox_System_Log.Text = Port_Name + Environment.NewLine + Baud_Rate;
                textBox_System_Log.Text = textBox_System_Log.Text + Environment.NewLine + SerialException.ToString();
                COMport.Close();
            }

            catch (System.IO.IOException SerialException)     // An attempt to set the state of the underlying port failed
            {
                MessageBox.Show(SerialException.ToString());
                textBox_System_Log.Text = Port_Name + Environment.NewLine + Baud_Rate;
                textBox_System_Log.Text = textBox_System_Log.Text + Environment.NewLine + SerialException.ToString();
                COMport.Close();
            }

            catch (InvalidOperationException SerialException) // The specified port on the current instance of the SerialPort is already open
            {
                MessageBox.Show(SerialException.ToString());
                textBox_System_Log.Text = Port_Name + Environment.NewLine + Baud_Rate;
                textBox_System_Log.Text = textBox_System_Log.Text + Environment.NewLine + SerialException.ToString();
                COMport.Close();
            }

            catch //Any other ERROR
            {
                MessageBox.Show("ERROR in Opening Serial PORT -- UnKnown ERROR");
                COMport.Close();
            }
            #endregion
        }

        private void Button_Transmit_Data_Click(object sender, EventArgs e)
        {
              //Local Variables
           string Port_Name = "COM3";    // Store the selected COM port name to "Port_Name" variable
            int Baud_Rate = 9600; // Convert the string "9600" to int32 9600
            string Data = TextBox_Transmit_Data.Text;                             //Store the string in Textbox to variable "Data"
            COMport.ReadTimeout = 3500; //Setting ReadTimeout =3500 ms or 3.5 seconds
            Console.WriteLine(COMport.IsOpen);
            COMport.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
            //Program1 prog = new Program1();

            //If we are able to open the port
            if (COMport.IsOpen == true)
            {
                COMport.WriteLine(Data);                // Send Data

                textBox_System_Log.Text = Port_Name + Environment.NewLine + Baud_Rate;
                textBox_System_Log.Text = textBox_System_Log.Text + Environment.NewLine + Data + "  Written to Port" + Environment.NewLine;
            }
            else
            {
                TextBox_Received_Data.Enabled = true; // Enable the Receive Groupbox
                MessageBox.Show("Unable to Write to COM port ");
                COMport.Close();
            }
        }

        private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
               SerialPort sp = (SerialPort)sender;

                indata = sp.ReadLine();
                this.Invoke(new EventHandler(display_data_event));
        }

        private void display_data_event(object sender, EventArgs e)
        {
            Datetime = DateTime.Now;
            String time = Datetime.Hour + ":" + Datetime.Minute + ":" + Datetime.Second;
            textBox_System_Log.AppendText(time + "\t\t\t" + indata + Environment.NewLine);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }

        private void label1_Click(object sender, EventArgs e)
        {
        }

        private void textBox_Received_Data_TextChanged(object sender, EventArgs e)
        {
        }

        private void TextBox_Transmit_Data_TextChanged(object sender, EventArgs e)
        {
        }
    }
}

This is my trail of console application:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WindowsFormsApplication2;
using System.Windows.Forms;

namespace ConsoleApplication1
{
    class Program1
    {
        private int val;
        public int Val
        {
            get { return val; }
            set { val = value; }
        }

        static void Main(string[] args)
        {
            Program1 serial = new Program1();
            serial.Val = 1;

            System.Windows.Forms.Application.Run(new Serial_comm_1(serial.Val));

            //Serial_comm_1 serial_form1 = new Serial_comm_1(serial.Val);
        }
    }
}

Comment: Let's go back a step: why have you got two separate applications to begin with? What is the purpose of your console application?
Comment: Hi
i am working on a project(window form) which is part of major application project. i am controlling  a servo motor from c# via Arduino and the servo motor is rotating some HMI knob ! When knob turns to a certain angle certain functionality of appliance is selected and this information of selection comes as feedback to my c# script which is a major application ! Now that feedback variable i need to communicate to my window form
Comment: Do you want to start the Windows forms app when the console app is ready to pass the value, or will the forms application be running already?
Comment: Form application will be running already
Comment: Ok so the idea of executing the forms application (in your original code, and in the answer below) will not work, then. One idea might be to write the data to a specific location (e.g. a file, or a database), and then the forms application can have a background worker running which checks for updates in that file, and then moves them into the textbox. Or the user can have a button to make the forms application go and check. Or potentially even you could try making a direct socket connection between the two, but this might be less easy to achieve reliably.
Comment: i want the data to be passed whenever data is ready in console app.And also can you please give me an example code or any reference for achieving the same ?
Comment: I've just described three methods by which you could potentially do it. All of them can be researched online, no need for me to give you a sample unless you try something and have a specific problem. This isn't a tutorial site. If you really want the Console app to actively _pass_ the data (rather than the forms application looking for it at frequent intervals), then a socket connection is the option you need. But like I said it's more complex, possibly less reliable and probably doesn't give you a big advantage. Polling a file is likely to be easier IMHO.
Comment: Thanks a lot ! i will look for these solutions :)
Answer: From your app you want to start the other app:
// Create a new Process
System.Diagnostics.Process process = new System.Diagnostics.Process();

process.StartInfo = new System.Diagnostics.ProcessStartInfo();
process.StartInfo.FileName = @"C:\Projects\Temp912\bin\Debug\Temp912.exe";
process.StartInfo.Arguments = "Test Argument";
process.StartInfo.UseShellExecute = false;
process.Start();

Now from your Windows Form App, modify the Main method:
using System;
using System.Windows.Forms;

namespace Temp912
{
    static class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            string arg1 = "";

            if ((args != null) && (args.Length > 0))
            {
                arg1 = args[0];

                MessageBox.Show("Arg1: " + arg1, "Arg App Started With Parameter");
            }
            else
            {
                MessageBox.Show("Arg1: N/A", "Arg App Started Without Parameter");
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

If you need to pass the parameter value(s) to your Main Form, expose a property or properties on your form, and set the value(s) before you launch the form.
Edit Per Question:
Form Code
public string MyProperty { get; set; } // change the data type to int or whatever
Than in Program.cs, instead of:
Application.Run(new Form1());

Do this:
// create an instance of your form
Form1 form1 = new Form1();

// set the property or properties
form1.MyProperty = arg1;

Then call:
// this is should work, I didn't test this like the other code
Application.Run(form1);

Comment: Hi !
where is in this code i am passing my variable to window form ?
i am new to c# please help
Comment: you are saying that i have to set the value in window form in order to pass parameter but what i want is pass that variable value from console application instead of setting it up in form itself
Comment: i dont think you have even read my question properly ! i am not passing variable from command line.
Comment: I didn't say you were passing from a command line. You can put that code in a button click, that is what I did.
Comment: Give me a few minutes, I putting a sample project together you can download that has a sample console app starting a Windows Form.
Comment: Here, I created a simple two project zip file with a console app and a windows form. http://datajuggler.com/Downloads/ConsoleAppStarter.zip  If you think this service was worth the price of free, please subscribe to my YouTube channel: https://www.youtube.com/channel/UCaw0joqvisKr3lYJ9Pd2vHA

You will need to build the Windows Form app once before you run the console app.

Thanks


Remove records based on priority in sql server

Question: details table
name age sports
john 27  football
john 27  cricket
john 27  basketball
kyle 28  baseball
kyle 28  football
nick 24  football
nick 24  hockey
ron  35  football

Priority table :
name       priority
futsal     1
basketball 2
football   3
cricket    4
baseball   5
hockey     6

desired table :

name age sports
john 27  basketball  --as basketball has the highest priority for john
kyle 28  baseball
nick 24  football
ron  35  football

What is desired is that i want to keep only 1 record for a name and rest should be deleted based on priority of sports .
I know to delete duplicate records but can anyone suggest me can this be accomplished in sql server and
how!!
Answer: You can use window functions.  Here is one method:
select dp.*
from (select d.*, min(p.priority) over (partition by d.name)
      from details d join
           priorities p
           on d.sport = p.name
     ) dp
where seqnum = 1;

Answer: Do the join use row_number():
select t.*
from (select d.name, d.age, d.sports,
             row_number() over (partition by d.name order by p.priority) as seq
      from details d inner join
           priority p
           on p.name = d.sports
     ) t
where seq = 1;

Comment: this will not work , basically you are joining with priority tables and removing the duplicates. What i want is that only those record should come up having the highest priority


Yup mixed não funciona notRequired ou nullable

Question: Boa tarde, estou validando os dados de um formulário com Yup e preciso que apenas imagens possam ser carregadas, então usei o seguinte código:
// formato que pode ser upado no input de email
const formatosSuportados = [
    "image/jpg",
    "image/jpeg",
    "image/gif",
    "image/png"
];

// Validação das entradas
const EsquemaDeValidacao = Yup.object().shape({
    email: Yup.string().email().required('enter email'),
    corpo: Yup.string().max(500, "Too Long!").required('enter any message'),
    arquivo: Yup.mixed().nullable().test('fileFormat', 'Unsupported Format', arquivo =>
        arquivo && formatosSuportados.includes(arquivo.type)
    )
})

O problema é que o arquivo está sendo obrigatório para eu conseguir enviar o email. Não dispara erro algum, apenas não envia se não tem nenhum arquivo upado.
Eu já tentei com nullable e notRequired, existe alguma outra forma de fazer isso?
Answer: Essa expressão sempre vai dar falso se não contiver nenhum arquivo selecionado, então, acredito uma lógica bem básica seria testar se o arquivo não existe, retorna true, se ele existir retornar o outro teste, exemplo:
arquivo => {
    if (!arquivo) {
        return true;
    }
    return formatosSuportados.includes(arquivo.type)
}

isso vai solucionar o seu problema.
Comment: Funcionou, obrigado!!!


Print Menu block Title and the menu

Question:
In admin/structure/menu I created a menu
In admin/structure/block I created a 'menu block' with above menu

With below code I am able to render the menu in page--front.tpl.php
<?php
 $block = module_invoke('menu_block', 'block_view', '3');
 print render($block['content']);
?>

But how do I render the Menu block Title?
Answer: Your implementation is right but you are missing the print subject, you only print the content of the block.
if you debug the $block variable you will find 'subject' as key with value or without value based on the block if it has a title or not.
So your code should be like this in order to print the title.
 $block = module_invoke('menu_block', 'block_view', '3');
 print render($block['subject']);
 print render($block['content']);

Comment: The best solution is always the simplest.
Answer: This renders it correctly, including all markup.
    $block = block_load('menu', 'menu-my-profile');
    $block = _block_render_blocks(array($block));
    $block = _block_get_renderable_array($block);
    print render($block);

Print Menu block Title and the menu


Filtered JSON from an XML

Question: I have an XML file like below .
<animals>
     <dog>
          <name>Rufus</name>
          <breed>labrador</breed>
     </dog>
     <dog>
          <name>Marty</name>
          <breed>whippet</breed>
     </dog>
     <cat name="Matilda"/>
</animals>
And i need the output to be a filtered JSON .
I got the XML converted to JSON with Jackson Library.
 {
        animals:{
             dog:[{name:'Rufus',breed:'Labrador'},
                 {name:'Marty',breed:'whippet'}],
             cat:{name:'Matilda'}
        }
    }

But i need a formatted output , with selected nodes.
Is there some jar which takes filters .
say if give an exclude filter as
animals.dog=true

I get an output like the below
{
        animals:{
                     cat:{name:'Matilda'}
                }
}

Comment: Read the XML into a model and then use gson to filter the field using an exclusion strategy - http://stackoverflow.com/questions/4802887/gson-how-to-exclude-specific-fields-from-serialization-without-annotations
Answer: I know this isn't the exact scenario since I am just using a class here and not an XML, but it may give you what you need as far as filtering a node out:
public class Answer28534834 {

public static class Animal
{
    private ArrayList<Dog> dogs;
    private ArrayList<Cat> cats;

    public Animal()
    {
        dogs = new ArrayList<Dog>();
        cats = new ArrayList<Cat>();
    }

    public void addDog(Dog dog)
    {
        dogs.add(dog);
    }

    public ArrayList<Dog> getDogs()
    {
        return dogs;
    }

    public void addCat(Cat cat)
    {
        cats.add(cat);
    }

    public ArrayList<Cat> getCats()
    {
        return cats;
    }
}

public static class Dog
{
    String name;
    String breed;

    public Dog(String name, String breed)
    {
        this.name = name;
    }

    public String getName()
    {
        return name;
    }

    public String getBreed()
    {
        return breed;
    }
}

public static class Cat
{
    String name;

    public Cat(String name)
    {
        this.name = name;
    }

    public String getName()
    {
        return name;
    }
}

public static class Example {
    private String fieldA;
    private String fieldB;
    private String fieldC;

    public Example(String a, String b, String c)
    {
        this.fieldA = a;
        this.fieldB = b;
        this.fieldC = c;
    }

    public String getFieldA() {
        return fieldA;
    }

    public String getFieldB() {
        return fieldB;
    }

    public String getFieldC() {
        return fieldC;
    }
}

public static void main(String [] args) throws Exception
{
    ObjectMapper mapper = new ObjectMapper();

    Animal animalList = new Animal();
    animalList.addDog(new Dog("Rufus", "Labrador"));
    animalList.addDog(new Dog("Marty", "Whippet"));
    animalList.addCat(new Cat("Matilda"));

    JsonNode node = mapper.convertValue(animalList, JsonNode.class);

    if (node.isObject())
    {
        for (Iterator<Entry<String, JsonNode>> it = node.fields(); it.hasNext(); )
        {
            Map.Entry<String, JsonNode> field = it.next();
            String key = field.getKey();

            if (!"cats".equals(key))
            {
                it.remove();
            }
        }
    }

    System.out.println(mapper.writeValueAsString(node));
}

}

Comment: It just gives us one level of iteration and we have to go to each and every node and check and filter it out ? My XML is gonna be really big with more inner nodes , wouldnt it take a performance hit checking like this . I'll have like 100K xml messages incoming in an hour and I've to filter it out in a dynamic way . Is it possible ?
Comment: Are you converting your XML to objects prior to serialization?  There are a few different approaches I am seeing that could be used, including implementing JsonSerializable and using Filters.
Comment: I receive different types of XML , and none of them have a confirmed structure . So it would be very difficult for me to convert to XML to Object as i'll have to create pojo's for each and every parent and child. I guess filtering out JSON might be more efficient that filtering XML ?
Comment: Can you post your code you are using?  It isn't a path I am familiar with, but I am willing to take a look

Filtered JSON from an XML


If $X=\{1,x,x^2,\dots,x^n\}$, $sp(X)=$? Also, is it finitely generated?

Question:
If $X=\{1,x,x^2,\dots,x^n\}$, $\operatorname{span}(X)=$? Also, is it finitely generated

Well, simply this is the set of polynomials of degree $\leq n$. So
$$\operatorname{span}(X)=\{a_0+a_1x+a_2x^2+\dots+a_nx^n|a_i\in F, i=0,1,2,\dots,n\}=P_n(F)$$
There are an infinite number of polynomials that we can create using the linear combinations of $X$, and so the span of $X$ is infinite. But then why does my answer say that the set is finitely generated? This is confusing me.
If we can create an infinite amount of functions, why is it "finitely generated' in this case?
Answer: In algebra, we say a vector space $V$ is generated by a set $S$ if it is the smallest vector space containing $S$. We also say $S$ generates $V$. We have the same sort of definition when $V$ is a group or an ideal or some other algebraic object.
For instance, the subspace of $\mathbf{R}^3$ generated by $(1,0,0)$ is $V = \{(a,0,0) : a \in \mathbf{R}\}$ because

$V$ is a vector space containing $(1,0,0)$
if $W$ is a subspace of $\mathbf{R}^3$ containing $(1,0,0)$ then it contains all scalar multiples of $(1,0,0)$ because subspaces are closed under taking scalar multiples

More generally, if $S$ is any set of vectors in a vector space $V$ then the subspace generated by $S$ is $\operatorname{span} S$ because

$\operatorname{span} S$ is a vector space containing $S$
if $W$ is a vector space containing $S$ then $W$ contains all linear combinations of elements of $S$, namely $W$ contains $\operatorname{span} S$

Given a vector space $V$, we say that $V$ is finitely generated if there is a finite set $S$ that generates $V$. For instance $\mathbf{R}^3$ is generated by $\mathbf{R}^3$ (which is infinite) and also by $S = \{(1,0,0), (0,1,0), (0,0,1)\}$ (which is finite). Since there exists a finite set that generates $\mathbf{R}^3$, namely $S$, we have that $\mathbf{R}^3$ is finitely generated.
An equivalent characterization of finitely generated vector spaces is finite dimension. If $\mathcal B$ is a finite basis for $V$ then $V$ is generated by $\mathcal B$ so $V$ is finitely generated. Conversely, if $V$ is finitely generated, say by $S$, then we can select a basis for $V$ by taking a maximally linearly independent subset of $S$.
Therefore the vector space of all polynomials is not finitely generated because it has an infinite linearly independent set, $\{1,x,x^2,\dots\}$ and therefore cannot have a finite basis. On the other hand, the vector space of all polynomials of degree $\le n$ is finitely generated because it is generated by the finite set $\{1,x,x^2,\dots,x^n\}$.
Answer: As a vector space over $F$, $V = \text{span} \, X$ is finitely generated by the elements $1, x, x^2, \dots, x^n$.
For a vector space $V$ to be finitely generated means that there is a finite set $S$ for which $V = \text{span} \, S$. But $S = X$ is such a set, because $X$ has finite size $n$.
This is different from saying whether $V$ is finite or infinite as a set. In this case, that will depend on the size of the field $F$.


Angular4: Locale for a user

Question: I want to have a LoginForm and after this user enters the application - either with German or English usage. As far as I understand I can set in the app.module.ts something like
import { LOCALE_ID } from '@angular/core';
providers: [{ provide: LOCALE_ID, useValue: 'de-DE' },...]

But that is at the startup and not when the LoginForm was already displayed :-/ Is there a way to change the locale for the whole app? (Not only for a specific component!) - Would be great if the translations could be changed as well on the fly. Any hints how to achieve? I only found the above way to deal with.
Answer: I followed the answer from this thread and I have the following solution:
import { LOCALE_ID } from '@angular/core';

@NgModule({
  // ...
  providers: [...
     {provide: LOCALE_ID,
      deps: [SettingsService],      // some service handling global settings
      useFactory: getLanguage  // returns locale string
    }
  ]
  // ...
})
export class AppModule { }
// the following function is required (for Angular 4.1.1!!!)
export function getLanguage(settingsService: SettingsService) {
  return settingsService.getLanguage();
}

Note: The usage of an extra function prevents the error Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function !!!!
and I create the class
import { Injectable } from '@angular/core';

@Injectable()
export class SettingsService {
  currentLang: string;

  constructor() {
    this.currentLang = 'en';
  }

  setLanguage(lang: string) {
    this.currentLang = lang;
  }
  getLanguage() {
    return this.currentLang;
  }
}

which changes the LOCALE_ID on the fly :-)
Comment: Whenever I change the current language, while all the `| translate` update correctly, the months in `| date` won't update
Comment: It doesn't work for the date Pipe, the months in MMM format stays in the default lang.
Comment: Sorry the late reply - but this works on my side, e.g. `{curDate|date:'medium'}} <--> {{curDate| date:'MMM' }} <-->  {{curDate| date:'MMMM' }} <-->` works perfectly ... don't know where/how you perceive the prob...
Comment: read the documentation, they've made `date` immutable to save on calculations, you should change the reference (create new `date` I guess) so it will trigger the change (haven't tried this yet)
Answer: How about this?

use local storage to store the locale (eg. 'fr')
load the associated translation file in main.ts (eg. messages.fr.xlf)
set the LOCALE_ID in app.module.ts

To change the locale

set the new locale in local storage
refresh the app

main.ts
declare const require;

const locale = localStorage.getItem('locale');
const translation = require(`raw-loader!./locale/messages.${locale}.xlf`)

platformBrowserDynamic().bootstrapModule(AppModule, {
  providers: [
    {provide: TRANSLATIONS, useValue: translation},
    {provide: TRANSLATIONS_FORMAT, useValue: 'xlf'}
  ]
});

app.module.ts
@NgModule({
  providers: [
    {provide: LOCALE_ID, useValue: localStorage.getItem('locale')}
  ]
})
export class AppModule { }

Comment: raw-loader is included by default in angular-cli
Comment: the approach looks interesting. But what is the `require`d `raw-loader!`? Is this a package which needs to be installed? Or a default Angular package?
Comment: It's "A loader for webpack that lets you import files as a string." https://github.com/webpack-contrib/raw-loader
Comment: Ah, I see what you were asking now LeO. Sorry for the hasty response.
Answer: What you're doing in app.module.ts is the right way to do this and for the whole app:
@NgModule({
  // ...
  providers: [
    { provide: LOCALE_ID, useValue: 'de-DE'}
  ]
  // ...
})
export class AppModule { }

But unfortunately I don't think that it's possible to change it on the fly.

Angular4: Locale for a user


Given the composition of function $f(g(x))$ and $g(x)$, what is the domain of $f(x)$?

Question: Suppose that I have $g(x)=\frac{1}{x}$ we know that the domain is all real numbers except 0 and $f(g(x))=\frac{2}{x}+5$. we know the domain is also all real numbers except 0 We know that to find $f(x)$, what we have to do is find the inverse function of $g(x)$, which is $g^{-1}(x)=\frac{1}{x}$. Then we substitute it and get $f(g(g^{-1}(x)))=2x+5$, so that $f(x)=2x+5$.
Does it affect the domain of $f(x)$? I mean, when you substitute $x$ with $g^{-1}(x)$ to $f(g(x))$, then the domain of $f(x)$ must be the domain of $g^{-1}(x)$, right (that is the domain of $f(x)$ is $x$ not $0$ which is same as the domain of $g^{-1}(x)$)? Please correct me if I am wrong.
Comment: If you want to find the domain of $f$, then I think it is quite important to specify the domains and ranges of $g$ and the composition $fg$. For example, is it $g:(0,\infty)\to(0,\infty)$ and $fg:(0,\infty)\to(0,\infty)$ ? Your question is not very clear.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: Let's frame it as follows: Define $g,h:(0,\infty)\to(0,\infty)$ by $g(x):=\frac{1}{x}$ and $h(x):=\frac{2}{x}+5$. We want to investigate the possible domains of a function $f$ satisfying $fg=h$.
Evaluating $fg=h$ at $x>0$ gives that $f(\frac{1}{x})=2(\frac{1}{x})+5$, so that $f(y)=2y+5$ for all $y>0$. Now let $(0,\infty)\subseteq A\subseteq\mathbb{R}$ and define $f:A\to\mathbb{R}$ by $f(x):=2x+5$.
Then $(fg)(x)=h(x)$ for all $x>0$. So this works for any domain containing $(0,\infty)$. In fact, it doesn't matter what values $f$ takes for $x\leq 0$, since $g$ maps only into $(0,\infty)$.
But this depends on the domain of $g$ and $h$, which are defined for all non-zero $x$. In short, there is no definitive answer to your question as stated. The domain of a function is almost always included as part of the definition. You might be able to work out where it needs to be defined for some particular purpose, but very often you could tack on some extra elements to the domain, and assign arbitrary values to those extra elements, without affecting anything all that much.
Comment: so for $f(x)$ the domain cannot be 0?i mean like f(0)
Comment: Are you asking if the domain of $f$ can be the set $\{0\}$? In that case, $g(x)$ would always be outside the domain of $f$ and the composition $fg$ would not be defined at all. In a composition $fg$, $g(x)$ must always be included in the domain of $f$.
Comment: Actually i little bit concerned about this . In Precalculus or algebra course we often see the composition function problems. Like given f(g(x)) and g(x) what is g(x)?and when we want to find f(x) of course we need to find the $g^{-1}(x)$ then we obtain f(x) ..but when we do that the domain of f(x) will be same with the domain of  $g^{-1}(x)$ right?
Comment: For example in my quetions you will get $f(x)=2x+5$ but the domain of f(x) must be same with the domain of $g^{-1}(x)$ that is all real numbers except $0$? correct me if i wrong
Comment: @WoxFrime No, the domain must contain specific points, and take specific values at those points, for the composition to work. That is all that can be deduced from the given information. You could define $f(0)$ to be anything you like and it will not affect the composition because $g(x)$ is never zero. Therefore nothing changes when you include $0$ in the domain of $f$.
Comment: So $f(0)$ is defined ? does it mean when we find the $f(x)$ from $f(g(x))$ the domain of $f(x)$ must be same with the domain of $g^{-1}(x)$ because , we know that the domain of $g(x)$ is all real numbers except 0 and the domain of $g^{-1}(x)$ is  all real numbers except 0 because the g^{-1}(x) = $\frac{1}{x}$ again and the domain is all real numbers except 0.Recall $g(g^{-1}(x))=x$ which x is the domain of $g^{-1}$.Then to find $f(x)$ given $f(g(x))$ and $g(x)$.to find $f(x)$ , we substitute $x$ with $g^{-1}(x)$ to $f(g(x))$ then we get $f(x)=2x+5$. but x is the domain of $g^{-1}(x)$ right?
Comment: which means the domain of $f(x)$ cannot be $0$.in other words $f(0)$ is undefined?
Answer: Usually, the domain of a function is part of its definition and cannot be obtained from its formula. You can ask questions like: What is the largest/smallest set on which $f$ can be defined s.t. it fulfills the requirements? But asking for the domain of a function does not have a mathematical meaning.
Having said that, in school there are often questions of that type, which are supposed to ask for the largest set on which some expression is defined. This is, in your case, trivial: $f(x)=2x+5$ can clearly be defined everywhere.
A slightly more interesting question, and what you probably intended to ask, is: What is the smallest possible domain on which $f$ has to be defined so that $f(g(x))=\frac2x+5$ holds for every $x\in\operatorname{dom}(g)=\mathbb R\setminus\{0\}$? Here, $\operatorname{dom}$ stands for the domain of a function and the statement $\operatorname{dom}(g)=\mathbb R\setminus\{0\}$ should be part of the definition of $g$. For $f(g(x))$ to be defined, $f$ must be defined for every $x$ in the image of $g$, that is it has to hold that$$\operatorname{im}(g):=\{g(x)\mid x\in\operatorname{dom}(g)\}\subseteq\operatorname{dom}(f).$$ To find the image of $g$, you can use the inverse function: One finds $$\operatorname{im}(g)=\operatorname{dom}(g^{-1})\overset{g^{-1}=g}=\operatorname{dom}(g)=\mathbb R\setminus\{0\}.$$ This means that $f$ has to befined everywhere except at $0$ for your conditions to hold for all $x\in\operatorname{dom}(g)$. (But could of course also be defined at $0$.)
Comment: i am actually little bit concerned about the composition functions problems like for example given f(g(x)) and g(x) what is f(x).But the problem is does it affect the domain of f(x)?For instance in my questions you will obtain $f(x)=2x+5$ but how do we know that? first you need to find $g^{-1}(x)$ the domain is same with the domain of $g(x)$ that is all real numbers except $0$ .Recall $g(g^{-1}(x))=x$ where x is the domain of $g^{-1}(x)$.Then you subtitute x with $g^{-1}(x)$ to $f(g(x))$ .when you do that you will  get $f(x)=2x+5$. Then the domain of $f(x)$ must be same with $g^{-1}$?
Comment: As I said in my answer, the domain of $f$ has to include the domain of $g^{-1}$, but could also be bigger. Basically, since $g^{-1}$ is not defined at $0$, $f$ can do whatever you want at $0$; it can be defined to be any real value or not defined at all.
Comment: why is that so?$f$ can do whatever you want at $0$?i need more explanation
Comment: The point is that $\frac 1x$ is never $0$, so $f(\frac1x)$ does not impose any restrictions on the value of $f(0)$. Consider the three functions $$f_1:\mathbb R\to\mathbb R,\ x\mapsto 2x+5$$ $$f_2:\mathbb R\setminus\{0\}\to\mathbb R,\ x\mapsto 2x+5$$ $$f_3:\mathbb R\to\mathbb R, x\mapsto\begin{cases}2x+5&\text{if }x\neq0,\\\sqrt{\frac\pi2}&\text{if }x=0\end{cases}$$ In all three cases, you can easily verify that $f_i(g(x))=\frac2x+5$ is true for all $x\neq0$, but $f_2$ is not defined at $0$, whereas $f_3$ and $f_1$ are, but take different values there.


How to prove this is homeomorphism?

Question: Let $\Bbb R^n \cup\{\infty\} $ be the Alexandroff compactification of  $\Bbb R^n$.
Prove that the function $\phi:\Bbb R^n \cup\{\infty\}\rightarrow\Bbb R^n \cup\{\infty\}, \ $ $\phi(x)=x/|x|^2$ if $ x\neq0,\infty$, $\phi(0)=\infty$ and $\phi(\infty)=0$ is an homeomorphism.
It's clear in case $x\neq0,\infty,$ but I don't know how to prove the continuity in the zero and infinity points. I also know if $\phi$ is continuous, then it's an homeomorphism because $\phi=\phi^{-1}$.
Comment: Recall from the definition of compactification that a set $U$ containing $\infty$ is open if and only if the complement of $U$ is a compact subset of $\mathbb{R}^n$. Use this to show continuity in the usual way.
Answer: So it remains to check the continuity of the function $\phi$ at points $0$ and $\infty$.
$0$: Since $\phi(0)=\infty$, for each $N>0$ we have to find $\delta>0$ such that $|x|<\delta$ implies $|\phi(x)|>N$.
It suffices to put $\delta=1/N$. Indeed, if $|x|<\delta$ then $|\phi(x)|=1/|x|>N$.
$\infty$: Since $\phi(\infty)=0$, for each $\delta>0$ we have to find $N>0$ such that $|x|>N $ implies $|\phi(x)| <\delta$.
It suffices to put $N=1/\delta$. Indeed, if $|x|>N$ then $|\phi(x)|=1/|x|<\delta$.
Answer: In the complex plane let $S^1=\{z: |z|=1\}.$ Let $g:\mathbb R\cup \{\infty \}\to S^1$  where $g(x)=e^{2i\tan^{-1}x}$ for $x\in \mathbb R,$ and $g(\infty)=-1.$ Let $h:S^1\to S^1$ where $h(e^{i\theta})=e^{i(\pi -\theta) }$ for real $\theta .$ Then $g,h,$ and $g^{-1}$ are homeomorphisms, and $f=g^{-1}hg.$
Comment: This doesn't answer OP's question as far as I can tell...

How to prove this is homeomorphism?


Databinding para objetos JSON.NET: como implementar?

Question: Minha aplicação lida muito com HTTP requests que retornam dados JSON. Eu uso a biblioteca JSON.NET para manipulá-los. Eis um exemplo simulado e bastante resumido da informação (há redundâncias nos dados originais, que não posso postar por serem informações sensíveis):
    [{
    "id": 1,
    "conta_movimento_id": 726,
    "conta_movimento": {
        "id": 726,
        "nome": "FULANO DE TAL - CONTA 2"
    },
    "especie_id": 1,
    "especie": {
        "id": 1,
        "nome": "PAGAMENTO"
    },
    "favorecido_id": 34,
    "favorecido": {
        "id": 34,
        "nome": "FULANO DE TAL",
        "contas": [{
            "id": 724,
            "nome": "FULANO DE TAL - CONTA 1"
        }, {
            "id": 726,
            "nome": "FULANO DE TAL - CONTA 2"
        }]
    },
    "valor": 1564.23
    }, {
    "id": 2,
    "conta_movimento_id": 725,
    "conta_movimento": {
        "id": 725,
        "nome": "SICRANO DE TAL - CONTA 1"
    },
    "especie_id": 1,
    "especie": {
        "id": 1,
        "nome": "PAGAMENTO"
    },
    "favorecido_id": 35,
    "favorecido": {
        "id": 35,
        "nome": "SICRANO DE TAL",
        "contas": [{
            "id": 725,
            "nome": "FULANO DE TAL - CONTA 1"
        }]
    },
    "valor": 2323.79
    }]

Preciso que esses dados sejam exibidos em controles Winforms que usam Databinding (principalmente ComboBox e DataGridView). Não pretendo editar dados nesse momento, só precisava exibi-los de forma amigável para o usuário.
Escrevi uma rotina improvisada que converte IEnumerable(Of JToken) para DataTable:
Module JsonAsDataTable
    <Runtime.CompilerServices.Extension> Public Function ToDataTable(ByVal jtokens As IEnumerable(Of JToken), Optional ByVal trim_object_columns As Boolean = False, Optional ByVal castToCLRtypes As Boolean = False, Optional ByVal orderBy As String = Nothing) As DataTable
        Dim dt As New DataTable, sdt As DataTable, dr, sdr As DataRow, dateproperty As Date
        If jtokens IsNot Nothing Then
            For Each jt In jtokens
                dr = dt.NewRow
                For Each jp In jt.Children(Of JProperty)
                    sdt = Nothing
                    If Not dt.Columns.Contains(jp.Name) Then dt.Columns.Add(jp.Name, IIf(castToCLRtypes, GetType(Object), GetType(JToken)))
                    If jp.Value.Type = JTokenType.Object AndAlso jp.Value.Children.Count = 1 AndAlso jp.Value.First.Type = JTokenType.Property AndAlso DirectCast(jp.Value.First, JProperty).Name = "date" Then
                        If Date.TryParse(DirectCast(jp.Value.First, JProperty).Value, dateproperty) Then
                            dr.SetField(jp.Name, New JValue(dateproperty))
                        Else
                            dr.SetField(jp.Name, JValue.CreateNull)
                        End If
                    Else
                        dr.SetField(jp.Name, jp.Value)
                        If jp.Value.Type = JTokenType.Object Then
                            sdt = AsDataTable({jp.Value}, trim_object_columns)
                        ElseIf jp.Value.Type = JTokenType.Array Then
                            sdt = AsDataTable(jp.Value, trim_object_columns)
                        End If
                        If sdt IsNot Nothing Then
                            sdr = sdt.Select.FirstOrDefault
                            For Each sdc As DataColumn In sdt.Columns
                                If Not dt.Columns.Contains(jp.Name & "." & sdc.ColumnName) Then dt.Columns.Add(jp.Name & "." & sdc.ColumnName, GetType(Object))
                                If sdr IsNot Nothing Then dr.SetField(jp.Name & "." & sdc.ColumnName, sdr(sdc.ColumnName))
                            Next
                            If trim_object_columns Then dt.Columns.Remove(jp.Name)
                        End If
                    End If
                Next
                dt.Rows.Add(dr)
            Next
            If castToCLRtypes Then
                For Each drow In dt.Select
                    For Each dcol As DataColumn In dt.Columns
                        If TypeOf drow(dcol) Is JToken Then drow(dcol) = ToField(drow(dcol))
                    Next
                Next
            End If
            If dt.Rows.Count > 0 AndAlso Not String.IsNullOrEmpty(orderBy) Then
                dt = dt.Select("", orderBy).CopyToDataTable
            End If
        End If
        Return dt
    End Function
    <Runtime.CompilerServices.Extension> Friend Function ToField(token As JToken) As Object
        If token Is Nothing Then Return Nothing
        Select Case token.Type
            Case JTokenType.Boolean
                Return token.Value(Of Boolean)
            Case JTokenType.Bytes
                Return token.Value(Of Byte())
            Case JTokenType.Date
                Return token.Value(Of Date)
            Case JTokenType.Float
                Return token.Value(Of Double)
            Case JTokenType.Guid
                Return token.Value(Of Guid)
            Case JTokenType.Integer
                Return token.Value(Of Integer)
            Case JTokenType.Null
                Return Nothing
            Case JTokenType.Property
                Return ExtractObjectFrom(CType(token, JProperty).Value)
            Case JTokenType.String
                Return token.Value(Of String)
            Case JTokenType.TimeSpan
                Return token.Value(Of TimeSpan)
            Case JTokenType.Uri
                Return token.Value(Of Uri)
            Case Else
                Return token.ToString
        End Select
    End Function
End Module

Agora eu estou ciente de que minha solução não é nem limpa nem confiável. É apenas a primeira coisa em que pensei para exibir os itens em um  DataGridView de uma maneira que o usuário pudesse classificar os dados clicando nos cabeçalhos das colunas, o que um simples Array de JToken não permitiria. Meu DataGridView deve ficar assim:
Conta-------------------------Movimento-Valor--------Favorecido-----
FULANO DE TAL - CONTA 2PAGAMENTOR$ 1.564,23FULANO DE TAL
SICRANO DE TAL - CONTA 1PAGAMENTOR$ 2.323,79SICRANO DE TAL
Este é um exemplo bem simples. Há casos em que cada item do JSON tem propriedades que também são objectos complexos, então eu uso dois DataGridView, sendo que o segundo é repovoado a cada vez que uma nova linha é selecionada no primeiro. Tudo baseado na conversão de JToken() em DataTable com base no código acima.
Não obstante, eu gostaria de escrever uma classe custom que embrulhasse os objetos JToken, e talvez uma classe Collection para listá-los de modo que o DataGridView entendesse e manipulasse com facilidade, ativando recursos tais como classificação (isto é essencial para mim) e filtragem (isto seria um prêmio extra se eu conseguisse).
Minha questão é: qual o conjunto mínimo de Interfaces que tais classes deveriam implementar para realizar isso?
Comment: Obrigado. Fiz edições para acrescentar mais detalhes.
Comment: A sua pergunta é boa, mas, muito ampla, poderia focar em um `JSON` com um exemplo `JSON` e como deseja exibir na `DataGridView` ou `Dropdownlist`. Usando `JSON.NET` que é a biblioteca que é a mais utilizada no mundo `.NET` o processo fica muito fácil com modelos de classe. Não vejo motivo para Reflexão se a classe `JSON.NET` for bem utilizada. Em relação a classificação e ordenação são outros passos após a disponibilidade da informação. Tem como fazer um [exemplo minimo e testavel](http://pt.stackoverflow.com/help/mcve)?
Answer: Como o seu problema não é muito pontual, me parece que possui diversos arquivos JSON, vou propor, então, na sua última edição referente ao JSON inserido na pergunta. A forma usual de trabalhar com isso seria criar os modelos de classes e utilizar a biblioteca JSON.NET para converter num objeto de classe.

Modelos:

Base
Public MustInherit Class Base
    <Newtonsoft.Json.JsonProperty("id")>
    Public Property Id As Integer

    <Newtonsoft.Json.JsonProperty("nome")>
    Public Property Nome As String
End Class

Especie
Public Class Especie
    Inherits Base
End Class

ContaMovimento
Public Class ContaMovimento
    Inherits Base
End Class

Contas
Public Class Contas
    Inherits Base
End Class

Favorecido
Public Class Favorecido
    Inherits Base
    <Newtonsoft.Json.JsonProperty("contas")>
    Public Property Contas As List(Of Contas)
End Class

Conta
Public Class Conta
    <Newtonsoft.Json.JsonProperty("id")>
    Public Property Id As Integer

    <Newtonsoft.Json.JsonProperty("conta_movimento_id")>
    Public Property ContaMovimentoId As Integer

    <Newtonsoft.Json.JsonProperty("conta_movimento")>
    Public Property ContaMovimento As ContaMovimento

    <Newtonsoft.Json.JsonProperty("especie_id")>
    Public Property EspecieId As Integer

    <Newtonsoft.Json.JsonProperty("especie")>
    Public Property Especie As Especie

    <Newtonsoft.Json.JsonProperty("favorecido_id")>
    Public Property FavorecidoId As Integer

    <Newtonsoft.Json.JsonProperty("favorecido")>
    Public Property Favorecido As Favorecido

    <Newtonsoft.Json.JsonProperty("valor")>
    Public Property Valor As Decimal
End Class

Observação: todas essas classes foram decoradas para saber qual item do JSON ele tem que deserializar (Newtonsoft.Json.JsonProperty)

Como utilizar:

Dim json = System.IO.File.ReadAllText("arquivo.json")
Dim result = JsonConvert.DeserializeObject(Of List(Of Conta))(json)

sendo que na variável result tem o resultado de um array de Conta com todas as informações do JSON organizadas e de fácil manipulação.

Para carregar isso dentro de um DataGridView é simples a partir do momento do carregamento dessa classe.
Form - Code
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim json = System.IO.File.ReadAllText("arquivo.json")
        Dim result = JsonConvert.DeserializeObject(Of List(Of Conta))(json)
        DataGridView1.DataSource =
            (From items In result
             Select New With {
                 .Conta = items.ContaMovimento.Nome,
                 .Movimento = items.Especie.Nome,
                 items.Valor,
                 .Favorecido = items.Favorecido.Nome
                 }).ToList()

    End Sub
End Class

Resultado em tela:

Isso é um exemplo e tem o que precisa, porque, o JSON ofereceu lista de itens, um objeto de um item e fica fácil com base nesse partir para os outros.
Mais alguns links que podem ser usados como tutorial:

Como ler uma struct dentro de outra com Json.Net?
Deserializar Array JSon em um Array de Objetos
Como ignorar um error usando Json.NET sem danificar o que já foi lido
Como converter uma resposta em JSON para um objeto em C#?
Comment: Não, não faltou nada. Eu apenas estava pensando em uma classe hipotética que recolhe dados a partir de uma lógica interna qualquer, e tem uma única propriedade pública default, `Default Property Item(byval key as String) as Object`. Imagine que eu tenha um grupo de instâncias dessa classe, e queira fornecê-lo como DataSource de um DataGridView, e depois definir manualmente as colunas do DataGridView indicando como .DataProperyName de cada uma delas o string que a classe vai interpretar e devolver o dado necessário. Não sei se devo fazer outra pergunta, nem se essa pergunta seria ampla demais.
Comment: Faça outra pergunta @VBobCat, e em vez de colocar o problema em um todo faça igual a essa, coloque um problema pontual ai fica fácil dar possibilidades de solução.
Comment: +1 e aceito como resposta, pois resolve o problema proposto. Não obstante, abstraindo a origem dos dados (neste caso, JSON), agradeço caso os colegas possam me instruir sobre como tornar uma dada classe qualquer apta a fornecer itens classificáveis e filtráveis para um DataSource... Grato!
Comment: @VBobCat faltou classificação e pequisa?


Drupal 8 migrate fields not filled

Question: I'm trying to migrate content to D8 site from sql source. In my migrate_plus.migration.node_article.yml config file I've following:
id: node_article
label: Article Migration
migration_group: node_migration
source:
  plugin: node_article
  bundle: node
destination:
  plugin: entity:node
process:
  uuid: uuid
  title: title
  type:
    plugin: default_value
    default_value: article
  field_seo_title: title
  field_teaser_text: title
migration_dependencies: {}
dependencies:
  enforced:
    module:
      - my_article_import

(field_seo_title is a textfield)
and NodeArticle.php:
class NodeArticle extends SqlBase
{

    public function query()
    {

        //query code ommited
    }

    public function fields()
    {
        $fields = [
            'uuid' => $this->t('Unique Unique Identifier'),
            'title' => $this->t('Title'),
            'field_teaser_text_value' => $this->t('field_teaser_text_value'),
            'field_seo_title_value' => $this->t('field_seo_title_value'),
        ];

        return $fields;
    }

    public function prepareRow(Row $row)
    {
        return parent::prepareRow($row);
    }

    public function getIds()
    {
        return [
            'nid' => [
                'type' => 'integer',
                'alias' => 'n',
            ],
        ];
    }

}

When I run migration, node is created, title get filled but all other fields are empty no matter what data I try to import. I spent almost a day trying to figure out why but running out of ideas. Does anyone have an idea what could be an issue please?
Thanks
Comment: Can you provide a complete example for you migration?
Comment: Also will be useful a dump of a row being migrated, you can get it if you add a breakpoint in `core/modules/migrate/src/MigrateExecutable.php:203`
Comment: ok, added complete yml config file and NodeArticle plugin. A screenshot of $row from MigrateExecutable::import:203:
https://www.screencast.com/t/5IarMfH4WAr
Comment: From the above screenshot, a node got created with title 'Milování "pod obojí"' but field_seo_title and field_teaser_text are emty.
Comment: I don't see anyting wrong in your YAML (perhaps the "bundle" under source, but I'm sure is a custom key). But caught my eye that the screenshot is showing that the destination has "nid" set, where did you get this? I mean on MigrateExecutable the entity is no saved yet, so no nid should be present there. Also can you implement `hook_node_presave` and make sure that just before saving the node everything is properly set?
Comment: I'm not sure, but maybe try mapping into an array rather than a single value. I look at some of the drupal field migration plugins, which, apart from the base class, are processing both value and format (in particular [TextField::defineValueProcessPipeline](https://api.drupal.org/api/drupal/core%21modules%21text%21src%21Plugin%21migrate%21field%21d6%21TextField.php/function/TextField%3A%3AdefineValueProcessPipeline/8.8.x)).
Answer: Assuming your source class works, there are two things I'm spotting:
A)
Do not prefill internal entity keys like nid, uuid or revision_id in the migration YML, the Migrate module will set them for you. Manually setting them is not required at best, and a potential cause of errors at worst.
B)
If your text fields are plain text fields, then your YML should be correct. But if your text fields are formatted text fields, then you also have to fill the  format sub column for those text fields:
  process:
    ...
    field_formattedtext/value: source_field
    field_formattedtext/format:
      plugin: default_value
      default_value: my_format_eg_basic_html
    ...

Comment: Thanks. Point A was a good hint - I removed all the extra keys and it started to work. The problematic was however 'langcode' key which i forgot to add to the above code.
The keys nid, uuid and revision_id were pertty much leftovers but I think the reason for those  was to keep the content as similar as possible to the original site. Not sure if it's a good idea to manually set nid to keep it the same though, I'll most likely remove it and leave it up to Drupal and migrate process to handle them.
Comment: Migrating the UUID should not be a problem (I've done it myself) but you never should try to migrate revisions neither database identifiers such 'nid'.

Drupal 8 migrate fields not filled


List existing file server permission groups/users

Question: So we took over a new client and their file server is frankly a mess.
We have migrated their old file server from a 2k box to a 2k8 DFS cluster and now I'm looking at rebuilding both the folder structure and their permissions. Unfortunately its been half done with AD groups (poorly named/no description/notes) and half with individuals named in security on the folders themselves.
What I'm looking to do is to dump a complete list of all the folders with their security permissions (ideally I'd like to ignore files but not essential).
CACLS got me half way there but fails with an odd error message and its output isn't particularly user friendly and I'm working with roughly 2Tb/250,000 files here so I really need something that gives me a bit more functionality.
Question : does anyone have any experience of something similar/know of a bit of software that might help me out?
Comment: Fails with what error message? Telling us it's "odd" doesn't exactly provide us with useful information which might allow us to help you out.
Comment: Yes - sorry about that. I didnt have the error to hand. I did get half the output from CACLS before it failed and looking at it I wasn't inspired to continue down that route, I'm not asking to resolve that issue but looking for an alternative.
Comment: you need to keep in mind that users do this sort of thing ("there was some kine of error message") to us all the time, so many of us have developed a low tolerance for it. ;)
Comment: Yes, Understood. 'I clicked OK on this error message a few times and now its broken.' I'll avoid this in the future :)
Answer: you have several options. But first I would suggest you maybe make your life easier by using xcopy to only copy the directories and their respective ACL/Auditing settings.
you might be able to continue with cacls or use something else...

AccessEnum from Sysinternals
PowerShell may have some possibilites. This LINK may help (corrected).
Python calling on Win32 API. I haven't tested this LINK, but have a look...

All that, but why not do the human part and sit down with people and ask who needs access to what? Then create a new structure and permissions based on the needs using your conventions and documentation.
Comment: In regards to point 3, don't you mean ANY language calling the Win32 API? Why would you specify a single language, especially one so little used on Windows?
Comment: AccessEnum looks like it might do the business, I'm testing it out now. As for your final point, unfortunately sitting down with the business isn't as straight forward as it might appear. We're talking about a large national company here, about 1000 users spread across a large number of small sites.  I have actually already moved a few departments into a new folder structure but trying to unpick the rest of the file system is proving to be a bit of a nightmare.
Comment: @John, good point, I did not mean to single out a language. It just happens to be my prefered language. I've found it to allow me certain freedoms that other languages do not as a Windows admin.
Comment: @Patrick, in your situation it's clearly impractical to discuss permissions with all the users but perhaps you should still talk to department heads, who can then talk to their staff.
Comment: @John. We've agreed a new folder structure with the business and some data as been successfully ported to it. The major problem I have is that there are a load of folders that are entirely unstructured and uncontrolled. 'Everybody' had full control and therefore the permissions are all over the place. The IT Dept we have taken over from appear to have had no policy for structuring file servers or any kind of naming convention for the AD groups that they have made. The whole thing is a mess. You should have see how the VPN was setup!
Answer: A number of years ago I created a system for my own use that was designed to save and recreate share based permissions. i.e. It will recreate shares and the permission son those share, plus any lower down permissions that differ from the share itself.
The only case I can think of where it might not do what you want to do is on a Terminal Server, where the permissions are not necessarily below a share. Although it has never been tested on 2008 I see no reason it shouldn't work on that version as well.
You can download it from here and you are free to use it without restriction. Be sure to read the ReadMe.txt before using it. It was created to be effective, not elegant.
Comment: I've just got back to the server that I ran this on as test and, although it looks extremely useful if I need to move shares, the output in the .perms files isn't anything like as useful as that from the AccessEnum. I'll keep hold of it though as I've had problems with moving shares before and that looks extremely useful. Thanks.
Comment: @Patrick, the perms files are certainly not very useful on their own, as well as being hard to read, but once you run DriveAdjust.exe the resulting batch file might be more useful.


Applying neural network algorithms on Encrypted data

Question: I have encrypted text dataset and i want to classify it using neural network algorithm. I know that there is a pattern in the encrypted data.
example of my input data :
diss%^ghghE(t dffd$#KL*vb xod@#:n>did ....
My questions is should i treat encrypted data as if its normal text and create vocabulary and transform my data into sequence of indices ?
should i clean my data first from all the special characters ?
What i tried is i cleaned all data from special characters, then created a vocabulary and transform my data into sequences however i am getting a very low accuracy. but my model works well when my data is in natural language.
Any help is appreciated.
Answer: By definition, a good encryption algorithm will not allow you to learn anything[*] from the encrypted data.
So, unless you suspect that the encryption algorithm is weak, I suggest you abandon this idea.
[*] apart from the approximate size of the original text
Comment: Thanks for your answer but i know that there is a pattern in this encrypted data. it's just hiding the normal words with random characters
Comment: Technically, the fact that a good encryption algorithm doesn't allow you to learn about the plaintext doesn't mean you can't run algorithms on the crypttext. But that is theoretical.


Disparar animação com scroll

Question: Tentei incluir a função de Fade nos seguintes elementos, porém não tive sucesso. O default que mostrado no site é este.
Quero aplicar isso a tag
 para quando eu der scroll e passar por elas, elas aumentem a fonte, ou deem fade-in. Mas não estou conseguindo entender como funciona
HTML

Papel Interfolhado

O papel toalha Safira tem qualidade
e maciez comprovada.

O guardanapo de papel Safira
é ultra-absorvente

É macio e foi feito pensando
na consciência ambiental e na
preservação do meio ambiente

JS
$(document).ready(function($) {
   // build tween
   var tween = TweenMax.fromTo("#animate2", 0.5,
       {"border-top": "0px solid white"},
       {"border-top": "30px solid white", backgroundColor: "blue", scale: 0.7}
     );

   // build scene
   var scene = new ScrollScene({triggerElement: "#trigger2", duration: 300})
           .setTween(tween)
           .addTo(controller);

   // show indicators (requires debug extension)
   scene.addIndicators();
});

JSFiddle.
ScrollMagic no GitHub.
Comment: Na forma atual, sua pergunta é incompreensível. Tente entender o problema que você está querendo resolver e depois [edit]e sua pergunta para esclarecer melhor qual é sua dúvida. Ajude-nos ajudar você.
Comment: vou tentar, e que ja apaguei o codigo e refiz.. nunca usei o stack.. to meio perdido aqui..
Comment: posta seu código tbm no jsfiddle.net
Comment: http://jsfiddle.net/zZEVJ/

quero fazer as letras aparecerem uma apos a outra conforme dou scroll na pagina.. to aprendendo jquery, e so acho tutoriais em ingles, to com uma dificuldade nervosa, acabei de pagar um curso de ingles, hahahaha nao da mais !
Comment: Oi, denis, bem vindo ao [pt.so]. Por favor, **[edit]e** sua pergunta sempre que tiver novas informações que acrescentar, e tente caprichar no português porque senão tem que vir um editor e consertar. Talvez não tenha feito o [**Tour**](http://pt.stackoverflow.com/tour) ainda, é fácil e explica porque o SOPT é diferente, se puder aproveite também e confira o mini-guia **[ask]**. Boa sorte!
Answer: Cansei de procurar no seu plugin. Não encontrei nenhuma relação entre o ScrollMagic e o TweenMax que colocou...
Assim aqui fica uma solução sem o plugin. Vale o que vale...
Versão minimalista: http://jsfiddle.net/9qn99fyp/
Exemplo com o teucódigo: http://jsfiddle.net/8j5ckd9v/
$(document).ready(function ($) {
    var elementos = $('section div p');
    elementos = elementos.map(function () {
        return {
            el: this,
            pos: $(this).position().top
        };
    });
    $(document).scroll(function () {
        var posicaoScroll = $(document).scrollTop();
        elementos.each(function () {
            if (this.pos < posicaoScroll) $(this.el).animate({'opacity': 1}, 500);
        })
    })
});

Os passos que dei:

procurei todos os elementos p dentro de section div, reorganizei essa array em array de objetos com o elemento e a posição do mesmo na página.
adicionei o .scroll() do jQuery para disparar o meu código quando o scroll acontece
a cada scroll vai procurar nos elementos os que têm posição inferior à do scroll (ou seja, já estão visiveis) e faz ele aparecer

Talvez precise de ajustes, mas a sua pergunta não foi muito clara. Se precisar mais ajuda é só comentar...
Answer: //Usa esse parâmetro aqui pra que tu possa situar o valor do scroll…
Escreve esse comando no teu código e depois da um console.log com event 'scroll'.
Const valorDoScroll = document.body.scrollheight + window.innerHeight
Console.log(ValordoScroll)
//A partir daqui tu pode usar isso pra fazer renderizar qualquer tipo de alteração no scroll.
Aí tu pode fazer o seguinte no caso de scrollar pra mudar o tamanho da fonte.
Window.addEventListen('scroll',function(){
//transforma o valor do scroll pra Int
Const ScrollInt = (Window.scrollX/valorDoScroll)*100
//se tudo estiver nos conformes você terá um valor de 0 a 100 relacionado ao tamanho da Window…
Aí tu aplica no elemento
Element.style.fontSize =${ScrollInt}px
//pronto! Com isso você vai disparar assim que scrollar…
Se quiser fazer isso em outros momentos específicos é só usar condicionais!
})
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

Disparar animação com scroll


Multiple wildcard certificates on one IIS site?

Question: We already have an SSL certificate for *.foo.com pointing to an IIS site. Now we want to point *.bar.co.nz point to the same web application and will purchase another wildcard certificate.
Is it possible to set up two wildcard SSL certificates under the one IIS site?
Answer: You would have to include both domains in a single wildcard certificate (with the use of "subject alternative name"). For more information, see RobLL's answer to this question.
Comment: Finding a CA that issues certificates with wildcards as SANs seems almost impossible. I'm thinking it'll be easier adding another IP address to the same binding and using a separate SSL certificate.
Comment: Well, by Googling for "Multi-Domain Wildcard SSL" I managed to find at least one company that offers such certificates.


python multiple threads redirecting stdout

Question: I'm building an icecast2 radio station which will restream existing stations in lower quality. This program will generate multiple FFmpeg processes restreaming 24/7. For troubleshooting purposes, I would like to have an output of every FFmpeg process redirected to the separate file.
import ffmpeg, csv
from threading import Thread

def run(name, mount, source):
icecast = "icecast://"+ICECAST2_USER+":"+ICECAST2_PASS+"@localhost:"+ICECAST2_PORT+"/"+mount
stream = (
        ffmpeg
        .input(source)
        .output(
            icecast,
            audio_bitrate=BITRATE, sample_rate=SAMPLE_RATE, format=FORMAT, acodec=CODEC,
            reconnect="1", reconnect_streamed="1", reconnect_at_eof="1", reconnect_delay_max="120",
            ice_name=name, ice_genre=source
            )
        )
return stream

with open('stations.csv', mode='r') as data:
for station in csv.DictReader(data):
    stream = run(station['name'], station['mount'], station['url'])
    thread = Thread(target=stream.run)
    thread.start()

As I understand I can't redirect stdout of each thread separately, I also can't use ffmpeg reporting which is only configured by an environment variable. Do I have any other options?
Comment: >an output of every FFmpeg process - do you mean to record what you are streaming or the log?
Comment: log, ffmpeg send everything to stdout, using option "loglevel" you can choose verbosity
Comment: That's incorrect. Everything is on `stderr`. You can attach any file stream object to each run of ffmpeg to capture every line of the log. (that is, assuming `ffmpeg-python` is not redirecting `stderr` to `stdout`)
Comment: I'm fighting with it whole day, could you please tell me how to do it?
Comment: Just looked at the source code, and you're right, it don't let you. You can either call `subprocess.Popen` yourself (run `stream.compile()` to get the command arguments) or I can share how I'd do it with my `ffmpegio`.
Comment: I tried os.system and subprocess.Popen, both fail to connect with the source stream even though FFmpeg settings are exactly the same. I'm open to any new solutions.
Answer: You need to create a thread function of your own

def stream_runner(stream,id):
    # open a stream-specific log file to write to
    with open(f'stream_{id}.log','wt') as f:
        # block until ffmpeg is done
        sp.run(stream.compile(),stderr=f)

for i, station in enumerate(csv.DictReader(data)):
    stream = run(station['name'], station['mount'], station['url'])
    thread = Thread(target=stream_runner,args=(stream,i))
    thread.start()

Something like this should work.
Comment: Thank you, working perfectly; I made small changes with log naming and put sp.run() into endless while loop, that's what even if ffmpeg crash it will reconnect
Answer: ffmpeg-python doesn't quite give you the tools to do this - you want to control one of the arguments to subprocess, stderr, but ffmpeg doesn't have an argument for this.
However, what ffmpeg-python does have, is the ability to show the command line arguments that it would have used. You can make your own call to subprocess after that.
You also don't need to use threads to do this - you can set up each ffmpeg subprocess, without waiting for it to complete, and check in on it each second. This example starts up two ffmpeg instances in parallel, and monitors each one by printing out the most recent line of output from each one every second, as well as tracking if they've exited.
I made two changes for testing:

It gets the stations from a dictionary rather than a CSV file.
It transcodes an MP4 file rather than an audio stream, since I don't have an icecast server. If you want to test it, it expects to have a file named 'sample.mp4' in the same directory.

Both should be pretty easy to change back.
import ffmpeg
import subprocess
import os
import time

stations = [
    {'name': 'foo1', 'input': 'sample.mp4', 'output': 'output.mp4'},
    {'name': 'foo2', 'input': 'sample.mp4', 'output': 'output2.mp4'},
]

class Transcoder():
    def __init__(self, arguments):
        self.arguments = arguments

    def run(self):
        stream = (
            ffmpeg
            .input(self.arguments['input'])
            .output(self.arguments['output'])
        )
        args = stream.compile(overwrite_output=True)
        with open(self.log_name(), 'ab') as logfile:
            self.subproc = subprocess.Popen(
                args,
                stdin=None,
                stdout=None,
                stderr=logfile,
            )

    def log_name(self):
        return self.arguments['name'] + "-ffmpeg.log"

    def still_running(self):
        return self.subproc.poll() is None

    def last_log_line(self):
        with open(self.log_name(), 'rb') as f:
            try:  # catch OSError in case of a one line file
                f.seek(-2, os.SEEK_END)
                while f.read(1) not in [b'\n', 'b\r']:
                    f.seek(-2, os.SEEK_CUR)
            except OSError:
                f.seek(0)
            last_line = f.readline().decode()
        last_line = last_line.split('\n')[-1]
        return last_line

    def name(self):
        return self.arguments['name']

transcoders = []
for station in stations:
    t = Transcoder(station)
    t.run()
    transcoders.append(t)

while True:
    for t in list(transcoders):
        if not t.still_running():
            print(f"{t.name()} has exited")
            transcoders.remove(t)
        print(t.name(), repr(t.last_log_line()))
    if len(transcoders) == 0:
        break
    time.sleep(1)

Comment: Thank you Nick, I used Kesh's solution it's a bit simpler and easier to troubleshoot for my programming level


using revealing module pattern with Knockout and Asp.net MVC4

Question: I'm trying to use knockout with my asp.net mvc 4 app. and this is what my code looks like.

This is sample Modular JS implementation for my client side Knockout base viewmodel. My view looks like following.

        Title
        Description
        Status
        Created By
        Created Date

I can see json data being pushed into the teamMembers ko.observableArray in my ajax call. This code should be working as per the tutorial that I'm trying to follow but i doesn't show my any data within my table. Can somebody guide me whats wrong with this code and why my table is not being rendered here. thanks
Answer: Your client side code looks fine might be something wrong with your server side code.  Check what you are returning from server especially is data returning in response variable.
I think response.result dont have any data that is why you are getting exception.  So please debug your client side code.
$.each(response.results, function (x, team) {}

Comment: I've already debugged my js and as I was saying data is there and being pushed in to the observableArray,
Comment: I also check the same code data was populated in table.  I use webapi for it and remove the .result because my result was in response varibale.  It would be good if you write your server side code or use jsfiddle.net to demonstrate


No effect by sd parameter in arima.sim model parameter

Question: I am new to R. I wanted to create an ARIMA(1,0,0) model which simulates data with the coefficient been 0.1. I used the following code:
set.seed(456)
## list description for AR(1) model with small coef
AR.sm <- list(order=c(1,0,0), ar=0.1, sd=0.0001)

## simulate AR(1)
AR1.sm <- arima.sim(n=50, model=AR.sm)

## setup plot region
par(mfrow=c(1,2))
## get y-limits for common plots
ylm <- c(min(AR1.sm), max(AR1.sm))

## plot the ts
plot.ts(AR1.sm, ylim=ylm,
        ylab=expression(italic(x)[italic(t)]),
        main=expression(paste(phi," = 0.1")))

print(paste('Mean:',mean(AR1.sm)))
print(paste('Std:',sd(AR1.sm)))

The std and mean of the data is:
[1] "Mean: 0.202367015812633"
[1] "Std: 1.03631583857173"

The problem is, no matter what I assign to the sd parameter (0.1, 1, 10), the standard deviation that is computed in the last line is about 1.
Why is it like this?
Answer: It looks like sd is not part of model but needs to be specified separately. The following does what you want:
set.seed(456)
AR.sm <- list(order=c(1,0,0), ar=0.1)
AR1.sm <- arima.sim(n=50, model=AR.sm, sd=0.0001)
sd(AR1.sm)

I got this idea from the examples in the help file of arima.sim:
arima.sim(n = 63, list(ar = c(0.8897, -0.4858), ma = c(-0.2279, 0.2488)), sd = sqrt(0.1796))

As you can see, sd is outside of the parenthesis of the model part.
Comment: Yeah, you are right. I read it from this source: https://nwfsc-timeseries.github.io/atsa-labs/sec-tslab-autoregressive-ar-models.html, which seems to be wrong. Thanks